···11-This is a retro TV-style video player application that displays a playlist of videos in a simulated television interface. The application:
11+This is a conference talk video player application that displays a playlist of videos The application:
2233-1. **Main Interface**: Presents videos in a retro TV UI with a CRT screen, channel dial, and TV controls
33+1. **Main Interface**: Presents a list of talks in a sidebar alongside a main video player.
442. **Video Playlist**: Fetches videos from the AT Protocol (Bluesky) via the place.stream.video collection
55-3. **Interactive Features**:
66- - Channel dial for navigating between videos
77- - Video list sidebar showing available videos with CH numbering
88- - Play button for individual video selection
99- - Refresh button to reload the video list
1010- - Video counter showing current/ total videos (e.g., "01/10")
1111-4. **Playback**: Supports HLS video streaming with random start positions and sequential playback
1212-5. **Responsive Design**: Adapts layout for mobile devices
1313-6. **Current State**: The application is designed as a TV-like video viewer that plays videos sequentially from a playlist, but the project goals indicate a transition to a standard selection interface where users can click on individual videos to navigate directly to them.
55+3. **Playback**: Supports HLS video streaming with random start positions and sequential playback
66+4. **Responsive Design**: Adapts layout for mobile devices
77+88+## Files
1491515-The codebase shows both the retro TV interface (dial-based navigation) and the modern video list interface with clickable items, representing the transition from the legacy TV metaphor to a more standard video selection experience.1010+`public/index.html` — Main HTML document
1111+`public/index.ts` — Main script
1212+`public/index.css` — Main styling
+3-5
README.md
···11# AtmosphereConf 2026 TV
2233-Channel surf through [AtmosphereConf 2026](https://atmosphereconf.org/) talks. [Check it out here](https://atmosphereconf-tv.btao.org/)!
44-55-My submission for the [@stream.place VOD jam](https://blog.stream.place/3micfu6ifyk2a)! :-)
33+Watch [AtmosphereConf 2026](https://atmosphereconf.org/) talks.
6477-This is entirely vibe-coded in one evening with Claude Code.
55+A submission for the [@stream.place VOD jam](https://blog.stream.place/3micfu6ifyk2a).
8697## Development
108···1412npm run dev
1513```
16141717-This will start a development server at `http://localhost:3000` with:
1515+This will start a development server at `http://localhost:8080` with:
1816- Hot module replacement
1917- Fast builds
2018- Error overlay
+111-346
build/index.html
···11<!doctype html>
22<html lang="en">
33- <head>
44- <meta charset="UTF-8" />
55- <meta name="viewport" content="width=device-width, initial-scale=1.0" />
66- <title>ATmosphereConf 2026 Talks</title>
33+ <head>
44+ <title>ATmosphereConf 2026 Talks</title>
55+66+ <meta charset="UTF-8" />
77+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
88+99+ <link rel="preconnect" href="https://fonts.googleapis.com" />
1010+ <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
1111+ <link
1212+ href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap"
1313+ rel="stylesheet"
1414+ />
71588- <!-- Meta Tags -->
99- <meta
1010- name="description"
1111- content="View ATmosphereConf 2026 Talks on-demand."
1212- />
1313- <meta property="og:title" content="ATmosphereConf 2026 Talks" />
1414- <meta
1515- property="og:description"
1616- content="View ATmosphereConf 2026 Talks on-demand"
1717- />
1818- <meta property="og:type" content="website" />
1919- <meta
2020- property="og:url"
2121- content="https://sites.wisp.place/timryan.org/atmosphereconf2026/"
2222- />
2323- <style>
2424- .safari-warning {
2525- display: none;
2626- position: fixed;
2727- bottom: 24px;
2828- left: 50%;
2929- transform: translateX(-50%);
3030- z-index: 100;
3131- background: rgba(30, 26, 20, 0.95);
3232- border: 1px solid rgba(160, 216, 160, 0.3);
3333- border-radius: 8px;
3434- padding: 12px 20px;
3535- font-family: "VT323", monospace;
3636- font-size: 18px;
3737- color: var(--phosphor);
3838- text-shadow: 0 0 6px rgba(100, 200, 100, 0.3);
3939- text-align: center;
4040- max-width: 90vw;
4141- box-shadow: 0 4px 20px rgba(0, 0, 0, 0.6);
4242- }
4343- .safari-warning.visible {
4444- display: block;
4545- }
4646- .safari-warning-close {
4747- background: none;
4848- border: none;
4949- color: var(--phosphor);
5050- font-family: "VT323", monospace;
5151- font-size: 18px;
5252- cursor: pointer;
5353- margin-left: 12px;
5454- opacity: 0.6;
5555- }
5656- .safari-warning-close:hover {
5757- opacity: 1;
5858- }
5959- </style>
6060- <style>.loading-indicator {
6161- position: absolute;
6262- bottom: 16px;
6363- left: 50%;
6464- transform: translateX(-50%);
6565- z-index: 7;
6666- font-family: sans-serif, monospace;
6767- font-size: 18px;
6868- color: var(--phosphor);
6969- text-shadow: 0 0 8px var(--phosphor);
7070- opacity: 0;
7171- transition: opacity 0.3s;
7272- pointer-events: none;
7373-}
7474-.loading-indicator.visible {
7575- opacity: 1;
7676-}
7777-/* Muted indicator */
7878-.muted-indicator {
7979- position: absolute;
8080- bottom: 16px;
8181- left: 16px;
8282- z-index: 7;
8383- font-family: "VT323", monospace;
8484- font-size: 20px;
8585- color: rgba(255, 255, 255, 0.6);
8686- text-shadow: 0 0 6px rgba(0, 0, 0, 0.8);
8787- pointer-events: none;
8888- opacity: 0;
8989- transition: opacity 0.5s;
9090-}
9191-.muted-indicator.visible {
9292- opacity: 1;
9393-}
9494-.muted-indicator.fade-out {
9595- opacity: 0;
9696- transition: opacity 1.5s;
9797-}
9898-.source-link {
9999- font-family: "VT323", monospace;
100100- font-size: 14px;
101101- color: rgba(255, 255, 255, 0.25);
102102- text-decoration: none;
103103- margin-top: 8px;
104104-}
105105-.source-link:hover {
106106- color: rgba(255, 255, 255, 0.5);
107107-}
108108-#video {
109109- width: 500px;
110110-}
111111-/* Video List Styling */
112112-.video-list {
113113- background: rgba(30, 26, 20, 0.9);
114114- border: 1px solid rgba(160, 216, 160, 0.3);
115115- border-radius: 8px;
116116- padding: 16px;
117117- margin-top: 16px;
118118- max-height: 400px;
119119- overflow-y: auto;
120120- box-shadow: 0 4px 12px rgba(0, 0, 0, 0.5);
121121-}
122122-.video-list-header {
123123- font-family: "VT323", monospace;
124124- font-size: 18px;
125125- color: var(--phosphor);
126126- margin-bottom: 12px;
127127- padding-bottom: 8px;
128128- border-bottom: 1px solid rgba(160, 216, 160, 0.2);
129129-}
130130-.video-list-container {
131131- display: flex;
132132- flex-direction: column;
133133- gap: 8px;
134134-}
135135-.video-list-item {
136136- background: rgba(20, 18, 14, 0.7);
137137- border: 1px solid rgba(160, 216, 160, 0.2);
138138- border-radius: 6px;
139139- padding: 10px 12px;
140140- display: flex;
141141- align-items: center;
142142- cursor: pointer;
143143- transition: all 0.2s ease;
144144-}
145145-.video-list-item:hover {
146146- background: rgba(25, 23, 18, 0.9);
147147- border-color: rgba(160, 216, 160, 0.4);
148148-}
149149-.video-list-item.focused {
150150- background: rgba(30, 26, 20, 0.9);
151151- border-color: var(--phosphor);
152152- box-shadow: 0 0 0 2px rgba(160, 216, 160, 0.3);
153153-}
154154-.video-list-number {
155155- font-family: "VT323", monospace;
156156- font-size: 16px;
157157- color: var(--phosphor);
158158- width: 60px;
159159- text-align: right;
160160- margin-right: 12px;
161161-}
162162-.video-list-title {
163163- font-family: "VT323", monospace;
164164- font-size: 16px;
165165- color: var(--phosphor);
166166- flex: 1;
167167- overflow: hidden;
168168- text-overflow: ellipsis;
169169- white-space: nowrap;
170170-}
171171-.video-list-actions {
172172- margin-left: 12px;
173173-}
174174-.play-video-btn {
175175- background: rgba(255, 255, 255, 0.2);
176176- border: 1px solid rgba(160, 216, 160, 0.3);
177177- border-radius: 4px;
178178- padding: 6px 12px;
179179- font-family: "VT323", monospace;
180180- font-size: 12px;
181181- color: var(--phosphor);
182182- cursor: pointer;
183183- transition: all 0.2s ease;
184184- margin: 0 4px;
185185-}
186186-.play-video-btn:hover {
187187- background: rgba(255, 255, 255, 0.3);
188188- border-color: rgba(160, 216, 160, 0.5);
189189-}
190190-.video-list-item.currently-playing {
191191- background: rgba(160, 216, 160, 0.15);
192192- border-color: var(--phosphor);
193193- box-shadow: 0 0 0 2px rgba(160, 216, 160, 0.5);
194194-}
195195-.video-list-item.currently-playing:hover {
196196- background: rgba(160, 216, 160, 0.2);
197197-}
198198-#videoCounter {
199199- font-family: "VT323", monospace;
200200- font-size: 14px;
201201- color: rgba(160, 216, 160, 0.6);
202202- margin-left: 8px;
203203-}
204204-.video-list-loading {
205205- font-family: "VT323", monospace;
206206- font-size: 16px;
207207- color: var(--phosphor);
208208- text-align: center;
209209- padding: 20px;
210210- background: rgba(20, 18, 14, 0.5);
211211- border-radius: 6px;
212212-}
213213-.video-list-empty {
214214- font-family: "VT323", monospace;
215215- font-size: 16px;
216216- color: rgba(160, 216, 160, 0.5);
217217- text-align: center;
218218- padding: 30px 20px;
219219- background: rgba(20, 18, 14, 0.3);
220220- border-radius: 6px;
221221- margin-top: 10px;
222222-}
223223- </style>
224224- <script type="module" crossorigin>(function(){const e=document.createElement("link").relList;if(e&&e.supports&&e.supports("modulepreload"))return;for(const i of document.querySelectorAll('link[rel="modulepreload"]'))s(i);new MutationObserver(i=>{for(const r of i)if(r.type==="childList")for(const n of r.addedNodes)n.tagName==="LINK"&&n.rel==="modulepreload"&&s(n)}).observe(document,{childList:!0,subtree:!0});function t(i){const r={};return i.integrity&&(r.integrity=i.integrity),i.referrerPolicy&&(r.referrerPolicy=i.referrerPolicy),i.crossOrigin==="use-credentials"?r.credentials="include":i.crossOrigin==="anonymous"?r.credentials="omit":r.credentials="same-origin",r}function s(i){if(i.ep)return;i.ep=!0;const r=t(i);fetch(i.href,r)}})();const M=Number.isFinite||function(a){return typeof a=="number"&&isFinite(a)},eo=Number.isSafeInteger||function(a){return typeof a=="number"&&Math.abs(a)<=to},to=Number.MAX_SAFE_INTEGER||9007199254740991;let V=function(a){return a.NETWORK_ERROR="networkError",a.MEDIA_ERROR="mediaError",a.KEY_SYSTEM_ERROR="keySystemError",a.MUX_ERROR="muxError",a.OTHER_ERROR="otherError",a}({}),R=function(a){return a.KEY_SYSTEM_NO_KEYS="keySystemNoKeys",a.KEY_SYSTEM_NO_ACCESS="keySystemNoAccess",a.KEY_SYSTEM_NO_SESSION="keySystemNoSession",a.KEY_SYSTEM_NO_CONFIGURED_LICENSE="keySystemNoConfiguredLicense",a.KEY_SYSTEM_LICENSE_REQUEST_FAILED="keySystemLicenseRequestFailed",a.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED="keySystemServerCertificateRequestFailed",a.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED="keySystemServerCertificateUpdateFailed",a.KEY_SYSTEM_SESSION_UPDATE_FAILED="keySystemSessionUpdateFailed",a.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED="keySystemStatusOutputRestricted",a.KEY_SYSTEM_STATUS_INTERNAL_ERROR="keySystemStatusInternalError",a.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR="keySystemDestroyMediaKeysError",a.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR="keySystemDestroyCloseSessionError",a.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR="keySystemDestroyRemoveSessionError",a.MANIFEST_LOAD_ERROR="manifestLoadError",a.MANIFEST_LOAD_TIMEOUT="manifestLoadTimeOut",a.MANIFEST_PARSING_ERROR="manifestParsingError",a.MANIFEST_INCOMPATIBLE_CODECS_ERROR="manifestIncompatibleCodecsError",a.LEVEL_EMPTY_ERROR="levelEmptyError",a.LEVEL_LOAD_ERROR="levelLoadError",a.LEVEL_LOAD_TIMEOUT="levelLoadTimeOut",a.LEVEL_PARSING_ERROR="levelParsingError",a.LEVEL_SWITCH_ERROR="levelSwitchError",a.AUDIO_TRACK_LOAD_ERROR="audioTrackLoadError",a.AUDIO_TRACK_LOAD_TIMEOUT="audioTrackLoadTimeOut",a.SUBTITLE_LOAD_ERROR="subtitleTrackLoadError",a.SUBTITLE_TRACK_LOAD_TIMEOUT="subtitleTrackLoadTimeOut",a.FRAG_LOAD_ERROR="fragLoadError",a.FRAG_LOAD_TIMEOUT="fragLoadTimeOut",a.FRAG_DECRYPT_ERROR="fragDecryptError",a.FRAG_PARSING_ERROR="fragParsingError",a.FRAG_GAP="fragGap",a.REMUX_ALLOC_ERROR="remuxAllocError",a.KEY_LOAD_ERROR="keyLoadError",a.KEY_LOAD_TIMEOUT="keyLoadTimeOut",a.BUFFER_ADD_CODEC_ERROR="bufferAddCodecError",a.BUFFER_INCOMPATIBLE_CODECS_ERROR="bufferIncompatibleCodecsError",a.BUFFER_APPEND_ERROR="bufferAppendError",a.BUFFER_APPENDING_ERROR="bufferAppendingError",a.BUFFER_STALLED_ERROR="bufferStalledError",a.BUFFER_FULL_ERROR="bufferFullError",a.BUFFER_SEEK_OVER_HOLE="bufferSeekOverHole",a.BUFFER_NUDGE_ON_STALL="bufferNudgeOnStall",a.ASSET_LIST_LOAD_ERROR="assetListLoadError",a.ASSET_LIST_LOAD_TIMEOUT="assetListLoadTimeout",a.ASSET_LIST_PARSING_ERROR="assetListParsingError",a.INTERSTITIAL_ASSET_ITEM_ERROR="interstitialAssetItemError",a.INTERNAL_EXCEPTION="internalException",a.INTERNAL_ABORTED="aborted",a.ATTACH_MEDIA_ERROR="attachMediaError",a.UNKNOWN="unknown",a}({}),m=function(a){return a.MEDIA_ATTACHING="hlsMediaAttaching",a.MEDIA_ATTACHED="hlsMediaAttached",a.MEDIA_DETACHING="hlsMediaDetaching",a.MEDIA_DETACHED="hlsMediaDetached",a.MEDIA_ENDED="hlsMediaEnded",a.STALL_RESOLVED="hlsStallResolved",a.BUFFER_RESET="hlsBufferReset",a.BUFFER_CODECS="hlsBufferCodecs",a.BUFFER_CREATED="hlsBufferCreated",a.BUFFER_APPENDING="hlsBufferAppending",a.BUFFER_APPENDED="hlsBufferAppended",a.BUFFER_EOS="hlsBufferEos",a.BUFFERED_TO_END="hlsBufferedToEnd",a.BUFFER_FLUSHING="hlsBufferFlushing",a.BUFFER_FLUSHED="hlsBufferFlushed",a.MANIFEST_LOADING="hlsManifestLoading",a.MANIFEST_LOADED="hlsManifestLoaded",a.MANIFEST_PARSED="hlsManifestParsed",a.LEVEL_SWITCHING="hlsLevelSwitching",a.LEVEL_SWITCHED="hlsLevelSwitched",a.LEVEL_LOADING="hlsLevelLoading",a.LEVEL_LOADED="hlsLevelLoaded",a.LEVEL_UPDATED="hlsLevelUpdated",a.LEVEL_PTS_UPDATED="hlsLevelPtsUpdated",a.LEVELS_UPDATED="hlsLevelsUpdated",a.AUDIO_TRACKS_UPDATED="hlsAudioTracksUpdated",a.AUDIO_TRACK_SWITCHING="hlsAudioTrackSwitching",a.AUDIO_TRACK_SWITCHED="hlsAudioTrackSwitched",a.AUDIO_TRACK_LOADING="hlsAudioTrackLoading",a.AUDIO_TRACK_LOADED="hlsAudioTrackLoaded",a.AUDIO_TRACK_UPDATED="hlsAudioTrackUpdated",a.SUBTITLE_TRACKS_UPDATED="hlsSubtitleTracksUpdated",a.SUBTITLE_TRACKS_CLEARED="hlsSubtitleTracksCleared",a.SUBTITLE_TRACK_SWITCH="hlsSubtitleTrackSwitch",a.SUBTITLE_TRACK_LOADING="hlsSubtitleTrackLoading",a.SUBTITLE_TRACK_LOADED="hlsSubtitleTrackLoaded",a.SUBTITLE_TRACK_UPDATED="hlsSubtitleTrackUpdated",a.SUBTITLE_FRAG_PROCESSED="hlsSubtitleFragProcessed",a.CUES_PARSED="hlsCuesParsed",a.NON_NATIVE_TEXT_TRACKS_FOUND="hlsNonNativeTextTracksFound",a.INIT_PTS_FOUND="hlsInitPtsFound",a.FRAG_LOADING="hlsFragLoading",a.FRAG_LOAD_EMERGENCY_ABORTED="hlsFragLoadEmergencyAborted",a.FRAG_LOADED="hlsFragLoaded",a.FRAG_DECRYPTED="hlsFragDecrypted",a.FRAG_PARSING_INIT_SEGMENT="hlsFragParsingInitSegment",a.FRAG_PARSING_USERDATA="hlsFragParsingUserdata",a.FRAG_PARSING_METADATA="hlsFragParsingMetadata",a.FRAG_PARSED="hlsFragParsed",a.FRAG_BUFFERED="hlsFragBuffered",a.FRAG_CHANGED="hlsFragChanged",a.FPS_DROP="hlsFpsDrop",a.FPS_DROP_LEVEL_CAPPING="hlsFpsDropLevelCapping",a.MAX_AUTO_LEVEL_UPDATED="hlsMaxAutoLevelUpdated",a.ERROR="hlsError",a.DESTROYING="hlsDestroying",a.KEY_LOADING="hlsKeyLoading",a.KEY_LOADED="hlsKeyLoaded",a.LIVE_BACK_BUFFER_REACHED="hlsLiveBackBufferReached",a.BACK_BUFFER_REACHED="hlsBackBufferReached",a.STEERING_MANIFEST_LOADED="hlsSteeringManifestLoaded",a.ASSET_LIST_LOADING="hlsAssetListLoading",a.ASSET_LIST_LOADED="hlsAssetListLoaded",a.INTERSTITIALS_UPDATED="hlsInterstitialsUpdated",a.INTERSTITIALS_BUFFERED_TO_BOUNDARY="hlsInterstitialsBufferedToBoundary",a.INTERSTITIAL_ASSET_PLAYER_CREATED="hlsInterstitialAssetPlayerCreated",a.INTERSTITIAL_STARTED="hlsInterstitialStarted",a.INTERSTITIAL_ASSET_STARTED="hlsInterstitialAssetStarted",a.INTERSTITIAL_ASSET_ENDED="hlsInterstitialAssetEnded",a.INTERSTITIAL_ASSET_ERROR="hlsInterstitialAssetError",a.INTERSTITIAL_ENDED="hlsInterstitialEnded",a.INTERSTITIALS_PRIMARY_RESUMED="hlsInterstitialsPrimaryResumed",a.PLAYOUT_LIMIT_REACHED="hlsPlayoutLimitReached",a.EVENT_CUE_ENTER="hlsEventCueEnter",a}({});var Q={MANIFEST:"manifest",LEVEL:"level",AUDIO_TRACK:"audioTrack",SUBTITLE_TRACK:"subtitleTrack"},B={MAIN:"main",AUDIO:"audio",SUBTITLE:"subtitle"};class pt{constructor(e,t=0,s=0){this.halfLife=void 0,this.alpha_=void 0,this.estimate_=void 0,this.totalWeight_=void 0,this.halfLife=e,this.alpha_=e?Math.exp(Math.log(.5)/e):0,this.estimate_=t,this.totalWeight_=s}sample(e,t){const s=Math.pow(this.alpha_,e);this.estimate_=t*(1-s)+s*this.estimate_,this.totalWeight_+=e}getTotalWeight(){return this.totalWeight_}getEstimate(){if(this.alpha_){const e=1-Math.pow(this.alpha_,this.totalWeight_);if(e)return this.estimate_/e}return this.estimate_}}class so{constructor(e,t,s,i=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_=s,this.minWeight_=.001,this.minDelayMs_=50,this.slow_=new pt(e),this.fast_=new pt(t),this.defaultTTFB_=i,this.ttfb_=new pt(e)}update(e,t){const{slow_:s,fast_:i,ttfb_:r}=this;s.halfLife!==e&&(this.slow_=new pt(e,s.getEstimate(),s.getTotalWeight())),i.halfLife!==t&&(this.fast_=new pt(t,i.getEstimate(),i.getTotalWeight())),r.halfLife!==e&&(this.ttfb_=new pt(e,r.getEstimate(),r.getTotalWeight()))}sample(e,t){e=Math.max(e,this.minDelayMs_);const s=8*t,i=e/1e3,r=s/i;this.fast_.sample(i,r),this.slow_.sample(i,r)}sampleTTFB(e){const t=e/1e3,s=Math.sqrt(2)*Math.exp(-Math.pow(t,2)/2);this.ttfb_.sample(s,Math.max(e,5))}canEstimate(){return this.fast_.getTotalWeight()>=this.minWeight_}getEstimate(){return this.canEstimate()?Math.min(this.fast_.getEstimate(),this.slow_.getEstimate()):this.defaultEstimate_}getEstimateTTFB(){return this.ttfb_.getTotalWeight()>=this.minWeight_?this.ttfb_.getEstimate():this.defaultTTFB_}get defaultEstimate(){return this.defaultEstimate_}destroy(){}}function io(a,e,t){return(e=no(e))in a?Object.defineProperty(a,e,{value:t,enumerable:!0,configurable:!0,writable:!0}):a[e]=t,a}function ie(){return ie=Object.assign?Object.assign.bind():function(a){for(var e=1;e<arguments.length;e++){var t=arguments[e];for(var s in t)({}).hasOwnProperty.call(t,s)&&(a[s]=t[s])}return a},ie.apply(null,arguments)}function Ji(a,e){var t=Object.keys(a);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(a);e&&(s=s.filter(function(i){return Object.getOwnPropertyDescriptor(a,i).enumerable})),t.push.apply(t,s)}return t}function te(a){for(var e=1;e<arguments.length;e++){var t=arguments[e]!=null?arguments[e]:{};e%2?Ji(Object(t),!0).forEach(function(s){io(a,s,t[s])}):Object.getOwnPropertyDescriptors?Object.defineProperties(a,Object.getOwnPropertyDescriptors(t)):Ji(Object(t)).forEach(function(s){Object.defineProperty(a,s,Object.getOwnPropertyDescriptor(t,s))})}return a}function ro(a,e){if(typeof a!="object"||!a)return a;var t=a[Symbol.toPrimitive];if(t!==void 0){var s=t.call(a,e);if(typeof s!="object")return s;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(a)}function no(a){var e=ro(a,"string");return typeof e=="symbol"?e:e+""}class we{constructor(e,t){this.trace=void 0,this.debug=void 0,this.log=void 0,this.warn=void 0,this.info=void 0,this.error=void 0;const s=`[${e}]:`;this.trace=et,this.debug=t.debug.bind(null,s),this.log=t.log.bind(null,s),this.warn=t.warn.bind(null,s),this.info=t.info.bind(null,s),this.error=t.error.bind(null,s)}}const et=function(){},ao={trace:et,debug:et,log:et,warn:et,info:et,error:et};function ri(){return ie({},ao)}function oo(a,e){const t=self.console[a];return t?t.bind(self.console,`${e?"["+e+"] ":""}[${a}] >`):et}function er(a,e,t){return e[a]?e[a].bind(e):oo(a,t)}const ni=ri();function lo(a,e,t){const s=ri();if(typeof console=="object"&&a===!0||typeof a=="object"){const i=["debug","log","info","warn","error"];i.forEach(r=>{s[r]=er(r,a,t)});try{s.log(`Debug logs enabled for "${e}" in hls.js version 1.6.15`)}catch{return ri()}i.forEach(r=>{ni[r]=er(r,a)})}else ie(ni,s);return s}const se=ni;function rt(a=!0){return typeof self>"u"?void 0:(a||!self.MediaSource)&&self.ManagedMediaSource||self.MediaSource||self.WebKitMediaSource}function co(a){return typeof self<"u"&&a===self.ManagedMediaSource}function Sn(a,e){const t=Object.keys(a),s=Object.keys(e),i=t.length,r=s.length;return!i||!r||i===r&&!t.some(n=>s.indexOf(n)===-1)}function be(a,e=!1){if(typeof TextDecoder<"u"){const l=new TextDecoder("utf-8").decode(a);if(e){const h=l.indexOf("\0");return h!==-1?l.substring(0,h):l}return l.replace(/\0/g,"")}const t=a.length;let s,i,r,n="",o=0;for(;o<t;){if(s=a[o++],s===0&&e)return n;if(s===0||s===3)continue;switch(s>>4){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:n+=String.fromCharCode(s);break;case 12:case 13:i=a[o++],n+=String.fromCharCode((s&31)<<6|i&63);break;case 14:i=a[o++],r=a[o++],n+=String.fromCharCode((s&15)<<12|(i&63)<<6|(r&63)<<0);break}}return n}function me(a){let e="";for(let t=0;t<a.length;t++){let s=a[t].toString(16);s.length<2&&(s="0"+s),e+=s}return e}function vn(a){return Uint8Array.from(a.replace(/^0x/,"").replace(/([\da-fA-F]{2}) ?/g,"0x$1 ").replace(/ +$/,"").split(" ")).buffer}function ho(a){return a&&a.__esModule&&Object.prototype.hasOwnProperty.call(a,"default")?a.default:a}var Os={exports:{}},tr;function uo(){return tr||(tr=1,function(a,e){(function(t){var s=/^(?=((?:[a-zA-Z0-9+\-.]+:)?))\1(?=((?:\/\/[^\/?#]*)?))\2(?=((?:(?:[^?#\/]*\/)*[^;?#\/]*)?))\3((?:;[^?#]*)?)(\?[^#]*)?(#[^]*)?$/,i=/^(?=([^\/?#]*))\1([^]*)$/,r=/(?:\/|^)\.(?=\/)/g,n=/(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g,o={buildAbsoluteURL:function(c,l,h){if(h=h||{},c=c.trim(),l=l.trim(),!l){if(!h.alwaysNormalize)return c;var d=o.parseURL(c);if(!d)throw new Error("Error trying to parse base URL.");return d.path=o.normalizePath(d.path),o.buildURLFromParts(d)}var u=o.parseURL(l);if(!u)throw new Error("Error trying to parse relative URL.");if(u.scheme)return h.alwaysNormalize?(u.path=o.normalizePath(u.path),o.buildURLFromParts(u)):l;var f=o.parseURL(c);if(!f)throw new Error("Error trying to parse base URL.");if(!f.netLoc&&f.path&&f.path[0]!=="/"){var g=i.exec(f.path);f.netLoc=g[1],f.path=g[2]}f.netLoc&&!f.path&&(f.path="/");var y={scheme:f.scheme,netLoc:u.netLoc,path:null,params:u.params,query:u.query,fragment:u.fragment};if(!u.netLoc&&(y.netLoc=f.netLoc,u.path[0]!=="/"))if(!u.path)y.path=f.path,u.params||(y.params=f.params,u.query||(y.query=f.query));else{var p=f.path,E=p.substring(0,p.lastIndexOf("/")+1)+u.path;y.path=o.normalizePath(E)}return y.path===null&&(y.path=h.alwaysNormalize?o.normalizePath(u.path):u.path),o.buildURLFromParts(y)},parseURL:function(c){var l=s.exec(c);return l?{scheme:l[1]||"",netLoc:l[2]||"",path:l[3]||"",params:l[4]||"",query:l[5]||"",fragment:l[6]||""}:null},normalizePath:function(c){for(c=c.split("").reverse().join("").replace(r,"");c.length!==(c=c.replace(n,"")).length;);return c.split("").reverse().join("")},buildURLFromParts:function(c){return c.scheme+c.netLoc+c.path+c.params+c.query+c.fragment}};a.exports=o})()}(Os)),Os.exports}var Ii=uo();class Li{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 re={AUDIO:"audio",VIDEO:"video",AUDIOVIDEO:"audiovideo"};class xn{constructor(e){this._byteRange=null,this._url=null,this._stats=null,this._streams=null,this.base=void 0,this.relurl=void 0,typeof e=="string"&&(e={url:e}),this.base=e,go(this,"stats")}setByteRange(e,t){const s=e.split("@",2);let i;s.length===1?i=(t==null?void 0:t.byteRangeEndOffset)||0:i=parseInt(s[1]),this._byteRange=[i,parseInt(s[0])+i]}get baseurl(){return this.base.url}get byteRange(){return this._byteRange===null?[]:this._byteRange}get byteRangeStartOffset(){return this.byteRange[0]}get byteRangeEndOffset(){return this.byteRange[1]}get elementaryStreams(){return this._streams===null&&(this._streams={[re.AUDIO]:null,[re.VIDEO]:null,[re.AUDIOVIDEO]:null}),this._streams}set elementaryStreams(e){this._streams=e}get hasStats(){return this._stats!==null}get hasStreams(){return this._streams!==null}get stats(){return this._stats===null&&(this._stats=new Li),this._stats}set stats(e){this._stats=e}get url(){return!this._url&&this.baseurl&&this.relurl&&(this._url=Ii.buildAbsoluteURL(this.baseurl,this.relurl,{alwaysNormalize:!0})),this._url||""}set url(e){this._url=e}clearElementaryStreamInfo(){const{elementaryStreams:e}=this;e[re.AUDIO]=null,e[re.VIDEO]=null,e[re.AUDIOVIDEO]=null}}function ce(a){return a.sn!=="initSegment"}class Fs extends xn{constructor(e,t){super(t),this._decryptdata=null,this._programDateTime=null,this._ref=null,this._bitrate=void 0,this.rawProgramDateTime=null,this.tagList=[],this.duration=0,this.sn=0,this.levelkeys=void 0,this.type=void 0,this.loader=null,this.keyLoader=null,this.level=-1,this.cc=0,this.startPTS=void 0,this.endPTS=void 0,this.startDTS=void 0,this.endDTS=void 0,this.start=0,this.playlistOffset=0,this.deltaPTS=void 0,this.maxStartPTS=void 0,this.minEndPTS=void 0,this.data=void 0,this.bitrateTest=!1,this.title=null,this.initSegment=null,this.endList=void 0,this.gap=void 0,this.urlId=0,this.type=e}get byteLength(){if(this.hasStats){const e=this.stats.total;if(e)return e}if(this.byteRange.length){const e=this.byteRange[0],t=this.byteRange[1];if(M(e)&&M(t))return t-e}return null}get bitrate(){return this.byteLength?this.byteLength*8/this.duration:this._bitrate?this._bitrate:null}set bitrate(e){this._bitrate=e}get decryptdata(){var e;const{levelkeys:t}=this;if(!t||t.NONE)return null;if(t.identity)this._decryptdata||(this._decryptdata=t.identity.getDecryptData(this.sn));else if(!((e=this._decryptdata)!=null&&e.keyId)){const s=Object.keys(t);if(s.length===1){const i=this._decryptdata=t[s[0]]||null;i&&(this._decryptdata=i.getDecryptData(this.sn,t))}}return this._decryptdata}get end(){return this.start+this.duration}get endProgramDateTime(){if(this.programDateTime===null)return null;const e=M(this.duration)?this.duration:0;return this.programDateTime+e*1e3}get encrypted(){var e;if((e=this._decryptdata)!=null&&e.encrypted)return!0;if(this.levelkeys){var t;const s=Object.keys(this.levelkeys),i=s.length;if(i>1||i===1&&(t=this.levelkeys[s[0]])!=null&&t.encrypted)return!0}return!1}get programDateTime(){return this._programDateTime===null&&this.rawProgramDateTime&&(this.programDateTime=Date.parse(this.rawProgramDateTime)),this._programDateTime}set programDateTime(e){if(!M(e)){this._programDateTime=this.rawProgramDateTime=null;return}this._programDateTime=e}get ref(){return ce(this)?(this._ref||(this._ref={base:this.base,start:this.start,duration:this.duration,sn:this.sn,programDateTime:this.programDateTime}),this._ref):null}addStart(e){this.setStart(this.start+e)}setStart(e){this.start=e,this._ref&&(this._ref.start=e)}setDuration(e){this.duration=e,this._ref&&(this._ref.duration=e)}setKeyFormat(e){const t=this.levelkeys;if(t){var s;const i=t[e];i&&!((s=this._decryptdata)!=null&&s.keyId)&&(this._decryptdata=i.getDecryptData(this.sn,t))}}abortRequests(){var e,t;(e=this.loader)==null||e.abort(),(t=this.keyLoader)==null||t.abort()}setElementaryStreamInfo(e,t,s,i,r,n=!1){const{elementaryStreams:o}=this,c=o[e];if(!c){o[e]={startPTS:t,endPTS:s,startDTS:i,endDTS:r,partial:n};return}c.startPTS=Math.min(c.startPTS,t),c.endPTS=Math.max(c.endPTS,s),c.startDTS=Math.min(c.startDTS,i),c.endDTS=Math.max(c.endDTS,r)}}class fo extends xn{constructor(e,t,s,i,r){super(s),this.fragOffset=0,this.duration=0,this.gap=!1,this.independent=!1,this.relurl=void 0,this.fragment=void 0,this.index=void 0,this.duration=e.decimalFloatingPoint("DURATION"),this.gap=e.bool("GAP"),this.independent=e.bool("INDEPENDENT"),this.relurl=e.enumeratedString("URI"),this.fragment=t,this.index=i;const n=e.enumeratedString("BYTERANGE");n&&this.setByteRange(n,r),r&&(this.fragOffset=r.fragOffset+r.duration)}get start(){return this.fragment.start+this.fragOffset}get end(){return this.start+this.duration}get loaded(){const{elementaryStreams:e}=this;return!!(e.audio||e.video||e.audiovideo)}}function An(a,e){const t=Object.getPrototypeOf(a);if(t){const s=Object.getOwnPropertyDescriptor(t,e);return s||An(t,e)}}function go(a,e){const t=An(a,e);t&&(t.enumerable=!0,Object.defineProperty(a,e,t))}const sr=Math.pow(2,32)-1,mo=[].push,In={video:1,audio:2,id3:3,text:4};function he(a){return String.fromCharCode.apply(null,a)}function Ln(a,e){const t=a[e]<<8|a[e+1];return t<0?65536+t:t}function W(a,e){const t=Rn(a,e);return t<0?4294967296+t:t}function ir(a,e){let t=W(a,e);return t*=Math.pow(2,32),t+=W(a,e+4),t}function Rn(a,e){return a[e]<<24|a[e+1]<<16|a[e+2]<<8|a[e+3]}function po(a){const e=a.byteLength;for(let t=0;t<e;){const s=W(a,t);if(s>8&&a[t+4]===109&&a[t+5]===111&&a[t+6]===111&&a[t+7]===102)return!0;t=s>1?t+s:e}return!1}function z(a,e){const t=[];if(!e.length)return t;const s=a.byteLength;for(let i=0;i<s;){const r=W(a,i),n=he(a.subarray(i+4,i+8)),o=r>1?i+r:s;if(n===e[0])if(e.length===1)t.push(a.subarray(i+8,o));else{const c=z(a.subarray(i+8,o),e.slice(1));c.length&&mo.apply(t,c)}i=o}return t}function yo(a){const e=[],t=a[0];let s=8;const i=W(a,s);s+=4;let r=0,n=0;t===0?(r=W(a,s),n=W(a,s+4),s+=8):(r=ir(a,s),n=ir(a,s+8),s+=16),s+=2;let o=a.length+n;const c=Ln(a,s);s+=2;for(let l=0;l<c;l++){let h=s;const d=W(a,h);h+=4;const u=d&2147483647;if((d&2147483648)>>>31===1)return se.warn("SIDX has hierarchical references (not supported)"),null;const g=W(a,h);h+=4,e.push({referenceSize:u,subsegmentDuration:g,info:{duration:g/i,start:o,end:o+u-1}}),o+=u,h+=4,s=h}return{earliestPresentationTime:r,timescale:i,version:t,referencesCount:c,references:e}}function bn(a){const e=[],t=z(a,["moov","trak"]);for(let i=0;i<t.length;i++){const r=t[i],n=z(r,["tkhd"])[0];if(n){let o=n[0];const c=W(n,o===0?12:20),l=z(r,["mdia","mdhd"])[0];if(l){o=l[0];const h=W(l,o===0?12:20),d=z(r,["mdia","hdlr"])[0];if(d){const u=he(d.subarray(8,12)),f={soun:re.AUDIO,vide:re.VIDEO}[u],g=z(r,["mdia","minf","stbl","stsd"])[0],y=Eo(g);f?(e[c]={timescale:h,type:f,stsd:y},e[f]=te({timescale:h,id:c},y)):e[c]={timescale:h,type:u,stsd:y}}}}}return z(a,["moov","mvex","trex"]).forEach(i=>{const r=W(i,4),n=e[r];n&&(n.default={duration:W(i,12),flags:W(i,20)})}),e}function Eo(a){const e=a.subarray(8),t=e.subarray(86),s=he(e.subarray(4,8));let i=s,r;const n=s==="enca"||s==="encv";if(n){const l=z(e,[s])[0].subarray(s==="enca"?28:78);z(l,["sinf"]).forEach(d=>{const u=z(d,["schm"])[0];if(u){const f=he(u.subarray(4,8));if(f==="cbcs"||f==="cenc"){const g=z(d,["frma"])[0];g&&(i=he(g))}}})}const o=i;switch(i){case"avc1":case"avc2":case"avc3":case"avc4":{const c=z(t,["avcC"])[0];c&&c.length>3&&(i+="."+qt(c[1])+qt(c[2])+qt(c[3]),r=Wt(o==="avc1"?"dva1":"dvav",t));break}case"mp4a":{const c=z(e,[s])[0],l=z(c.subarray(28),["esds"])[0];if(l&&l.length>7){let h=4;if(l[h++]!==3)break;h=Ms(l,h),h+=2;const d=l[h++];if(d&128&&(h+=2),d&64&&(h+=l[h++]),l[h++]!==4)break;h=Ms(l,h);const u=l[h++];if(u===64)i+="."+qt(u);else break;if(h+=12,l[h++]!==5)break;h=Ms(l,h);const f=l[h++];let g=(f&248)>>3;g===31&&(g+=1+((f&7)<<3)+((l[h]&224)>>5)),i+="."+g}break}case"hvc1":case"hev1":{const c=z(t,["hvcC"])[0];if(c&&c.length>12){const l=c[1],h=["","A","B","C"][l>>6],d=l&31,u=W(c,2),f=(l&32)>>5?"H":"L",g=c[12],y=c.subarray(6,12);i+="."+h+d,i+="."+To(u).toString(16).toUpperCase(),i+="."+f+g;let p="";for(let E=y.length;E--;){const T=y[E];(T||p)&&(p="."+T.toString(16).toUpperCase()+p)}i+=p}r=Wt(o=="hev1"?"dvhe":"dvh1",t);break}case"dvh1":case"dvhe":case"dvav":case"dva1":case"dav1":{i=Wt(i,t)||i;break}case"vp09":{const c=z(t,["vpcC"])[0];if(c&&c.length>6){const l=c[4],h=c[5],d=c[6]>>4&15;i+="."+Ge(l)+"."+Ge(h)+"."+Ge(d)}break}case"av01":{const c=z(t,["av1C"])[0];if(c&&c.length>2){const l=c[1]>>>5,h=c[1]&31,d=c[2]>>>7?"H":"M",u=(c[2]&64)>>6,f=(c[2]&32)>>5,g=l===2&&u?f?12:10:u?10:8,y=(c[2]&16)>>4,p=(c[2]&8)>>3,E=(c[2]&4)>>2,T=c[2]&3;i+="."+l+"."+Ge(h)+d+"."+Ge(g)+"."+y+"."+p+E+T+"."+Ge(1)+"."+Ge(1)+"."+Ge(1)+"."+0,r=Wt("dav1",t)}break}}return{codec:i,encrypted:n,supplemental:r}}function Wt(a,e){const t=z(e,["dvvC"]),s=t.length?t[0]:z(e,["dvcC"])[0];if(s){const i=s[2]>>1&127,r=s[2]<<5&32|s[3]>>3&31;return a+"."+Ge(i)+"."+Ge(r)}}function To(a){let e=0;for(let t=0;t<32;t++)e|=(a>>t&1)<<31-t;return e>>>0}function Ms(a,e){const t=e+5;for(;a[e++]&128&&e<t;);return e}function qt(a){return("0"+a.toString(16).toUpperCase()).slice(-2)}function Ge(a){return(a<10?"0":"")+a}function So(a,e){if(!a||!e)return;const t=e.keyId;t&&e.isCommonEncryption&&_n(a,(s,i)=>{const r=s.subarray(8,24);r.some(n=>n!==0)||(se.log(`[eme] Patching keyId in 'enc${i?"a":"v"}>sinf>>tenc' box: ${me(r)} -> ${me(t)}`),s.set(t,8))})}function vo(a){const e=[];return _n(a,t=>e.push(t.subarray(8,24))),e}function _n(a,e){z(a,["moov","trak"]).forEach(s=>{const i=z(s,["mdia","minf","stbl","stsd"])[0];if(!i)return;const r=i.subarray(8);let n=z(r,["enca"]);const o=n.length>0;o||(n=z(r,["encv"])),n.forEach(c=>{const l=o?c.subarray(28):c.subarray(78);z(l,["sinf"]).forEach(d=>{const u=Dn(d);u&&e(u,o)})})})}function Dn(a){const e=z(a,["schm"])[0];if(e){const t=he(e.subarray(4,8));if(t==="cbcs"||t==="cenc"){const s=z(a,["schi","tenc"])[0];if(s)return s}}}function xo(a,e,t){const s={},i=z(a,["moof","traf"]);for(let r=0;r<i.length;r++){const n=i[r],o=z(n,["tfhd"])[0],c=W(o,4),l=e[c];if(!l)continue;s[c]||(s[c]={start:NaN,duration:0,sampleCount:0,timescale:l.timescale,type:l.type});const h=s[c],d=z(n,["tfdt"])[0];if(d){const S=d[0];let v=W(d,4);S===1&&(v===sr?t.warn("[mp4-demuxer]: Ignoring assumed invalid signed 64-bit track fragment decode time"):(v*=sr+1,v+=W(d,8))),M(v)&&(!M(h.start)||v<h.start)&&(h.start=v)}const u=l.default,f=W(o,0)|(u==null?void 0:u.flags);let g=(u==null?void 0:u.duration)||0;f&8&&(f&2?g=W(o,12):g=W(o,8));const y=z(n,["trun"]);let p=h.start||0,E=0,T=g;for(let S=0;S<y.length;S++){const v=y[S],A=W(v,4),D=h.sampleCount;h.sampleCount+=A;const x=v[3]&1,b=v[3]&4,_=v[2]&1,I=v[2]&2,P=v[2]&4,F=v[2]&8;let U=8,H=A;for(x&&(U+=4),b&&A&&(!(v[U+1]&1)&&h.keyFrameIndex===void 0&&(h.keyFrameIndex=D),U+=4,_?(T=W(v,U),U+=4):T=g,I&&(U+=4),F&&(U+=4),p+=T,E+=T,H--);H--;)_?(T=W(v,U),U+=4):T=g,I&&(U+=4),P&&(v[U+1]&1||h.keyFrameIndex===void 0&&(h.keyFrameIndex=h.sampleCount-(H+1),h.keyFrameStart=p),U+=4),F&&(U+=4),p+=T,E+=T;!E&&g&&(E+=g*A)}h.duration+=E}if(!Object.keys(s).some(r=>s[r].duration)){let r=1/0,n=0;const o=z(a,["sidx"]);for(let c=0;c<o.length;c++){const l=yo(o[c]);if(l!=null&&l.references){r=Math.min(r,l.earliestPresentationTime/l.timescale);const h=l.references.reduce((d,u)=>d+u.info.duration||0,0);n=Math.max(n,h+l.earliestPresentationTime/l.timescale)}}n&&M(n)&&Object.keys(s).forEach(c=>{s[c].duration||(s[c].duration=n*s[c].timescale-s[c].start)})}return s}function Ao(a){const e={valid:null,remainder:null},t=z(a,["moof"]);if(t.length<2)return e.remainder=a,e;const s=t[t.length-1];return e.valid=a.slice(0,s.byteOffset-8),e.remainder=a.slice(s.byteOffset-8),e}function ke(a,e){const t=new Uint8Array(a.length+e.length);return t.set(a),t.set(e,a.length),t}function rr(a,e){const t=[],s=e.samples,i=e.timescale,r=e.id;let n=!1;return z(s,["moof"]).map(c=>{const l=c.byteOffset-8;z(c,["traf"]).map(d=>{const u=z(d,["tfdt"]).map(f=>{const g=f[0];let y=W(f,4);return g===1&&(y*=Math.pow(2,32),y+=W(f,8)),y/i})[0];return u!==void 0&&(a=u),z(d,["tfhd"]).map(f=>{const g=W(f,4),y=W(f,0)&16777215,p=(y&1)!==0,E=(y&2)!==0,T=(y&8)!==0;let S=0;const v=(y&16)!==0;let A=0;const D=(y&32)!==0;let x=8;g===r&&(p&&(x+=8),E&&(x+=4),T&&(S=W(f,x),x+=4),v&&(A=W(f,x),x+=4),D&&(x+=4),e.type==="video"&&(n=Ds(e.codec)),z(d,["trun"]).map(b=>{const _=b[0],I=W(b,0)&16777215,P=(I&1)!==0;let F=0;const U=(I&4)!==0,H=(I&256)!==0;let $=0;const k=(I&512)!==0;let G=0;const N=(I&1024)!==0,K=(I&2048)!==0;let Y=0;const w=W(b,4);let O=8;P&&(F=W(b,O),O+=4),U&&(O+=4);let j=F+l;for(let ee=0;ee<w;ee++){if(H?($=W(b,O),O+=4):$=S,k?(G=W(b,O),O+=4):G=A,N&&(O+=4),K&&(_===0?Y=W(b,O):Y=Rn(b,O),O+=4),e.type===re.VIDEO){let X=0;for(;X<G;){const Z=W(s,j);if(j+=4,Io(n,s[j])){const ye=s.subarray(j,j+Z);Ri(ye,n?2:1,a+Y/i,t)}j+=Z,X+=Z+4}}a+=$/i}}))})})}),t}function Ds(a){if(!a)return!1;const e=a.substring(0,4);return e==="hvc1"||e==="hev1"||e==="dvh1"||e==="dvhe"}function Io(a,e){if(a){const t=e>>1&63;return t===39||t===40}else return(e&31)===6}function Ri(a,e,t,s){const i=Cn(a);let r=0;r+=e;let n=0,o=0,c=0;for(;r<i.length;){n=0;do{if(r>=i.length)break;c=i[r++],n+=c}while(c===255);o=0;do{if(r>=i.length)break;c=i[r++],o+=c}while(c===255);const l=i.length-r;let h=r;if(o<l)r+=o;else if(o>l){se.error(`Malformed SEI payload. ${o} is too small, only ${l} bytes left to parse.`);break}if(n===4){if(i[h++]===181){const u=Ln(i,h);if(h+=2,u===49){const f=W(i,h);if(h+=4,f===1195456820){const g=i[h++];if(g===3){const y=i[h++],p=31&y,E=64&y,T=E?2+p*3:0,S=new Uint8Array(T);if(E){S[0]=y;for(let v=1;v<T;v++)S[v]=i[h++]}s.push({type:g,payloadType:n,pts:t,bytes:S})}}}}}else if(n===5&&o>16){const d=[];for(let g=0;g<16;g++){const y=i[h++].toString(16);d.push(y.length==1?"0"+y:y),(g===3||g===5||g===7||g===9)&&d.push("-")}const u=o-16,f=new Uint8Array(u);for(let g=0;g<u;g++)f[g]=i[h++];s.push({payloadType:n,pts:t,uuid:d.join(""),userData:be(f),userDataBytes:f})}}}function Cn(a){const e=a.byteLength,t=[];let s=1;for(;s<e-2;)a[s]===0&&a[s+1]===0&&a[s+2]===3?(t.push(s+2),s+=2):s++;if(t.length===0)return a;const i=e-t.length,r=new Uint8Array(i);let n=0;for(s=0;s<i;n++,s++)n===t[0]&&(n++,t.shift()),r[s]=a[n];return r}function Lo(a){const e=a[0];let t="",s="",i=0,r=0,n=0,o=0,c=0,l=0;if(e===0){for(;he(a.subarray(l,l+1))!=="\0";)t+=he(a.subarray(l,l+1)),l+=1;for(t+=he(a.subarray(l,l+1)),l+=1;he(a.subarray(l,l+1))!=="\0";)s+=he(a.subarray(l,l+1)),l+=1;s+=he(a.subarray(l,l+1)),l+=1,i=W(a,12),r=W(a,16),o=W(a,20),c=W(a,24),l=28}else if(e===1){l+=4,i=W(a,l),l+=4;const d=W(a,l);l+=4;const u=W(a,l);for(l+=4,n=2**32*d+u,eo(n)||(n=Number.MAX_SAFE_INTEGER,se.warn("Presentation time exceeds safe integer limit and wrapped to max safe integer in parsing emsg box")),o=W(a,l),l+=4,c=W(a,l),l+=4;he(a.subarray(l,l+1))!=="\0";)t+=he(a.subarray(l,l+1)),l+=1;for(t+=he(a.subarray(l,l+1)),l+=1;he(a.subarray(l,l+1))!=="\0";)s+=he(a.subarray(l,l+1)),l+=1;s+=he(a.subarray(l,l+1)),l+=1}const h=a.subarray(l,a.byteLength);return{schemeIdUri:t,value:s,timeScale:i,presentationTime:n,presentationTimeDelta:r,eventDuration:o,id:c,payload:h}}function Ro(a,...e){const t=e.length;let s=8,i=t;for(;i--;)s+=e[i].byteLength;const r=new Uint8Array(s);for(r[0]=s>>24&255,r[1]=s>>16&255,r[2]=s>>8&255,r[3]=s&255,r.set(a,4),i=0,s=8;i<t;i++)r.set(e[i],s),s+=e[i].byteLength;return r}function bo(a,e,t){if(a.byteLength!==16)throw new RangeError("Invalid system id");let s,i;s=0,i=new Uint8Array;let r;s>0?(r=new Uint8Array(4),e.length>0&&new DataView(r.buffer).setUint32(0,e.length,!1)):r=new Uint8Array;const n=new Uint8Array(4);return t.byteLength>0&&new DataView(n.buffer).setUint32(0,t.byteLength,!1),Ro([112,115,115,104],new Uint8Array([s,0,0,0]),a,r,i,n,t)}function _o(a){const e=[];if(a instanceof ArrayBuffer){const t=a.byteLength;let s=0;for(;s+32<t;){const i=new DataView(a,s),r=Do(i);e.push(r),s+=r.size}}return e}function Do(a){const e=a.getUint32(0),t=a.byteOffset,s=a.byteLength;if(s<e)return{offset:t,size:s};if(a.getUint32(4)!==1886614376)return{offset:t,size:e};const r=a.getUint32(8)>>>24;if(r!==0&&r!==1)return{offset:t,size:e};const n=a.buffer,o=me(new Uint8Array(n,t+12,16));let c=null,l=null,h=0;if(r===0)h=28;else{const u=a.getUint32(28);if(!u||s<32+u*16)return{offset:t,size:e};c=[];for(let f=0;f<u;f++)c.push(new Uint8Array(n,t+32+f*16,16));h=32+u*16}if(!h)return{offset:t,size:e};const d=a.getUint32(h);return e-32<d?{offset:t,size:e}:(l=new Uint8Array(n,t+h+4,d),{version:r,systemId:o,kids:c,data:l,offset:t,size:e})}const Pn=()=>/\(Windows.+Firefox\//i.test(navigator.userAgent),_t={audio:{a3ds:1,"ac-3":.95,"ac-4":1,alac:.9,alaw:1,dra1:1,"dts+":1,"dts-":1,dtsc:1,dtse:1,dtsh:1,"ec-3":.9,enca:1,fLaC:.9,flac:.9,FLAC:.9,g719:1,g726:1,m4ae:1,mha1:1,mha2:1,mhm1:1,mhm2:1,mlpa:1,mp4a:1,"raw ":1,Opus:1,opus:1,samr:1,sawb:1,sawp:1,sevc:1,sqcp:1,ssmv:1,twos:1,ulaw:1},video:{avc1:1,avc2:1,avc3:1,avc4:1,avcp:1,av01:.8,dav1:.8,drac:1,dva1:1,dvav:1,dvh1:.7,dvhe:.7,encv:1,hev1:.75,hvc1:.75,mjp2:1,mp4v:1,mvc1:1,mvc2:1,mvc3:1,mvc4:1,resv:1,rv60:1,s263:1,svc1:1,svc2:1,"vc-1":1,vp08:1,vp09:.9},text:{stpp:1,wvtt:1}};function bi(a,e){const t=_t[e];return!!t&&!!t[a.slice(0,4)]}function Bt(a,e,t=!0){return!a.split(",").some(s=>!_i(s,e,t))}function _i(a,e,t=!0){var s;const i=rt(t);return(s=i==null?void 0:i.isTypeSupported(Ut(a,e)))!=null?s:!1}function Ut(a,e){return`${e}/mp4;codecs=${a}`}function nr(a){if(a){const e=a.substring(0,4);return _t.video[e]}return 2}function Es(a){const e=Pn();return a.split(",").reduce((t,s)=>{const r=e&&Ds(s)?9:_t.video[s];return r?(r*2+t)/(t?3:2):(_t.audio[s]+t)/(t?2:1)},0)}const Ns={};function Co(a,e=!0){if(Ns[a])return Ns[a];const t={flac:["flac","fLaC","FLAC"],opus:["opus","Opus"],"mp4a.40.34":["mp3"]}[a];for(let i=0;i<t.length;i++){var s;if(_i(t[i],"audio",e))return Ns[a]=t[i],t[i];if(t[i]==="mp3"&&(s=rt(e))!=null&&s.isTypeSupported("audio/mpeg"))return""}return a}const Po=/flac|opus|mp4a\.40\.34/i;function Ts(a,e=!0){return a.replace(Po,t=>Co(t.toLowerCase(),e))}function ko(a,e){const t=[];if(a){const s=a.split(",");for(let i=0;i<s.length;i++)bi(s[i],"video")||t.push(s[i])}return e&&t.push(e),t.join(",")}function cs(a,e){if(a&&(a.length>4||["ac-3","ec-3","alac","fLaC","Opus"].indexOf(a)!==-1)&&(ar(a,"audio")||ar(a,"video")))return a;if(e){const t=e.split(",");if(t.length>1){if(a){for(let s=t.length;s--;)if(t[s].substring(0,4)===a.substring(0,4))return t[s]}return t[0]}}return e||a}function ar(a,e){return bi(a,e)&&_i(a,e)}function wo(a){const e=a.split(",");for(let t=0;t<e.length;t++){const s=e[t].split(".");s.length>2&&s[0]==="avc1"&&(e[t]=`avc1.${parseInt(s[1]).toString(16)}${("000"+parseInt(s[2]).toString(16)).slice(-4)}`)}return e.join(",")}function Oo(a){if(a.startsWith("av01.")){const e=a.split("."),t=["0","111","01","01","01","0"];for(let s=e.length;s>4&&s<10;s++)e[s]=t[s-4];return e.join(".")}return a}function or(a){const e=rt(a)||{isTypeSupported:()=>!1};return{mpeg:e.isTypeSupported("audio/mpeg"),mp3:e.isTypeSupported('audio/mp4; codecs="mp3"'),ac3:e.isTypeSupported('audio/mp4; codecs="ac-3"')}}function ai(a){return a.replace(/^.+codecs=["']?([^"']+).*$/,"$1")}const Fo={supported:!0,powerEfficient:!0,smooth:!0},Mo={supported:!1,smooth:!1,powerEfficient:!1},kn={supported:!0,configurations:[],decodingInfoResults:[Fo]};function wn(a,e){return{supported:!1,configurations:e,decodingInfoResults:[Mo],error:a}}function No(a,e,t,s,i,r){const n=a.videoCodec,o=a.audioCodec?a.audioGroups:null,c=r==null?void 0:r.audioCodec,l=r==null?void 0:r.channels,h=l?parseInt(l):c?1/0:2;let d=null;if(o!=null&&o.length)try{o.length===1&&o[0]?d=e.groups[o[0]].channels:d=o.reduce((u,f)=>{if(f){const g=e.groups[f];if(!g)throw new Error(`Audio track group ${f} not found`);Object.keys(g.channels).forEach(y=>{u[y]=(u[y]||0)+g.channels[y]})}return u},{2:0})}catch{return!0}return n!==void 0&&(n.split(",").some(u=>Ds(u))||a.width>1920&&a.height>1088||a.height>1920&&a.width>1088||a.frameRate>Math.max(s,30)||a.videoRange!=="SDR"&&a.videoRange!==t||a.bitrate>Math.max(i,8e6))||!!d&&M(h)&&Object.keys(d).some(u=>parseInt(u)>h)}function On(a,e,t,s={}){const i=a.videoCodec;if(!i&&!a.audioCodec||!t)return Promise.resolve(kn);const r=[],n=Bo(a),o=n.length,c=Uo(a,e,o>0),l=c.length;for(let h=o||1*l||1;h--;){const d={type:"media-source"};if(o&&(d.video=n[h%o]),l){d.audio=c[h%l];const u=d.audio.bitrate;d.video&&u&&(d.video.bitrate-=u)}r.push(d)}if(i){const h=navigator.userAgent;if(i.split(",").some(d=>Ds(d))&&Pn())return Promise.resolve(wn(new Error(`Overriding Windows Firefox HEVC MediaCapabilities result based on user-agent string: (${h})`),r))}return Promise.all(r.map(h=>{const d=Go(h);return s[d]||(s[d]=t.decodingInfo(h))})).then(h=>({supported:!h.some(d=>!d.supported),configurations:r,decodingInfoResults:h})).catch(h=>({supported:!1,configurations:r,decodingInfoResults:[],error:h}))}function Bo(a){var e;const t=(e=a.videoCodec)==null?void 0:e.split(","),s=Fn(a),i=a.width||640,r=a.height||480,n=a.frameRate||30,o=a.videoRange.toLowerCase();return t?t.map(c=>{const l={contentType:Ut(Oo(c),"video"),width:i,height:r,bitrate:s,framerate:n};return o!=="sdr"&&(l.transferFunction=o),l}):[]}function Uo(a,e,t){var s;const i=(s=a.audioCodec)==null?void 0:s.split(","),r=Fn(a);return i&&a.audioGroups?a.audioGroups.reduce((n,o)=>{var c;const l=o?(c=e.groups[o])==null?void 0:c.tracks:null;return l?l.reduce((h,d)=>{if(d.groupId===o){const u=parseFloat(d.channels||"");i.forEach(f=>{const g={contentType:Ut(f,"audio"),bitrate:t?$o(f,r):r};u&&(g.channels=""+u),h.push(g)})}return h},n):n},[]):[]}function $o(a,e){if(e<=1)return 1;let t=128e3;return a==="ec-3"?t=768e3:a==="ac-3"&&(t=64e4),Math.min(e/2,t)}function Fn(a){return Math.ceil(Math.max(a.bitrate*.9,a.averageBitrate)/1e3)*1e3||1}function Go(a){let e="";const{audio:t,video:s}=a;if(s){const i=ai(s.contentType);e+=`${i}_r${s.height}x${s.width}f${Math.ceil(s.framerate)}${s.transferFunction||"sd"}_${Math.ceil(s.bitrate/1e5)}`}if(t){const i=ai(t.contentType);e+=`${s?"_":""}${i}_c${t.channels}`}return e}const oi=["NONE","TYPE-0","TYPE-1",null];function Ko(a){return oi.indexOf(a)>-1}const Ss=["SDR","PQ","HLG"];function Vo(a){return!!a&&Ss.indexOf(a)>-1}var hs={No:"",Yes:"YES",v2:"v2"};function lr(a){const{canSkipUntil:e,canSkipDateRanges:t,age:s}=a,i=s<e/2;return e&&i?t?hs.v2:hs.Yes:hs.No}class cr{constructor(e,t,s){this.msn=void 0,this.part=void 0,this.skip=void 0,this.msn=e,this.part=t,this.skip=s}addDirectives(e){const t=new self.URL(e);return this.msn!==void 0&&t.searchParams.set("_HLS_msn",this.msn.toString()),this.part!==void 0&&t.searchParams.set("_HLS_part",this.part.toString()),this.skip&&t.searchParams.set("_HLS_skip",this.skip),t.href}}class $t{constructor(e){if(this._attrs=void 0,this.audioCodec=void 0,this.bitrate=void 0,this.codecSet=void 0,this.url=void 0,this.frameRate=void 0,this.height=void 0,this.id=void 0,this.name=void 0,this.supplemental=void 0,this.videoCodec=void 0,this.width=void 0,this.details=void 0,this.fragmentError=0,this.loadError=0,this.loaded=void 0,this.realBitrate=0,this.supportedPromise=void 0,this.supportedResult=void 0,this._avgBitrate=0,this._audioGroups=void 0,this._subtitleGroups=void 0,this._urlId=0,this.url=[e.url],this._attrs=[e.attrs],this.bitrate=e.bitrate,e.details&&(this.details=e.details),this.id=e.id||0,this.name=e.name,this.width=e.width||0,this.height=e.height||0,this.frameRate=e.attrs.optionalFloat("FRAME-RATE",0),this._avgBitrate=e.attrs.decimalInteger("AVERAGE-BANDWIDTH"),this.audioCodec=e.audioCodec,this.videoCodec=e.videoCodec,this.codecSet=[e.videoCodec,e.audioCodec].filter(s=>!!s).map(s=>s.substring(0,4)).join(","),"supplemental"in e){var t;this.supplemental=e.supplemental;const s=(t=e.supplemental)==null?void 0:t.videoCodec;s&&s!==e.videoCodec&&(this.codecSet+=`,${s.substring(0,4)}`)}this.addGroupId("audio",e.attrs.AUDIO),this.addGroupId("text",e.attrs.SUBTITLES)}get maxBitrate(){return Math.max(this.realBitrate,this.bitrate)}get averageBitrate(){return this._avgBitrate||this.realBitrate||this.bitrate}get attrs(){return this._attrs[0]}get codecs(){return this.attrs.CODECS||""}get pathwayId(){return this.attrs["PATHWAY-ID"]||"."}get videoRange(){return this.attrs["VIDEO-RANGE"]||"SDR"}get score(){return this.attrs.optionalFloat("SCORE",0)}get uri(){return this.url[0]||""}hasAudioGroup(e){return hr(this._audioGroups,e)}hasSubtitleGroup(e){return hr(this._subtitleGroups,e)}get audioGroups(){return this._audioGroups}get subtitleGroups(){return this._subtitleGroups}addGroupId(e,t){if(t){if(e==="audio"){let s=this._audioGroups;s||(s=this._audioGroups=[]),s.indexOf(t)===-1&&s.push(t)}else if(e==="text"){let s=this._subtitleGroups;s||(s=this._subtitleGroups=[]),s.indexOf(t)===-1&&s.push(t)}}}get urlId(){return 0}set urlId(e){}get audioGroupIds(){return this.audioGroups?[this.audioGroupId]:void 0}get textGroupIds(){return this.subtitleGroups?[this.textGroupId]:void 0}get audioGroupId(){var e;return(e=this.audioGroups)==null?void 0:e[0]}get textGroupId(){var e;return(e=this.subtitleGroups)==null?void 0:e[0]}addFallback(){}}function hr(a,e){return!e||!a?!1:a.indexOf(e)!==-1}function Ho(){if(typeof matchMedia=="function"){const a=matchMedia("(dynamic-range: high)"),e=matchMedia("bad query");if(a.media!==e.media)return a.matches===!0}return!1}function Yo(a,e){let t=!1,s=[];if(a&&(t=a!=="SDR",s=[a]),e){s=e.allowedVideoRanges||Ss.slice(0);const i=s.join("")!=="SDR"&&!e.videoCodec;t=e.preferHDR!==void 0?e.preferHDR:i&&Ho(),t||(s=["SDR"])}return{preferHDR:t,allowedVideoRanges:s}}const Wo=a=>{const e=new WeakSet;return(t,s)=>{if(a&&(s=a(t,s)),typeof s=="object"&&s!==null){if(e.has(s))return;e.add(s)}return s}},ne=(a,e)=>JSON.stringify(a,Wo(e));function qo(a,e,t,s,i){const r=Object.keys(a),n=s==null?void 0:s.channels,o=s==null?void 0:s.audioCodec,c=i==null?void 0:i.videoCodec,l=n&&parseInt(n)===2;let h=!1,d=!1,u=1/0,f=1/0,g=1/0,y=1/0,p=0,E=[];const{preferHDR:T,allowedVideoRanges:S}=Yo(e,i);for(let b=r.length;b--;){const _=a[r[b]];h||(h=_.channels[2]>0),u=Math.min(u,_.minHeight),f=Math.min(f,_.minFramerate),g=Math.min(g,_.minBitrate),S.filter(P=>_.videoRanges[P]>0).length>0&&(d=!0)}u=M(u)?u:0,f=M(f)?f:0;const v=Math.max(1080,u),A=Math.max(30,f);g=M(g)?g:t,t=Math.max(g,t),d||(e=void 0);const D=r.length>1;return{codecSet:r.reduce((b,_)=>{const I=a[_];if(_===b)return b;if(E=d?S.filter(P=>I.videoRanges[P]>0):[],D){if(I.minBitrate>t)return Ue(_,`min bitrate of ${I.minBitrate} > current estimate of ${t}`),b;if(!I.hasDefaultAudio)return Ue(_,"no renditions with default or auto-select sound found"),b;if(o&&_.indexOf(o.substring(0,4))%5!==0)return Ue(_,`audio codec preference "${o}" not found`),b;if(n&&!l){if(!I.channels[n])return Ue(_,`no renditions with ${n} channel sound found (channels options: ${Object.keys(I.channels)})`),b}else if((!o||l)&&h&&I.channels[2]===0)return Ue(_,"no renditions with stereo sound found"),b;if(I.minHeight>v)return Ue(_,`min resolution of ${I.minHeight} > maximum of ${v}`),b;if(I.minFramerate>A)return Ue(_,`min framerate of ${I.minFramerate} > maximum of ${A}`),b;if(!E.some(P=>I.videoRanges[P]>0))return Ue(_,`no variants with VIDEO-RANGE of ${ne(E)} found`),b;if(c&&_.indexOf(c.substring(0,4))%5!==0)return Ue(_,`video codec preference "${c}" not found`),b;if(I.maxScore<p)return Ue(_,`max score of ${I.maxScore} < selected max of ${p}`),b}return b&&(Es(_)>=Es(b)||I.fragmentError>a[b].fragmentError)?b:(y=I.minIndex,p=I.maxScore,_)},void 0),videoRanges:E,preferHDR:T,minFramerate:f,minBitrate:g,minIndex:y}}function Ue(a,e){se.log(`[abr] start candidates with "${a}" ignored because ${e}`)}function Mn(a){return a.reduce((e,t)=>{let s=e.groups[t.groupId];s||(s=e.groups[t.groupId]={tracks:[],channels:{2:0},hasDefault:!1,hasAutoSelect:!1}),s.tracks.push(t);const i=t.channels||"2";return s.channels[i]=(s.channels[i]||0)+1,s.hasDefault=s.hasDefault||t.default,s.hasAutoSelect=s.hasAutoSelect||t.autoselect,s.hasDefault&&(e.hasDefaultAudio=!0),s.hasAutoSelect&&(e.hasAutoSelectAudio=!0),e},{hasDefaultAudio:!1,hasAutoSelectAudio:!1,groups:{}})}function jo(a,e,t,s){return a.slice(t,s+1).reduce((i,r,n)=>{if(!r.codecSet)return i;const o=r.audioGroups;let c=i[r.codecSet];c||(i[r.codecSet]=c={minBitrate:1/0,minHeight:1/0,minFramerate:1/0,minIndex:n,maxScore:0,videoRanges:{SDR:0},channels:{2:0},hasDefaultAudio:!o,fragmentError:0}),c.minBitrate=Math.min(c.minBitrate,r.bitrate);const l=Math.min(r.height,r.width);return c.minHeight=Math.min(c.minHeight,l),c.minFramerate=Math.min(c.minFramerate,r.frameRate),c.minIndex=Math.min(c.minIndex,n),c.maxScore=Math.max(c.maxScore,r.score),c.fragmentError+=r.fragmentError,c.videoRanges[r.videoRange]=(c.videoRanges[r.videoRange]||0)+1,o&&o.forEach(h=>{if(!h)return;const d=e.groups[h];d&&(c.hasDefaultAudio=c.hasDefaultAudio||e.hasDefaultAudio?d.hasDefault:d.hasAutoSelect||!e.hasDefaultAudio&&!e.hasAutoSelectAudio,Object.keys(d.channels).forEach(u=>{c.channels[u]=(c.channels[u]||0)+d.channels[u]}))}),i},{})}function dr(a){if(!a)return a;const{lang:e,assocLang:t,characteristics:s,channels:i,audioCodec:r}=a;return{lang:e,assocLang:t,characteristics:s,channels:i,audioCodec:r}}function Ve(a,e,t){if("attrs"in a){const s=e.indexOf(a);if(s!==-1)return s}for(let s=0;s<e.length;s++){const i=e[s];if(ft(a,i,t))return s}return-1}function ft(a,e,t){const{groupId:s,name:i,lang:r,assocLang:n,default:o}=a,c=a.forced;return(s===void 0||e.groupId===s)&&(i===void 0||e.name===i)&&(r===void 0||Xo(r,e.lang))&&(r===void 0||e.assocLang===n)&&(o===void 0||e.default===o)&&(c===void 0||e.forced===c)&&(!("characteristics"in a)||zo(a.characteristics||"",e.characteristics))&&(t===void 0||t(a,e))}function Xo(a,e="--"){return a.length===e.length?a===e:a.startsWith(e)||e.startsWith(a)}function zo(a,e=""){const t=a.split(","),s=e.split(",");return t.length===s.length&&!t.some(i=>s.indexOf(i)===-1)}function ut(a,e){const{audioCodec:t,channels:s}=a;return(t===void 0||(e.audioCodec||"").substring(0,4)===t.substring(0,4))&&(s===void 0||s===(e.channels||"2"))}function Qo(a,e,t,s,i){const r=e[s],o=e.reduce((u,f,g)=>{const y=f.uri;return(u[y]||(u[y]=[])).push(g),u},{})[r.uri];o.length>1&&(s=Math.max.apply(Math,o));const c=r.videoRange,l=r.frameRate,h=r.codecSet.substring(0,4),d=ur(e,s,u=>{if(u.videoRange!==c||u.frameRate!==l||u.codecSet.substring(0,4)!==h)return!1;const f=u.audioGroups,g=t.filter(y=>!f||f.indexOf(y.groupId)!==-1);return Ve(a,g,i)>-1});return d>-1?d:ur(e,s,u=>{const f=u.audioGroups,g=t.filter(y=>!f||f.indexOf(y.groupId)!==-1);return Ve(a,g,i)>-1})}function ur(a,e,t){for(let s=e;s>-1;s--)if(t(a[s]))return s;for(let s=e+1;s<a.length;s++)if(t(a[s]))return s;return-1}function vs(a,e){var t;return!!a&&a!==((t=e.loadLevelObj)==null?void 0:t.uri)}class Zo extends we{constructor(e){super("abr",e.logger),this.hls=void 0,this.lastLevelLoadSec=0,this.lastLoadedFragLevel=-1,this.firstSelection=-1,this._nextAutoLevel=-1,this.nextAutoLevelKey="",this.audioTracksByGroup=null,this.codecTiers=null,this.timer=-1,this.fragCurrent=null,this.partCurrent=null,this.bitrateTestDelay=0,this.rebufferNotice=-1,this.supportedCache={},this.bwEstimator=void 0,this._abandonRulesCheck=t=>{var s;const{fragCurrent:i,partCurrent:r,hls:n}=this,{autoLevelEnabled:o,media:c}=n;if(!i||!c)return;const l=performance.now(),h=r?r.stats:i.stats,d=r?r.duration:i.duration,u=l-h.loading.start,f=n.minAutoLevel,g=i.level,y=this._nextAutoLevel;if(h.aborted||h.loaded&&h.loaded===h.total||g<=f){this.clearTimer(),this._nextAutoLevel=-1;return}if(!o)return;const p=y>-1&&y!==g,E=!!t||p;if(!E&&(c.paused||!c.playbackRate||!c.readyState))return;const T=n.mainForwardBufferInfo;if(!E&&T===null)return;const S=this.bwEstimator.getEstimateTTFB(),v=Math.abs(c.playbackRate);if(u<=Math.max(S,1e3*(d/(v*2))))return;const A=T?T.len/v:0,D=h.loading.first?h.loading.first-h.loading.start:-1,x=h.loaded&&D>-1,b=this.getBwEstimate(),_=n.levels,I=_[g],P=Math.max(h.loaded,Math.round(d*(i.bitrate||I.averageBitrate)/8));let F=x?u-D:u;F<1&&x&&(F=Math.min(u,h.loaded*8/b));const U=x?h.loaded*1e3/F:0,H=S/1e3,$=U?(P-h.loaded)/U:P*8/b+H;if($<=A)return;const k=U?U*8:b,G=((s=(t==null?void 0:t.details)||this.hls.latestLevelDetails)==null?void 0:s.live)===!0,N=this.hls.config.abrBandWidthUpFactor;let K=Number.POSITIVE_INFINITY,Y;for(Y=g-1;Y>f;Y--){const ee=_[Y].maxBitrate,X=!_[Y].details||G;if(K=this.getTimeToLoadFrag(H,k,d*ee,X),K<Math.min(A,d+H))break}if(K>=$||K>d*10)return;x?this.bwEstimator.sample(u-Math.min(S,D),h.loaded):this.bwEstimator.sampleTTFB(u);const w=_[Y].maxBitrate;this.getBwEstimate()*N>w&&this.resetEstimator(w);const O=this.findBestLevel(w,f,Y,0,A,1,1);O>-1&&(Y=O),this.warn(`Fragment ${i.sn}${r?" part "+r.index:""} of level ${g} is loading too slowly;
1616+ <!-- Meta Tags -->
1717+ <meta
1818+ name="description"
1919+ content="View ATmosphereConf 2026 Talks on-demand."
2020+ />
2121+ <meta property="og:title" content="ATmosphereConf 2026 Talks" />
2222+ <meta
2323+ property="og:description"
2424+ content="View ATmosphereConf 2026 Talks on-demand"
2525+ />
2626+ <meta property="og:type" content="website" />
2727+ <meta
2828+ property="og:url"
2929+ content="https://sites.wisp.place/timryan.org/atmosphereconf2026/"
3030+ />
3131+3232+ <style>/*! tailwindcss v4.2.2 | MIT License | https://tailwindcss.com */
3333+@layer properties{@supports (((-webkit-hyphens:none)) and (not (margin-trim:inline))) or ((-moz-orient:inline) and (not (color:rgb(from red r g b)))){*,:before,:after,::backdrop{--tw-translate-x:0;--tw-translate-y:0;--tw-translate-z:0;--tw-border-style:solid;--tw-leading:initial;--tw-font-weight:initial;--tw-tracking:initial;--tw-duration:initial;--tw-ease:initial}}}@layer theme{:root,:host{--font-sans:ui-sans-serif, system-ui, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji";--font-mono:ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace;--color-white:#fff;--spacing:.25rem;--text-xs:.75rem;--text-xs--line-height:calc(1 / .75);--text-sm:.875rem;--text-sm--line-height:calc(1.25 / .875);--text-lg:1.125rem;--text-lg--line-height:calc(1.75 / 1.125);--text-2xl:1.5rem;--text-2xl--line-height:calc(2 / 1.5);--text-3xl:1.875rem;--text-3xl--line-height:calc(2.25 / 1.875);--font-weight-semibold:600;--tracking-wide:.025em;--tracking-widest:.1em;--leading-tight:1.25;--radius-lg:.5rem;--ease-in-out:cubic-bezier(.4, 0, .2, 1);--default-transition-duration:.15s;--default-transition-timing-function:cubic-bezier(.4, 0, .2, 1);--default-font-family:var(--font-sans);--default-mono-font-family:var(--font-mono)}}@layer base{*,:after,:before,::backdrop{box-sizing:border-box;border:0 solid;margin:0;padding:0}::file-selector-button{box-sizing:border-box;border:0 solid;margin:0;padding:0}html,:host{-webkit-text-size-adjust:100%;tab-size:4;line-height:1.5;font-family:var(--default-font-family,ui-sans-serif, system-ui, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji");font-feature-settings:var(--default-font-feature-settings,normal);font-variation-settings:var(--default-font-variation-settings,normal);-webkit-tap-highlight-color:transparent}hr{height:0;color:inherit;border-top-width:1px}abbr:where([title]){-webkit-text-decoration:underline dotted;text-decoration:underline dotted}h1,h2,h3,h4,h5,h6{font-size:inherit;font-weight:inherit}a{color:inherit;-webkit-text-decoration:inherit;-webkit-text-decoration:inherit;-webkit-text-decoration:inherit;text-decoration:inherit}b,strong{font-weight:bolder}code,kbd,samp,pre{font-family:var(--default-mono-font-family,ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace);font-feature-settings:var(--default-mono-font-feature-settings,normal);font-variation-settings:var(--default-mono-font-variation-settings,normal);font-size:1em}small{font-size:80%}sub,sup{vertical-align:baseline;font-size:75%;line-height:0;position:relative}sub{bottom:-.25em}sup{top:-.5em}table{text-indent:0;border-color:inherit;border-collapse:collapse}:-moz-focusring{outline:auto}progress{vertical-align:baseline}summary{display:list-item}ol,ul,menu{list-style:none}img,svg,video,canvas,audio,iframe,embed,object{vertical-align:middle;display:block}img,video{max-width:100%;height:auto}button,input,select,optgroup,textarea{font:inherit;font-feature-settings:inherit;font-variation-settings:inherit;letter-spacing:inherit;color:inherit;opacity:1;background-color:#0000;border-radius:0}::file-selector-button{font:inherit;font-feature-settings:inherit;font-variation-settings:inherit;letter-spacing:inherit;color:inherit;opacity:1;background-color:#0000;border-radius:0}:where(select:is([multiple],[size])) optgroup{font-weight:bolder}:where(select:is([multiple],[size])) optgroup option{padding-inline-start:20px}::file-selector-button{margin-inline-end:4px}::placeholder{opacity:1}@supports (not ((-webkit-appearance:-apple-pay-button))) or (contain-intrinsic-size:1px){::placeholder{color:currentColor}@supports (color:color-mix(in lab, red, red)){::placeholder{color:color-mix(in oklab, currentcolor 50%, transparent)}}}textarea{resize:vertical}::-webkit-search-decoration{-webkit-appearance:none}::-webkit-date-and-time-value{min-height:1lh;text-align:inherit}::-webkit-datetime-edit{display:inline-flex}::-webkit-datetime-edit-fields-wrapper{padding:0}::-webkit-datetime-edit{padding-block:0}::-webkit-datetime-edit-year-field{padding-block:0}::-webkit-datetime-edit-month-field{padding-block:0}::-webkit-datetime-edit-day-field{padding-block:0}::-webkit-datetime-edit-hour-field{padding-block:0}::-webkit-datetime-edit-minute-field{padding-block:0}::-webkit-datetime-edit-second-field{padding-block:0}::-webkit-datetime-edit-millisecond-field{padding-block:0}::-webkit-datetime-edit-meridiem-field{padding-block:0}::-webkit-calendar-picker-indicator{line-height:1}:-moz-ui-invalid{box-shadow:none}button,input:where([type=button],[type=reset],[type=submit]){appearance:button}::file-selector-button{appearance:button}::-webkit-inner-spin-button{height:auto}::-webkit-outer-spin-button{height:auto}[hidden]:where(:not([hidden=until-found])){display:none!important}}@layer components;@layer utilities{.pointer-events-none{pointer-events:none}.absolute{position:absolute}.relative{position:relative}.inset-0{inset:calc(var(--spacing) * 0)}.top-4{top:calc(var(--spacing) * 4)}.right-5{right:calc(var(--spacing) * 5)}.bottom-2\.5{bottom:calc(var(--spacing) * 2.5)}.bottom-4{bottom:calc(var(--spacing) * 4)}.left-1\/2{left:50%}.left-4{left:calc(var(--spacing) * 4)}.z-7{z-index:7}.z-10{z-index:10}.m-0{margin:calc(var(--spacing) * 0)}.mt-2{margin-top:calc(var(--spacing) * 2)}.mb-3{margin-bottom:calc(var(--spacing) * 3)}.ml-2{margin-left:calc(var(--spacing) * 2)}.flex{display:flex}.hidden{display:none}.h-screen{height:100vh}.min-h-\[100px\]{min-height:100px}.w-0{width:calc(var(--spacing) * 0)}.w-\[400px\]{width:400px}.w-full{width:100%}.min-w-0{min-width:calc(var(--spacing) * 0)}.min-w-\[400px\]{min-width:400px}.flex-1{flex:1}.shrink-0{flex-shrink:0}.-translate-x-1\/2{--tw-translate-x:calc(calc(1 / 2 * 100%) * -1);translate:var(--tw-translate-x) var(--tw-translate-y)}.cursor-pointer{cursor:pointer}.flex-col{flex-direction:column}.flex-row{flex-direction:row}.items-center{align-items:center}.justify-between{justify-content:space-between}.justify-center{justify-content:center}.gap-1{gap:calc(var(--spacing) * 1)}.gap-1\.5{gap:calc(var(--spacing) * 1.5)}.gap-3{gap:calc(var(--spacing) * 3)}.overflow-hidden{overflow:hidden}.overflow-y-auto{overflow-y:auto}.rounded{border-radius:.25rem}.rounded-lg{border-radius:var(--radius-lg)}.border{border-style:var(--tw-border-style);border-width:1px}.border-r-0{border-right-style:var(--tw-border-style);border-right-width:0}.border-b{border-bottom-style:var(--tw-border-style);border-bottom-width:1px}.border-l-\[3px\]{border-left-style:var(--tw-border-style);border-left-width:3px}.border-\[\#7dd3fc\]{border-color:#7dd3fc}.border-\[rgba\(125\,211\,252\,0\.2\)\]{border-color:#7dd3fc33}.border-\[rgba\(125\,211\,252\,0\.3\)\]{border-color:#7dd3fc4d}.border-\[rgba\(125\,211\,252\,0\.4\)\]{border-color:#7dd3fc66}.border-l-\[\#7dd3fc\]{border-left-color:#7dd3fc}.border-l-\[rgba\(125\,211\,252\,0\.6\)\]{border-left-color:#7dd3fc99}.bg-\[\#0a0806\]{background-color:#0a0806}.bg-\[\#1a1a1a\]{background-color:#1a1a1a}.bg-\[rgba\(125\,211\,252\,0\.15\)\]{background-color:#7dd3fc26}.bg-transparent{background-color:#0000}.object-contain{object-fit:contain}.p-1{padding:calc(var(--spacing) * 1)}.p-2\.5{padding:calc(var(--spacing) * 2.5)}.px-1{padding-inline:calc(var(--spacing) * 1)}.px-5{padding-inline:calc(var(--spacing) * 5)}.py-2{padding-block:calc(var(--spacing) * 2)}.py-4{padding-block:calc(var(--spacing) * 4)}.pb-2{padding-bottom:calc(var(--spacing) * 2)}.text-center{text-align:center}.font-sans{font-family:var(--font-sans)}.text-2xl{font-size:var(--text-2xl);line-height:var(--tw-leading,var(--text-2xl--line-height))}.text-3xl{font-size:var(--text-3xl);line-height:var(--tw-leading,var(--text-3xl--line-height))}.text-lg{font-size:var(--text-lg);line-height:var(--tw-leading,var(--text-lg--line-height))}.text-sm{font-size:var(--text-sm);line-height:var(--tw-leading,var(--text-sm--line-height))}.text-xs{font-size:var(--text-xs);line-height:var(--tw-leading,var(--text-xs--line-height))}.text-\[11px\]{font-size:11px}.leading-tight{--tw-leading:var(--leading-tight);line-height:var(--leading-tight)}.font-semibold{--tw-font-weight:var(--font-weight-semibold);font-weight:var(--font-weight-semibold)}.tracking-wide{--tw-tracking:var(--tracking-wide);letter-spacing:var(--tracking-wide)}.tracking-widest{--tw-tracking:var(--tracking-widest);letter-spacing:var(--tracking-widest)}.text-\[\#7dd3fc\]{color:#7dd3fc}.text-\[rgba\(125\,211\,252\,0\.5\)\]{color:#7dd3fc80}.text-\[rgba\(125\,211\,252\,0\.6\)\]{color:#7dd3fc99}.text-\[rgba\(125\,211\,252\,0\.7\)\]{color:#7dd3fcb3}.text-white\/25{color:#ffffff40}@supports (color:color-mix(in lab, red, red)){.text-white\/25{color:color-mix(in oklab, var(--color-white) 25%, transparent)}}.no-underline{text-decoration-line:none}.opacity-0{opacity:0}.opacity-100{opacity:1}.transition-all{transition-property:all;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration))}.transition-colors{transition-property:color,background-color,border-color,outline-color,text-decoration-color,fill,stroke,--tw-gradient-from,--tw-gradient-via,--tw-gradient-to;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration))}.transition-opacity{transition-property:opacity;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration))}.duration-150{--tw-duration:.15s;transition-duration:.15s}.duration-300{--tw-duration:.3s;transition-duration:.3s}.ease-in-out{--tw-ease:var(--ease-in-out);transition-timing-function:var(--ease-in-out)}.\[background\:linear-gradient\(45deg\,\#0a0806_0\%\,\#1a1410_50\%\,\#0a0806_100\%\)\]{background:linear-gradient(45deg,#0a0806 0%,#1a1410 50%,#0a0806 100%)}.last\:border-r:last-child{border-right-style:var(--tw-border-style);border-right-width:1px}.last\:border-\[rgba\(125\,211\,252\,0\.3\)\]:last-child{border-color:#7dd3fc4d}@media (hover:hover){.hover\:border-\[rgba\(125\,211\,252\,0\.6\)\]:hover{border-color:#7dd3fc99}.hover\:border-l-\[\#7dd3fc\]:hover{border-left-color:#7dd3fc}.hover\:bg-\[rgba\(125\,211\,252\,0\.1\)\]:hover{background-color:#7dd3fc1a}.hover\:bg-\[rgba\(125\,211\,252\,0\.2\)\]:hover{background-color:#7dd3fc33}.hover\:bg-\[rgba\(125\,211\,252\,0\.08\)\]:hover{background-color:#7dd3fc14}.hover\:text-white\/50:hover{color:#ffffff80}@supports (color:color-mix(in lab, red, red)){.hover\:text-white\/50:hover{color:color-mix(in oklab, var(--color-white) 50%, transparent)}}.hover\:underline:hover{text-decoration-line:underline}}}@property --tw-translate-x{syntax:"*";inherits:false;initial-value:0}@property --tw-translate-y{syntax:"*";inherits:false;initial-value:0}@property --tw-translate-z{syntax:"*";inherits:false;initial-value:0}@property --tw-border-style{syntax:"*";inherits:false;initial-value:solid}@property --tw-leading{syntax:"*";inherits:false}@property --tw-font-weight{syntax:"*";inherits:false}@property --tw-tracking{syntax:"*";inherits:false}@property --tw-duration{syntax:"*";inherits:false}@property --tw-ease{syntax:"*";inherits:false}</style>
3434+ <script type="module" crossorigin>(function(){const e=document.createElement("link").relList;if(e&&e.supports&&e.supports("modulepreload"))return;for(const i of document.querySelectorAll('link[rel="modulepreload"]'))s(i);new MutationObserver(i=>{for(const r of i)if(r.type==="childList")for(const a of r.addedNodes)a.tagName==="LINK"&&a.rel==="modulepreload"&&s(a)}).observe(document,{childList:!0,subtree:!0});function t(i){const r={};return i.integrity&&(r.integrity=i.integrity),i.referrerPolicy&&(r.referrerPolicy=i.referrerPolicy),i.crossOrigin==="use-credentials"?r.credentials="include":i.crossOrigin==="anonymous"?r.credentials="omit":r.credentials="same-origin",r}function s(i){if(i.ep)return;i.ep=!0;const r=t(i);fetch(i.href,r)}})();var Us,ae,ta,tt,vr,sa,ia,ra,Ki,yi,Ei,na,As={},_s=[],sl=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i,qt=Array.isArray;function Ze(n,e){for(var t in e)n[t]=e[t];return n}function Vi(n){n&&n.parentNode&&n.parentNode.removeChild(n)}function Is(n,e,t){var s,i,r,a={};for(r in e)r=="key"?s=e[r]:r=="ref"?i=e[r]:a[r]=e[r];if(arguments.length>2&&(a.children=arguments.length>3?Us.call(arguments,2):t),typeof n=="function"&&n.defaultProps!=null)for(r in n.defaultProps)a[r]===void 0&&(a[r]=n.defaultProps[r]);return ds(n,a,s,i,null)}function ds(n,e,t,s,i){var r={type:n,props:e,key:t,ref:s,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:i??++ta,__i:-1,__u:0};return i==null&&ae.vnode!=null&&ae.vnode(r),r}function jt(n){return n.children}function fs(n,e){this.props=n,this.context=e}function bt(n,e){if(e==null)return n.__?bt(n.__,n.__i+1):null;for(var t;e<n.__k.length;e++)if((t=n.__k[e])!=null&&t.__e!=null)return t.__e;return typeof n.type=="function"?bt(n):null}function il(n){if(n.__P&&n.__d){var e=n.__v,t=e.__e,s=[],i=[],r=Ze({},e);r.__v=e.__v+1,ae.vnode&&ae.vnode(r),Hi(n.__P,r,e,n.__n,n.__P.namespaceURI,32&e.__u?[t]:null,s,t??bt(e),!!(32&e.__u),i),r.__v=e.__v,r.__.__k[r.__i]=r,ha(s,r,i),e.__e=e.__=null,r.__e!=t&&aa(r)}}function aa(n){if((n=n.__)!=null&&n.__c!=null)return n.__e=n.__c.base=null,n.__k.some(function(e){if(e!=null&&e.__e!=null)return n.__e=n.__c.base=e.__e}),aa(n)}function Ti(n){(!n.__d&&(n.__d=!0)&&tt.push(n)&&!Ls.__r++||vr!=ae.debounceRendering)&&((vr=ae.debounceRendering)||sa)(Ls)}function Ls(){try{for(var n,e=1;tt.length;)tt.length>e&&tt.sort(ia),n=tt.shift(),e=tt.length,il(n)}finally{tt.length=Ls.__r=0}}function oa(n,e,t,s,i,r,a,o,c,l,h){var u,d,f,g,p,y,E,T=s&&s.__k||_s,S=e.length;for(c=rl(t,e,T,c,S),u=0;u<S;u++)(f=t.__k[u])!=null&&(d=f.__i!=-1&&T[f.__i]||As,f.__i=u,y=Hi(n,f,d,i,r,a,o,c,l,h),g=f.__e,f.ref&&d.ref!=f.ref&&(d.ref&&Wi(d.ref,null,f),h.push(f.ref,f.__c||g,f)),p==null&&g!=null&&(p=g),(E=!!(4&f.__u))||d.__k===f.__k?c=la(f,c,n,E):typeof f.type=="function"&&y!==void 0?c=y:g&&(c=g.nextSibling),f.__u&=-7);return t.__e=p,c}function rl(n,e,t,s,i){var r,a,o,c,l,h=t.length,u=h,d=0;for(n.__k=new Array(i),r=0;r<i;r++)(a=e[r])!=null&&typeof a!="boolean"&&typeof a!="function"?(typeof a=="string"||typeof a=="number"||typeof a=="bigint"||a.constructor==String?a=n.__k[r]=ds(null,a,null,null,null):qt(a)?a=n.__k[r]=ds(jt,{children:a},null,null,null):a.constructor===void 0&&a.__b>0?a=n.__k[r]=ds(a.type,a.props,a.key,a.ref?a.ref:null,a.__v):n.__k[r]=a,c=r+d,a.__=n,a.__b=n.__b+1,o=null,(l=a.__i=nl(a,t,c,u))!=-1&&(u--,(o=t[l])&&(o.__u|=2)),o==null||o.__v==null?(l==-1&&(i>h?d--:i<h&&d++),typeof a.type!="function"&&(a.__u|=4)):l!=c&&(l==c-1?d--:l==c+1?d++:(l>c?d--:d++,a.__u|=4))):n.__k[r]=null;if(u)for(r=0;r<h;r++)(o=t[r])!=null&&!(2&o.__u)&&(o.__e==s&&(s=bt(o)),da(o,o));return s}function la(n,e,t,s){var i,r;if(typeof n.type=="function"){for(i=n.__k,r=0;i&&r<i.length;r++)i[r]&&(i[r].__=n,e=la(i[r],e,t,s));return e}n.__e!=e&&(s&&(e&&n.type&&!e.parentNode&&(e=bt(n)),t.insertBefore(n.__e,e||null)),e=n.__e);do e=e&&e.nextSibling;while(e!=null&&e.nodeType==8);return e}function ca(n,e){return e=e||[],n==null||typeof n=="boolean"||(qt(n)?n.some(function(t){ca(t,e)}):e.push(n)),e}function nl(n,e,t,s){var i,r,a,o=n.key,c=n.type,l=e[t],h=l!=null&&(2&l.__u)==0;if(l===null&&o==null||h&&o==l.key&&c==l.type)return t;if(s>(h?1:0)){for(i=t-1,r=t+1;i>=0||r<e.length;)if((l=e[a=i>=0?i--:r++])!=null&&!(2&l.__u)&&o==l.key&&c==l.type)return a}return-1}function xr(n,e,t){e[0]=="-"?n.setProperty(e,t??""):n[e]=t==null?"":typeof t!="number"||sl.test(e)?t:t+"px"}function zt(n,e,t,s,i){var r,a;e:if(e=="style")if(typeof t=="string")n.style.cssText=t;else{if(typeof s=="string"&&(n.style.cssText=s=""),s)for(e in s)t&&e in t||xr(n.style,e,"");if(t)for(e in t)s&&t[e]==s[e]||xr(n.style,e,t[e])}else if(e[0]=="o"&&e[1]=="n")r=e!=(e=e.replace(ra,"$1")),a=e.toLowerCase(),e=a in n||e=="onFocusOut"||e=="onFocusIn"?a.slice(2):e.slice(2),n.l||(n.l={}),n.l[e+r]=t,t?s?t.u=s.u:(t.u=Ki,n.addEventListener(e,r?Ei:yi,r)):n.removeEventListener(e,r?Ei:yi,r);else{if(i=="http://www.w3.org/2000/svg")e=e.replace(/xlink(H|:h)/,"h").replace(/sName$/,"s");else if(e!="width"&&e!="height"&&e!="href"&&e!="list"&&e!="form"&&e!="tabIndex"&&e!="download"&&e!="rowSpan"&&e!="colSpan"&&e!="role"&&e!="popover"&&e in n)try{n[e]=t??"";break e}catch{}typeof t=="function"||(t==null||t===!1&&e[4]!="-"?n.removeAttribute(e):n.setAttribute(e,e=="popover"&&t==1?"":t))}}function Ar(n){return function(e){if(this.l){var t=this.l[e.type+n];if(e.t==null)e.t=Ki++;else if(e.t<t.u)return;return t(ae.event?ae.event(e):e)}}}function Hi(n,e,t,s,i,r,a,o,c,l){var h,u,d,f,g,p,y,E,T,S,v,x,D,A,b,I=e.type;if(e.constructor!==void 0)return null;128&t.__u&&(c=!!(32&t.__u),r=[o=e.__e=t.__e]),(h=ae.__b)&&h(e);e:if(typeof I=="function")try{if(E=e.props,T=I.prototype&&I.prototype.render,S=(h=I.contextType)&&s[h.__c],v=h?S?S.props.value:h.__:s,t.__c?y=(u=e.__c=t.__c).__=u.__E:(T?e.__c=u=new I(E,v):(e.__c=u=new fs(E,v),u.constructor=I,u.render=ol),S&&S.sub(u),u.state||(u.state={}),u.__n=s,d=u.__d=!0,u.__h=[],u._sb=[]),T&&u.__s==null&&(u.__s=u.state),T&&I.getDerivedStateFromProps!=null&&(u.__s==u.state&&(u.__s=Ze({},u.__s)),Ze(u.__s,I.getDerivedStateFromProps(E,u.__s))),f=u.props,g=u.state,u.__v=e,d)T&&I.getDerivedStateFromProps==null&&u.componentWillMount!=null&&u.componentWillMount(),T&&u.componentDidMount!=null&&u.__h.push(u.componentDidMount);else{if(T&&I.getDerivedStateFromProps==null&&E!==f&&u.componentWillReceiveProps!=null&&u.componentWillReceiveProps(E,v),e.__v==t.__v||!u.__e&&u.shouldComponentUpdate!=null&&u.shouldComponentUpdate(E,u.__s,v)===!1){e.__v!=t.__v&&(u.props=E,u.state=u.__s,u.__d=!1),e.__e=t.__e,e.__k=t.__k,e.__k.some(function(_){_&&(_.__=e)}),_s.push.apply(u.__h,u._sb),u._sb=[],u.__h.length&&a.push(u);break e}u.componentWillUpdate!=null&&u.componentWillUpdate(E,u.__s,v),T&&u.componentDidUpdate!=null&&u.__h.push(function(){u.componentDidUpdate(f,g,p)})}if(u.context=v,u.props=E,u.__P=n,u.__e=!1,x=ae.__r,D=0,T)u.state=u.__s,u.__d=!1,x&&x(e),h=u.render(u.props,u.state,u.context),_s.push.apply(u.__h,u._sb),u._sb=[];else do u.__d=!1,x&&x(e),h=u.render(u.props,u.state,u.context),u.state=u.__s;while(u.__d&&++D<25);u.state=u.__s,u.getChildContext!=null&&(s=Ze(Ze({},s),u.getChildContext())),T&&!d&&u.getSnapshotBeforeUpdate!=null&&(p=u.getSnapshotBeforeUpdate(f,g)),A=h!=null&&h.type===jt&&h.key==null?ua(h.props.children):h,o=oa(n,qt(A)?A:[A],e,t,s,i,r,a,o,c,l),u.base=e.__e,e.__u&=-161,u.__h.length&&a.push(u),y&&(u.__E=u.__=null)}catch(_){if(e.__v=null,c||r!=null)if(_.then){for(e.__u|=c?160:128;o&&o.nodeType==8&&o.nextSibling;)o=o.nextSibling;r[r.indexOf(o)]=null,e.__e=o}else{for(b=r.length;b--;)Vi(r[b]);Si(e)}else e.__e=t.__e,e.__k=t.__k,_.then||Si(e);ae.__e(_,e,t)}else r==null&&e.__v==t.__v?(e.__k=t.__k,e.__e=t.__e):o=e.__e=al(t.__e,e,t,s,i,r,a,c,l);return(h=ae.diffed)&&h(e),128&e.__u?void 0:o}function Si(n){n&&(n.__c&&(n.__c.__e=!0),n.__k&&n.__k.some(Si))}function ha(n,e,t){for(var s=0;s<t.length;s++)Wi(t[s],t[++s],t[++s]);ae.__c&&ae.__c(e,n),n.some(function(i){try{n=i.__h,i.__h=[],n.some(function(r){r.call(i)})}catch(r){ae.__e(r,i.__v)}})}function ua(n){return typeof n!="object"||n==null||n.__b>0?n:qt(n)?n.map(ua):Ze({},n)}function al(n,e,t,s,i,r,a,o,c){var l,h,u,d,f,g,p,y=t.props||As,E=e.props,T=e.type;if(T=="svg"?i="http://www.w3.org/2000/svg":T=="math"?i="http://www.w3.org/1998/Math/MathML":i||(i="http://www.w3.org/1999/xhtml"),r!=null){for(l=0;l<r.length;l++)if((f=r[l])&&"setAttribute"in f==!!T&&(T?f.localName==T:f.nodeType==3)){n=f,r[l]=null;break}}if(n==null){if(T==null)return document.createTextNode(E);n=document.createElementNS(i,T,E.is&&E),o&&(ae.__m&&ae.__m(e,r),o=!1),r=null}if(T==null)y===E||o&&n.data==E||(n.data=E);else{if(r=r&&Us.call(n.childNodes),!o&&r!=null)for(y={},l=0;l<n.attributes.length;l++)y[(f=n.attributes[l]).name]=f.value;for(l in y)f=y[l],l=="dangerouslySetInnerHTML"?u=f:l=="children"||l in E||l=="value"&&"defaultValue"in E||l=="checked"&&"defaultChecked"in E||zt(n,l,null,f,i);for(l in E)f=E[l],l=="children"?d=f:l=="dangerouslySetInnerHTML"?h=f:l=="value"?g=f:l=="checked"?p=f:o&&typeof f!="function"||y[l]===f||zt(n,l,f,y[l],i);if(h)o||u&&(h.__html==u.__html||h.__html==n.innerHTML)||(n.innerHTML=h.__html),e.__k=[];else if(u&&(n.innerHTML=""),oa(e.type=="template"?n.content:n,qt(d)?d:[d],e,t,s,T=="foreignObject"?"http://www.w3.org/1999/xhtml":i,r,a,r?r[0]:t.__k&&bt(t,0),o,c),r!=null)for(l=r.length;l--;)Vi(r[l]);o||(l="value",T=="progress"&&g==null?n.removeAttribute("value"):g!=null&&(g!==n[l]||T=="progress"&&!g||T=="option"&&g!=y[l])&&zt(n,l,g,y[l],i),l="checked",p!=null&&p!=n[l]&&zt(n,l,p,y[l],i))}return n}function Wi(n,e,t){try{if(typeof n=="function"){var s=typeof n.__u=="function";s&&n.__u(),s&&e==null||(n.__u=n(e))}else n.current=e}catch(i){ae.__e(i,t)}}function da(n,e,t){var s,i;if(ae.unmount&&ae.unmount(n),(s=n.ref)&&(s.current&&s.current!=n.__e||Wi(s,null,e)),(s=n.__c)!=null){if(s.componentWillUnmount)try{s.componentWillUnmount()}catch(r){ae.__e(r,e)}s.base=s.__P=null}if(s=n.__k)for(i=0;i<s.length;i++)s[i]&&da(s[i],e,t||typeof n.type!="function");t||Vi(n.__e),n.__c=n.__=n.__e=void 0}function ol(n,e,t){return this.constructor(n,t)}function ll(n,e,t){var s,i,r,a;e==document&&(e=document.documentElement),ae.__&&ae.__(n,e),i=(s=!1)?null:e.__k,r=[],a=[],Hi(e,n=e.__k=Is(jt,null,[n]),i||As,As,e.namespaceURI,i?null:e.firstChild?Us.call(e.childNodes):null,r,i?i.__e:e.firstChild,s,a),ha(r,n,a)}function cl(n){function e(t){var s,i;return this.getChildContext||(s=new Set,(i={})[e.__c]=this,this.getChildContext=function(){return i},this.componentWillUnmount=function(){s=null},this.shouldComponentUpdate=function(r){this.props.value!=r.value&&s.forEach(function(a){a.__e=!0,Ti(a)})},this.sub=function(r){s.add(r);var a=r.componentWillUnmount;r.componentWillUnmount=function(){s&&s.delete(r),a&&a.call(r)}}),t.children}return e.__c="__cC"+na++,e.__=n,e.Provider=e.__l=(e.Consumer=function(t,s){return t.children(s)}).contextType=e,e}Us=_s.slice,ae={__e:function(n,e,t,s){for(var i,r,a;e=e.__;)if((i=e.__c)&&!i.__)try{if((r=i.constructor)&&r.getDerivedStateFromError!=null&&(i.setState(r.getDerivedStateFromError(n)),a=i.__d),i.componentDidCatch!=null&&(i.componentDidCatch(n,s||{}),a=i.__d),a)return i.__E=i}catch(o){n=o}throw n}},ta=0,fs.prototype.setState=function(n,e){var t;t=this.__s!=null&&this.__s!=this.state?this.__s:this.__s=Ze({},this.state),typeof n=="function"&&(n=n(Ze({},t),this.props)),n&&Ze(t,n),n!=null&&this.__v&&(e&&this._sb.push(e),Ti(this))},fs.prototype.forceUpdate=function(n){this.__v&&(this.__e=!0,n&&this.__h.push(n),Ti(this))},fs.prototype.render=jt,tt=[],sa=typeof Promise=="function"?Promise.prototype.then.bind(Promise.resolve()):setTimeout,ia=function(n,e){return n.__v.__b-e.__v.__b},Ls.__r=0,ra=/(PointerCapture)$|Capture$/i,Ki=0,yi=Ar(!1),Ei=Ar(!0),na=0;var hl=0;function Z(n,e,t,s,i,r){e||(e={});var a,o,c=e;if("ref"in c)for(o in c={},e)o=="ref"?a=e[o]:c[o]=e[o];var l={type:n,props:c,key:t,ref:a,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:--hl,__i:-1,__u:0,__source:i,__self:r};if(typeof n=="function"&&(a=n.defaultProps))for(o in a)c[o]===void 0&&(c[o]=a[o]);return ae.vnode&&ae.vnode(l),l}var Dt,ce,Ys,_r,Rs=0,fa=[],fe=ae,Ir=fe.__b,Lr=fe.__r,Rr=fe.diffed,br=fe.__c,Dr=fe.unmount,Cr=fe.__;function $s(n,e){fe.__h&&fe.__h(ce,n,Rs||e),Rs=0;var t=ce.__H||(ce.__H={__:[],__h:[]});return n>=t.__.length&&t.__.push({}),t.__[n]}function rt(n){return Rs=1,ul(ma,n)}function ul(n,e,t){var s=$s(Dt++,2);if(s.t=n,!s.__c&&(s.__=[ma(void 0,e),function(o){var c=s.__N?s.__N[0]:s.__[0],l=s.t(c,o);c!==l&&(s.__N=[l,s.__[1]],s.__c.setState({}))}],s.__c=ce,!ce.__f)){var i=function(o,c,l){if(!s.__c.__H)return!0;var h=s.__c.__H.__.filter(function(d){return d.__c});if(h.every(function(d){return!d.__N}))return!r||r.call(this,o,c,l);var u=s.__c.props!==o;return h.some(function(d){if(d.__N){var f=d.__[0];d.__=d.__N,d.__N=void 0,f!==d.__[0]&&(u=!0)}}),r&&r.call(this,o,c,l)||u};ce.__f=!0;var r=ce.shouldComponentUpdate,a=ce.componentWillUpdate;ce.componentWillUpdate=function(o,c,l){if(this.__e){var h=r;r=void 0,i(o,c,l),r=h}a&&a.call(this,o,c,l)},ce.shouldComponentUpdate=i}return s.__N||s.__}function vi(n,e){var t=$s(Dt++,3);!fe.__s&&ga(t.__H,e)&&(t.__=n,t.u=e,ce.__H.__h.push(t))}function Mt(n){return Rs=5,dl(function(){return{current:n}},[])}function dl(n,e){var t=$s(Dt++,7);return ga(t.__H,e)&&(t.__=n(),t.__H=e,t.__h=n),t.__}function fl(n){var e=ce.context[n.__c],t=$s(Dt++,9);return t.c=n,e?(t.__==null&&(t.__=!0,e.sub(ce)),e.props.value):n.__}function gl(){for(var n;n=fa.shift();){var e=n.__H;if(n.__P&&e)try{e.__h.some(gs),e.__h.some(xi),e.__h=[]}catch(t){e.__h=[],fe.__e(t,n.__v)}}}fe.__b=function(n){ce=null,Ir&&Ir(n)},fe.__=function(n,e){n&&e.__k&&e.__k.__m&&(n.__m=e.__k.__m),Cr&&Cr(n,e)},fe.__r=function(n){Lr&&Lr(n),Dt=0;var e=(ce=n.__c).__H;e&&(Ys===ce?(e.__h=[],ce.__h=[],e.__.some(function(t){t.__N&&(t.__=t.__N),t.u=t.__N=void 0})):(e.__h.some(gs),e.__h.some(xi),e.__h=[],Dt=0)),Ys=ce},fe.diffed=function(n){Rr&&Rr(n);var e=n.__c;e&&e.__H&&(e.__H.__h.length&&(fa.push(e)!==1&&_r===fe.requestAnimationFrame||((_r=fe.requestAnimationFrame)||ml)(gl)),e.__H.__.some(function(t){t.u&&(t.__H=t.u),t.u=void 0})),Ys=ce=null},fe.__c=function(n,e){e.some(function(t){try{t.__h.some(gs),t.__h=t.__h.filter(function(s){return!s.__||xi(s)})}catch(s){e.some(function(i){i.__h&&(i.__h=[])}),e=[],fe.__e(s,t.__v)}}),br&&br(n,e)},fe.unmount=function(n){Dr&&Dr(n);var e,t=n.__c;t&&t.__H&&(t.__H.__.some(function(s){try{gs(s)}catch(i){e=i}}),t.__H=void 0,e&&fe.__e(e,t.__v))};var Pr=typeof requestAnimationFrame=="function";function ml(n){var e,t=function(){clearTimeout(s),Pr&&cancelAnimationFrame(e),setTimeout(n)},s=setTimeout(t,35);Pr&&(e=requestAnimationFrame(t))}function gs(n){var e=ce,t=n.__c;typeof t=="function"&&(n.__c=void 0,t()),ce=e}function xi(n){var e=ce;n.__c=n.__(),ce=e}function ga(n,e){return!n||n.length!==e.length||e.some(function(t,s){return t!==n[s]})}function ma(n,e){return typeof e=="function"?e(n):e}const pl="https://iameli.com",yl="did:plc:rbvrr34edl5ddpuwcubjiost",El="place.stream.video";async function Tl(){let n=[],e;do{const t=new URLSearchParams({repo:yl,collection:El,limit:"100"});e&&t.set("cursor",e);const s=await(await fetch(`${pl}/xrpc/com.atproto.repo.listRecords?${t}`)).json();n=n.concat(s.records||[]),e=s.cursor}while(e);return console.info(n),n.reverse()}function Sl(n){const e=Math.floor(n/3600),t=Math.floor(n%3600/60),s=n%60;return e>0?`${e}:${String(t).padStart(2,"0")}:${String(s).padStart(2,"0")}`:`${t}:${String(s).padStart(2,"0")}`}function vl(n){return new Date(n).toLocaleTimeString("en-US",{hour:"numeric",minute:"2-digit",hour12:!0,timeZone:"America/Los_Angeles"})}function pa(n){return new Date(n.value.createdAt).toLocaleDateString("en-CA",{timeZone:"America/Los_Angeles"})}function xl(n){const[e,t,s]=n.split("-").map(Number);return new Date(e,t-1,s).toLocaleDateString("en-US",{weekday:"short",month:"short",day:"numeric"})}function Al({days:n,selectedDay:e,onSelectDay:t}){return Z("div",{class:"flex w-full",children:n.map(s=>Z("button",{class:`flex-1 py-2 px-1 bg-transparent border border-[rgba(125,211,252,0.3)] border-r-0 last:border-r last:border-[rgba(125,211,252,0.3)] text-[rgba(125,211,252,0.7)] text-xs cursor-pointer transition-all duration-150 text-center hover:bg-[rgba(125,211,252,0.1)] ${s===e?"bg-[rgba(125,211,252,0.15)] border-[#7dd3fc] text-[#7dd3fc]":""}`,onClick:()=>t(s),children:xl(s)}))})}function _l({record:n,index:e,isSelected:t,onClick:s}){const i=n.value.title||"Unknown Programme",r=Math.round((n.value.duration||0)/1e9),a=r>0?` (${Sl(r)})`:"",o=vl(n.value.createdAt);return Z("div",{class:`bg-transparent border border-[rgba(125,211,252,0.4)] border-l-[3px] border-l-[rgba(125,211,252,0.6)] rounded p-2.5 flex flex-col gap-1 cursor-pointer transition-all duration-150 min-h-[100px] hover:bg-[rgba(125,211,252,0.08)] hover:border-[rgba(125,211,252,0.6)] hover:border-l-[#7dd3fc] ${t?"bg-[rgba(125,211,252,0.15)] border-[#7dd3fc] border-l-[#7dd3fc] hover:bg-[rgba(125,211,252,0.2)]":""}`,onClick:s,children:[Z("div",{class:"text-[11px] text-[rgba(125,211,252,0.5)] tracking-wide",children:o}),Z("div",{class:"text-sm text-[#7dd3fc] leading-tight",children:[i,a]})]})}function Il({vods:n,selectedDay:e,currentChannel:t,onSelectVideo:s}){const i=e?n.filter(o=>pa(o)===e):n,r=i.findIndex(o=>o.uri===t);let a="0/0";return i.length>0&&(a=r>=0?`${r+1}/${i.length}`:`${i.length} videos`),Z(jt,{children:[Z("div",{class:"text-lg text-[#7dd3fc] mb-3 pb-2 border-b border-[rgba(125,211,252,0.2)] flex justify-between items-center",children:Z("h3",{class:"m-0",children:["Available Videos",Z("span",{class:"text-sm text-[rgba(125,211,252,0.6)] ml-2",children:a})]})}),Z("div",{class:"flex flex-col gap-1.5 p-1",id:"videoListContainer",children:i.map((o,c)=>Z(_l,{record:o,index:c,isSelected:o.uri===t,onClick:()=>s(o.uri)},o.uri))})]})}function Ll(n){const e=new Map;for(const t of n){const s=pa(t);e.has(s)||e.set(s,[]),e.get(s).push(t)}return e}function Rl({vods:n,currentChannel:e,selectedDay:t,onSelectDay:s,onSelectVideo:i,collapsed:r}){const a=Ll(n),o=Array.from(a.keys()).sort();return Z("div",{class:`transition-all duration-300 ease-in-out overflow-hidden ${r?"w-0 min-w-0":"w-[400px] min-w-[400px]"} h-screen overflow-y-auto bg-[#1a1a1a]`,children:Z("div",{class:r?"opacity-0 pointer-events-none":"opacity-100",children:[Z(Al,{days:o,selectedDay:t,onSelectDay:s}),Z(Il,{vods:n,selectedDay:t,currentChannel:e,onSelectVideo:i})]})})}function bl({currentTitle:n,currentUri:e,isLoading:t,showStandby:s,videoRef:i,audioRef:r}){return Z("div",{class:"relative flex flex-1 flex-col",children:[Z("div",{class:"relative flex flex-col justify-center items-center overflow-hidden rounded-lg [background:linear-gradient(45deg,#0a0806_0%,#1a1410_50%,#0a0806_100%)]",children:[Z("video",{id:"video",ref:i,controls:!0,class:"w-full object-contain bg-[#0a0806]"}),Z("audio",{id:"audio",ref:r,preload:"none"}),Z("div",{class:`absolute top-4 left-4 z-10 transition-opacity duration-300 ${n?"opacity-100":"opacity-0"}`,id:"channelOverlay",children:n&&e&&Z("a",{class:"font-sans text-sm text-[#7dd3fc] no-underline hover:underline",href:`https://pds.ls/${e}`,target:"_blank",rel:"noopener",children:n})}),Z("div",{class:`absolute bottom-4 left-1/2 -translate-x-1/2 z-7 font-sans text-lg text-[#7dd3fc] transition-opacity duration-300 pointer-events-none ${t?"opacity-100":"opacity-0"}`,id:"loadingIndicator",children:"Loading..."}),Z("div",{class:`absolute inset-0 flex flex-col justify-center items-center [background:linear-gradient(45deg,#0a0806_0%,#1a1410_50%,#0a0806_100%)] ${s?"":"hidden"}`,id:"standby",children:Z("div",{class:"font-sans text-3xl font-semibold text-[#7dd3fc] tracking-widest",children:"ATmosphereConf 2026"})})]}),Z("a",{class:"font-sans text-xs text-white/25 no-underline mt-2 absolute bottom-2.5 right-5 hover:text-white/50",href:"https://tangled.org/timryan.org/atmosphereconf2026",target:"_blank",rel:"noopener",children:"View Source"})]})}/**
3535+ * @license lucide-preact v1.7.0 - ISC
3636+ *
3737+ * This source code is licensed under the ISC license.
3838+ * See the LICENSE file in the root directory of this source tree.
3939+ */const ya=(...n)=>n.filter((e,t,s)=>!!e&&e.trim()!==""&&s.indexOf(e)===t).join(" ").trim();/**
4040+ * @license lucide-preact v1.7.0 - ISC
4141+ *
4242+ * This source code is licensed under the ISC license.
4343+ * See the LICENSE file in the root directory of this source tree.
4444+ */const kr=n=>n.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase();/**
4545+ * @license lucide-preact v1.7.0 - ISC
4646+ *
4747+ * This source code is licensed under the ISC license.
4848+ * See the LICENSE file in the root directory of this source tree.
4949+ */const Dl=n=>n.replace(/^([A-Z])|[\s-_]+(\w)/g,(e,t,s)=>s?s.toUpperCase():t.toLowerCase());/**
5050+ * @license lucide-preact v1.7.0 - ISC
5151+ *
5252+ * This source code is licensed under the ISC license.
5353+ * See the LICENSE file in the root directory of this source tree.
5454+ */const wr=n=>{const e=Dl(n);return e.charAt(0).toUpperCase()+e.slice(1)};/**
5555+ * @license lucide-preact v1.7.0 - ISC
5656+ *
5757+ * This source code is licensed under the ISC license.
5858+ * See the LICENSE file in the root directory of this source tree.
5959+ */var Cl={xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round"};/**
6060+ * @license lucide-preact v1.7.0 - ISC
6161+ *
6262+ * This source code is licensed under the ISC license.
6363+ * See the LICENSE file in the root directory of this source tree.
6464+ */const Pl=cl({size:24,color:"currentColor",strokeWidth:2,absoluteStrokeWidth:!1,class:""}),kl=()=>fl(Pl);/**
6565+ * @license lucide-preact v1.7.0 - ISC
6666+ *
6767+ * This source code is licensed under the ISC license.
6868+ * See the LICENSE file in the root directory of this source tree.
6969+ */const wl=n=>{for(const e in n)if(e.startsWith("aria-")||e==="role"||e==="title")return!0;return!1};/**
7070+ * @license lucide-preact v1.7.0 - ISC
7171+ *
7272+ * This source code is licensed under the ISC license.
7373+ * See the LICENSE file in the root directory of this source tree.
7474+ */const Ol=({color:n,size:e,strokeWidth:t,absoluteStrokeWidth:s,children:i,iconNode:r,class:a="",...o})=>{const{size:c=24,strokeWidth:l=2,absoluteStrokeWidth:h=!1,color:u="currentColor",class:d=""}=kl()??{},f=s??h?Number(t??l)*24/Number(e??c):t??l;return Is("svg",{...Cl,width:e??c??24,height:e??c??24,stroke:n??u,"stroke-width":f,class:ya("lucide",d,a),...!i&&!wl(o)&&{"aria-hidden":"true"},...o},[...r.map(([g,p])=>Is(g,p)),...ca(i)])};/**
7575+ * @license lucide-preact v1.7.0 - ISC
7676+ *
7777+ * This source code is licensed under the ISC license.
7878+ * See the LICENSE file in the root directory of this source tree.
7979+ */const Ea=(n,e)=>{const t=({class:s="",className:i="",children:r,...a})=>Is(Ol,{...a,iconNode:e,class:ya(`lucide-${kr(wr(n))}`,`lucide-${kr(n)}`,s,i)},r);return t.displayName=wr(n),t};/**
8080+ * @license lucide-preact v1.7.0 - ISC
8181+ *
8282+ * This source code is licensed under the ISC license.
8383+ * See the LICENSE file in the root directory of this source tree.
8484+ */const Fl=Ea("panel-left-close",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M9 3v18",key:"fh3hqa"}],["path",{d:"m16 15-3-3 3-3",key:"14y99z"}]]);/**
8585+ * @license lucide-preact v1.7.0 - ISC
8686+ *
8787+ * This source code is licensed under the ISC license.
8888+ * See the LICENSE file in the root directory of this source tree.
8989+ */const Ml=Ea("panel-left",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M9 3v18",key:"fh3hqa"}]]);function Nl({sidebarCollapsed:n,onToggleSidebar:e}){return Z("h1",{class:"font-sans text-2xl font-semibold text-[#7dd3fc] m-0 py-4 px-5 tracking-wide shrink-0 flex items-center gap-3",children:[Z("button",{onClick:e,class:"p-1 hover:bg-[rgba(125,211,252,0.1)] rounded transition-colors text-[#7dd3fc] cursor-pointer","aria-label":n?"Expand sidebar":"Collapse sidebar",children:n?Z(Ml,{size:24}):Z(Fl,{size:24})}),Z("span",{children:"AtmosphereConf 2026"})]})}const M=Number.isFinite||function(n){return typeof n=="number"&&isFinite(n)},Bl=Number.isSafeInteger||function(n){return typeof n=="number"&&Math.abs(n)<=Ul},Ul=Number.MAX_SAFE_INTEGER||9007199254740991;let H=function(n){return n.NETWORK_ERROR="networkError",n.MEDIA_ERROR="mediaError",n.KEY_SYSTEM_ERROR="keySystemError",n.MUX_ERROR="muxError",n.OTHER_ERROR="otherError",n}({}),R=function(n){return n.KEY_SYSTEM_NO_KEYS="keySystemNoKeys",n.KEY_SYSTEM_NO_ACCESS="keySystemNoAccess",n.KEY_SYSTEM_NO_SESSION="keySystemNoSession",n.KEY_SYSTEM_NO_CONFIGURED_LICENSE="keySystemNoConfiguredLicense",n.KEY_SYSTEM_LICENSE_REQUEST_FAILED="keySystemLicenseRequestFailed",n.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED="keySystemServerCertificateRequestFailed",n.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED="keySystemServerCertificateUpdateFailed",n.KEY_SYSTEM_SESSION_UPDATE_FAILED="keySystemSessionUpdateFailed",n.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED="keySystemStatusOutputRestricted",n.KEY_SYSTEM_STATUS_INTERNAL_ERROR="keySystemStatusInternalError",n.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR="keySystemDestroyMediaKeysError",n.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR="keySystemDestroyCloseSessionError",n.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR="keySystemDestroyRemoveSessionError",n.MANIFEST_LOAD_ERROR="manifestLoadError",n.MANIFEST_LOAD_TIMEOUT="manifestLoadTimeOut",n.MANIFEST_PARSING_ERROR="manifestParsingError",n.MANIFEST_INCOMPATIBLE_CODECS_ERROR="manifestIncompatibleCodecsError",n.LEVEL_EMPTY_ERROR="levelEmptyError",n.LEVEL_LOAD_ERROR="levelLoadError",n.LEVEL_LOAD_TIMEOUT="levelLoadTimeOut",n.LEVEL_PARSING_ERROR="levelParsingError",n.LEVEL_SWITCH_ERROR="levelSwitchError",n.AUDIO_TRACK_LOAD_ERROR="audioTrackLoadError",n.AUDIO_TRACK_LOAD_TIMEOUT="audioTrackLoadTimeOut",n.SUBTITLE_LOAD_ERROR="subtitleTrackLoadError",n.SUBTITLE_TRACK_LOAD_TIMEOUT="subtitleTrackLoadTimeOut",n.FRAG_LOAD_ERROR="fragLoadError",n.FRAG_LOAD_TIMEOUT="fragLoadTimeOut",n.FRAG_DECRYPT_ERROR="fragDecryptError",n.FRAG_PARSING_ERROR="fragParsingError",n.FRAG_GAP="fragGap",n.REMUX_ALLOC_ERROR="remuxAllocError",n.KEY_LOAD_ERROR="keyLoadError",n.KEY_LOAD_TIMEOUT="keyLoadTimeOut",n.BUFFER_ADD_CODEC_ERROR="bufferAddCodecError",n.BUFFER_INCOMPATIBLE_CODECS_ERROR="bufferIncompatibleCodecsError",n.BUFFER_APPEND_ERROR="bufferAppendError",n.BUFFER_APPENDING_ERROR="bufferAppendingError",n.BUFFER_STALLED_ERROR="bufferStalledError",n.BUFFER_FULL_ERROR="bufferFullError",n.BUFFER_SEEK_OVER_HOLE="bufferSeekOverHole",n.BUFFER_NUDGE_ON_STALL="bufferNudgeOnStall",n.ASSET_LIST_LOAD_ERROR="assetListLoadError",n.ASSET_LIST_LOAD_TIMEOUT="assetListLoadTimeout",n.ASSET_LIST_PARSING_ERROR="assetListParsingError",n.INTERSTITIAL_ASSET_ITEM_ERROR="interstitialAssetItemError",n.INTERNAL_EXCEPTION="internalException",n.INTERNAL_ABORTED="aborted",n.ATTACH_MEDIA_ERROR="attachMediaError",n.UNKNOWN="unknown",n}({}),m=function(n){return n.MEDIA_ATTACHING="hlsMediaAttaching",n.MEDIA_ATTACHED="hlsMediaAttached",n.MEDIA_DETACHING="hlsMediaDetaching",n.MEDIA_DETACHED="hlsMediaDetached",n.MEDIA_ENDED="hlsMediaEnded",n.STALL_RESOLVED="hlsStallResolved",n.BUFFER_RESET="hlsBufferReset",n.BUFFER_CODECS="hlsBufferCodecs",n.BUFFER_CREATED="hlsBufferCreated",n.BUFFER_APPENDING="hlsBufferAppending",n.BUFFER_APPENDED="hlsBufferAppended",n.BUFFER_EOS="hlsBufferEos",n.BUFFERED_TO_END="hlsBufferedToEnd",n.BUFFER_FLUSHING="hlsBufferFlushing",n.BUFFER_FLUSHED="hlsBufferFlushed",n.MANIFEST_LOADING="hlsManifestLoading",n.MANIFEST_LOADED="hlsManifestLoaded",n.MANIFEST_PARSED="hlsManifestParsed",n.LEVEL_SWITCHING="hlsLevelSwitching",n.LEVEL_SWITCHED="hlsLevelSwitched",n.LEVEL_LOADING="hlsLevelLoading",n.LEVEL_LOADED="hlsLevelLoaded",n.LEVEL_UPDATED="hlsLevelUpdated",n.LEVEL_PTS_UPDATED="hlsLevelPtsUpdated",n.LEVELS_UPDATED="hlsLevelsUpdated",n.AUDIO_TRACKS_UPDATED="hlsAudioTracksUpdated",n.AUDIO_TRACK_SWITCHING="hlsAudioTrackSwitching",n.AUDIO_TRACK_SWITCHED="hlsAudioTrackSwitched",n.AUDIO_TRACK_LOADING="hlsAudioTrackLoading",n.AUDIO_TRACK_LOADED="hlsAudioTrackLoaded",n.AUDIO_TRACK_UPDATED="hlsAudioTrackUpdated",n.SUBTITLE_TRACKS_UPDATED="hlsSubtitleTracksUpdated",n.SUBTITLE_TRACKS_CLEARED="hlsSubtitleTracksCleared",n.SUBTITLE_TRACK_SWITCH="hlsSubtitleTrackSwitch",n.SUBTITLE_TRACK_LOADING="hlsSubtitleTrackLoading",n.SUBTITLE_TRACK_LOADED="hlsSubtitleTrackLoaded",n.SUBTITLE_TRACK_UPDATED="hlsSubtitleTrackUpdated",n.SUBTITLE_FRAG_PROCESSED="hlsSubtitleFragProcessed",n.CUES_PARSED="hlsCuesParsed",n.NON_NATIVE_TEXT_TRACKS_FOUND="hlsNonNativeTextTracksFound",n.INIT_PTS_FOUND="hlsInitPtsFound",n.FRAG_LOADING="hlsFragLoading",n.FRAG_LOAD_EMERGENCY_ABORTED="hlsFragLoadEmergencyAborted",n.FRAG_LOADED="hlsFragLoaded",n.FRAG_DECRYPTED="hlsFragDecrypted",n.FRAG_PARSING_INIT_SEGMENT="hlsFragParsingInitSegment",n.FRAG_PARSING_USERDATA="hlsFragParsingUserdata",n.FRAG_PARSING_METADATA="hlsFragParsingMetadata",n.FRAG_PARSED="hlsFragParsed",n.FRAG_BUFFERED="hlsFragBuffered",n.FRAG_CHANGED="hlsFragChanged",n.FPS_DROP="hlsFpsDrop",n.FPS_DROP_LEVEL_CAPPING="hlsFpsDropLevelCapping",n.MAX_AUTO_LEVEL_UPDATED="hlsMaxAutoLevelUpdated",n.ERROR="hlsError",n.DESTROYING="hlsDestroying",n.KEY_LOADING="hlsKeyLoading",n.KEY_LOADED="hlsKeyLoaded",n.LIVE_BACK_BUFFER_REACHED="hlsLiveBackBufferReached",n.BACK_BUFFER_REACHED="hlsBackBufferReached",n.STEERING_MANIFEST_LOADED="hlsSteeringManifestLoaded",n.ASSET_LIST_LOADING="hlsAssetListLoading",n.ASSET_LIST_LOADED="hlsAssetListLoaded",n.INTERSTITIALS_UPDATED="hlsInterstitialsUpdated",n.INTERSTITIALS_BUFFERED_TO_BOUNDARY="hlsInterstitialsBufferedToBoundary",n.INTERSTITIAL_ASSET_PLAYER_CREATED="hlsInterstitialAssetPlayerCreated",n.INTERSTITIAL_STARTED="hlsInterstitialStarted",n.INTERSTITIAL_ASSET_STARTED="hlsInterstitialAssetStarted",n.INTERSTITIAL_ASSET_ENDED="hlsInterstitialAssetEnded",n.INTERSTITIAL_ASSET_ERROR="hlsInterstitialAssetError",n.INTERSTITIAL_ENDED="hlsInterstitialEnded",n.INTERSTITIALS_PRIMARY_RESUMED="hlsInterstitialsPrimaryResumed",n.PLAYOUT_LIMIT_REACHED="hlsPlayoutLimitReached",n.EVENT_CUE_ENTER="hlsEventCueEnter",n}({});var Q={MANIFEST:"manifest",LEVEL:"level",AUDIO_TRACK:"audioTrack",SUBTITLE_TRACK:"subtitleTrack"},U={MAIN:"main",AUDIO:"audio",SUBTITLE:"subtitle"};class yt{constructor(e,t=0,s=0){this.halfLife=void 0,this.alpha_=void 0,this.estimate_=void 0,this.totalWeight_=void 0,this.halfLife=e,this.alpha_=e?Math.exp(Math.log(.5)/e):0,this.estimate_=t,this.totalWeight_=s}sample(e,t){const s=Math.pow(this.alpha_,e);this.estimate_=t*(1-s)+s*this.estimate_,this.totalWeight_+=e}getTotalWeight(){return this.totalWeight_}getEstimate(){if(this.alpha_){const e=1-Math.pow(this.alpha_,this.totalWeight_);if(e)return this.estimate_/e}return this.estimate_}}class $l{constructor(e,t,s,i=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_=s,this.minWeight_=.001,this.minDelayMs_=50,this.slow_=new yt(e),this.fast_=new yt(t),this.defaultTTFB_=i,this.ttfb_=new yt(e)}update(e,t){const{slow_:s,fast_:i,ttfb_:r}=this;s.halfLife!==e&&(this.slow_=new yt(e,s.getEstimate(),s.getTotalWeight())),i.halfLife!==t&&(this.fast_=new yt(t,i.getEstimate(),i.getTotalWeight())),r.halfLife!==e&&(this.ttfb_=new yt(e,r.getEstimate(),r.getTotalWeight()))}sample(e,t){e=Math.max(e,this.minDelayMs_);const s=8*t,i=e/1e3,r=s/i;this.fast_.sample(i,r),this.slow_.sample(i,r)}sampleTTFB(e){const t=e/1e3,s=Math.sqrt(2)*Math.exp(-Math.pow(t,2)/2);this.ttfb_.sample(s,Math.max(e,5))}canEstimate(){return this.fast_.getTotalWeight()>=this.minWeight_}getEstimate(){return this.canEstimate()?Math.min(this.fast_.getEstimate(),this.slow_.getEstimate()):this.defaultEstimate_}getEstimateTTFB(){return this.ttfb_.getTotalWeight()>=this.minWeight_?this.ttfb_.getEstimate():this.defaultTTFB_}get defaultEstimate(){return this.defaultEstimate_}destroy(){}}function Gl(n,e,t){return(e=Vl(e))in n?Object.defineProperty(n,e,{value:t,enumerable:!0,configurable:!0,writable:!0}):n[e]=t,n}function re(){return re=Object.assign?Object.assign.bind():function(n){for(var e=1;e<arguments.length;e++){var t=arguments[e];for(var s in t)({}).hasOwnProperty.call(t,s)&&(n[s]=t[s])}return n},re.apply(null,arguments)}function Or(n,e){var t=Object.keys(n);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(n);e&&(s=s.filter(function(i){return Object.getOwnPropertyDescriptor(n,i).enumerable})),t.push.apply(t,s)}return t}function se(n){for(var e=1;e<arguments.length;e++){var t=arguments[e]!=null?arguments[e]:{};e%2?Or(Object(t),!0).forEach(function(s){Gl(n,s,t[s])}):Object.getOwnPropertyDescriptors?Object.defineProperties(n,Object.getOwnPropertyDescriptors(t)):Or(Object(t)).forEach(function(s){Object.defineProperty(n,s,Object.getOwnPropertyDescriptor(t,s))})}return n}function Kl(n,e){if(typeof n!="object"||!n)return n;var t=n[Symbol.toPrimitive];if(t!==void 0){var s=t.call(n,e);if(typeof s!="object")return s;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(n)}function Vl(n){var e=Kl(n,"string");return typeof e=="symbol"?e:e+""}class Fe{constructor(e,t){this.trace=void 0,this.debug=void 0,this.log=void 0,this.warn=void 0,this.info=void 0,this.error=void 0;const s=`[${e}]:`;this.trace=st,this.debug=t.debug.bind(null,s),this.log=t.log.bind(null,s),this.warn=t.warn.bind(null,s),this.info=t.info.bind(null,s),this.error=t.error.bind(null,s)}}const st=function(){},Hl={trace:st,debug:st,log:st,warn:st,info:st,error:st};function Ai(){return re({},Hl)}function Wl(n,e){const t=self.console[n];return t?t.bind(self.console,`${e?"["+e+"] ":""}[${n}] >`):st}function Fr(n,e,t){return e[n]?e[n].bind(e):Wl(n,t)}const _i=Ai();function Yl(n,e,t){const s=Ai();if(typeof console=="object"&&n===!0||typeof n=="object"){const i=["debug","log","info","warn","error"];i.forEach(r=>{s[r]=Fr(r,n,t)});try{s.log(`Debug logs enabled for "${e}" in hls.js version 1.6.15`)}catch{return Ai()}i.forEach(r=>{_i[r]=Fr(r,n)})}else re(_i,s);return s}const ie=_i;function at(n=!0){return typeof self>"u"?void 0:(n||!self.MediaSource)&&self.ManagedMediaSource||self.MediaSource||self.WebKitMediaSource}function ql(n){return typeof self<"u"&&n===self.ManagedMediaSource}function Ta(n,e){const t=Object.keys(n),s=Object.keys(e),i=t.length,r=s.length;return!i||!r||i===r&&!t.some(a=>s.indexOf(a)===-1)}function Ce(n,e=!1){if(typeof TextDecoder<"u"){const l=new TextDecoder("utf-8").decode(n);if(e){const h=l.indexOf("\0");return h!==-1?l.substring(0,h):l}return l.replace(/\0/g,"")}const t=n.length;let s,i,r,a="",o=0;for(;o<t;){if(s=n[o++],s===0&&e)return a;if(s===0||s===3)continue;switch(s>>4){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:a+=String.fromCharCode(s);break;case 12:case 13:i=n[o++],a+=String.fromCharCode((s&31)<<6|i&63);break;case 14:i=n[o++],r=n[o++],a+=String.fromCharCode((s&15)<<12|(i&63)<<6|(r&63)<<0);break}}return a}function Te(n){let e="";for(let t=0;t<n.length;t++){let s=n[t].toString(16);s.length<2&&(s="0"+s),e+=s}return e}function Sa(n){return Uint8Array.from(n.replace(/^0x/,"").replace(/([\da-fA-F]{2}) ?/g,"0x$1 ").replace(/ +$/,"").split(" ")).buffer}function jl(n){return n&&n.__esModule&&Object.prototype.hasOwnProperty.call(n,"default")?n.default:n}var qs={exports:{}},Mr;function Xl(){return Mr||(Mr=1,function(n,e){(function(t){var s=/^(?=((?:[a-zA-Z0-9+\-.]+:)?))\1(?=((?:\/\/[^\/?#]*)?))\2(?=((?:(?:[^?#\/]*\/)*[^;?#\/]*)?))\3((?:;[^?#]*)?)(\?[^#]*)?(#[^]*)?$/,i=/^(?=([^\/?#]*))\1([^]*)$/,r=/(?:\/|^)\.(?=\/)/g,a=/(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g,o={buildAbsoluteURL:function(c,l,h){if(h=h||{},c=c.trim(),l=l.trim(),!l){if(!h.alwaysNormalize)return c;var u=o.parseURL(c);if(!u)throw new Error("Error trying to parse base URL.");return u.path=o.normalizePath(u.path),o.buildURLFromParts(u)}var d=o.parseURL(l);if(!d)throw new Error("Error trying to parse relative URL.");if(d.scheme)return h.alwaysNormalize?(d.path=o.normalizePath(d.path),o.buildURLFromParts(d)):l;var f=o.parseURL(c);if(!f)throw new Error("Error trying to parse base URL.");if(!f.netLoc&&f.path&&f.path[0]!=="/"){var g=i.exec(f.path);f.netLoc=g[1],f.path=g[2]}f.netLoc&&!f.path&&(f.path="/");var p={scheme:f.scheme,netLoc:d.netLoc,path:null,params:d.params,query:d.query,fragment:d.fragment};if(!d.netLoc&&(p.netLoc=f.netLoc,d.path[0]!=="/"))if(!d.path)p.path=f.path,d.params||(p.params=f.params,d.query||(p.query=f.query));else{var y=f.path,E=y.substring(0,y.lastIndexOf("/")+1)+d.path;p.path=o.normalizePath(E)}return p.path===null&&(p.path=h.alwaysNormalize?o.normalizePath(d.path):d.path),o.buildURLFromParts(p)},parseURL:function(c){var l=s.exec(c);return l?{scheme:l[1]||"",netLoc:l[2]||"",path:l[3]||"",params:l[4]||"",query:l[5]||"",fragment:l[6]||""}:null},normalizePath:function(c){for(c=c.split("").reverse().join("").replace(r,"");c.length!==(c=c.replace(a,"")).length;);return c.split("").reverse().join("")},buildURLFromParts:function(c){return c.scheme+c.netLoc+c.path+c.params+c.query+c.fragment}};n.exports=o})()}(qs)),qs.exports}var Yi=Xl();class qi{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 ne={AUDIO:"audio",VIDEO:"video",AUDIOVIDEO:"audiovideo"};class va{constructor(e){this._byteRange=null,this._url=null,this._stats=null,this._streams=null,this.base=void 0,this.relurl=void 0,typeof e=="string"&&(e={url:e}),this.base=e,Ql(this,"stats")}setByteRange(e,t){const s=e.split("@",2);let i;s.length===1?i=(t==null?void 0:t.byteRangeEndOffset)||0:i=parseInt(s[1]),this._byteRange=[i,parseInt(s[0])+i]}get baseurl(){return this.base.url}get byteRange(){return this._byteRange===null?[]:this._byteRange}get byteRangeStartOffset(){return this.byteRange[0]}get byteRangeEndOffset(){return this.byteRange[1]}get elementaryStreams(){return this._streams===null&&(this._streams={[ne.AUDIO]:null,[ne.VIDEO]:null,[ne.AUDIOVIDEO]:null}),this._streams}set elementaryStreams(e){this._streams=e}get hasStats(){return this._stats!==null}get hasStreams(){return this._streams!==null}get stats(){return this._stats===null&&(this._stats=new qi),this._stats}set stats(e){this._stats=e}get url(){return!this._url&&this.baseurl&&this.relurl&&(this._url=Yi.buildAbsoluteURL(this.baseurl,this.relurl,{alwaysNormalize:!0})),this._url||""}set url(e){this._url=e}clearElementaryStreamInfo(){const{elementaryStreams:e}=this;e[ne.AUDIO]=null,e[ne.VIDEO]=null,e[ne.AUDIOVIDEO]=null}}function de(n){return n.sn!=="initSegment"}class js extends va{constructor(e,t){super(t),this._decryptdata=null,this._programDateTime=null,this._ref=null,this._bitrate=void 0,this.rawProgramDateTime=null,this.tagList=[],this.duration=0,this.sn=0,this.levelkeys=void 0,this.type=void 0,this.loader=null,this.keyLoader=null,this.level=-1,this.cc=0,this.startPTS=void 0,this.endPTS=void 0,this.startDTS=void 0,this.endDTS=void 0,this.start=0,this.playlistOffset=0,this.deltaPTS=void 0,this.maxStartPTS=void 0,this.minEndPTS=void 0,this.data=void 0,this.bitrateTest=!1,this.title=null,this.initSegment=null,this.endList=void 0,this.gap=void 0,this.urlId=0,this.type=e}get byteLength(){if(this.hasStats){const e=this.stats.total;if(e)return e}if(this.byteRange.length){const e=this.byteRange[0],t=this.byteRange[1];if(M(e)&&M(t))return t-e}return null}get bitrate(){return this.byteLength?this.byteLength*8/this.duration:this._bitrate?this._bitrate:null}set bitrate(e){this._bitrate=e}get decryptdata(){var e;const{levelkeys:t}=this;if(!t||t.NONE)return null;if(t.identity)this._decryptdata||(this._decryptdata=t.identity.getDecryptData(this.sn));else if(!((e=this._decryptdata)!=null&&e.keyId)){const s=Object.keys(t);if(s.length===1){const i=this._decryptdata=t[s[0]]||null;i&&(this._decryptdata=i.getDecryptData(this.sn,t))}}return this._decryptdata}get end(){return this.start+this.duration}get endProgramDateTime(){if(this.programDateTime===null)return null;const e=M(this.duration)?this.duration:0;return this.programDateTime+e*1e3}get encrypted(){var e;if((e=this._decryptdata)!=null&&e.encrypted)return!0;if(this.levelkeys){var t;const s=Object.keys(this.levelkeys),i=s.length;if(i>1||i===1&&(t=this.levelkeys[s[0]])!=null&&t.encrypted)return!0}return!1}get programDateTime(){return this._programDateTime===null&&this.rawProgramDateTime&&(this.programDateTime=Date.parse(this.rawProgramDateTime)),this._programDateTime}set programDateTime(e){if(!M(e)){this._programDateTime=this.rawProgramDateTime=null;return}this._programDateTime=e}get ref(){return de(this)?(this._ref||(this._ref={base:this.base,start:this.start,duration:this.duration,sn:this.sn,programDateTime:this.programDateTime}),this._ref):null}addStart(e){this.setStart(this.start+e)}setStart(e){this.start=e,this._ref&&(this._ref.start=e)}setDuration(e){this.duration=e,this._ref&&(this._ref.duration=e)}setKeyFormat(e){const t=this.levelkeys;if(t){var s;const i=t[e];i&&!((s=this._decryptdata)!=null&&s.keyId)&&(this._decryptdata=i.getDecryptData(this.sn,t))}}abortRequests(){var e,t;(e=this.loader)==null||e.abort(),(t=this.keyLoader)==null||t.abort()}setElementaryStreamInfo(e,t,s,i,r,a=!1){const{elementaryStreams:o}=this,c=o[e];if(!c){o[e]={startPTS:t,endPTS:s,startDTS:i,endDTS:r,partial:a};return}c.startPTS=Math.min(c.startPTS,t),c.endPTS=Math.max(c.endPTS,s),c.startDTS=Math.min(c.startDTS,i),c.endDTS=Math.max(c.endDTS,r)}}class zl extends va{constructor(e,t,s,i,r){super(s),this.fragOffset=0,this.duration=0,this.gap=!1,this.independent=!1,this.relurl=void 0,this.fragment=void 0,this.index=void 0,this.duration=e.decimalFloatingPoint("DURATION"),this.gap=e.bool("GAP"),this.independent=e.bool("INDEPENDENT"),this.relurl=e.enumeratedString("URI"),this.fragment=t,this.index=i;const a=e.enumeratedString("BYTERANGE");a&&this.setByteRange(a,r),r&&(this.fragOffset=r.fragOffset+r.duration)}get start(){return this.fragment.start+this.fragOffset}get end(){return this.start+this.duration}get loaded(){const{elementaryStreams:e}=this;return!!(e.audio||e.video||e.audiovideo)}}function xa(n,e){const t=Object.getPrototypeOf(n);if(t){const s=Object.getOwnPropertyDescriptor(t,e);return s||xa(t,e)}}function Ql(n,e){const t=xa(n,e);t&&(t.enumerable=!0,Object.defineProperty(n,e,t))}const Nr=Math.pow(2,32)-1,Zl=[].push,Aa={video:1,audio:2,id3:3,text:4};function ge(n){return String.fromCharCode.apply(null,n)}function _a(n,e){const t=n[e]<<8|n[e+1];return t<0?65536+t:t}function Y(n,e){const t=Ia(n,e);return t<0?4294967296+t:t}function Br(n,e){let t=Y(n,e);return t*=Math.pow(2,32),t+=Y(n,e+4),t}function Ia(n,e){return n[e]<<24|n[e+1]<<16|n[e+2]<<8|n[e+3]}function Jl(n){const e=n.byteLength;for(let t=0;t<e;){const s=Y(n,t);if(s>8&&n[t+4]===109&&n[t+5]===111&&n[t+6]===111&&n[t+7]===102)return!0;t=s>1?t+s:e}return!1}function z(n,e){const t=[];if(!e.length)return t;const s=n.byteLength;for(let i=0;i<s;){const r=Y(n,i),a=ge(n.subarray(i+4,i+8)),o=r>1?i+r:s;if(a===e[0])if(e.length===1)t.push(n.subarray(i+8,o));else{const c=z(n.subarray(i+8,o),e.slice(1));c.length&&Zl.apply(t,c)}i=o}return t}function ec(n){const e=[],t=n[0];let s=8;const i=Y(n,s);s+=4;let r=0,a=0;t===0?(r=Y(n,s),a=Y(n,s+4),s+=8):(r=Br(n,s),a=Br(n,s+8),s+=16),s+=2;let o=n.length+a;const c=_a(n,s);s+=2;for(let l=0;l<c;l++){let h=s;const u=Y(n,h);h+=4;const d=u&2147483647;if((u&2147483648)>>>31===1)return ie.warn("SIDX has hierarchical references (not supported)"),null;const g=Y(n,h);h+=4,e.push({referenceSize:d,subsegmentDuration:g,info:{duration:g/i,start:o,end:o+d-1}}),o+=d,h+=4,s=h}return{earliestPresentationTime:r,timescale:i,version:t,referencesCount:c,references:e}}function La(n){const e=[],t=z(n,["moov","trak"]);for(let i=0;i<t.length;i++){const r=t[i],a=z(r,["tkhd"])[0];if(a){let o=a[0];const c=Y(a,o===0?12:20),l=z(r,["mdia","mdhd"])[0];if(l){o=l[0];const h=Y(l,o===0?12:20),u=z(r,["mdia","hdlr"])[0];if(u){const d=ge(u.subarray(8,12)),f={soun:ne.AUDIO,vide:ne.VIDEO}[d],g=z(r,["mdia","minf","stbl","stsd"])[0],p=tc(g);f?(e[c]={timescale:h,type:f,stsd:p},e[f]=se({timescale:h,id:c},p)):e[c]={timescale:h,type:d,stsd:p}}}}}return z(n,["moov","mvex","trex"]).forEach(i=>{const r=Y(i,4),a=e[r];a&&(a.default={duration:Y(i,12),flags:Y(i,20)})}),e}function tc(n){const e=n.subarray(8),t=e.subarray(86),s=ge(e.subarray(4,8));let i=s,r;const a=s==="enca"||s==="encv";if(a){const l=z(e,[s])[0].subarray(s==="enca"?28:78);z(l,["sinf"]).forEach(u=>{const d=z(u,["schm"])[0];if(d){const f=ge(d.subarray(4,8));if(f==="cbcs"||f==="cenc"){const g=z(u,["frma"])[0];g&&(i=ge(g))}}})}const o=i;switch(i){case"avc1":case"avc2":case"avc3":case"avc4":{const c=z(t,["avcC"])[0];c&&c.length>3&&(i+="."+Zt(c[1])+Zt(c[2])+Zt(c[3]),r=Qt(o==="avc1"?"dva1":"dvav",t));break}case"mp4a":{const c=z(e,[s])[0],l=z(c.subarray(28),["esds"])[0];if(l&&l.length>7){let h=4;if(l[h++]!==3)break;h=Xs(l,h),h+=2;const u=l[h++];if(u&128&&(h+=2),u&64&&(h+=l[h++]),l[h++]!==4)break;h=Xs(l,h);const d=l[h++];if(d===64)i+="."+Zt(d);else break;if(h+=12,l[h++]!==5)break;h=Xs(l,h);const f=l[h++];let g=(f&248)>>3;g===31&&(g+=1+((f&7)<<3)+((l[h]&224)>>5)),i+="."+g}break}case"hvc1":case"hev1":{const c=z(t,["hvcC"])[0];if(c&&c.length>12){const l=c[1],h=["","A","B","C"][l>>6],u=l&31,d=Y(c,2),f=(l&32)>>5?"H":"L",g=c[12],p=c.subarray(6,12);i+="."+h+u,i+="."+sc(d).toString(16).toUpperCase(),i+="."+f+g;let y="";for(let E=p.length;E--;){const T=p[E];(T||y)&&(y="."+T.toString(16).toUpperCase()+y)}i+=y}r=Qt(o=="hev1"?"dvhe":"dvh1",t);break}case"dvh1":case"dvhe":case"dvav":case"dva1":case"dav1":{i=Qt(i,t)||i;break}case"vp09":{const c=z(t,["vpcC"])[0];if(c&&c.length>6){const l=c[4],h=c[5],u=c[6]>>4&15;i+="."+Ke(l)+"."+Ke(h)+"."+Ke(u)}break}case"av01":{const c=z(t,["av1C"])[0];if(c&&c.length>2){const l=c[1]>>>5,h=c[1]&31,u=c[2]>>>7?"H":"M",d=(c[2]&64)>>6,f=(c[2]&32)>>5,g=l===2&&d?f?12:10:d?10:8,p=(c[2]&16)>>4,y=(c[2]&8)>>3,E=(c[2]&4)>>2,T=c[2]&3;i+="."+l+"."+Ke(h)+u+"."+Ke(g)+"."+p+"."+y+E+T+"."+Ke(1)+"."+Ke(1)+"."+Ke(1)+"."+0,r=Qt("dav1",t)}break}}return{codec:i,encrypted:a,supplemental:r}}function Qt(n,e){const t=z(e,["dvvC"]),s=t.length?t[0]:z(e,["dvcC"])[0];if(s){const i=s[2]>>1&127,r=s[2]<<5&32|s[3]>>3&31;return n+"."+Ke(i)+"."+Ke(r)}}function sc(n){let e=0;for(let t=0;t<32;t++)e|=(n>>t&1)<<31-t;return e>>>0}function Xs(n,e){const t=e+5;for(;n[e++]&128&&e<t;);return e}function Zt(n){return("0"+n.toString(16).toUpperCase()).slice(-2)}function Ke(n){return(n<10?"0":"")+n}function ic(n,e){if(!n||!e)return;const t=e.keyId;t&&e.isCommonEncryption&&Ra(n,(s,i)=>{const r=s.subarray(8,24);r.some(a=>a!==0)||(ie.log(`[eme] Patching keyId in 'enc${i?"a":"v"}>sinf>>tenc' box: ${Te(r)} -> ${Te(t)}`),s.set(t,8))})}function rc(n){const e=[];return Ra(n,t=>e.push(t.subarray(8,24))),e}function Ra(n,e){z(n,["moov","trak"]).forEach(s=>{const i=z(s,["mdia","minf","stbl","stsd"])[0];if(!i)return;const r=i.subarray(8);let a=z(r,["enca"]);const o=a.length>0;o||(a=z(r,["encv"])),a.forEach(c=>{const l=o?c.subarray(28):c.subarray(78);z(l,["sinf"]).forEach(u=>{const d=ba(u);d&&e(d,o)})})})}function ba(n){const e=z(n,["schm"])[0];if(e){const t=ge(e.subarray(4,8));if(t==="cbcs"||t==="cenc"){const s=z(n,["schi","tenc"])[0];if(s)return s}}}function nc(n,e,t){const s={},i=z(n,["moof","traf"]);for(let r=0;r<i.length;r++){const a=i[r],o=z(a,["tfhd"])[0],c=Y(o,4),l=e[c];if(!l)continue;s[c]||(s[c]={start:NaN,duration:0,sampleCount:0,timescale:l.timescale,type:l.type});const h=s[c],u=z(a,["tfdt"])[0];if(u){const S=u[0];let v=Y(u,4);S===1&&(v===Nr?t.warn("[mp4-demuxer]: Ignoring assumed invalid signed 64-bit track fragment decode time"):(v*=Nr+1,v+=Y(u,8))),M(v)&&(!M(h.start)||v<h.start)&&(h.start=v)}const d=l.default,f=Y(o,0)|(d==null?void 0:d.flags);let g=(d==null?void 0:d.duration)||0;f&8&&(f&2?g=Y(o,12):g=Y(o,8));const p=z(a,["trun"]);let y=h.start||0,E=0,T=g;for(let S=0;S<p.length;S++){const v=p[S],x=Y(v,4),D=h.sampleCount;h.sampleCount+=x;const A=v[3]&1,b=v[3]&4,I=v[2]&1,_=v[2]&2,C=v[2]&4,k=v[2]&8;let B=8,K=x;for(A&&(B+=4),b&&x&&(!(v[B+1]&1)&&h.keyFrameIndex===void 0&&(h.keyFrameIndex=D),B+=4,I?(T=Y(v,B),B+=4):T=g,_&&(B+=4),k&&(B+=4),y+=T,E+=T,K--);K--;)I?(T=Y(v,B),B+=4):T=g,_&&(B+=4),C&&(v[B+1]&1||h.keyFrameIndex===void 0&&(h.keyFrameIndex=h.sampleCount-(K+1),h.keyFrameStart=y),B+=4),k&&(B+=4),y+=T,E+=T;!E&&g&&(E+=g*x)}h.duration+=E}if(!Object.keys(s).some(r=>s[r].duration)){let r=1/0,a=0;const o=z(n,["sidx"]);for(let c=0;c<o.length;c++){const l=ec(o[c]);if(l!=null&&l.references){r=Math.min(r,l.earliestPresentationTime/l.timescale);const h=l.references.reduce((u,d)=>u+d.info.duration||0,0);a=Math.max(a,h+l.earliestPresentationTime/l.timescale)}}a&&M(a)&&Object.keys(s).forEach(c=>{s[c].duration||(s[c].duration=a*s[c].timescale-s[c].start)})}return s}function ac(n){const e={valid:null,remainder:null},t=z(n,["moof"]);if(t.length<2)return e.remainder=n,e;const s=t[t.length-1];return e.valid=n.slice(0,s.byteOffset-8),e.remainder=n.slice(s.byteOffset-8),e}function Oe(n,e){const t=new Uint8Array(n.length+e.length);return t.set(n),t.set(e,n.length),t}function Ur(n,e){const t=[],s=e.samples,i=e.timescale,r=e.id;let a=!1;return z(s,["moof"]).map(c=>{const l=c.byteOffset-8;z(c,["traf"]).map(u=>{const d=z(u,["tfdt"]).map(f=>{const g=f[0];let p=Y(f,4);return g===1&&(p*=Math.pow(2,32),p+=Y(f,8)),p/i})[0];return d!==void 0&&(n=d),z(u,["tfhd"]).map(f=>{const g=Y(f,4),p=Y(f,0)&16777215,y=(p&1)!==0,E=(p&2)!==0,T=(p&8)!==0;let S=0;const v=(p&16)!==0;let x=0;const D=(p&32)!==0;let A=8;g===r&&(y&&(A+=8),E&&(A+=4),T&&(S=Y(f,A),A+=4),v&&(x=Y(f,A),A+=4),D&&(A+=4),e.type==="video"&&(a=Gs(e.codec)),z(u,["trun"]).map(b=>{const I=b[0],_=Y(b,0)&16777215,C=(_&1)!==0;let k=0;const B=(_&4)!==0,K=(_&256)!==0;let $=0;const w=(_&512)!==0;let G=0;const N=(_&1024)!==0,V=(_&2048)!==0;let W=0;const O=Y(b,4);let F=8;C&&(k=Y(b,F),F+=4),B&&(F+=4);let j=k+l;for(let te=0;te<O;te++){if(K?($=Y(b,F),F+=4):$=S,w?(G=Y(b,F),F+=4):G=x,N&&(F+=4),V&&(I===0?W=Y(b,F):W=Ia(b,F),F+=4),e.type===ne.VIDEO){let X=0;for(;X<G;){const J=Y(s,j);if(j+=4,oc(a,s[j])){const ve=s.subarray(j,j+J);ji(ve,a?2:1,n+W/i,t)}j+=J,X+=J+4}}n+=$/i}}))})})}),t}function Gs(n){if(!n)return!1;const e=n.substring(0,4);return e==="hvc1"||e==="hev1"||e==="dvh1"||e==="dvhe"}function oc(n,e){if(n){const t=e>>1&63;return t===39||t===40}else return(e&31)===6}function ji(n,e,t,s){const i=Da(n);let r=0;r+=e;let a=0,o=0,c=0;for(;r<i.length;){a=0;do{if(r>=i.length)break;c=i[r++],a+=c}while(c===255);o=0;do{if(r>=i.length)break;c=i[r++],o+=c}while(c===255);const l=i.length-r;let h=r;if(o<l)r+=o;else if(o>l){ie.error(`Malformed SEI payload. ${o} is too small, only ${l} bytes left to parse.`);break}if(a===4){if(i[h++]===181){const d=_a(i,h);if(h+=2,d===49){const f=Y(i,h);if(h+=4,f===1195456820){const g=i[h++];if(g===3){const p=i[h++],y=31&p,E=64&p,T=E?2+y*3:0,S=new Uint8Array(T);if(E){S[0]=p;for(let v=1;v<T;v++)S[v]=i[h++]}s.push({type:g,payloadType:a,pts:t,bytes:S})}}}}}else if(a===5&&o>16){const u=[];for(let g=0;g<16;g++){const p=i[h++].toString(16);u.push(p.length==1?"0"+p:p),(g===3||g===5||g===7||g===9)&&u.push("-")}const d=o-16,f=new Uint8Array(d);for(let g=0;g<d;g++)f[g]=i[h++];s.push({payloadType:a,pts:t,uuid:u.join(""),userData:Ce(f),userDataBytes:f})}}}function Da(n){const e=n.byteLength,t=[];let s=1;for(;s<e-2;)n[s]===0&&n[s+1]===0&&n[s+2]===3?(t.push(s+2),s+=2):s++;if(t.length===0)return n;const i=e-t.length,r=new Uint8Array(i);let a=0;for(s=0;s<i;a++,s++)a===t[0]&&(a++,t.shift()),r[s]=n[a];return r}function lc(n){const e=n[0];let t="",s="",i=0,r=0,a=0,o=0,c=0,l=0;if(e===0){for(;ge(n.subarray(l,l+1))!=="\0";)t+=ge(n.subarray(l,l+1)),l+=1;for(t+=ge(n.subarray(l,l+1)),l+=1;ge(n.subarray(l,l+1))!=="\0";)s+=ge(n.subarray(l,l+1)),l+=1;s+=ge(n.subarray(l,l+1)),l+=1,i=Y(n,12),r=Y(n,16),o=Y(n,20),c=Y(n,24),l=28}else if(e===1){l+=4,i=Y(n,l),l+=4;const u=Y(n,l);l+=4;const d=Y(n,l);for(l+=4,a=2**32*u+d,Bl(a)||(a=Number.MAX_SAFE_INTEGER,ie.warn("Presentation time exceeds safe integer limit and wrapped to max safe integer in parsing emsg box")),o=Y(n,l),l+=4,c=Y(n,l),l+=4;ge(n.subarray(l,l+1))!=="\0";)t+=ge(n.subarray(l,l+1)),l+=1;for(t+=ge(n.subarray(l,l+1)),l+=1;ge(n.subarray(l,l+1))!=="\0";)s+=ge(n.subarray(l,l+1)),l+=1;s+=ge(n.subarray(l,l+1)),l+=1}const h=n.subarray(l,n.byteLength);return{schemeIdUri:t,value:s,timeScale:i,presentationTime:a,presentationTimeDelta:r,eventDuration:o,id:c,payload:h}}function cc(n,...e){const t=e.length;let s=8,i=t;for(;i--;)s+=e[i].byteLength;const r=new Uint8Array(s);for(r[0]=s>>24&255,r[1]=s>>16&255,r[2]=s>>8&255,r[3]=s&255,r.set(n,4),i=0,s=8;i<t;i++)r.set(e[i],s),s+=e[i].byteLength;return r}function hc(n,e,t){if(n.byteLength!==16)throw new RangeError("Invalid system id");let s,i;s=0,i=new Uint8Array;let r;s>0?(r=new Uint8Array(4),e.length>0&&new DataView(r.buffer).setUint32(0,e.length,!1)):r=new Uint8Array;const a=new Uint8Array(4);return t.byteLength>0&&new DataView(a.buffer).setUint32(0,t.byteLength,!1),cc([112,115,115,104],new Uint8Array([s,0,0,0]),n,r,i,a,t)}function uc(n){const e=[];if(n instanceof ArrayBuffer){const t=n.byteLength;let s=0;for(;s+32<t;){const i=new DataView(n,s),r=dc(i);e.push(r),s+=r.size}}return e}function dc(n){const e=n.getUint32(0),t=n.byteOffset,s=n.byteLength;if(s<e)return{offset:t,size:s};if(n.getUint32(4)!==1886614376)return{offset:t,size:e};const r=n.getUint32(8)>>>24;if(r!==0&&r!==1)return{offset:t,size:e};const a=n.buffer,o=Te(new Uint8Array(a,t+12,16));let c=null,l=null,h=0;if(r===0)h=28;else{const d=n.getUint32(28);if(!d||s<32+d*16)return{offset:t,size:e};c=[];for(let f=0;f<d;f++)c.push(new Uint8Array(a,t+32+f*16,16));h=32+d*16}if(!h)return{offset:t,size:e};const u=n.getUint32(h);return e-32<u?{offset:t,size:e}:(l=new Uint8Array(a,t+h+4,u),{version:r,systemId:o,kids:c,data:l,offset:t,size:e})}const Ca=()=>/\(Windows.+Firefox\//i.test(navigator.userAgent),Ct={audio:{a3ds:1,"ac-3":.95,"ac-4":1,alac:.9,alaw:1,dra1:1,"dts+":1,"dts-":1,dtsc:1,dtse:1,dtsh:1,"ec-3":.9,enca:1,fLaC:.9,flac:.9,FLAC:.9,g719:1,g726:1,m4ae:1,mha1:1,mha2:1,mhm1:1,mhm2:1,mlpa:1,mp4a:1,"raw ":1,Opus:1,opus:1,samr:1,sawb:1,sawp:1,sevc:1,sqcp:1,ssmv:1,twos:1,ulaw:1},video:{avc1:1,avc2:1,avc3:1,avc4:1,avcp:1,av01:.8,dav1:.8,drac:1,dva1:1,dvav:1,dvh1:.7,dvhe:.7,encv:1,hev1:.75,hvc1:.75,mjp2:1,mp4v:1,mvc1:1,mvc2:1,mvc3:1,mvc4:1,resv:1,rv60:1,s263:1,svc1:1,svc2:1,"vc-1":1,vp08:1,vp09:.9},text:{stpp:1,wvtt:1}};function Xi(n,e){const t=Ct[e];return!!t&&!!t[n.slice(0,4)]}function $t(n,e,t=!0){return!n.split(",").some(s=>!zi(s,e,t))}function zi(n,e,t=!0){var s;const i=at(t);return(s=i==null?void 0:i.isTypeSupported(Gt(n,e)))!=null?s:!1}function Gt(n,e){return`${e}/mp4;codecs=${n}`}function $r(n){if(n){const e=n.substring(0,4);return Ct.video[e]}return 2}function bs(n){const e=Ca();return n.split(",").reduce((t,s)=>{const r=e&&Gs(s)?9:Ct.video[s];return r?(r*2+t)/(t?3:2):(Ct.audio[s]+t)/(t?2:1)},0)}const zs={};function fc(n,e=!0){if(zs[n])return zs[n];const t={flac:["flac","fLaC","FLAC"],opus:["opus","Opus"],"mp4a.40.34":["mp3"]}[n];for(let i=0;i<t.length;i++){var s;if(zi(t[i],"audio",e))return zs[n]=t[i],t[i];if(t[i]==="mp3"&&(s=at(e))!=null&&s.isTypeSupported("audio/mpeg"))return""}return n}const gc=/flac|opus|mp4a\.40\.34/i;function Ds(n,e=!0){return n.replace(gc,t=>fc(t.toLowerCase(),e))}function mc(n,e){const t=[];if(n){const s=n.split(",");for(let i=0;i<s.length;i++)Xi(s[i],"video")||t.push(s[i])}return e&&t.push(e),t.join(",")}function ms(n,e){if(n&&(n.length>4||["ac-3","ec-3","alac","fLaC","Opus"].indexOf(n)!==-1)&&(Gr(n,"audio")||Gr(n,"video")))return n;if(e){const t=e.split(",");if(t.length>1){if(n){for(let s=t.length;s--;)if(t[s].substring(0,4)===n.substring(0,4))return t[s]}return t[0]}}return e||n}function Gr(n,e){return Xi(n,e)&&zi(n,e)}function pc(n){const e=n.split(",");for(let t=0;t<e.length;t++){const s=e[t].split(".");s.length>2&&s[0]==="avc1"&&(e[t]=`avc1.${parseInt(s[1]).toString(16)}${("000"+parseInt(s[2]).toString(16)).slice(-4)}`)}return e.join(",")}function yc(n){if(n.startsWith("av01.")){const e=n.split("."),t=["0","111","01","01","01","0"];for(let s=e.length;s>4&&s<10;s++)e[s]=t[s-4];return e.join(".")}return n}function Kr(n){const e=at(n)||{isTypeSupported:()=>!1};return{mpeg:e.isTypeSupported("audio/mpeg"),mp3:e.isTypeSupported('audio/mp4; codecs="mp3"'),ac3:e.isTypeSupported('audio/mp4; codecs="ac-3"')}}function Ii(n){return n.replace(/^.+codecs=["']?([^"']+).*$/,"$1")}const Ec={supported:!0,powerEfficient:!0,smooth:!0},Tc={supported:!1,smooth:!1,powerEfficient:!1},Pa={supported:!0,configurations:[],decodingInfoResults:[Ec]};function ka(n,e){return{supported:!1,configurations:e,decodingInfoResults:[Tc],error:n}}function Sc(n,e,t,s,i,r){const a=n.videoCodec,o=n.audioCodec?n.audioGroups:null,c=r==null?void 0:r.audioCodec,l=r==null?void 0:r.channels,h=l?parseInt(l):c?1/0:2;let u=null;if(o!=null&&o.length)try{o.length===1&&o[0]?u=e.groups[o[0]].channels:u=o.reduce((d,f)=>{if(f){const g=e.groups[f];if(!g)throw new Error(`Audio track group ${f} not found`);Object.keys(g.channels).forEach(p=>{d[p]=(d[p]||0)+g.channels[p]})}return d},{2:0})}catch{return!0}return a!==void 0&&(a.split(",").some(d=>Gs(d))||n.width>1920&&n.height>1088||n.height>1920&&n.width>1088||n.frameRate>Math.max(s,30)||n.videoRange!=="SDR"&&n.videoRange!==t||n.bitrate>Math.max(i,8e6))||!!u&&M(h)&&Object.keys(u).some(d=>parseInt(d)>h)}function wa(n,e,t,s={}){const i=n.videoCodec;if(!i&&!n.audioCodec||!t)return Promise.resolve(Pa);const r=[],a=vc(n),o=a.length,c=xc(n,e,o>0),l=c.length;for(let h=o||1*l||1;h--;){const u={type:"media-source"};if(o&&(u.video=a[h%o]),l){u.audio=c[h%l];const d=u.audio.bitrate;u.video&&d&&(u.video.bitrate-=d)}r.push(u)}if(i){const h=navigator.userAgent;if(i.split(",").some(u=>Gs(u))&&Ca())return Promise.resolve(ka(new Error(`Overriding Windows Firefox HEVC MediaCapabilities result based on user-agent string: (${h})`),r))}return Promise.all(r.map(h=>{const u=_c(h);return s[u]||(s[u]=t.decodingInfo(h))})).then(h=>({supported:!h.some(u=>!u.supported),configurations:r,decodingInfoResults:h})).catch(h=>({supported:!1,configurations:r,decodingInfoResults:[],error:h}))}function vc(n){var e;const t=(e=n.videoCodec)==null?void 0:e.split(","),s=Oa(n),i=n.width||640,r=n.height||480,a=n.frameRate||30,o=n.videoRange.toLowerCase();return t?t.map(c=>{const l={contentType:Gt(yc(c),"video"),width:i,height:r,bitrate:s,framerate:a};return o!=="sdr"&&(l.transferFunction=o),l}):[]}function xc(n,e,t){var s;const i=(s=n.audioCodec)==null?void 0:s.split(","),r=Oa(n);return i&&n.audioGroups?n.audioGroups.reduce((a,o)=>{var c;const l=o?(c=e.groups[o])==null?void 0:c.tracks:null;return l?l.reduce((h,u)=>{if(u.groupId===o){const d=parseFloat(u.channels||"");i.forEach(f=>{const g={contentType:Gt(f,"audio"),bitrate:t?Ac(f,r):r};d&&(g.channels=""+d),h.push(g)})}return h},a):a},[]):[]}function Ac(n,e){if(e<=1)return 1;let t=128e3;return n==="ec-3"?t=768e3:n==="ac-3"&&(t=64e4),Math.min(e/2,t)}function Oa(n){return Math.ceil(Math.max(n.bitrate*.9,n.averageBitrate)/1e3)*1e3||1}function _c(n){let e="";const{audio:t,video:s}=n;if(s){const i=Ii(s.contentType);e+=`${i}_r${s.height}x${s.width}f${Math.ceil(s.framerate)}${s.transferFunction||"sd"}_${Math.ceil(s.bitrate/1e5)}`}if(t){const i=Ii(t.contentType);e+=`${s?"_":""}${i}_c${t.channels}`}return e}const Li=["NONE","TYPE-0","TYPE-1",null];function Ic(n){return Li.indexOf(n)>-1}const Cs=["SDR","PQ","HLG"];function Lc(n){return!!n&&Cs.indexOf(n)>-1}var ps={No:"",Yes:"YES",v2:"v2"};function Vr(n){const{canSkipUntil:e,canSkipDateRanges:t,age:s}=n,i=s<e/2;return e&&i?t?ps.v2:ps.Yes:ps.No}class Hr{constructor(e,t,s){this.msn=void 0,this.part=void 0,this.skip=void 0,this.msn=e,this.part=t,this.skip=s}addDirectives(e){const t=new self.URL(e);return this.msn!==void 0&&t.searchParams.set("_HLS_msn",this.msn.toString()),this.part!==void 0&&t.searchParams.set("_HLS_part",this.part.toString()),this.skip&&t.searchParams.set("_HLS_skip",this.skip),t.href}}class Kt{constructor(e){if(this._attrs=void 0,this.audioCodec=void 0,this.bitrate=void 0,this.codecSet=void 0,this.url=void 0,this.frameRate=void 0,this.height=void 0,this.id=void 0,this.name=void 0,this.supplemental=void 0,this.videoCodec=void 0,this.width=void 0,this.details=void 0,this.fragmentError=0,this.loadError=0,this.loaded=void 0,this.realBitrate=0,this.supportedPromise=void 0,this.supportedResult=void 0,this._avgBitrate=0,this._audioGroups=void 0,this._subtitleGroups=void 0,this._urlId=0,this.url=[e.url],this._attrs=[e.attrs],this.bitrate=e.bitrate,e.details&&(this.details=e.details),this.id=e.id||0,this.name=e.name,this.width=e.width||0,this.height=e.height||0,this.frameRate=e.attrs.optionalFloat("FRAME-RATE",0),this._avgBitrate=e.attrs.decimalInteger("AVERAGE-BANDWIDTH"),this.audioCodec=e.audioCodec,this.videoCodec=e.videoCodec,this.codecSet=[e.videoCodec,e.audioCodec].filter(s=>!!s).map(s=>s.substring(0,4)).join(","),"supplemental"in e){var t;this.supplemental=e.supplemental;const s=(t=e.supplemental)==null?void 0:t.videoCodec;s&&s!==e.videoCodec&&(this.codecSet+=`,${s.substring(0,4)}`)}this.addGroupId("audio",e.attrs.AUDIO),this.addGroupId("text",e.attrs.SUBTITLES)}get maxBitrate(){return Math.max(this.realBitrate,this.bitrate)}get averageBitrate(){return this._avgBitrate||this.realBitrate||this.bitrate}get attrs(){return this._attrs[0]}get codecs(){return this.attrs.CODECS||""}get pathwayId(){return this.attrs["PATHWAY-ID"]||"."}get videoRange(){return this.attrs["VIDEO-RANGE"]||"SDR"}get score(){return this.attrs.optionalFloat("SCORE",0)}get uri(){return this.url[0]||""}hasAudioGroup(e){return Wr(this._audioGroups,e)}hasSubtitleGroup(e){return Wr(this._subtitleGroups,e)}get audioGroups(){return this._audioGroups}get subtitleGroups(){return this._subtitleGroups}addGroupId(e,t){if(t){if(e==="audio"){let s=this._audioGroups;s||(s=this._audioGroups=[]),s.indexOf(t)===-1&&s.push(t)}else if(e==="text"){let s=this._subtitleGroups;s||(s=this._subtitleGroups=[]),s.indexOf(t)===-1&&s.push(t)}}}get urlId(){return 0}set urlId(e){}get audioGroupIds(){return this.audioGroups?[this.audioGroupId]:void 0}get textGroupIds(){return this.subtitleGroups?[this.textGroupId]:void 0}get audioGroupId(){var e;return(e=this.audioGroups)==null?void 0:e[0]}get textGroupId(){var e;return(e=this.subtitleGroups)==null?void 0:e[0]}addFallback(){}}function Wr(n,e){return!e||!n?!1:n.indexOf(e)!==-1}function Rc(){if(typeof matchMedia=="function"){const n=matchMedia("(dynamic-range: high)"),e=matchMedia("bad query");if(n.media!==e.media)return n.matches===!0}return!1}function bc(n,e){let t=!1,s=[];if(n&&(t=n!=="SDR",s=[n]),e){s=e.allowedVideoRanges||Cs.slice(0);const i=s.join("")!=="SDR"&&!e.videoCodec;t=e.preferHDR!==void 0?e.preferHDR:i&&Rc(),t||(s=["SDR"])}return{preferHDR:t,allowedVideoRanges:s}}const Dc=n=>{const e=new WeakSet;return(t,s)=>{if(n&&(s=n(t,s)),typeof s=="object"&&s!==null){if(e.has(s))return;e.add(s)}return s}},oe=(n,e)=>JSON.stringify(n,Dc(e));function Cc(n,e,t,s,i){const r=Object.keys(n),a=s==null?void 0:s.channels,o=s==null?void 0:s.audioCodec,c=i==null?void 0:i.videoCodec,l=a&&parseInt(a)===2;let h=!1,u=!1,d=1/0,f=1/0,g=1/0,p=1/0,y=0,E=[];const{preferHDR:T,allowedVideoRanges:S}=bc(e,i);for(let b=r.length;b--;){const I=n[r[b]];h||(h=I.channels[2]>0),d=Math.min(d,I.minHeight),f=Math.min(f,I.minFramerate),g=Math.min(g,I.minBitrate),S.filter(C=>I.videoRanges[C]>0).length>0&&(u=!0)}d=M(d)?d:0,f=M(f)?f:0;const v=Math.max(1080,d),x=Math.max(30,f);g=M(g)?g:t,t=Math.max(g,t),u||(e=void 0);const D=r.length>1;return{codecSet:r.reduce((b,I)=>{const _=n[I];if(I===b)return b;if(E=u?S.filter(C=>_.videoRanges[C]>0):[],D){if(_.minBitrate>t)return $e(I,`min bitrate of ${_.minBitrate} > current estimate of ${t}`),b;if(!_.hasDefaultAudio)return $e(I,"no renditions with default or auto-select sound found"),b;if(o&&I.indexOf(o.substring(0,4))%5!==0)return $e(I,`audio codec preference "${o}" not found`),b;if(a&&!l){if(!_.channels[a])return $e(I,`no renditions with ${a} channel sound found (channels options: ${Object.keys(_.channels)})`),b}else if((!o||l)&&h&&_.channels[2]===0)return $e(I,"no renditions with stereo sound found"),b;if(_.minHeight>v)return $e(I,`min resolution of ${_.minHeight} > maximum of ${v}`),b;if(_.minFramerate>x)return $e(I,`min framerate of ${_.minFramerate} > maximum of ${x}`),b;if(!E.some(C=>_.videoRanges[C]>0))return $e(I,`no variants with VIDEO-RANGE of ${oe(E)} found`),b;if(c&&I.indexOf(c.substring(0,4))%5!==0)return $e(I,`video codec preference "${c}" not found`),b;if(_.maxScore<y)return $e(I,`max score of ${_.maxScore} < selected max of ${y}`),b}return b&&(bs(I)>=bs(b)||_.fragmentError>n[b].fragmentError)?b:(p=_.minIndex,y=_.maxScore,I)},void 0),videoRanges:E,preferHDR:T,minFramerate:f,minBitrate:g,minIndex:p}}function $e(n,e){ie.log(`[abr] start candidates with "${n}" ignored because ${e}`)}function Fa(n){return n.reduce((e,t)=>{let s=e.groups[t.groupId];s||(s=e.groups[t.groupId]={tracks:[],channels:{2:0},hasDefault:!1,hasAutoSelect:!1}),s.tracks.push(t);const i=t.channels||"2";return s.channels[i]=(s.channels[i]||0)+1,s.hasDefault=s.hasDefault||t.default,s.hasAutoSelect=s.hasAutoSelect||t.autoselect,s.hasDefault&&(e.hasDefaultAudio=!0),s.hasAutoSelect&&(e.hasAutoSelectAudio=!0),e},{hasDefaultAudio:!1,hasAutoSelectAudio:!1,groups:{}})}function Pc(n,e,t,s){return n.slice(t,s+1).reduce((i,r,a)=>{if(!r.codecSet)return i;const o=r.audioGroups;let c=i[r.codecSet];c||(i[r.codecSet]=c={minBitrate:1/0,minHeight:1/0,minFramerate:1/0,minIndex:a,maxScore:0,videoRanges:{SDR:0},channels:{2:0},hasDefaultAudio:!o,fragmentError:0}),c.minBitrate=Math.min(c.minBitrate,r.bitrate);const l=Math.min(r.height,r.width);return c.minHeight=Math.min(c.minHeight,l),c.minFramerate=Math.min(c.minFramerate,r.frameRate),c.minIndex=Math.min(c.minIndex,a),c.maxScore=Math.max(c.maxScore,r.score),c.fragmentError+=r.fragmentError,c.videoRanges[r.videoRange]=(c.videoRanges[r.videoRange]||0)+1,o&&o.forEach(h=>{if(!h)return;const u=e.groups[h];u&&(c.hasDefaultAudio=c.hasDefaultAudio||e.hasDefaultAudio?u.hasDefault:u.hasAutoSelect||!e.hasDefaultAudio&&!e.hasAutoSelectAudio,Object.keys(u.channels).forEach(d=>{c.channels[d]=(c.channels[d]||0)+u.channels[d]}))}),i},{})}function Yr(n){if(!n)return n;const{lang:e,assocLang:t,characteristics:s,channels:i,audioCodec:r}=n;return{lang:e,assocLang:t,characteristics:s,channels:i,audioCodec:r}}function He(n,e,t){if("attrs"in n){const s=e.indexOf(n);if(s!==-1)return s}for(let s=0;s<e.length;s++){const i=e[s];if(gt(n,i,t))return s}return-1}function gt(n,e,t){const{groupId:s,name:i,lang:r,assocLang:a,default:o}=n,c=n.forced;return(s===void 0||e.groupId===s)&&(i===void 0||e.name===i)&&(r===void 0||kc(r,e.lang))&&(r===void 0||e.assocLang===a)&&(o===void 0||e.default===o)&&(c===void 0||e.forced===c)&&(!("characteristics"in n)||wc(n.characteristics||"",e.characteristics))&&(t===void 0||t(n,e))}function kc(n,e="--"){return n.length===e.length?n===e:n.startsWith(e)||e.startsWith(n)}function wc(n,e=""){const t=n.split(","),s=e.split(",");return t.length===s.length&&!t.some(i=>s.indexOf(i)===-1)}function ft(n,e){const{audioCodec:t,channels:s}=n;return(t===void 0||(e.audioCodec||"").substring(0,4)===t.substring(0,4))&&(s===void 0||s===(e.channels||"2"))}function Oc(n,e,t,s,i){const r=e[s],o=e.reduce((d,f,g)=>{const p=f.uri;return(d[p]||(d[p]=[])).push(g),d},{})[r.uri];o.length>1&&(s=Math.max.apply(Math,o));const c=r.videoRange,l=r.frameRate,h=r.codecSet.substring(0,4),u=qr(e,s,d=>{if(d.videoRange!==c||d.frameRate!==l||d.codecSet.substring(0,4)!==h)return!1;const f=d.audioGroups,g=t.filter(p=>!f||f.indexOf(p.groupId)!==-1);return He(n,g,i)>-1});return u>-1?u:qr(e,s,d=>{const f=d.audioGroups,g=t.filter(p=>!f||f.indexOf(p.groupId)!==-1);return He(n,g,i)>-1})}function qr(n,e,t){for(let s=e;s>-1;s--)if(t(n[s]))return s;for(let s=e+1;s<n.length;s++)if(t(n[s]))return s;return-1}function Ps(n,e){var t;return!!n&&n!==((t=e.loadLevelObj)==null?void 0:t.uri)}class Fc extends Fe{constructor(e){super("abr",e.logger),this.hls=void 0,this.lastLevelLoadSec=0,this.lastLoadedFragLevel=-1,this.firstSelection=-1,this._nextAutoLevel=-1,this.nextAutoLevelKey="",this.audioTracksByGroup=null,this.codecTiers=null,this.timer=-1,this.fragCurrent=null,this.partCurrent=null,this.bitrateTestDelay=0,this.rebufferNotice=-1,this.supportedCache={},this.bwEstimator=void 0,this._abandonRulesCheck=t=>{var s;const{fragCurrent:i,partCurrent:r,hls:a}=this,{autoLevelEnabled:o,media:c}=a;if(!i||!c)return;const l=performance.now(),h=r?r.stats:i.stats,u=r?r.duration:i.duration,d=l-h.loading.start,f=a.minAutoLevel,g=i.level,p=this._nextAutoLevel;if(h.aborted||h.loaded&&h.loaded===h.total||g<=f){this.clearTimer(),this._nextAutoLevel=-1;return}if(!o)return;const y=p>-1&&p!==g,E=!!t||y;if(!E&&(c.paused||!c.playbackRate||!c.readyState))return;const T=a.mainForwardBufferInfo;if(!E&&T===null)return;const S=this.bwEstimator.getEstimateTTFB(),v=Math.abs(c.playbackRate);if(d<=Math.max(S,1e3*(u/(v*2))))return;const x=T?T.len/v:0,D=h.loading.first?h.loading.first-h.loading.start:-1,A=h.loaded&&D>-1,b=this.getBwEstimate(),I=a.levels,_=I[g],C=Math.max(h.loaded,Math.round(u*(i.bitrate||_.averageBitrate)/8));let k=A?d-D:d;k<1&&A&&(k=Math.min(d,h.loaded*8/b));const B=A?h.loaded*1e3/k:0,K=S/1e3,$=B?(C-h.loaded)/B:C*8/b+K;if($<=x)return;const w=B?B*8:b,G=((s=(t==null?void 0:t.details)||this.hls.latestLevelDetails)==null?void 0:s.live)===!0,N=this.hls.config.abrBandWidthUpFactor;let V=Number.POSITIVE_INFINITY,W;for(W=g-1;W>f;W--){const te=I[W].maxBitrate,X=!I[W].details||G;if(V=this.getTimeToLoadFrag(K,w,u*te,X),V<Math.min(x,u+K))break}if(V>=$||V>u*10)return;A?this.bwEstimator.sample(d-Math.min(S,D),h.loaded):this.bwEstimator.sampleTTFB(d);const O=I[W].maxBitrate;this.getBwEstimate()*N>O&&this.resetEstimator(O);const F=this.findBestLevel(O,f,W,0,x,1,1);F>-1&&(W=F),this.warn(`Fragment ${i.sn}${r?" part "+r.index:""} of level ${g} is loading too slowly;
22590 Fragment duration: ${i.duration.toFixed(3)}
226226- Time to underbuffer: ${A.toFixed(3)} s
9191+ Time to underbuffer: ${x.toFixed(3)} s
22792 Estimated load time for current fragment: ${$.toFixed(3)} s
228228- Estimated load time for down switch fragment: ${K.toFixed(3)} s
9393+ Estimated load time for down switch fragment: ${V.toFixed(3)} s
22994 TTFB estimate: ${D|0} ms
23095 Current BW estimate: ${M(b)?b|0:"Unknown"} bps
23196 New BW estimate: ${this.getBwEstimate()|0} bps
232232- Switching to level ${Y} @ ${w|0} bps`),n.nextLoadLevel=n.nextAutoLevel=Y,this.clearTimer();const j=()=>{if(this.clearTimer(),this.fragCurrent===i&&this.hls.loadLevel===Y&&Y>0){const ee=this.getStarvationDelay();if(this.warn(`Aborting inflight request ${Y>0?"and switching down":""}
9797+ Switching to level ${W} @ ${O|0} bps`),a.nextLoadLevel=a.nextAutoLevel=W,this.clearTimer();const j=()=>{if(this.clearTimer(),this.fragCurrent===i&&this.hls.loadLevel===W&&W>0){const te=this.getStarvationDelay();if(this.warn(`Aborting inflight request ${W>0?"and switching down":""}
23398 Fragment duration: ${i.duration.toFixed(3)} s
234234- Time to underbuffer: ${ee.toFixed(3)} s`),i.abortRequests(),this.fragCurrent=this.partCurrent=null,Y>f){let X=this.findBestLevel(this.hls.levels[f].bitrate,f,Y,0,ee,1,1);X===-1&&(X=f),this.hls.nextLoadLevel=this.hls.nextAutoLevel=X,this.resetEstimator(this.hls.levels[X].bitrate)}}};p||$>K*2?j():this.timer=self.setInterval(j,K*1e3),n.trigger(m.FRAG_LOAD_EMERGENCY_ABORTED,{frag:i,part:r,stats:h})},this.hls=e,this.bwEstimator=this.initEstimator(),this.registerListeners()}resetEstimator(e){e&&(this.log(`setting initial bwe to ${e}`),this.hls.config.abrEwmaDefaultEstimate=e),this.firstSelection=-1,this.bwEstimator=this.initEstimator()}initEstimator(){const e=this.hls.config;return new so(e.abrEwmaSlowVoD,e.abrEwmaFastVoD,e.abrEwmaDefaultEstimate)}registerListeners(){const{hls:e}=this;e.on(m.MANIFEST_LOADING,this.onManifestLoading,this),e.on(m.FRAG_LOADING,this.onFragLoading,this),e.on(m.FRAG_LOADED,this.onFragLoaded,this),e.on(m.FRAG_BUFFERED,this.onFragBuffered,this),e.on(m.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(m.LEVEL_LOADED,this.onLevelLoaded,this),e.on(m.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(m.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.on(m.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e&&(e.off(m.MANIFEST_LOADING,this.onManifestLoading,this),e.off(m.FRAG_LOADING,this.onFragLoading,this),e.off(m.FRAG_LOADED,this.onFragLoaded,this),e.off(m.FRAG_BUFFERED,this.onFragBuffered,this),e.off(m.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(m.LEVEL_LOADED,this.onLevelLoaded,this),e.off(m.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(m.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.off(m.ERROR,this.onError,this))}destroy(){this.unregisterListeners(),this.clearTimer(),this.hls=this._abandonRulesCheck=this.supportedCache=null,this.fragCurrent=this.partCurrent=null}onManifestLoading(e,t){this.lastLoadedFragLevel=-1,this.firstSelection=-1,this.lastLevelLoadSec=0,this.supportedCache={},this.fragCurrent=this.partCurrent=null,this.onLevelsUpdated(),this.clearTimer()}onLevelsUpdated(){this.lastLoadedFragLevel>-1&&this.fragCurrent&&(this.lastLoadedFragLevel=this.fragCurrent.level),this._nextAutoLevel=-1,this.onMaxAutoLevelUpdated(),this.codecTiers=null,this.audioTracksByGroup=null}onMaxAutoLevelUpdated(){this.firstSelection=-1,this.nextAutoLevelKey=""}onFragLoading(e,t){const s=t.frag;if(!this.ignoreFragment(s)){if(!s.bitrateTest){var i;this.fragCurrent=s,this.partCurrent=(i=t.part)!=null?i:null}this.clearTimer(),this.timer=self.setInterval(this._abandonRulesCheck,100)}}onLevelSwitching(e,t){this.clearTimer()}onError(e,t){if(!t.fatal)switch(t.details){case R.BUFFER_ADD_CODEC_ERROR:case R.BUFFER_APPEND_ERROR:this.lastLoadedFragLevel=-1,this.firstSelection=-1;break;case R.FRAG_LOAD_TIMEOUT:{const s=t.frag,{fragCurrent:i,partCurrent:r}=this;if(s&&i&&s.sn===i.sn&&s.level===i.level){const n=performance.now(),o=r?r.stats:s.stats,c=n-o.loading.start,l=o.loading.first?o.loading.first-o.loading.start:-1;if(o.loaded&&l>-1){const d=this.bwEstimator.getEstimateTTFB();this.bwEstimator.sample(c-Math.min(d,l),o.loaded)}else this.bwEstimator.sampleTTFB(c)}break}}}getTimeToLoadFrag(e,t,s,i){const r=e+s/t,n=i?e+this.lastLevelLoadSec:0;return r+n}onLevelLoaded(e,t){const s=this.hls.config,{loading:i}=t.stats,r=i.end-i.first;M(r)&&(this.lastLevelLoadSec=r/1e3),t.details.live?this.bwEstimator.update(s.abrEwmaSlowLive,s.abrEwmaFastLive):this.bwEstimator.update(s.abrEwmaSlowVoD,s.abrEwmaFastVoD),this.timer>-1&&this._abandonRulesCheck(t.levelInfo)}onFragLoaded(e,{frag:t,part:s}){const i=s?s.stats:t.stats;if(t.type===B.MAIN&&this.bwEstimator.sampleTTFB(i.loading.first-i.loading.start),!this.ignoreFragment(t)){if(this.clearTimer(),t.level===this._nextAutoLevel&&(this._nextAutoLevel=-1),this.firstSelection=-1,this.hls.config.abrMaxWithRealBitrate){const r=s?s.duration:t.duration,n=this.hls.levels[t.level],o=(n.loaded?n.loaded.bytes:0)+i.loaded,c=(n.loaded?n.loaded.duration:0)+r;n.loaded={bytes:o,duration:c},n.realBitrate=Math.round(8*o/c)}if(t.bitrateTest){const r={stats:i,frag:t,part:s,id:t.type};this.onFragBuffered(m.FRAG_BUFFERED,r),t.bitrateTest=!1}else this.lastLoadedFragLevel=t.level}}onFragBuffered(e,t){const{frag:s,part:i}=t,r=i!=null&&i.stats.loaded?i.stats:s.stats;if(r.aborted||this.ignoreFragment(s))return;const n=r.parsing.end-r.loading.start-Math.min(r.loading.first-r.loading.start,this.bwEstimator.getEstimateTTFB());this.bwEstimator.sample(n,r.loaded),r.bwEstimate=this.getBwEstimate(),s.bitrateTest?this.bitrateTestDelay=n/1e3:this.bitrateTestDelay=0}ignoreFragment(e){return e.type!==B.MAIN||e.sn==="initSegment"}clearTimer(){this.timer>-1&&(self.clearInterval(this.timer),this.timer=-1)}get firstAutoLevel(){const{maxAutoLevel:e,minAutoLevel:t}=this.hls,s=this.getBwEstimate(),i=this.hls.config.maxStarvationDelay,r=this.findBestLevel(s,t,e,0,i,1,1);if(r>-1)return r;const n=this.hls.firstLevel,o=Math.min(Math.max(n,t),e);return this.warn(`Could not find best starting auto level. Defaulting to first in playlist ${n} clamped to ${o}`),o}get forcedAutoLevel(){return this.nextAutoLevelKey?-1:this._nextAutoLevel}get nextAutoLevel(){const e=this.forcedAutoLevel,s=this.bwEstimator.canEstimate(),i=this.lastLoadedFragLevel>-1;if(e!==-1&&(!s||!i||this.nextAutoLevelKey===this.getAutoLevelKey()))return e;const r=s&&i?this.getNextABRAutoLevel():this.firstAutoLevel;if(e!==-1){const n=this.hls.levels;if(n.length>Math.max(e,r)&&n[e].loadError<=n[r].loadError)return e}return this._nextAutoLevel=r,this.nextAutoLevelKey=this.getAutoLevelKey(),r}getAutoLevelKey(){return`${this.getBwEstimate()}_${this.getStarvationDelay().toFixed(2)}`}getNextABRAutoLevel(){const{fragCurrent:e,partCurrent:t,hls:s}=this;if(s.levels.length<=1)return s.loadLevel;const{maxAutoLevel:i,config:r,minAutoLevel:n}=s,o=t?t.duration:e?e.duration:0,c=this.getBwEstimate(),l=this.getStarvationDelay();let h=r.abrBandWidthFactor,d=r.abrBandWidthUpFactor;if(l){const p=this.findBestLevel(c,n,i,l,0,h,d);if(p>=0)return this.rebufferNotice=-1,p}let u=o?Math.min(o,r.maxStarvationDelay):r.maxStarvationDelay;if(!l){const p=this.bitrateTestDelay;p&&(u=(o?Math.min(o,r.maxLoadingDelay):r.maxLoadingDelay)-p,this.info(`bitrate test took ${Math.round(1e3*p)}ms, set first fragment max fetchDuration to ${Math.round(1e3*u)} ms`),h=d=1)}const f=this.findBestLevel(c,n,i,l,u,h,d);if(this.rebufferNotice!==f&&(this.rebufferNotice=f,this.info(`${l?"rebuffering expected":"buffer is empty"}, optimal quality level ${f}`)),f>-1)return f;const g=s.levels[n],y=s.loadLevelObj;return y&&(g==null?void 0:g.bitrate)<y.bitrate?n:s.loadLevel}getStarvationDelay(){const e=this.hls,t=e.media;if(!t)return 1/0;const s=t&&t.playbackRate!==0?Math.abs(t.playbackRate):1,i=e.mainForwardBufferInfo;return(i?i.len:0)/s}getBwEstimate(){return this.bwEstimator.canEstimate()?this.bwEstimator.getEstimate():this.hls.config.abrEwmaDefaultEstimate}findBestLevel(e,t,s,i,r,n,o){var c;const l=i+r,h=this.lastLoadedFragLevel,d=h===-1?this.hls.firstLevel:h,{fragCurrent:u,partCurrent:f}=this,{levels:g,allAudioTracks:y,loadLevel:p,config:E}=this.hls;if(g.length===1)return 0;const T=g[d],S=!!((c=this.hls.latestLevelDetails)!=null&&c.live),v=p===-1||h===-1;let A,D="SDR",x=(T==null?void 0:T.frameRate)||0;const{audioPreference:b,videoPreference:_}=E,I=this.audioTracksByGroup||(this.audioTracksByGroup=Mn(y));let P=-1;if(v){if(this.firstSelection!==-1)return this.firstSelection;const k=this.codecTiers||(this.codecTiers=jo(g,I,t,s)),G=qo(k,D,e,b,_),{codecSet:N,videoRanges:K,minFramerate:Y,minBitrate:w,minIndex:O,preferHDR:j}=G;P=O,A=N,D=j?K[K.length-1]:K[0],x=Y,e=Math.max(e,w),this.log(`picked start tier ${ne(G)}`)}else A=T==null?void 0:T.codecSet,D=T==null?void 0:T.videoRange;const F=f?f.duration:u?u.duration:0,U=this.bwEstimator.getEstimateTTFB()/1e3,H=[];for(let k=s;k>=t;k--){var $;const G=g[k],N=k>d;if(!G)continue;if(E.useMediaCapabilities&&!G.supportedResult&&!G.supportedPromise){const X=navigator.mediaCapabilities;typeof(X==null?void 0:X.decodingInfo)=="function"&&No(G,I,D,x,e,b)?(G.supportedPromise=On(G,I,X,this.supportedCache),G.supportedPromise.then(Z=>{if(!this.hls)return;G.supportedResult=Z;const ye=this.hls.levels,fe=ye.indexOf(G);Z.error?this.warn(`MediaCapabilities decodingInfo error: "${Z.error}" for level ${fe} ${ne(Z)}`):Z.supported?Z.decodingInfoResults.some(_e=>_e.smooth===!1||_e.powerEfficient===!1)&&this.log(`MediaCapabilities decodingInfo for level ${fe} not smooth or powerEfficient: ${ne(Z)}`):(this.warn(`Unsupported MediaCapabilities decodingInfo result for level ${fe} ${ne(Z)}`),fe>-1&&ye.length>1&&(this.log(`Removing unsupported level ${fe}`),this.hls.removeLevel(fe),this.hls.loadLevel===-1&&(this.hls.nextLoadLevel=0)))}).catch(Z=>{this.warn(`Error handling MediaCapabilities decodingInfo: ${Z}`)})):G.supportedResult=kn}if((A&&G.codecSet!==A||D&&G.videoRange!==D||N&&x>G.frameRate||!N&&x>0&&x<G.frameRate||($=G.supportedResult)!=null&&($=$.decodingInfoResults)!=null&&$.some(X=>X.smooth===!1))&&(!v||k!==P)){H.push(k);continue}const K=G.details,Y=(f?K==null?void 0:K.partTarget:K==null?void 0:K.averagetargetduration)||F;let w;N?w=o*e:w=n*e;const O=F&&i>=F*2&&r===0?G.averageBitrate:G.maxBitrate,j=this.getTimeToLoadFrag(U,w,O*Y,K===void 0);if(w>=O&&(k===h||G.loadError===0&&G.fragmentError===0)&&(j<=U||!M(j)||S&&!this.bitrateTestDelay||j<l)){const X=this.forcedAutoLevel;return k!==p&&(X===-1||X!==p)&&(H.length&&this.trace(`Skipped level(s) ${H.join(",")} of ${s} max with CODECS and VIDEO-RANGE:"${g[H[0]].codecs}" ${g[H[0]].videoRange}; not compatible with "${A}" ${D}`),this.info(`switch candidate:${d}->${k} adjustedbw(${Math.round(w)})-bitrate=${Math.round(w-O)} ttfb:${U.toFixed(1)} avgDuration:${Y.toFixed(1)} maxFetchDuration:${l.toFixed(1)} fetchDuration:${j.toFixed(1)} firstSelection:${v} codecSet:${G.codecSet} videoRange:${G.videoRange} hls.loadLevel:${p}`)),v&&(this.firstSelection=k),k}}return-1}set nextAutoLevel(e){const t=this.deriveNextAutoLevel(e);this._nextAutoLevel!==t&&(this.nextAutoLevelKey="",this._nextAutoLevel=t)}deriveNextAutoLevel(e){const{maxAutoLevel:t,minAutoLevel:s}=this.hls;return Math.min(Math.max(e,s),t)}}const Nn={search:function(a,e){let t=0,s=a.length-1,i=null,r=null;for(;t<=s;){i=(t+s)/2|0,r=a[i];const n=e(r);if(n>0)t=i+1;else if(n<0)s=i-1;else return r}return null}};function Jo(a,e,t){if(e===null||!Array.isArray(a)||!a.length||!M(e))return null;const s=a[0].programDateTime;if(e<(s||0))return null;const i=a[a.length-1].endProgramDateTime;if(e>=(i||0))return null;for(let r=0;r<a.length;++r){const n=a[r];if(tl(e,t,n))return n}return null}function gt(a,e,t=0,s=0,i=.005){let r=null;if(a){r=e[1+a.sn-e[0].sn]||null;const o=a.endDTS-t;o>0&&o<15e-7&&(t+=15e-7),r&&a.level!==r.level&&r.end<=a.end&&(r=e[2+a.sn-e[0].sn]||null)}else t===0&&e[0].start===0&&(r=e[0]);if(r&&((!a||a.level===r.level)&&fr(t,s,r)===0||el(r,a,Math.min(i,s))))return r;const n=Nn.search(e,fr.bind(null,t,s));return n&&(n!==a||!r)?n:r}function el(a,e,t){if(e&&e.start===0&&e.level<a.level&&(e.endPTS||0)>0){const s=e.tagList.reduce((i,r)=>(r[0]==="INF"&&(i+=parseFloat(r[1])),i),t);return a.start<=s}return!1}function fr(a=0,e=0,t){if(t.start<=a&&t.start+t.duration>a)return 0;const s=Math.min(e,t.duration+(t.deltaPTS?t.deltaPTS:0));return t.start+t.duration-s<=a?1:t.start-s>a&&t.start?-1:0}function tl(a,e,t){const s=Math.min(e,t.duration+(t.deltaPTS?t.deltaPTS:0))*1e3;return(t.endProgramDateTime||0)-s>a}function Bn(a,e,t){if(a&&a.startCC<=e&&a.endCC>=e){let s=a.fragments;const{fragmentHint:i}=a;i&&(s=s.concat(i));let r;return Nn.search(s,n=>n.cc<e?1:n.cc>e?-1:(r=n,n.end<=t?1:n.start>t?-1:0)),r||null}return null}function xs(a){switch(a.details){case R.FRAG_LOAD_TIMEOUT:case R.KEY_LOAD_TIMEOUT:case R.LEVEL_LOAD_TIMEOUT:case R.MANIFEST_LOAD_TIMEOUT:return!0}return!1}function Un(a){return a.details.startsWith("key")}function $n(a){return Un(a)&&!!a.frag&&!a.frag.decryptdata}function gr(a,e){const t=xs(e);return a.default[`${t?"timeout":"error"}Retry`]}function Di(a,e){const t=a.backoff==="linear"?1:Math.pow(2,e);return Math.min(t*a.retryDelayMs,a.maxRetryDelayMs)}function mr(a){return te(te({},a),{errorRetry:null,timeoutRetry:null})}function As(a,e,t,s){if(!a)return!1;const i=s==null?void 0:s.code,r=e<a.maxNumRetry&&(sl(i)||!!t);return a.shouldRetry?a.shouldRetry(a,e,t,s,r):r}function sl(a){return li(a)||!!a&&(a<400||a>499)}function li(a){return a===0&&navigator.onLine===!1}var ge={DoNothing:0,SendAlternateToPenaltyBox:2,RemoveAlternatePermanently:3,RetryRequest:5},Ie={None:0,MoveAllAlternatesMatchingHost:1,MoveAllAlternatesMatchingHDCP:2,MoveAllAlternatesMatchingKey:4};class il extends we{constructor(e){super("error-controller",e.logger),this.hls=void 0,this.playlistError=0,this.hls=e,this.registerListeners()}registerListeners(){const e=this.hls;e.on(m.ERROR,this.onError,this),e.on(m.MANIFEST_LOADING,this.onManifestLoading,this),e.on(m.LEVEL_UPDATED,this.onLevelUpdated,this)}unregisterListeners(){const e=this.hls;e&&(e.off(m.ERROR,this.onError,this),e.off(m.ERROR,this.onErrorOut,this),e.off(m.MANIFEST_LOADING,this.onManifestLoading,this),e.off(m.LEVEL_UPDATED,this.onLevelUpdated,this))}destroy(){this.unregisterListeners(),this.hls=null}startLoad(e){}stopLoad(){this.playlistError=0}getVariantLevelIndex(e){return(e==null?void 0:e.type)===B.MAIN?e.level:this.getVariantIndex()}getVariantIndex(){var e;const t=this.hls,s=t.currentLevel;return(e=t.loadLevelObj)!=null&&e.details||s===-1?t.loadLevel:s}variantHasKey(e,t){if(e){var s;if((s=e.details)!=null&&s.hasKey(t))return!0;const i=e.audioGroups;if(i)return this.hls.allAudioTracks.filter(n=>i.indexOf(n.groupId)>=0).some(n=>{var o;return(o=n.details)==null?void 0:o.hasKey(t)})}return!1}onManifestLoading(){this.playlistError=0}onLevelUpdated(){this.playlistError=0}onError(e,t){var s;if(t.fatal)return;const i=this.hls,r=t.context;switch(t.details){case R.FRAG_LOAD_ERROR:case R.FRAG_LOAD_TIMEOUT:case R.KEY_LOAD_ERROR:case R.KEY_LOAD_TIMEOUT:t.errorAction=this.getFragRetryOrSwitchAction(t);return;case R.FRAG_PARSING_ERROR:if((s=t.frag)!=null&&s.gap){t.errorAction=It();return}case R.FRAG_GAP:case R.FRAG_DECRYPT_ERROR:{t.errorAction=this.getFragRetryOrSwitchAction(t),t.errorAction.action=ge.SendAlternateToPenaltyBox;return}case R.LEVEL_EMPTY_ERROR:case R.LEVEL_PARSING_ERROR:{var n;const c=t.parent===B.MAIN?t.level:i.loadLevel;t.details===R.LEVEL_EMPTY_ERROR&&((n=t.context)!=null&&(n=n.levelDetails)!=null&&n.live)?t.errorAction=this.getPlaylistRetryOrSwitchAction(t,c):(t.levelRetry=!1,t.errorAction=this.getLevelSwitchAction(t,c))}return;case R.LEVEL_LOAD_ERROR:case R.LEVEL_LOAD_TIMEOUT:typeof(r==null?void 0:r.level)=="number"&&(t.errorAction=this.getPlaylistRetryOrSwitchAction(t,r.level));return;case R.AUDIO_TRACK_LOAD_ERROR:case R.AUDIO_TRACK_LOAD_TIMEOUT:case R.SUBTITLE_LOAD_ERROR:case R.SUBTITLE_TRACK_LOAD_TIMEOUT:if(r){const c=i.loadLevelObj;if(c&&(r.type===Q.AUDIO_TRACK&&c.hasAudioGroup(r.groupId)||r.type===Q.SUBTITLE_TRACK&&c.hasSubtitleGroup(r.groupId))){t.errorAction=this.getPlaylistRetryOrSwitchAction(t,i.loadLevel),t.errorAction.action=ge.SendAlternateToPenaltyBox,t.errorAction.flags=Ie.MoveAllAlternatesMatchingHost;return}}return;case R.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:t.errorAction={action:ge.SendAlternateToPenaltyBox,flags:Ie.MoveAllAlternatesMatchingHDCP};return;case R.KEY_SYSTEM_SESSION_UPDATE_FAILED:case R.KEY_SYSTEM_STATUS_INTERNAL_ERROR:case R.KEY_SYSTEM_NO_SESSION:t.errorAction={action:ge.SendAlternateToPenaltyBox,flags:Ie.MoveAllAlternatesMatchingKey};return;case R.BUFFER_ADD_CODEC_ERROR:case R.REMUX_ALLOC_ERROR:case R.BUFFER_APPEND_ERROR:if(!t.errorAction){var o;t.errorAction=this.getLevelSwitchAction(t,(o=t.level)!=null?o:i.loadLevel)}return;case R.INTERNAL_EXCEPTION:case R.BUFFER_APPENDING_ERROR:case R.BUFFER_FULL_ERROR:case R.LEVEL_SWITCH_ERROR:case R.BUFFER_STALLED_ERROR:case R.BUFFER_SEEK_OVER_HOLE:case R.BUFFER_NUDGE_ON_STALL:t.errorAction=It();return}t.type===V.KEY_SYSTEM_ERROR&&(t.levelRetry=!1,t.errorAction=It())}getPlaylistRetryOrSwitchAction(e,t){const s=this.hls,i=gr(s.config.playlistLoadPolicy,e),r=this.playlistError++;if(As(i,r,xs(e),e.response))return{action:ge.RetryRequest,flags:Ie.None,retryConfig:i,retryCount:r};const o=this.getLevelSwitchAction(e,t);return i&&(o.retryConfig=i,o.retryCount=r),o}getFragRetryOrSwitchAction(e){const t=this.hls,s=this.getVariantLevelIndex(e.frag),i=t.levels[s],{fragLoadPolicy:r,keyLoadPolicy:n}=t.config,o=gr(Un(e)?n:r,e),c=t.levels.reduce((h,d)=>h+d.fragmentError,0);if(i&&(e.details!==R.FRAG_GAP&&i.fragmentError++,!$n(e)&&As(o,c,xs(e),e.response)))return{action:ge.RetryRequest,flags:Ie.None,retryConfig:o,retryCount:c};const l=this.getLevelSwitchAction(e,s);return o&&(l.retryConfig=o,l.retryCount=c),l}getLevelSwitchAction(e,t){const s=this.hls;t==null&&(t=s.loadLevel);const i=this.hls.levels[t];if(i){var r,n;const l=e.details;i.loadError++,l===R.BUFFER_APPEND_ERROR&&i.fragmentError++;let h=-1;const{levels:d,loadLevel:u,minAutoLevel:f,maxAutoLevel:g}=s;!s.autoLevelEnabled&&!s.config.preserveManualLevelOnError&&(s.loadLevel=-1);const y=(r=e.frag)==null?void 0:r.type,E=(y===B.AUDIO&&l===R.FRAG_PARSING_ERROR||e.sourceBufferName==="audio"&&(l===R.BUFFER_ADD_CODEC_ERROR||l===R.BUFFER_APPEND_ERROR))&&d.some(({audioCodec:D})=>i.audioCodec!==D),S=e.sourceBufferName==="video"&&(l===R.BUFFER_ADD_CODEC_ERROR||l===R.BUFFER_APPEND_ERROR)&&d.some(({codecSet:D,audioCodec:x})=>i.codecSet!==D&&i.audioCodec===x),{type:v,groupId:A}=(n=e.context)!=null?n:{};for(let D=d.length;D--;){const x=(D+u)%d.length;if(x!==u&&x>=f&&x<=g&&d[x].loadError===0){var o,c;const b=d[x];if(l===R.FRAG_GAP&&y===B.MAIN&&e.frag){const _=d[x].details;if(_){const I=gt(e.frag,_.fragments,e.frag.start);if(I!=null&&I.gap)continue}}else{if(v===Q.AUDIO_TRACK&&b.hasAudioGroup(A)||v===Q.SUBTITLE_TRACK&&b.hasSubtitleGroup(A))continue;if(y===B.AUDIO&&(o=i.audioGroups)!=null&&o.some(_=>b.hasAudioGroup(_))||y===B.SUBTITLE&&(c=i.subtitleGroups)!=null&&c.some(_=>b.hasSubtitleGroup(_))||E&&i.audioCodec===b.audioCodec||S&&i.codecSet===b.codecSet||!E&&i.codecSet!==b.codecSet)continue}h=x;break}}if(h>-1&&s.loadLevel!==h)return e.levelRetry=!0,this.playlistError=0,{action:ge.SendAlternateToPenaltyBox,flags:Ie.None,nextAutoLevel:h}}return{action:ge.SendAlternateToPenaltyBox,flags:Ie.MoveAllAlternatesMatchingHost}}onErrorOut(e,t){var s;switch((s=t.errorAction)==null?void 0:s.action){case ge.DoNothing:break;case ge.SendAlternateToPenaltyBox:this.sendAlternateToPenaltyBox(t),!t.errorAction.resolved&&t.details!==R.FRAG_GAP?t.fatal=!0:/MediaSource readyState: ended/.test(t.error.message)&&(this.warn(`MediaSource ended after "${t.sourceBufferName}" sourceBuffer append error. Attempting to recover from media error.`),this.hls.recoverMediaError());break}if(t.fatal){this.hls.stopLoad();return}}sendAlternateToPenaltyBox(e){const t=this.hls,s=e.errorAction;if(!s)return;const{flags:i}=s,r=s.nextAutoLevel;switch(i){case Ie.None:this.switchLevel(e,r);break;case Ie.MoveAllAlternatesMatchingHDCP:{const c=this.getVariantLevelIndex(e.frag),l=t.levels[c],h=l==null?void 0:l.attrs["HDCP-LEVEL"];if(s.hdcpLevel=h,h==="NONE")this.warn("HDCP policy resticted output with HDCP-LEVEL=NONE");else if(h){t.maxHdcpLevel=oi[oi.indexOf(h)-1],s.resolved=!0,this.warn(`Restricting playback to HDCP-LEVEL of "${t.maxHdcpLevel}" or lower`);break}}case Ie.MoveAllAlternatesMatchingKey:{const c=e.decryptdata;if(c){const l=this.hls.levels,h=l.length;for(let u=h;u--;)if(this.variantHasKey(l[u],c)){var n,o;this.log(`Banned key found in level ${u} (${l[u].bitrate}bps) or audio group "${(n=l[u].audioGroups)==null?void 0:n.join(",")}" (${(o=e.frag)==null?void 0:o.type} fragment) ${me(c.keyId||[])}`),l[u].fragmentError++,l[u].loadError++,this.log(`Removing level ${u} with key error (${e.error})`),this.hls.removeLevel(u)}const d=e.frag;if(this.hls.levels.length<h)s.resolved=!0;else if(d&&d.type!==B.MAIN){const u=d.decryptdata;u&&!c.matches(u)&&(s.resolved=!0)}}break}}s.resolved||this.switchLevel(e,r)}switchLevel(e,t){if(t!==void 0&&e.errorAction&&(this.warn(`switching to level ${t} after ${e.details}`),this.hls.nextAutoLevel=t,e.errorAction.resolved=!0,this.hls.nextLoadLevel=this.hls.nextAutoLevel,e.details===R.BUFFER_ADD_CODEC_ERROR&&e.mimeType&&e.sourceBufferName!=="audiovideo")){const s=ai(e.mimeType),i=this.hls.levels;for(let r=i.length;r--;)i[r][`${e.sourceBufferName}Codec`]===s&&(this.log(`Removing level ${r} for ${e.details} ("${s}" not supported)`),this.hls.removeLevel(r))}}}function It(a){const e={action:ge.DoNothing,flags:Ie.None};return a&&(e.resolved=!0),e}var de={NOT_LOADED:"NOT_LOADED",APPENDING:"APPENDING",PARTIAL:"PARTIAL",OK:"OK"};class rl{constructor(e){this.activePartLists=Object.create(null),this.endListFragments=Object.create(null),this.fragments=Object.create(null),this.timeRanges=Object.create(null),this.bufferPadding=.2,this.hls=void 0,this.hasGaps=!1,this.hls=e,this._registerListeners()}_registerListeners(){const{hls:e}=this;e&&(e.on(m.MANIFEST_LOADING,this.onManifestLoading,this),e.on(m.BUFFER_APPENDED,this.onBufferAppended,this),e.on(m.FRAG_BUFFERED,this.onFragBuffered,this),e.on(m.FRAG_LOADED,this.onFragLoaded,this))}_unregisterListeners(){const{hls:e}=this;e&&(e.off(m.MANIFEST_LOADING,this.onManifestLoading,this),e.off(m.BUFFER_APPENDED,this.onBufferAppended,this),e.off(m.FRAG_BUFFERED,this.onFragBuffered,this),e.off(m.FRAG_LOADED,this.onFragLoaded,this))}destroy(){this._unregisterListeners(),this.hls=this.fragments=this.activePartLists=this.endListFragments=this.timeRanges=null}getAppendedFrag(e,t){const s=this.activePartLists[t];if(s)for(let i=s.length;i--;){const r=s[i];if(!r)break;if(r.start<=e&&e<=r.end&&r.loaded)return r}return this.getBufferedFrag(e,t)}getBufferedFrag(e,t){return this.getFragAtPos(e,t,!0)}getFragAtPos(e,t,s){const{fragments:i}=this,r=Object.keys(i);for(let n=r.length;n--;){const o=i[r[n]];if((o==null?void 0:o.body.type)===t&&(!s||o.buffered)){const c=o.body;if(c.start<=e&&e<=c.end)return c}}return null}detectEvictedFragments(e,t,s,i,r){this.timeRanges&&(this.timeRanges[e]=t);const n=(i==null?void 0:i.fragment.sn)||-1;Object.keys(this.fragments).forEach(o=>{const c=this.fragments[o];if(!c||n>=c.body.sn)return;if(!c.buffered&&(!c.loaded||r)){c.body.type===s&&this.removeFragment(c.body);return}const l=c.range[e];if(l){if(l.time.length===0){this.removeFragment(c.body);return}l.time.some(h=>{const d=!this.isTimeBuffered(h.startPTS,h.endPTS,t);return d&&this.removeFragment(c.body),d})}})}detectPartialFragments(e){const t=this.timeRanges;if(!t||e.frag.sn==="initSegment")return;const s=e.frag,i=yt(s),r=this.fragments[i];if(!r||r.buffered&&s.gap)return;const n=!s.relurl;Object.keys(t).forEach(o=>{const c=s.elementaryStreams[o];if(!c)return;const l=t[o],h=n||c.partial===!0;r.range[o]=this.getBufferedTimes(s,e.part,h,l)}),r.loaded=null,Object.keys(r.range).length?(this.bufferedEnd(r,s),jt(r)||this.removeParts(s.sn-1,s.type)):this.removeFragment(r.body)}bufferedEnd(e,t){e.buffered=!0,(e.body.endList=t.endList||e.body.endList)&&(this.endListFragments[e.body.type]=e)}removeParts(e,t){const s=this.activePartLists[t];s&&(this.activePartLists[t]=pr(s,i=>i.fragment.sn>=e))}fragBuffered(e,t){const s=yt(e);let i=this.fragments[s];!i&&t&&(i=this.fragments[s]={body:e,appendedPTS:null,loaded:null,buffered:!1,range:Object.create(null)},e.gap&&(this.hasGaps=!0)),i&&(i.loaded=null,this.bufferedEnd(i,e))}getBufferedTimes(e,t,s,i){const r={time:[],partial:s},n=e.start,o=e.end,c=e.minEndPTS||o,l=e.maxStartPTS||n;for(let h=0;h<i.length;h++){const d=i.start(h)-this.bufferPadding,u=i.end(h)+this.bufferPadding;if(l>=d&&c<=u){r.time.push({startPTS:Math.max(n,i.start(h)),endPTS:Math.min(o,i.end(h))});break}else if(n<u&&o>d){const f=Math.max(n,i.start(h)),g=Math.min(o,i.end(h));g>f&&(r.partial=!0,r.time.push({startPTS:f,endPTS:g}))}else if(o<=d)break}return r}getPartialFragment(e){let t=null,s,i,r,n=0;const{bufferPadding:o,fragments:c}=this;return Object.keys(c).forEach(l=>{const h=c[l];h&&jt(h)&&(i=h.body.start-o,r=h.body.end+o,e>=i&&e<=r&&(s=Math.min(e-i,r-e),n<=s&&(t=h.body,n=s)))}),t}isEndListAppended(e){const t=this.endListFragments[e];return t!==void 0&&(t.buffered||jt(t))}getState(e){const t=yt(e),s=this.fragments[t];return s?s.buffered?jt(s)?de.PARTIAL:de.OK:de.APPENDING:de.NOT_LOADED}isTimeBuffered(e,t,s){let i,r;for(let n=0;n<s.length;n++){if(i=s.start(n)-this.bufferPadding,r=s.end(n)+this.bufferPadding,e>=i&&t<=r)return!0;if(t<=i)return!1}return!1}onManifestLoading(){this.removeAllFragments()}onFragLoaded(e,t){if(t.frag.sn==="initSegment"||t.frag.bitrateTest)return;const s=t.frag,i=t.part?null:t,r=yt(s);this.fragments[r]={body:s,appendedPTS:null,loaded:i,buffered:!1,range:Object.create(null)}}onBufferAppended(e,t){const{frag:s,part:i,timeRanges:r,type:n}=t;if(s.sn==="initSegment")return;const o=s.type;if(i){let l=this.activePartLists[o];l||(this.activePartLists[o]=l=[]),l.push(i)}this.timeRanges=r;const c=r[n];this.detectEvictedFragments(n,c,o,i)}onFragBuffered(e,t){this.detectPartialFragments(t)}hasFragment(e){const t=yt(e);return!!this.fragments[t]}hasFragments(e){const{fragments:t}=this,s=Object.keys(t);if(!e)return s.length>0;for(let i=s.length;i--;){const r=t[s[i]];if((r==null?void 0:r.body.type)===e)return!0}return!1}hasParts(e){var t;return!!((t=this.activePartLists[e])!=null&&t.length)}removeFragmentsInRange(e,t,s,i,r){i&&!this.hasGaps||Object.keys(this.fragments).forEach(n=>{const o=this.fragments[n];if(!o)return;const c=o.body;c.type!==s||i&&!c.gap||c.start<t&&c.end>e&&(o.buffered||r)&&this.removeFragment(c)})}removeFragment(e){const t=yt(e);e.clearElementaryStreamInfo();const s=this.activePartLists[e.type];if(s){const i=e.sn;this.activePartLists[e.type]=pr(s,r=>r.fragment.sn!==i)}delete this.fragments[t],e.endList&&delete this.endListFragments[e.type]}removeAllFragments(){var e;this.fragments=Object.create(null),this.endListFragments=Object.create(null),this.activePartLists=Object.create(null),this.hasGaps=!1;const t=(e=this.hls)==null||(e=e.latestLevelDetails)==null?void 0:e.partList;t&&t.forEach(s=>s.clearElementaryStreamInfo())}}function jt(a){var e,t,s;return a.buffered&&!!(a.body.gap||(e=a.range.video)!=null&&e.partial||(t=a.range.audio)!=null&&t.partial||(s=a.range.audiovideo)!=null&&s.partial)}function yt(a){return`${a.type}_${a.level}_${a.sn}`}function pr(a,e){return a.filter(t=>{const s=e(t);return s||t.clearElementaryStreamInfo(),s})}var nt={cbc:0,ctr:1};class nl{constructor(e,t,s){this.subtle=void 0,this.aesIV=void 0,this.aesMode=void 0,this.subtle=e,this.aesIV=t,this.aesMode=s}decrypt(e,t){switch(this.aesMode){case nt.cbc:return this.subtle.decrypt({name:"AES-CBC",iv:this.aesIV},t,e);case nt.ctr:return this.subtle.decrypt({name:"AES-CTR",counter:this.aesIV,length:64},t,e);default:throw new Error(`[AESCrypto] invalid aes mode ${this.aesMode}`)}}}function al(a){const e=a.byteLength,t=e&&new DataView(a.buffer).getUint8(e-1);return t?a.slice(0,e-t):a}class ol{constructor(){this.rcon=[0,1,2,4,8,16,32,64,128,27,54],this.subMix=[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)],this.invSubMix=[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)],this.sBox=new Uint32Array(256),this.invSBox=new Uint32Array(256),this.key=new Uint32Array(0),this.ksRows=0,this.keySize=0,this.keySchedule=void 0,this.invKeySchedule=void 0,this.initTable()}uint8ArrayToUint32Array_(e){const t=new DataView(e),s=new Uint32Array(4);for(let i=0;i<4;i++)s[i]=t.getUint32(i*4);return s}initTable(){const e=this.sBox,t=this.invSBox,s=this.subMix,i=s[0],r=s[1],n=s[2],o=s[3],c=this.invSubMix,l=c[0],h=c[1],d=c[2],u=c[3],f=new Uint32Array(256);let g=0,y=0,p=0;for(p=0;p<256;p++)p<128?f[p]=p<<1:f[p]=p<<1^283;for(p=0;p<256;p++){let E=y^y<<1^y<<2^y<<3^y<<4;E=E>>>8^E&255^99,e[g]=E,t[E]=g;const T=f[g],S=f[T],v=f[S];let A=f[E]*257^E*16843008;i[g]=A<<24|A>>>8,r[g]=A<<16|A>>>16,n[g]=A<<8|A>>>24,o[g]=A,A=v*16843009^S*65537^T*257^g*16843008,l[E]=A<<24|A>>>8,h[E]=A<<16|A>>>16,d[E]=A<<8|A>>>24,u[E]=A,g?(g=T^f[f[f[v^T]]],y^=f[f[y]]):g=y=1}}expandKey(e){const t=this.uint8ArrayToUint32Array_(e);let s=!0,i=0;for(;i<t.length&&s;)s=t[i]===this.key[i],i++;if(s)return;this.key=t;const r=this.keySize=t.length;if(r!==4&&r!==6&&r!==8)throw new Error("Invalid aes key size="+r);const n=this.ksRows=(r+6+1)*4;let o,c;const l=this.keySchedule=new Uint32Array(n),h=this.invKeySchedule=new Uint32Array(n),d=this.sBox,u=this.rcon,f=this.invSubMix,g=f[0],y=f[1],p=f[2],E=f[3];let T,S;for(o=0;o<n;o++){if(o<r){T=l[o]=t[o];continue}S=T,o%r===0?(S=S<<8|S>>>24,S=d[S>>>24]<<24|d[S>>>16&255]<<16|d[S>>>8&255]<<8|d[S&255],S^=u[o/r|0]<<24):r>6&&o%r===4&&(S=d[S>>>24]<<24|d[S>>>16&255]<<16|d[S>>>8&255]<<8|d[S&255]),l[o]=T=(l[o-r]^S)>>>0}for(c=0;c<n;c++)o=n-c,c&3?S=l[o]:S=l[o-4],c<4||o<=4?h[c]=S:h[c]=g[d[S>>>24]]^y[d[S>>>16&255]]^p[d[S>>>8&255]]^E[d[S&255]],h[c]=h[c]>>>0}networkToHostOrderSwap(e){return e<<24|(e&65280)<<8|(e&16711680)>>8|e>>>24}decrypt(e,t,s){const i=this.keySize+6,r=this.invKeySchedule,n=this.invSBox,o=this.invSubMix,c=o[0],l=o[1],h=o[2],d=o[3],u=this.uint8ArrayToUint32Array_(s);let f=u[0],g=u[1],y=u[2],p=u[3];const E=new Int32Array(e),T=new Int32Array(E.length);let S,v,A,D,x,b,_,I,P,F,U,H,$,k;const G=this.networkToHostOrderSwap;for(;t<E.length;){for(P=G(E[t]),F=G(E[t+1]),U=G(E[t+2]),H=G(E[t+3]),x=P^r[0],b=H^r[1],_=U^r[2],I=F^r[3],$=4,k=1;k<i;k++)S=c[x>>>24]^l[b>>16&255]^h[_>>8&255]^d[I&255]^r[$],v=c[b>>>24]^l[_>>16&255]^h[I>>8&255]^d[x&255]^r[$+1],A=c[_>>>24]^l[I>>16&255]^h[x>>8&255]^d[b&255]^r[$+2],D=c[I>>>24]^l[x>>16&255]^h[b>>8&255]^d[_&255]^r[$+3],x=S,b=v,_=A,I=D,$=$+4;S=n[x>>>24]<<24^n[b>>16&255]<<16^n[_>>8&255]<<8^n[I&255]^r[$],v=n[b>>>24]<<24^n[_>>16&255]<<16^n[I>>8&255]<<8^n[x&255]^r[$+1],A=n[_>>>24]<<24^n[I>>16&255]<<16^n[x>>8&255]<<8^n[b&255]^r[$+2],D=n[I>>>24]<<24^n[x>>16&255]<<16^n[b>>8&255]<<8^n[_&255]^r[$+3],T[t]=G(S^f),T[t+1]=G(D^g),T[t+2]=G(A^y),T[t+3]=G(v^p),f=P,g=F,y=U,p=H,t=t+4}return T.buffer}}class ll{constructor(e,t,s){this.subtle=void 0,this.key=void 0,this.aesMode=void 0,this.subtle=e,this.key=t,this.aesMode=s}expandKey(){const e=cl(this.aesMode);return this.subtle.importKey("raw",this.key,{name:e},!1,["encrypt","decrypt"])}}function cl(a){switch(a){case nt.cbc:return"AES-CBC";case nt.ctr:return"AES-CTR";default:throw new Error(`[FastAESKey] invalid aes mode ${a}`)}}const hl=16;class Ci{constructor(e,{removePKCS7Padding:t=!0}={}){if(this.logEnabled=!0,this.removePKCS7Padding=void 0,this.subtle=null,this.softwareDecrypter=null,this.key=null,this.fastAesKey=null,this.remainderData=null,this.currentIV=null,this.currentResult=null,this.useSoftware=void 0,this.enableSoftwareAES=void 0,this.enableSoftwareAES=e.enableSoftwareAES,this.removePKCS7Padding=t,t)try{const s=self.crypto;s&&(this.subtle=s.subtle||s.webkitSubtle)}catch{}this.useSoftware=!this.subtle}destroy(){this.subtle=null,this.softwareDecrypter=null,this.key=null,this.fastAesKey=null,this.remainderData=null,this.currentIV=null,this.currentResult=null}isSync(){return this.useSoftware}flush(){const{currentResult:e,remainderData:t}=this;if(!e||t)return this.reset(),null;const s=new Uint8Array(e);return this.reset(),this.removePKCS7Padding?al(s):s}reset(){this.currentResult=null,this.currentIV=null,this.remainderData=null,this.softwareDecrypter&&(this.softwareDecrypter=null)}decrypt(e,t,s,i){return this.useSoftware?new Promise((r,n)=>{const o=ArrayBuffer.isView(e)?e:new Uint8Array(e);this.softwareDecrypt(o,t,s,i);const c=this.flush();c?r(c.buffer):n(new Error("[softwareDecrypt] Failed to decrypt data"))}):this.webCryptoDecrypt(new Uint8Array(e),t,s,i)}softwareDecrypt(e,t,s,i){const{currentIV:r,currentResult:n,remainderData:o}=this;if(i!==nt.cbc||t.byteLength!==16)return se.warn("SoftwareDecrypt: can only handle AES-128-CBC"),null;this.logOnce("JS AES decrypt"),o&&(e=ke(o,e),this.remainderData=null);const c=this.getValidChunk(e);if(!c.length)return null;r&&(s=r);let l=this.softwareDecrypter;l||(l=this.softwareDecrypter=new ol),l.expandKey(t);const h=n;return this.currentResult=l.decrypt(c.buffer,0,s),this.currentIV=c.slice(-16).buffer,h||null}webCryptoDecrypt(e,t,s,i){if(this.key!==t||!this.fastAesKey){if(!this.subtle)return Promise.resolve(this.onWebCryptoError(e,t,s,i));this.key=t,this.fastAesKey=new ll(this.subtle,t,i)}return this.fastAesKey.expandKey().then(r=>this.subtle?(this.logOnce("WebCrypto AES decrypt"),new nl(this.subtle,new Uint8Array(s),i).decrypt(e.buffer,r)):Promise.reject(new Error("web crypto not initialized"))).catch(r=>(se.warn(`[decrypter]: WebCrypto Error, disable WebCrypto API, ${r.name}: ${r.message}`),this.onWebCryptoError(e,t,s,i)))}onWebCryptoError(e,t,s,i){const r=this.enableSoftwareAES;if(r){this.useSoftware=!0,this.logEnabled=!0,this.softwareDecrypt(e,t,s,i);const n=this.flush();if(n)return n.buffer}throw new Error("WebCrypto"+(r?" and softwareDecrypt":"")+": failed to decrypt data")}getValidChunk(e){let t=e;const s=e.length-e.length%hl;return s!==e.length&&(t=e.slice(0,s),this.remainderData=e.slice(s)),t}logOnce(e){this.logEnabled&&(se.log(`[decrypter]: ${e}`),this.logEnabled=!1)}}const yr=Math.pow(2,17);class dl{constructor(e){this.config=void 0,this.loader=null,this.partLoadTimeout=-1,this.config=e}destroy(){this.loader&&(this.loader.destroy(),this.loader=null)}abort(){this.loader&&this.loader.abort()}load(e,t){const s=e.url;if(!s)return Promise.reject(new Xe({type:V.NETWORK_ERROR,details:R.FRAG_LOAD_ERROR,fatal:!1,frag:e,error:new Error(`Fragment does not have a ${s?"part list":"url"}`),networkDetails:null}));this.abort();const i=this.config,r=i.fLoader,n=i.loader;return new Promise((o,c)=>{if(this.loader&&this.loader.destroy(),e.gap)if(e.tagList.some(g=>g[0]==="GAP")){c(Tr(e));return}else e.gap=!1;const l=this.loader=r?new r(i):new n(i),h=Er(e);e.loader=l;const d=mr(i.fragLoadPolicy.default),u={loadPolicy:d,timeout:d.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:e.sn==="initSegment"?1/0:yr};e.stats=l.stats;const f={onSuccess:(g,y,p,E)=>{this.resetLoader(e,l);let T=g.data;p.resetIV&&e.decryptdata&&(e.decryptdata.iv=new Uint8Array(T.slice(0,16)),T=T.slice(16)),o({frag:e,part:null,payload:T,networkDetails:E})},onError:(g,y,p,E)=>{this.resetLoader(e,l),c(new Xe({type:V.NETWORK_ERROR,details:R.FRAG_LOAD_ERROR,fatal:!1,frag:e,response:te({url:s,data:void 0},g),error:new Error(`HTTP Error ${g.code} ${g.text}`),networkDetails:p,stats:E}))},onAbort:(g,y,p)=>{this.resetLoader(e,l),c(new Xe({type:V.NETWORK_ERROR,details:R.INTERNAL_ABORTED,fatal:!1,frag:e,error:new Error("Aborted"),networkDetails:p,stats:g}))},onTimeout:(g,y,p)=>{this.resetLoader(e,l),c(new Xe({type:V.NETWORK_ERROR,details:R.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,error:new Error(`Timeout after ${u.timeout}ms`),networkDetails:p,stats:g}))}};t&&(f.onProgress=(g,y,p,E)=>t({frag:e,part:null,payload:p,networkDetails:E})),l.load(h,u,f)})}loadPart(e,t,s){this.abort();const i=this.config,r=i.fLoader,n=i.loader;return new Promise((o,c)=>{if(this.loader&&this.loader.destroy(),e.gap||t.gap){c(Tr(e,t));return}const l=this.loader=r?new r(i):new n(i),h=Er(e,t);e.loader=l;const d=mr(i.fragLoadPolicy.default),u={loadPolicy:d,timeout:d.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:yr};t.stats=l.stats,l.load(h,u,{onSuccess:(f,g,y,p)=>{this.resetLoader(e,l),this.updateStatsFromPart(e,t);const E={frag:e,part:t,payload:f.data,networkDetails:p};s(E),o(E)},onError:(f,g,y,p)=>{this.resetLoader(e,l),c(new Xe({type:V.NETWORK_ERROR,details:R.FRAG_LOAD_ERROR,fatal:!1,frag:e,part:t,response:te({url:h.url,data:void 0},f),error:new Error(`HTTP Error ${f.code} ${f.text}`),networkDetails:y,stats:p}))},onAbort:(f,g,y)=>{e.stats.aborted=t.stats.aborted,this.resetLoader(e,l),c(new Xe({type:V.NETWORK_ERROR,details:R.INTERNAL_ABORTED,fatal:!1,frag:e,part:t,error:new Error("Aborted"),networkDetails:y,stats:f}))},onTimeout:(f,g,y)=>{this.resetLoader(e,l),c(new Xe({type:V.NETWORK_ERROR,details:R.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,part:t,error:new Error(`Timeout after ${u.timeout}ms`),networkDetails:y,stats:f}))}})})}updateStatsFromPart(e,t){const s=e.stats,i=t.stats,r=i.total;if(s.loaded+=i.loaded,r){const c=Math.round(e.duration/t.duration),l=Math.min(Math.round(s.loaded/r),c),d=(c-l)*Math.round(s.loaded/l);s.total=s.loaded+d}else s.total=Math.max(s.loaded,s.total);const n=s.loading,o=i.loading;n.start?n.first+=o.first-o.start:(n.start=o.start,n.first=o.first),n.end=o.end}resetLoader(e,t){e.loader=null,this.loader===t&&(self.clearTimeout(this.partLoadTimeout),this.loader=null),t.destroy()}}function Er(a,e=null){const t=e||a,s={frag:a,part:e,responseType:"arraybuffer",url:t.url,headers:{},rangeStart:0,rangeEnd:0},i=t.byteRangeStartOffset,r=t.byteRangeEndOffset;if(M(i)&&M(r)){var n;let o=i,c=r;if(a.sn==="initSegment"&&ul((n=a.decryptdata)==null?void 0:n.method)){const l=r-i;l%16&&(c=r+(16-l%16)),i!==0&&(s.resetIV=!0,o=i-16)}s.rangeStart=o,s.rangeEnd=c}return s}function Tr(a,e){const t=new Error(`GAP ${a.gap?"tag":"attribute"} found`),s={type:V.MEDIA_ERROR,details:R.FRAG_GAP,fatal:!1,frag:a,error:t,networkDetails:null};return e&&(s.part=e),(e||a).stats.aborted=!0,new Xe(s)}function ul(a){return a==="AES-128"||a==="AES-256"}class Xe extends Error{constructor(e){super(e.error.message),this.data=void 0,this.data=e}}class Gn extends we{constructor(e,t){super(e,t),this._boundTick=void 0,this._tickTimer=null,this._tickInterval=null,this._tickCallCount=0,this._boundTick=this.tick.bind(this)}destroy(){this.onHandlerDestroying(),this.onHandlerDestroyed()}onHandlerDestroying(){this.clearNextTick(),this.clearInterval()}onHandlerDestroyed(){}hasInterval(){return!!this._tickInterval}hasNextTick(){return!!this._tickTimer}setInterval(e){return this._tickInterval?!1:(this._tickCallCount=0,this._tickInterval=self.setInterval(this._boundTick,e),!0)}clearInterval(){return this._tickInterval?(self.clearInterval(this._tickInterval),this._tickInterval=null,!0):!1}clearNextTick(){return this._tickTimer?(self.clearTimeout(this._tickTimer),this._tickTimer=null,!0):!1}tick(){this._tickCallCount++,this._tickCallCount===1&&(this.doTick(),this._tickCallCount>1&&this.tickImmediate(),this._tickCallCount=0)}tickImmediate(){this.clearNextTick(),this._tickTimer=self.setTimeout(this._boundTick,0)}doTick(){}}class Pi{constructor(e,t,s,i=0,r=-1,n=!1){this.level=void 0,this.sn=void 0,this.part=void 0,this.id=void 0,this.size=void 0,this.partial=void 0,this.transmuxing=Xt(),this.buffering={audio:Xt(),video:Xt(),audiovideo:Xt()},this.level=e,this.sn=t,this.id=s,this.size=i,this.part=r,this.partial=n}}function Xt(){return{start:0,executeStart:0,executeEnd:0,end:0}}const Sr={length:0,start:()=>0,end:()=>0};class q{static isBuffered(e,t){if(e){const s=q.getBuffered(e);for(let i=s.length;i--;)if(t>=s.start(i)&&t<=s.end(i))return!0}return!1}static bufferedRanges(e){if(e){const t=q.getBuffered(e);return q.timeRangesToArray(t)}return[]}static timeRangesToArray(e){const t=[];for(let s=0;s<e.length;s++)t.push({start:e.start(s),end:e.end(s)});return t}static bufferInfo(e,t,s){if(e){const i=q.bufferedRanges(e);if(i.length)return q.bufferedInfo(i,t,s)}return{len:0,start:t,end:t,bufferedIndex:-1}}static bufferedInfo(e,t,s){t=Math.max(0,t),e.length>1&&e.sort((h,d)=>h.start-d.start||d.end-h.end);let i=-1,r=[];if(s)for(let h=0;h<e.length;h++){t>=e[h].start&&t<=e[h].end&&(i=h);const d=r.length;if(d){const u=r[d-1].end;e[h].start-u<s?e[h].end>u&&(r[d-1].end=e[h].end):r.push(e[h])}else r.push(e[h])}else r=e;let n=0,o,c=t,l=t;for(let h=0;h<r.length;h++){const d=r[h].start,u=r[h].end;if(i===-1&&t>=d&&t<=u&&(i=h),t+s>=d&&t<u)c=d,l=u,n=l-t;else if(t+s<d){o=d;break}}return{len:n,start:c||0,end:l||0,nextStart:o,buffered:e,bufferedIndex:i}}static getBuffered(e){try{return e.buffered||Sr}catch(t){return se.log("failed to get media.buffered",t),Sr}}}const Kn=/\{\$([a-zA-Z0-9-_]+)\}/g;function vr(a){return Kn.test(a)}function ci(a,e){if(a.variableList!==null||a.hasVariableRefs){const t=a.variableList;return e.replace(Kn,s=>{const i=s.substring(2,s.length-1),r=t==null?void 0:t[i];return r===void 0?(a.playlistParsingError||(a.playlistParsingError=new Error(`Missing preceding EXT-X-DEFINE tag for Variable Reference: "${i}"`)),s):r})}return e}function xr(a,e,t){let s=a.variableList;s||(a.variableList=s={});let i,r;if("QUERYPARAM"in e){i=e.QUERYPARAM;try{const n=new self.URL(t).searchParams;if(n.has(i))r=n.get(i);else throw new Error(`"${i}" does not match any query parameter in URI: "${t}"`)}catch(n){a.playlistParsingError||(a.playlistParsingError=new Error(`EXT-X-DEFINE QUERYPARAM: ${n.message}`))}}else i=e.NAME,r=e.VALUE;i in s?a.playlistParsingError||(a.playlistParsingError=new Error(`EXT-X-DEFINE duplicate Variable Name declarations: "${i}"`)):s[i]=r||""}function fl(a,e,t){const s=e.IMPORT;if(t&&s in t){let i=a.variableList;i||(a.variableList=i={}),i[s]=t[s]}else a.playlistParsingError||(a.playlistParsingError=new Error(`EXT-X-DEFINE IMPORT attribute not found in Multivariant Playlist: "${s}"`))}const gl=/^(\d+)x(\d+)$/,Ar=/(.+?)=(".*?"|.*?)(?:,|$)/g;class ae{constructor(e,t){typeof e=="string"&&(e=ae.parseAttrList(e,t)),ie(this,e)}get clientAttrs(){return Object.keys(this).filter(e=>e.substring(0,2)==="X-")}decimalInteger(e){const t=parseInt(this[e],10);return t>Number.MAX_SAFE_INTEGER?1/0:t}hexadecimalInteger(e){if(this[e]){let t=(this[e]||"0x").slice(2);t=(t.length&1?"0":"")+t;const s=new Uint8Array(t.length/2);for(let i=0;i<t.length/2;i++)s[i]=parseInt(t.slice(i*2,i*2+2),16);return s}return null}hexadecimalIntegerAsNumber(e){const t=parseInt(this[e],16);return t>Number.MAX_SAFE_INTEGER?1/0:t}decimalFloatingPoint(e){return parseFloat(this[e])}optionalFloat(e,t){const s=this[e];return s?parseFloat(s):t}enumeratedString(e){return this[e]}enumeratedStringList(e,t){const s=this[e];return(s?s.split(/[ ,]+/):[]).reduce((i,r)=>(i[r.toLowerCase()]=!0,i),t)}bool(e){return this[e]==="YES"}decimalResolution(e){const t=gl.exec(this[e]);if(t!==null)return{width:parseInt(t[1],10),height:parseInt(t[2],10)}}static parseAttrList(e,t){let s;const i={},r='"';for(Ar.lastIndex=0;(s=Ar.exec(e))!==null;){const n=s[1].trim();let o=s[2];const c=o.indexOf(r)===0&&o.lastIndexOf(r)===o.length-1;let l=!1;if(c)o=o.slice(1,-1);else switch(n){case"IV":case"SCTE35-CMD":case"SCTE35-IN":case"SCTE35-OUT":l=!0}if(t&&(c||l))o=ci(t,o);else if(!l&&!c)switch(n){case"CLOSED-CAPTIONS":if(o==="NONE")break;case"ALLOWED-CPC":case"CLASS":case"ASSOC-LANGUAGE":case"AUDIO":case"BYTERANGE":case"CHANNELS":case"CHARACTERISTICS":case"CODECS":case"DATA-ID":case"END-DATE":case"GROUP-ID":case"ID":case"IMPORT":case"INSTREAM-ID":case"KEYFORMAT":case"KEYFORMATVERSIONS":case"LANGUAGE":case"NAME":case"PATHWAY-ID":case"QUERYPARAM":case"RECENTLY-REMOVED-DATERANGES":case"SERVER-URI":case"STABLE-RENDITION-ID":case"STABLE-VARIANT-ID":case"START-DATE":case"SUBTITLES":case"SUPPLEMENTAL-CODECS":case"URI":case"VALUE":case"VIDEO":case"X-ASSET-LIST":case"X-ASSET-URI":se.warn(`${e}: attribute ${n} is missing quotes`)}i[n]=o}return i}}const ml="com.apple.hls.interstitial";function pl(a){return a!=="ID"&&a!=="CLASS"&&a!=="CUE"&&a!=="START-DATE"&&a!=="DURATION"&&a!=="END-DATE"&&a!=="END-ON-NEXT"}function yl(a){return a==="SCTE35-OUT"||a==="SCTE35-IN"||a==="SCTE35-CMD"}class Vn{constructor(e,t,s=0){var i;if(this.attr=void 0,this.tagAnchor=void 0,this.tagOrder=void 0,this._startDate=void 0,this._endDate=void 0,this._dateAtEnd=void 0,this._cue=void 0,this._badValueForSameId=void 0,this.tagAnchor=(t==null?void 0:t.tagAnchor)||null,this.tagOrder=(i=t==null?void 0:t.tagOrder)!=null?i:s,t){const r=t.attr;for(const n in r)if(Object.prototype.hasOwnProperty.call(e,n)&&e[n]!==r[n]){se.warn(`DATERANGE tag attribute: "${n}" does not match for tags with ID: "${e.ID}"`),this._badValueForSameId=n;break}e=ie(new ae({}),r,e)}if(this.attr=e,t?(this._startDate=t._startDate,this._cue=t._cue,this._endDate=t._endDate,this._dateAtEnd=t._dateAtEnd):this._startDate=new Date(e["START-DATE"]),"END-DATE"in this.attr){const r=(t==null?void 0:t.endDate)||new Date(this.attr["END-DATE"]);M(r.getTime())&&(this._endDate=r)}}get id(){return this.attr.ID}get class(){return this.attr.CLASS}get cue(){const e=this._cue;return e===void 0?this._cue=this.attr.enumeratedStringList(this.attr.CUE?"CUE":"X-CUE",{pre:!1,post:!1,once:!1}):e}get startTime(){const{tagAnchor:e}=this;return e===null||e.programDateTime===null?(se.warn(`Expected tagAnchor Fragment with PDT set for DateRange "${this.id}": ${e}`),NaN):e.start+(this.startDate.getTime()-e.programDateTime)/1e3}get startDate(){return this._startDate}get endDate(){const e=this._endDate||this._dateAtEnd;if(e)return e;const t=this.duration;return t!==null?this._dateAtEnd=new Date(this._startDate.getTime()+t*1e3):null}get duration(){if("DURATION"in this.attr){const e=this.attr.decimalFloatingPoint("DURATION");if(M(e))return e}else if(this._endDate)return(this._endDate.getTime()-this._startDate.getTime())/1e3;return null}get plannedDuration(){return"PLANNED-DURATION"in this.attr?this.attr.decimalFloatingPoint("PLANNED-DURATION"):null}get endOnNext(){return this.attr.bool("END-ON-NEXT")}get isInterstitial(){return this.class===ml}get isValid(){return!!this.id&&!this._badValueForSameId&&M(this.startDate.getTime())&&(this.duration===null||this.duration>=0)&&(!this.endOnNext||!!this.class)&&(!this.attr.CUE||!this.cue.pre&&!this.cue.post||this.cue.pre!==this.cue.post)&&(!this.isInterstitial||"X-ASSET-URI"in this.attr||"X-ASSET-LIST"in this.attr)}}const El=10;class Tl{constructor(e){this.PTSKnown=!1,this.alignedSliding=!1,this.averagetargetduration=void 0,this.endCC=0,this.endSN=0,this.fragments=void 0,this.fragmentHint=void 0,this.partList=null,this.dateRanges=void 0,this.dateRangeTagCount=0,this.live=!0,this.requestScheduled=-1,this.ageHeader=0,this.advancedDateTime=void 0,this.updated=!0,this.advanced=!0,this.misses=0,this.startCC=0,this.startSN=0,this.startTimeOffset=null,this.targetduration=0,this.totalduration=0,this.type=null,this.url=void 0,this.m3u8="",this.version=null,this.canBlockReload=!1,this.canSkipUntil=0,this.canSkipDateRanges=!1,this.skippedSegments=0,this.recentlyRemovedDateranges=void 0,this.partHoldBack=0,this.holdBack=0,this.partTarget=0,this.preloadHint=void 0,this.renditionReports=void 0,this.tuneInGoal=0,this.deltaUpdateFailed=void 0,this.driftStartTime=0,this.driftEndTime=0,this.driftStart=0,this.driftEnd=0,this.encryptedFragments=void 0,this.playlistParsingError=null,this.variableList=null,this.hasVariableRefs=!1,this.appliedTimelineOffset=void 0,this.fragments=[],this.encryptedFragments=[],this.dateRanges={},this.url=e}reloaded(e){if(!e){this.advanced=!0,this.updated=!0;return}const t=this.lastPartSn-e.lastPartSn,s=this.lastPartIndex-e.lastPartIndex;this.updated=this.endSN!==e.endSN||!!s||!!t||!this.live,this.advanced=this.endSN>e.endSN||t>0||t===0&&s>0,this.updated||this.advanced?this.misses=Math.floor(e.misses*.6):this.misses=e.misses+1}hasKey(e){return this.encryptedFragments.some(t=>{let s=t.decryptdata;return s||(t.setKeyFormat(e.keyFormat),s=t.decryptdata),!!s&&e.matches(s)})}get hasProgramDateTime(){return this.fragments.length?M(this.fragments[this.fragments.length-1].programDateTime):!1}get levelTargetDuration(){return this.averagetargetduration||this.targetduration||El}get drift(){const e=this.driftEndTime-this.driftStartTime;return e>0?(this.driftEnd-this.driftStart)*1e3/e:1}get edge(){return this.partEnd||this.fragmentEnd}get partEnd(){var e;return(e=this.partList)!=null&&e.length?this.partList[this.partList.length-1].end:this.fragmentEnd}get fragmentEnd(){return this.fragments.length?this.fragments[this.fragments.length-1].end:0}get fragmentStart(){return this.fragments.length?this.fragments[0].start:0}get age(){return this.advancedDateTime?Math.max(Date.now()-this.advancedDateTime,0)/1e3:0}get lastPartIndex(){var e;return(e=this.partList)!=null&&e.length?this.partList[this.partList.length-1].index:-1}get maxPartIndex(){const e=this.partList;if(e){const t=this.lastPartIndex;if(t!==-1){for(let s=e.length;s--;)if(e[s].index>t)return e[s].index;return t}}return 0}get lastPartSn(){var e;return(e=this.partList)!=null&&e.length?this.partList[this.partList.length-1].fragment.sn:this.endSN}get expired(){if(this.live&&this.age&&this.misses<3){const e=this.partEnd-this.fragmentStart;return this.age>Math.max(e,this.totalduration)+this.levelTargetDuration}return!1}}function Is(a,e){return a.length===e.length?!a.some((t,s)=>t!==e[s]):!1}function Ir(a,e){return!a&&!e?!0:!a||!e?!1:Is(a,e)}function Lt(a){return a==="AES-128"||a==="AES-256"||a==="AES-256-CTR"}function ki(a){switch(a){case"AES-128":case"AES-256":return nt.cbc;case"AES-256-CTR":return nt.ctr;default:throw new Error(`invalid full segment method ${a}`)}}function wi(a){return Uint8Array.from(atob(a),e=>e.charCodeAt(0))}function hi(a){return Uint8Array.from(unescape(encodeURIComponent(a)),e=>e.charCodeAt(0))}function Sl(a){const e=hi(a).subarray(0,16),t=new Uint8Array(16);return t.set(e,16-e.length),t}function Hn(a){const e=function(s,i,r){const n=s[i];s[i]=s[r],s[r]=n};e(a,0,3),e(a,1,2),e(a,4,5),e(a,6,7)}function Yn(a){const e=a.split(":");let t=null;if(e[0]==="data"&&e.length===2){const s=e[1].split(";"),i=s[s.length-1].split(",");if(i.length===2){const r=i[0]==="base64",n=i[1];r?(s.splice(-1,1),t=wi(n)):t=Sl(n)}}return t}const Ls=typeof self<"u"?self:void 0;var oe={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.fps",PLAYREADY:"com.microsoft.playready",WIDEVINE:"com.widevine.alpha"},pe={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.streamingkeydelivery",PLAYREADY:"com.microsoft.playready",WIDEVINE:"urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed"};function ds(a){switch(a){case pe.FAIRPLAY:return oe.FAIRPLAY;case pe.PLAYREADY:return oe.PLAYREADY;case pe.WIDEVINE:return oe.WIDEVINE;case pe.CLEARKEY:return oe.CLEARKEY}}function Bs(a){switch(a){case oe.FAIRPLAY:return pe.FAIRPLAY;case oe.PLAYREADY:return pe.PLAYREADY;case oe.WIDEVINE:return pe.WIDEVINE;case oe.CLEARKEY:return pe.CLEARKEY}}function wt(a){const{drmSystems:e,widevineLicenseUrl:t}=a,s=e?[oe.FAIRPLAY,oe.WIDEVINE,oe.PLAYREADY,oe.CLEARKEY].filter(i=>!!e[i]):[];return!s[oe.WIDEVINE]&&t&&s.push(oe.WIDEVINE),s}const Wn=function(a){return Ls!=null&&(a=Ls.navigator)!=null&&a.requestMediaKeySystemAccess?self.navigator.requestMediaKeySystemAccess.bind(self.navigator):null}();function vl(a,e,t,s){let i;switch(a){case oe.FAIRPLAY:i=["cenc","sinf"];break;case oe.WIDEVINE:case oe.PLAYREADY:i=["cenc"];break;case oe.CLEARKEY:i=["cenc","keyids"];break;default:throw new Error(`Unknown key-system: ${a}`)}return xl(i,e,t,s)}function xl(a,e,t,s){return[{initDataTypes:a,persistentState:s.persistentState||"optional",distinctiveIdentifier:s.distinctiveIdentifier||"optional",sessionTypes:s.sessionTypes||[s.sessionType||"temporary"],audioCapabilities:e.map(r=>({contentType:`audio/mp4; codecs=${r}`,robustness:s.audioRobustness||"",encryptionScheme:s.audioEncryptionScheme||null})),videoCapabilities:t.map(r=>({contentType:`video/mp4; codecs=${r}`,robustness:s.videoRobustness||"",encryptionScheme:s.videoEncryptionScheme||null}))}]}function Al(a){var e;return!!a&&(a.sessionType==="persistent-license"||!!((e=a.sessionTypes)!=null&&e.some(t=>t==="persistent-license")))}function qn(a){const e=new Uint16Array(a.buffer,a.byteOffset,a.byteLength/2),t=String.fromCharCode.apply(null,Array.from(e)),s=t.substring(t.indexOf("<"),t.length),n=new DOMParser().parseFromString(s,"text/xml").getElementsByTagName("KID")[0];if(n){const o=n.childNodes[0]?n.childNodes[0].nodeValue:n.getAttribute("VALUE");if(o){const c=wi(o).subarray(0,16);return Hn(c),c}}return null}let Et={};class it{static clearKeyUriToKeyIdMap(){Et={}}static setKeyIdForUri(e,t){Et[e]=t}static addKeyIdForUri(e){const t=Object.keys(Et).length%Number.MAX_SAFE_INTEGER,s=new Uint8Array(16);return new DataView(s.buffer,12,4).setUint32(0,t),Et[e]=s,s}constructor(e,t,s,i=[1],r=null,n){this.uri=void 0,this.method=void 0,this.keyFormat=void 0,this.keyFormatVersions=void 0,this.encrypted=void 0,this.isCommonEncryption=void 0,this.iv=null,this.key=null,this.keyId=null,this.pssh=null,this.method=e,this.uri=t,this.keyFormat=s,this.keyFormatVersions=i,this.iv=r,this.encrypted=e?e!=="NONE":!1,this.isCommonEncryption=this.encrypted&&!Lt(e),n!=null&&n.startsWith("0x")&&(this.keyId=new Uint8Array(vn(n)))}matches(e){return e.uri===this.uri&&e.method===this.method&&e.encrypted===this.encrypted&&e.keyFormat===this.keyFormat&&Is(e.keyFormatVersions,this.keyFormatVersions)&&Ir(e.iv,this.iv)&&Ir(e.keyId,this.keyId)}isSupported(){if(this.method){if(Lt(this.method)||this.method==="NONE")return!0;if(this.keyFormat==="identity")return this.method==="SAMPLE-AES";switch(this.keyFormat){case pe.FAIRPLAY:case pe.WIDEVINE:case pe.PLAYREADY:case pe.CLEARKEY:return["SAMPLE-AES","SAMPLE-AES-CENC","SAMPLE-AES-CTR"].indexOf(this.method)!==-1}}return!1}getDecryptData(e,t){if(!this.encrypted||!this.uri)return null;if(Lt(this.method)){let r=this.iv;return r||(typeof e!="number"&&(se.warn(`missing IV for initialization segment with method="${this.method}" - compliance issue`),e=0),r=Ll(e)),new it(this.method,this.uri,"identity",this.keyFormatVersions,r)}if(this.keyId){const r=Et[this.uri];if(r&&!Is(this.keyId,r)&&it.setKeyIdForUri(this.uri,this.keyId),this.pssh)return this}const s=Yn(this.uri);if(s)switch(this.keyFormat){case pe.WIDEVINE:if(this.pssh=s,!this.keyId){const r=_o(s.buffer);if(r.length){var i;const n=r[0];this.keyId=(i=n.kids)!=null&&i.length?n.kids[0]:null}}this.keyId||(this.keyId=Lr(t));break;case pe.PLAYREADY:{const r=new Uint8Array([154,4,240,121,152,64,66,134,171,146,230,91,224,136,95,149]);this.pssh=bo(r,null,s),this.keyId=qn(s);break}default:{let r=s.subarray(0,16);if(r.length!==16){const n=new Uint8Array(16);n.set(r,16-r.length),r=n}this.keyId=r;break}}if(!this.keyId||this.keyId.byteLength!==16){let r;r=Il(t),r||(r=Lr(t),r||(r=Et[this.uri])),r&&(this.keyId=r,it.setKeyIdForUri(this.uri,r))}return this}}function Il(a){const e=a==null?void 0:a[pe.WIDEVINE];return e?e.keyId:null}function Lr(a){const e=a==null?void 0:a[pe.PLAYREADY];if(e){const t=Yn(e.uri);if(t)return qn(t)}return null}function Ll(a){const e=new Uint8Array(16);for(let t=12;t<16;t++)e[t]=a>>8*(15-t)&255;return e}const Rr=/#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,br=/#EXT-X-MEDIA:(.*)/g,Rl=/^#EXT(?:INF|-X-TARGETDURATION):/m,Us=new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,/(?!#) *(\S[^\r\n]*)/.source,/#.*/.source].join("|"),"g"),bl=new RegExp([/#EXT-X-(PROGRAM-DATE-TIME|BYTERANGE|DATERANGE|DEFINE|KEY|MAP|PART|PART-INF|PLAYLIST-TYPE|PRELOAD-HINT|RENDITION-REPORT|SERVER-CONTROL|SKIP|START):(.+)/.source,/#EXT-X-(BITRATE|DISCONTINUITY-SEQUENCE|MEDIA-SEQUENCE|TARGETDURATION|VERSION): *(\d+)/.source,/#EXT-X-(DISCONTINUITY|ENDLIST|GAP|INDEPENDENT-SEGMENTS)/.source,/(#)([^:]*):(.*)/.source,/(#)(.*)(?:.*)\r?\n?/.source].join("|"));class He{static findGroup(e,t){for(let s=0;s<e.length;s++){const i=e[s];if(i.id===t)return i}}static resolve(e,t){return Ii.buildAbsoluteURL(t,e,{alwaysNormalize:!0})}static isMediaPlaylist(e){return Rl.test(e)}static parseMasterPlaylist(e,t){const s=vr(e),i={contentSteering:null,levels:[],playlistParsingError:null,sessionData:null,sessionKeys:null,startTimeOffset:null,variableList:null,hasVariableRefs:s},r=[];if(Rr.lastIndex=0,!e.startsWith("#EXTM3U"))return i.playlistParsingError=new Error("no EXTM3U delimiter"),i;let n;for(;(n=Rr.exec(e))!=null;)if(n[1]){var o;const l=new ae(n[1],i),h=ci(i,n[2]),d={attrs:l,bitrate:l.decimalInteger("BANDWIDTH")||l.decimalInteger("AVERAGE-BANDWIDTH"),name:l.NAME,url:He.resolve(h,t)},u=l.decimalResolution("RESOLUTION");u&&(d.width=u.width,d.height=u.height),Cr(l.CODECS,d);const f=l["SUPPLEMENTAL-CODECS"];f&&(d.supplemental={},Cr(f,d.supplemental)),(o=d.unknownCodecs)!=null&&o.length||r.push(d),i.levels.push(d)}else if(n[3]){const l=n[3],h=n[4];switch(l){case"SESSION-DATA":{const d=new ae(h,i),u=d["DATA-ID"];u&&(i.sessionData===null&&(i.sessionData={}),i.sessionData[u]=d);break}case"SESSION-KEY":{const d=_r(h,t,i);d.encrypted&&d.isSupported()?(i.sessionKeys===null&&(i.sessionKeys=[]),i.sessionKeys.push(d)):se.warn(`[Keys] Ignoring invalid EXT-X-SESSION-KEY tag: "${h}"`);break}case"DEFINE":{{const d=new ae(h,i);xr(i,d,t)}break}case"CONTENT-STEERING":{const d=new ae(h,i);i.contentSteering={uri:He.resolve(d["SERVER-URI"],t),pathwayId:d["PATHWAY-ID"]||"."};break}case"START":{i.startTimeOffset=Dr(h);break}}}const c=r.length>0&&r.length<i.levels.length;return i.levels=c?r:i.levels,i.levels.length===0&&(i.playlistParsingError=new Error("no levels found in manifest")),i}static parseMasterPlaylistMedia(e,t,s){let i;const r={},n=s.levels,o={AUDIO:n.map(l=>({id:l.attrs.AUDIO,audioCodec:l.audioCodec})),SUBTITLES:n.map(l=>({id:l.attrs.SUBTITLES,textCodec:l.textCodec})),"CLOSED-CAPTIONS":[]};let c=0;for(br.lastIndex=0;(i=br.exec(e))!==null;){const l=new ae(i[1],s),h=l.TYPE;if(h){const d=o[h],u=r[h]||[];r[h]=u;const f=l.LANGUAGE,g=l["ASSOC-LANGUAGE"],y=l.CHANNELS,p=l.CHARACTERISTICS,E=l["INSTREAM-ID"],T={attrs:l,bitrate:0,id:c++,groupId:l["GROUP-ID"]||"",name:l.NAME||f||"",type:h,default:l.bool("DEFAULT"),autoselect:l.bool("AUTOSELECT"),forced:l.bool("FORCED"),lang:f,url:l.URI?He.resolve(l.URI,t):""};if(g&&(T.assocLang=g),y&&(T.channels=y),p&&(T.characteristics=p),E&&(T.instreamId=E),d!=null&&d.length){const S=He.findGroup(d,T.groupId)||d[0];Pr(T,S,"audioCodec"),Pr(T,S,"textCodec")}u.push(T)}}return r}static parseLevelPlaylist(e,t,s,i,r,n){var o;const c={url:t},l=new Tl(t),h=l.fragments,d=[];let u=null,f=0,g=0,y=0,p=0,E=0,T=null,S=new Fs(i,c),v,A,D,x=-1,b=!1,_=null,I;if(Us.lastIndex=0,l.m3u8=e,l.hasVariableRefs=vr(e),((o=Us.exec(e))==null?void 0:o[0])!=="#EXTM3U")return l.playlistParsingError=new Error("Missing format identifier #EXTM3U"),l;for(;(v=Us.exec(e))!==null;){b&&(b=!1,S=new Fs(i,c),S.playlistOffset=y,S.setStart(y),S.sn=f,S.cc=p,E&&(S.bitrate=E),S.level=s,u&&(S.initSegment=u,u.rawProgramDateTime&&(S.rawProgramDateTime=u.rawProgramDateTime,u.rawProgramDateTime=null),_&&(S.setByteRange(_),_=null)));const H=v[1];if(H){S.duration=parseFloat(H);const $=(" "+v[2]).slice(1);S.title=$||null,S.tagList.push($?["INF",H,$]:["INF",H])}else if(v[3]){if(M(S.duration)){S.playlistOffset=y,S.setStart(y),D&&wr(S,D,l),S.sn=f,S.level=s,S.cc=p,h.push(S);const $=(" "+v[3]).slice(1);S.relurl=ci(l,$),di(S,T,d),T=S,y+=S.duration,f++,g=0,b=!0}}else{if(v=v[0].match(bl),!v){se.warn("No matches on slow regex match for level playlist!");continue}for(A=1;A<v.length&&v[A]===void 0;A++);const $=(" "+v[A]).slice(1),k=(" "+v[A+1]).slice(1),G=v[A+2]?(" "+v[A+2]).slice(1):null;switch($){case"BYTERANGE":T?S.setByteRange(k,T):S.setByteRange(k);break;case"PROGRAM-DATE-TIME":S.rawProgramDateTime=k,S.tagList.push(["PROGRAM-DATE-TIME",k]),x===-1&&(x=h.length);break;case"PLAYLIST-TYPE":l.type&&qe(l,$,v),l.type=k.toUpperCase();break;case"MEDIA-SEQUENCE":l.startSN!==0?qe(l,$,v):h.length>0&&Or(l,$,v),f=l.startSN=parseInt(k);break;case"SKIP":{l.skippedSegments&&qe(l,$,v);const N=new ae(k,l),K=N.decimalInteger("SKIPPED-SEGMENTS");if(M(K)){l.skippedSegments+=K;for(let w=K;w--;)h.push(null);f+=K}const Y=N.enumeratedString("RECENTLY-REMOVED-DATERANGES");Y&&(l.recentlyRemovedDateranges=(l.recentlyRemovedDateranges||[]).concat(Y.split(" ")));break}case"TARGETDURATION":l.targetduration!==0&&qe(l,$,v),l.targetduration=Math.max(parseInt(k),1);break;case"VERSION":l.version!==null&&qe(l,$,v),l.version=parseInt(k);break;case"INDEPENDENT-SEGMENTS":break;case"ENDLIST":l.live||qe(l,$,v),l.live=!1;break;case"#":(k||G)&&S.tagList.push(G?[k,G]:[k]);break;case"DISCONTINUITY":p++,S.tagList.push(["DIS"]);break;case"GAP":S.gap=!0,S.tagList.push([$]);break;case"BITRATE":S.tagList.push([$,k]),E=parseInt(k)*1e3,M(E)?S.bitrate=E:E=0;break;case"DATERANGE":{const N=new ae(k,l),K=new Vn(N,l.dateRanges[N.ID],l.dateRangeTagCount);l.dateRangeTagCount++,K.isValid||l.skippedSegments?l.dateRanges[K.id]=K:se.warn(`Ignoring invalid DATERANGE tag: "${k}"`),S.tagList.push(["EXT-X-DATERANGE",k]);break}case"DEFINE":{{const N=new ae(k,l);"IMPORT"in N?fl(l,N,n):xr(l,N,t)}break}case"DISCONTINUITY-SEQUENCE":l.startCC!==0?qe(l,$,v):h.length>0&&Or(l,$,v),l.startCC=p=parseInt(k);break;case"KEY":{const N=_r(k,t,l);if(N.isSupported()){if(N.method==="NONE"){D=void 0;break}D||(D={});const K=D[N.keyFormat];K!=null&&K.matches(N)||(K&&(D=ie({},D)),D[N.keyFormat]=N)}else se.warn(`[Keys] Ignoring unsupported EXT-X-KEY tag: "${k}"`);break}case"START":l.startTimeOffset=Dr(k);break;case"MAP":{const N=new ae(k,l);if(S.duration){const K=new Fs(i,c);kr(K,N,s,D),u=K,S.initSegment=u,u.rawProgramDateTime&&!S.rawProgramDateTime&&(S.rawProgramDateTime=u.rawProgramDateTime)}else{const K=S.byteRangeEndOffset;if(K){const Y=S.byteRangeStartOffset;_=`${K-Y}@${Y}`}else _=null;kr(S,N,s,D),u=S,b=!0}u.cc=p;break}case"SERVER-CONTROL":{I&&qe(l,$,v),I=new ae(k),l.canBlockReload=I.bool("CAN-BLOCK-RELOAD"),l.canSkipUntil=I.optionalFloat("CAN-SKIP-UNTIL",0),l.canSkipDateRanges=l.canSkipUntil>0&&I.bool("CAN-SKIP-DATERANGES"),l.partHoldBack=I.optionalFloat("PART-HOLD-BACK",0),l.holdBack=I.optionalFloat("HOLD-BACK",0);break}case"PART-INF":{l.partTarget&&qe(l,$,v);const N=new ae(k);l.partTarget=N.decimalFloatingPoint("PART-TARGET");break}case"PART":{let N=l.partList;N||(N=l.partList=[]);const K=g>0?N[N.length-1]:void 0,Y=g++,w=new ae(k,l),O=new fo(w,S,c,Y,K);N.push(O),S.duration+=O.duration;break}case"PRELOAD-HINT":{const N=new ae(k,l);l.preloadHint=N;break}case"RENDITION-REPORT":{const N=new ae(k,l);l.renditionReports=l.renditionReports||[],l.renditionReports.push(N);break}default:se.warn(`line parsed but not handled: ${v}`);break}}}T&&!T.relurl?(h.pop(),y-=T.duration,l.partList&&(l.fragmentHint=T)):l.partList&&(di(S,T,d),S.cc=p,l.fragmentHint=S,D&&wr(S,D,l)),l.targetduration||(l.playlistParsingError=new Error("Missing Target Duration"));const P=h.length,F=h[0],U=h[P-1];if(y+=l.skippedSegments*l.targetduration,y>0&&P&&U){l.averagetargetduration=y/P;const H=U.sn;l.endSN=H!=="initSegment"?H:0,l.live||(U.endList=!0),x>0&&(Dl(h,x),F&&d.unshift(F))}return l.fragmentHint&&(y+=l.fragmentHint.duration),l.totalduration=y,d.length&&l.dateRangeTagCount&&F&&jn(d,l),l.endCC=p,l}}function jn(a,e){let t=a.length;if(!t)if(e.hasProgramDateTime){const o=e.fragments[e.fragments.length-1];a.push(o),t++}else return;const s=a[t-1],i=e.live?1/0:e.totalduration,r=Object.keys(e.dateRanges);for(let o=r.length;o--;){const c=e.dateRanges[r[o]],l=c.startDate.getTime();c.tagAnchor=s.ref;for(let h=t;h--;){var n;if(((n=a[h])==null?void 0:n.sn)<e.startSN)break;const d=_l(e,l,a,h,i);if(d!==-1){c.tagAnchor=e.fragments[d].ref;break}}}}function _l(a,e,t,s,i){const r=t[s];if(r){const o=r.programDateTime;if(e>=o||s===0){var n;const c=(((n=t[s+1])==null?void 0:n.start)||i)-r.start;if(e<=o+c*1e3){const l=t[s].sn-a.startSN;if(l<0)return-1;const h=a.fragments;if(h.length>t.length){const u=(t[s+1]||h[h.length-1]).sn-a.startSN;for(let f=u;f>l;f--){const g=h[f].programDateTime;if(e>=g&&e<g+h[f].duration*1e3)return f}}return l}}}return-1}function _r(a,e,t){var s,i;const r=new ae(a,t),n=(s=r.METHOD)!=null?s:"",o=r.URI,c=r.hexadecimalInteger("IV"),l=r.KEYFORMATVERSIONS,h=(i=r.KEYFORMAT)!=null?i:"identity";o&&r.IV&&!c&&se.error(`Invalid IV: ${r.IV}`);const d=o?He.resolve(o,e):"",u=(l||"1").split("/").map(Number).filter(Number.isFinite);return new it(n,d,h,u,c,r.KEYID)}function Dr(a){const t=new ae(a).decimalFloatingPoint("TIME-OFFSET");return M(t)?t:null}function Cr(a,e){let t=(a||"").split(/[ ,]+/).filter(s=>s);["video","audio","text"].forEach(s=>{const i=t.filter(r=>bi(r,s));i.length&&(e[`${s}Codec`]=i.map(r=>r.split("/")[0]).join(","),t=t.filter(r=>i.indexOf(r)===-1))}),e.unknownCodecs=t}function Pr(a,e,t){const s=e[t];s&&(a[t]=s)}function Dl(a,e){let t=a[e];for(let s=e;s--;){const i=a[s];if(!i)return;i.programDateTime=t.programDateTime-i.duration*1e3,t=i}}function di(a,e,t){a.rawProgramDateTime?t.push(a):e!=null&&e.programDateTime&&(a.programDateTime=e.endProgramDateTime)}function kr(a,e,t,s){a.relurl=e.URI,e.BYTERANGE&&a.setByteRange(e.BYTERANGE),a.level=t,a.sn="initSegment",s&&(a.levelkeys=s),a.initSegment=null}function wr(a,e,t){a.levelkeys=e;const{encryptedFragments:s}=t;(!s.length||s[s.length-1].levelkeys!==e)&&Object.keys(e).some(i=>e[i].isCommonEncryption)&&s.push(a)}function qe(a,e,t){a.playlistParsingError=new Error(`#EXT-X-${e} must not appear more than once (${t[0]})`)}function Or(a,e,t){a.playlistParsingError=new Error(`#EXT-X-${e} must appear before the first Media Segment (${t[0]})`)}function $s(a,e){const t=e.startPTS;if(M(t)){let s=0,i;e.sn>a.sn?(s=t-a.start,i=a):(s=a.start-t,i=e),i.duration!==s&&i.setDuration(s)}else e.sn>a.sn?a.cc===e.cc&&a.minEndPTS?e.setStart(a.start+(a.minEndPTS-a.start)):e.setStart(a.start+a.duration):e.setStart(Math.max(a.start-e.duration,0))}function Xn(a,e,t,s,i,r,n){s-t<=0&&(n.warn("Fragment should have a positive duration",e),s=t+e.duration,r=i+e.duration);let c=t,l=s;const h=e.startPTS,d=e.endPTS;if(M(h)){const E=Math.abs(h-t);a&&E>a.totalduration?n.warn(`media timestamps and playlist times differ by ${E}s for level ${e.level} ${a.url}`):M(e.deltaPTS)?e.deltaPTS=Math.max(E,e.deltaPTS):e.deltaPTS=E,c=Math.max(t,h),t=Math.min(t,h),i=e.startDTS!==void 0?Math.min(i,e.startDTS):i,l=Math.min(s,d),s=Math.max(s,d),r=e.endDTS!==void 0?Math.max(r,e.endDTS):r}const u=t-e.start;e.start!==0&&e.setStart(t),e.setDuration(s-e.start),e.startPTS=t,e.maxStartPTS=c,e.startDTS=i,e.endPTS=s,e.minEndPTS=l,e.endDTS=r;const f=e.sn;if(!a||f<a.startSN||f>a.endSN)return 0;let g;const y=f-a.startSN,p=a.fragments;for(p[y]=e,g=y;g>0;g--)$s(p[g],p[g-1]);for(g=y;g<p.length-1;g++)$s(p[g],p[g+1]);return a.fragmentHint&&$s(p[p.length-1],a.fragmentHint),a.PTSKnown=a.alignedSliding=!0,u}function Cl(a,e,t){if(a===e)return;let s=null;const i=a.fragments;for(let h=i.length-1;h>=0;h--){const d=i[h].initSegment;if(d){s=d;break}}a.fragmentHint&&delete a.fragmentHint.endPTS;let r;wl(a,e,(h,d,u,f)=>{if((!e.startCC||e.skippedSegments)&&d.cc!==h.cc){const g=h.cc-d.cc;for(let y=u;y<f.length;y++)f[y].cc+=g;e.endCC=f[f.length-1].cc}M(h.startPTS)&&M(h.endPTS)&&(d.setStart(d.startPTS=h.startPTS),d.startDTS=h.startDTS,d.maxStartPTS=h.maxStartPTS,d.endPTS=h.endPTS,d.endDTS=h.endDTS,d.minEndPTS=h.minEndPTS,d.setDuration(h.endPTS-h.startPTS),d.duration&&(r=d),e.PTSKnown=e.alignedSliding=!0),h.hasStreams&&(d.elementaryStreams=h.elementaryStreams),d.loader=h.loader,h.hasStats&&(d.stats=h.stats),h.initSegment&&(d.initSegment=h.initSegment,s=h.initSegment)});const n=e.fragments,o=e.fragmentHint?n.concat(e.fragmentHint):n;if(s&&o.forEach(h=>{var d;h&&(!h.initSegment||h.initSegment.relurl===((d=s)==null?void 0:d.relurl))&&(h.initSegment=s)}),e.skippedSegments){if(e.deltaUpdateFailed=n.some(h=>!h),e.deltaUpdateFailed){t.warn("[level-helper] Previous playlist missing segments skipped in delta playlist");for(let h=e.skippedSegments;h--;)n.shift();e.startSN=n[0].sn}else{e.canSkipDateRanges&&(e.dateRanges=Pl(a.dateRanges,e,t));const h=a.fragments.filter(d=>d.rawProgramDateTime);if(a.hasProgramDateTime&&!e.hasProgramDateTime)for(let d=1;d<o.length;d++)o[d].programDateTime===null&&di(o[d],o[d-1],h);jn(h,e)}e.endCC=n[n.length-1].cc}if(!e.startCC){var c;const h=Zn(a,e.startSN-1);e.startCC=(c=h==null?void 0:h.cc)!=null?c:n[0].cc}kl(a.partList,e.partList,(h,d)=>{d.elementaryStreams=h.elementaryStreams,d.stats=h.stats}),r?Xn(e,r,r.startPTS,r.endPTS,r.startDTS,r.endDTS,t):zn(a,e),n.length&&(e.totalduration=e.edge-n[0].start),e.driftStartTime=a.driftStartTime,e.driftStart=a.driftStart;const l=e.advancedDateTime;if(e.advanced&&l){const h=e.edge;e.driftStart||(e.driftStartTime=l,e.driftStart=h),e.driftEndTime=l,e.driftEnd=h}else e.driftEndTime=a.driftEndTime,e.driftEnd=a.driftEnd,e.advancedDateTime=a.advancedDateTime;e.requestScheduled===-1&&(e.requestScheduled=a.requestScheduled)}function Pl(a,e,t){const{dateRanges:s,recentlyRemovedDateranges:i}=e,r=ie({},a);i&&i.forEach(c=>{delete r[c]});const o=Object.keys(r).length;return o?(Object.keys(s).forEach(c=>{const l=r[c],h=new Vn(s[c].attr,l);h.isValid?(r[c]=h,l||(h.tagOrder+=o)):t.warn(`Ignoring invalid Playlist Delta Update DATERANGE tag: "${ne(s[c].attr)}"`)}),r):s}function kl(a,e,t){if(a&&e){let s=0;for(let i=0,r=a.length;i<=r;i++){const n=a[i],o=e[i+s];n&&o&&n.index===o.index&&n.fragment.sn===o.fragment.sn?t(n,o):s--}}}function wl(a,e,t){const s=e.skippedSegments,i=Math.max(a.startSN,e.startSN)-e.startSN,r=(a.fragmentHint?1:0)+(s?e.endSN:Math.min(a.endSN,e.endSN))-e.startSN,n=e.startSN-a.startSN,o=e.fragmentHint?e.fragments.concat(e.fragmentHint):e.fragments,c=a.fragmentHint?a.fragments.concat(a.fragmentHint):a.fragments;for(let l=i;l<=r;l++){const h=c[n+l];let d=o[l];if(s&&!d&&h&&(d=e.fragments[l]=h),h&&d){t(h,d,l,o);const u=h.relurl,f=d.relurl;if(u&&Ol(u,f)){e.playlistParsingError=Fr(`media sequence mismatch ${d.sn}:`,a,e,h,d);return}else if(h.cc!==d.cc){e.playlistParsingError=Fr(`discontinuity sequence mismatch (${h.cc}!=${d.cc})`,a,e,h,d);return}}}}function Fr(a,e,t,s,i){return new Error(`${a} ${i.url}
9999+ Time to underbuffer: ${te.toFixed(3)} s`),i.abortRequests(),this.fragCurrent=this.partCurrent=null,W>f){let X=this.findBestLevel(this.hls.levels[f].bitrate,f,W,0,te,1,1);X===-1&&(X=f),this.hls.nextLoadLevel=this.hls.nextAutoLevel=X,this.resetEstimator(this.hls.levels[X].bitrate)}}};y||$>V*2?j():this.timer=self.setInterval(j,V*1e3),a.trigger(m.FRAG_LOAD_EMERGENCY_ABORTED,{frag:i,part:r,stats:h})},this.hls=e,this.bwEstimator=this.initEstimator(),this.registerListeners()}resetEstimator(e){e&&(this.log(`setting initial bwe to ${e}`),this.hls.config.abrEwmaDefaultEstimate=e),this.firstSelection=-1,this.bwEstimator=this.initEstimator()}initEstimator(){const e=this.hls.config;return new $l(e.abrEwmaSlowVoD,e.abrEwmaFastVoD,e.abrEwmaDefaultEstimate)}registerListeners(){const{hls:e}=this;e.on(m.MANIFEST_LOADING,this.onManifestLoading,this),e.on(m.FRAG_LOADING,this.onFragLoading,this),e.on(m.FRAG_LOADED,this.onFragLoaded,this),e.on(m.FRAG_BUFFERED,this.onFragBuffered,this),e.on(m.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(m.LEVEL_LOADED,this.onLevelLoaded,this),e.on(m.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(m.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.on(m.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e&&(e.off(m.MANIFEST_LOADING,this.onManifestLoading,this),e.off(m.FRAG_LOADING,this.onFragLoading,this),e.off(m.FRAG_LOADED,this.onFragLoaded,this),e.off(m.FRAG_BUFFERED,this.onFragBuffered,this),e.off(m.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(m.LEVEL_LOADED,this.onLevelLoaded,this),e.off(m.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(m.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.off(m.ERROR,this.onError,this))}destroy(){this.unregisterListeners(),this.clearTimer(),this.hls=this._abandonRulesCheck=this.supportedCache=null,this.fragCurrent=this.partCurrent=null}onManifestLoading(e,t){this.lastLoadedFragLevel=-1,this.firstSelection=-1,this.lastLevelLoadSec=0,this.supportedCache={},this.fragCurrent=this.partCurrent=null,this.onLevelsUpdated(),this.clearTimer()}onLevelsUpdated(){this.lastLoadedFragLevel>-1&&this.fragCurrent&&(this.lastLoadedFragLevel=this.fragCurrent.level),this._nextAutoLevel=-1,this.onMaxAutoLevelUpdated(),this.codecTiers=null,this.audioTracksByGroup=null}onMaxAutoLevelUpdated(){this.firstSelection=-1,this.nextAutoLevelKey=""}onFragLoading(e,t){const s=t.frag;if(!this.ignoreFragment(s)){if(!s.bitrateTest){var i;this.fragCurrent=s,this.partCurrent=(i=t.part)!=null?i:null}this.clearTimer(),this.timer=self.setInterval(this._abandonRulesCheck,100)}}onLevelSwitching(e,t){this.clearTimer()}onError(e,t){if(!t.fatal)switch(t.details){case R.BUFFER_ADD_CODEC_ERROR:case R.BUFFER_APPEND_ERROR:this.lastLoadedFragLevel=-1,this.firstSelection=-1;break;case R.FRAG_LOAD_TIMEOUT:{const s=t.frag,{fragCurrent:i,partCurrent:r}=this;if(s&&i&&s.sn===i.sn&&s.level===i.level){const a=performance.now(),o=r?r.stats:s.stats,c=a-o.loading.start,l=o.loading.first?o.loading.first-o.loading.start:-1;if(o.loaded&&l>-1){const u=this.bwEstimator.getEstimateTTFB();this.bwEstimator.sample(c-Math.min(u,l),o.loaded)}else this.bwEstimator.sampleTTFB(c)}break}}}getTimeToLoadFrag(e,t,s,i){const r=e+s/t,a=i?e+this.lastLevelLoadSec:0;return r+a}onLevelLoaded(e,t){const s=this.hls.config,{loading:i}=t.stats,r=i.end-i.first;M(r)&&(this.lastLevelLoadSec=r/1e3),t.details.live?this.bwEstimator.update(s.abrEwmaSlowLive,s.abrEwmaFastLive):this.bwEstimator.update(s.abrEwmaSlowVoD,s.abrEwmaFastVoD),this.timer>-1&&this._abandonRulesCheck(t.levelInfo)}onFragLoaded(e,{frag:t,part:s}){const i=s?s.stats:t.stats;if(t.type===U.MAIN&&this.bwEstimator.sampleTTFB(i.loading.first-i.loading.start),!this.ignoreFragment(t)){if(this.clearTimer(),t.level===this._nextAutoLevel&&(this._nextAutoLevel=-1),this.firstSelection=-1,this.hls.config.abrMaxWithRealBitrate){const r=s?s.duration:t.duration,a=this.hls.levels[t.level],o=(a.loaded?a.loaded.bytes:0)+i.loaded,c=(a.loaded?a.loaded.duration:0)+r;a.loaded={bytes:o,duration:c},a.realBitrate=Math.round(8*o/c)}if(t.bitrateTest){const r={stats:i,frag:t,part:s,id:t.type};this.onFragBuffered(m.FRAG_BUFFERED,r),t.bitrateTest=!1}else this.lastLoadedFragLevel=t.level}}onFragBuffered(e,t){const{frag:s,part:i}=t,r=i!=null&&i.stats.loaded?i.stats:s.stats;if(r.aborted||this.ignoreFragment(s))return;const a=r.parsing.end-r.loading.start-Math.min(r.loading.first-r.loading.start,this.bwEstimator.getEstimateTTFB());this.bwEstimator.sample(a,r.loaded),r.bwEstimate=this.getBwEstimate(),s.bitrateTest?this.bitrateTestDelay=a/1e3:this.bitrateTestDelay=0}ignoreFragment(e){return e.type!==U.MAIN||e.sn==="initSegment"}clearTimer(){this.timer>-1&&(self.clearInterval(this.timer),this.timer=-1)}get firstAutoLevel(){const{maxAutoLevel:e,minAutoLevel:t}=this.hls,s=this.getBwEstimate(),i=this.hls.config.maxStarvationDelay,r=this.findBestLevel(s,t,e,0,i,1,1);if(r>-1)return r;const a=this.hls.firstLevel,o=Math.min(Math.max(a,t),e);return this.warn(`Could not find best starting auto level. Defaulting to first in playlist ${a} clamped to ${o}`),o}get forcedAutoLevel(){return this.nextAutoLevelKey?-1:this._nextAutoLevel}get nextAutoLevel(){const e=this.forcedAutoLevel,s=this.bwEstimator.canEstimate(),i=this.lastLoadedFragLevel>-1;if(e!==-1&&(!s||!i||this.nextAutoLevelKey===this.getAutoLevelKey()))return e;const r=s&&i?this.getNextABRAutoLevel():this.firstAutoLevel;if(e!==-1){const a=this.hls.levels;if(a.length>Math.max(e,r)&&a[e].loadError<=a[r].loadError)return e}return this._nextAutoLevel=r,this.nextAutoLevelKey=this.getAutoLevelKey(),r}getAutoLevelKey(){return`${this.getBwEstimate()}_${this.getStarvationDelay().toFixed(2)}`}getNextABRAutoLevel(){const{fragCurrent:e,partCurrent:t,hls:s}=this;if(s.levels.length<=1)return s.loadLevel;const{maxAutoLevel:i,config:r,minAutoLevel:a}=s,o=t?t.duration:e?e.duration:0,c=this.getBwEstimate(),l=this.getStarvationDelay();let h=r.abrBandWidthFactor,u=r.abrBandWidthUpFactor;if(l){const y=this.findBestLevel(c,a,i,l,0,h,u);if(y>=0)return this.rebufferNotice=-1,y}let d=o?Math.min(o,r.maxStarvationDelay):r.maxStarvationDelay;if(!l){const y=this.bitrateTestDelay;y&&(d=(o?Math.min(o,r.maxLoadingDelay):r.maxLoadingDelay)-y,this.info(`bitrate test took ${Math.round(1e3*y)}ms, set first fragment max fetchDuration to ${Math.round(1e3*d)} ms`),h=u=1)}const f=this.findBestLevel(c,a,i,l,d,h,u);if(this.rebufferNotice!==f&&(this.rebufferNotice=f,this.info(`${l?"rebuffering expected":"buffer is empty"}, optimal quality level ${f}`)),f>-1)return f;const g=s.levels[a],p=s.loadLevelObj;return p&&(g==null?void 0:g.bitrate)<p.bitrate?a:s.loadLevel}getStarvationDelay(){const e=this.hls,t=e.media;if(!t)return 1/0;const s=t&&t.playbackRate!==0?Math.abs(t.playbackRate):1,i=e.mainForwardBufferInfo;return(i?i.len:0)/s}getBwEstimate(){return this.bwEstimator.canEstimate()?this.bwEstimator.getEstimate():this.hls.config.abrEwmaDefaultEstimate}findBestLevel(e,t,s,i,r,a,o){var c;const l=i+r,h=this.lastLoadedFragLevel,u=h===-1?this.hls.firstLevel:h,{fragCurrent:d,partCurrent:f}=this,{levels:g,allAudioTracks:p,loadLevel:y,config:E}=this.hls;if(g.length===1)return 0;const T=g[u],S=!!((c=this.hls.latestLevelDetails)!=null&&c.live),v=y===-1||h===-1;let x,D="SDR",A=(T==null?void 0:T.frameRate)||0;const{audioPreference:b,videoPreference:I}=E,_=this.audioTracksByGroup||(this.audioTracksByGroup=Fa(p));let C=-1;if(v){if(this.firstSelection!==-1)return this.firstSelection;const w=this.codecTiers||(this.codecTiers=Pc(g,_,t,s)),G=Cc(w,D,e,b,I),{codecSet:N,videoRanges:V,minFramerate:W,minBitrate:O,minIndex:F,preferHDR:j}=G;C=F,x=N,D=j?V[V.length-1]:V[0],A=W,e=Math.max(e,O),this.log(`picked start tier ${oe(G)}`)}else x=T==null?void 0:T.codecSet,D=T==null?void 0:T.videoRange;const k=f?f.duration:d?d.duration:0,B=this.bwEstimator.getEstimateTTFB()/1e3,K=[];for(let w=s;w>=t;w--){var $;const G=g[w],N=w>u;if(!G)continue;if(E.useMediaCapabilities&&!G.supportedResult&&!G.supportedPromise){const X=navigator.mediaCapabilities;typeof(X==null?void 0:X.decodingInfo)=="function"&&Sc(G,_,D,A,e,b)?(G.supportedPromise=wa(G,_,X,this.supportedCache),G.supportedPromise.then(J=>{if(!this.hls)return;G.supportedResult=J;const ve=this.hls.levels,ye=ve.indexOf(G);J.error?this.warn(`MediaCapabilities decodingInfo error: "${J.error}" for level ${ye} ${oe(J)}`):J.supported?J.decodingInfoResults.some(Pe=>Pe.smooth===!1||Pe.powerEfficient===!1)&&this.log(`MediaCapabilities decodingInfo for level ${ye} not smooth or powerEfficient: ${oe(J)}`):(this.warn(`Unsupported MediaCapabilities decodingInfo result for level ${ye} ${oe(J)}`),ye>-1&&ve.length>1&&(this.log(`Removing unsupported level ${ye}`),this.hls.removeLevel(ye),this.hls.loadLevel===-1&&(this.hls.nextLoadLevel=0)))}).catch(J=>{this.warn(`Error handling MediaCapabilities decodingInfo: ${J}`)})):G.supportedResult=Pa}if((x&&G.codecSet!==x||D&&G.videoRange!==D||N&&A>G.frameRate||!N&&A>0&&A<G.frameRate||($=G.supportedResult)!=null&&($=$.decodingInfoResults)!=null&&$.some(X=>X.smooth===!1))&&(!v||w!==C)){K.push(w);continue}const V=G.details,W=(f?V==null?void 0:V.partTarget:V==null?void 0:V.averagetargetduration)||k;let O;N?O=o*e:O=a*e;const F=k&&i>=k*2&&r===0?G.averageBitrate:G.maxBitrate,j=this.getTimeToLoadFrag(B,O,F*W,V===void 0);if(O>=F&&(w===h||G.loadError===0&&G.fragmentError===0)&&(j<=B||!M(j)||S&&!this.bitrateTestDelay||j<l)){const X=this.forcedAutoLevel;return w!==y&&(X===-1||X!==y)&&(K.length&&this.trace(`Skipped level(s) ${K.join(",")} of ${s} max with CODECS and VIDEO-RANGE:"${g[K[0]].codecs}" ${g[K[0]].videoRange}; not compatible with "${x}" ${D}`),this.info(`switch candidate:${u}->${w} adjustedbw(${Math.round(O)})-bitrate=${Math.round(O-F)} ttfb:${B.toFixed(1)} avgDuration:${W.toFixed(1)} maxFetchDuration:${l.toFixed(1)} fetchDuration:${j.toFixed(1)} firstSelection:${v} codecSet:${G.codecSet} videoRange:${G.videoRange} hls.loadLevel:${y}`)),v&&(this.firstSelection=w),w}}return-1}set nextAutoLevel(e){const t=this.deriveNextAutoLevel(e);this._nextAutoLevel!==t&&(this.nextAutoLevelKey="",this._nextAutoLevel=t)}deriveNextAutoLevel(e){const{maxAutoLevel:t,minAutoLevel:s}=this.hls;return Math.min(Math.max(e,s),t)}}const Ma={search:function(n,e){let t=0,s=n.length-1,i=null,r=null;for(;t<=s;){i=(t+s)/2|0,r=n[i];const a=e(r);if(a>0)t=i+1;else if(a<0)s=i-1;else return r}return null}};function Mc(n,e,t){if(e===null||!Array.isArray(n)||!n.length||!M(e))return null;const s=n[0].programDateTime;if(e<(s||0))return null;const i=n[n.length-1].endProgramDateTime;if(e>=(i||0))return null;for(let r=0;r<n.length;++r){const a=n[r];if(Bc(e,t,a))return a}return null}function mt(n,e,t=0,s=0,i=.005){let r=null;if(n){r=e[1+n.sn-e[0].sn]||null;const o=n.endDTS-t;o>0&&o<15e-7&&(t+=15e-7),r&&n.level!==r.level&&r.end<=n.end&&(r=e[2+n.sn-e[0].sn]||null)}else t===0&&e[0].start===0&&(r=e[0]);if(r&&((!n||n.level===r.level)&&jr(t,s,r)===0||Nc(r,n,Math.min(i,s))))return r;const a=Ma.search(e,jr.bind(null,t,s));return a&&(a!==n||!r)?a:r}function Nc(n,e,t){if(e&&e.start===0&&e.level<n.level&&(e.endPTS||0)>0){const s=e.tagList.reduce((i,r)=>(r[0]==="INF"&&(i+=parseFloat(r[1])),i),t);return n.start<=s}return!1}function jr(n=0,e=0,t){if(t.start<=n&&t.start+t.duration>n)return 0;const s=Math.min(e,t.duration+(t.deltaPTS?t.deltaPTS:0));return t.start+t.duration-s<=n?1:t.start-s>n&&t.start?-1:0}function Bc(n,e,t){const s=Math.min(e,t.duration+(t.deltaPTS?t.deltaPTS:0))*1e3;return(t.endProgramDateTime||0)-s>n}function Na(n,e,t){if(n&&n.startCC<=e&&n.endCC>=e){let s=n.fragments;const{fragmentHint:i}=n;i&&(s=s.concat(i));let r;return Ma.search(s,a=>a.cc<e?1:a.cc>e?-1:(r=a,a.end<=t?1:a.start>t?-1:0)),r||null}return null}function ks(n){switch(n.details){case R.FRAG_LOAD_TIMEOUT:case R.KEY_LOAD_TIMEOUT:case R.LEVEL_LOAD_TIMEOUT:case R.MANIFEST_LOAD_TIMEOUT:return!0}return!1}function Ba(n){return n.details.startsWith("key")}function Ua(n){return Ba(n)&&!!n.frag&&!n.frag.decryptdata}function Xr(n,e){const t=ks(e);return n.default[`${t?"timeout":"error"}Retry`]}function Qi(n,e){const t=n.backoff==="linear"?1:Math.pow(2,e);return Math.min(t*n.retryDelayMs,n.maxRetryDelayMs)}function zr(n){return se(se({},n),{errorRetry:null,timeoutRetry:null})}function ws(n,e,t,s){if(!n)return!1;const i=s==null?void 0:s.code,r=e<n.maxNumRetry&&(Uc(i)||!!t);return n.shouldRetry?n.shouldRetry(n,e,t,s,r):r}function Uc(n){return Ri(n)||!!n&&(n<400||n>499)}function Ri(n){return n===0&&navigator.onLine===!1}var Ee={DoNothing:0,SendAlternateToPenaltyBox:2,RemoveAlternatePermanently:3,RetryRequest:5},Re={None:0,MoveAllAlternatesMatchingHost:1,MoveAllAlternatesMatchingHDCP:2,MoveAllAlternatesMatchingKey:4};class $c extends Fe{constructor(e){super("error-controller",e.logger),this.hls=void 0,this.playlistError=0,this.hls=e,this.registerListeners()}registerListeners(){const e=this.hls;e.on(m.ERROR,this.onError,this),e.on(m.MANIFEST_LOADING,this.onManifestLoading,this),e.on(m.LEVEL_UPDATED,this.onLevelUpdated,this)}unregisterListeners(){const e=this.hls;e&&(e.off(m.ERROR,this.onError,this),e.off(m.ERROR,this.onErrorOut,this),e.off(m.MANIFEST_LOADING,this.onManifestLoading,this),e.off(m.LEVEL_UPDATED,this.onLevelUpdated,this))}destroy(){this.unregisterListeners(),this.hls=null}startLoad(e){}stopLoad(){this.playlistError=0}getVariantLevelIndex(e){return(e==null?void 0:e.type)===U.MAIN?e.level:this.getVariantIndex()}getVariantIndex(){var e;const t=this.hls,s=t.currentLevel;return(e=t.loadLevelObj)!=null&&e.details||s===-1?t.loadLevel:s}variantHasKey(e,t){if(e){var s;if((s=e.details)!=null&&s.hasKey(t))return!0;const i=e.audioGroups;if(i)return this.hls.allAudioTracks.filter(a=>i.indexOf(a.groupId)>=0).some(a=>{var o;return(o=a.details)==null?void 0:o.hasKey(t)})}return!1}onManifestLoading(){this.playlistError=0}onLevelUpdated(){this.playlistError=0}onError(e,t){var s;if(t.fatal)return;const i=this.hls,r=t.context;switch(t.details){case R.FRAG_LOAD_ERROR:case R.FRAG_LOAD_TIMEOUT:case R.KEY_LOAD_ERROR:case R.KEY_LOAD_TIMEOUT:t.errorAction=this.getFragRetryOrSwitchAction(t);return;case R.FRAG_PARSING_ERROR:if((s=t.frag)!=null&&s.gap){t.errorAction=_t();return}case R.FRAG_GAP:case R.FRAG_DECRYPT_ERROR:{t.errorAction=this.getFragRetryOrSwitchAction(t),t.errorAction.action=Ee.SendAlternateToPenaltyBox;return}case R.LEVEL_EMPTY_ERROR:case R.LEVEL_PARSING_ERROR:{var a;const c=t.parent===U.MAIN?t.level:i.loadLevel;t.details===R.LEVEL_EMPTY_ERROR&&((a=t.context)!=null&&(a=a.levelDetails)!=null&&a.live)?t.errorAction=this.getPlaylistRetryOrSwitchAction(t,c):(t.levelRetry=!1,t.errorAction=this.getLevelSwitchAction(t,c))}return;case R.LEVEL_LOAD_ERROR:case R.LEVEL_LOAD_TIMEOUT:typeof(r==null?void 0:r.level)=="number"&&(t.errorAction=this.getPlaylistRetryOrSwitchAction(t,r.level));return;case R.AUDIO_TRACK_LOAD_ERROR:case R.AUDIO_TRACK_LOAD_TIMEOUT:case R.SUBTITLE_LOAD_ERROR:case R.SUBTITLE_TRACK_LOAD_TIMEOUT:if(r){const c=i.loadLevelObj;if(c&&(r.type===Q.AUDIO_TRACK&&c.hasAudioGroup(r.groupId)||r.type===Q.SUBTITLE_TRACK&&c.hasSubtitleGroup(r.groupId))){t.errorAction=this.getPlaylistRetryOrSwitchAction(t,i.loadLevel),t.errorAction.action=Ee.SendAlternateToPenaltyBox,t.errorAction.flags=Re.MoveAllAlternatesMatchingHost;return}}return;case R.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:t.errorAction={action:Ee.SendAlternateToPenaltyBox,flags:Re.MoveAllAlternatesMatchingHDCP};return;case R.KEY_SYSTEM_SESSION_UPDATE_FAILED:case R.KEY_SYSTEM_STATUS_INTERNAL_ERROR:case R.KEY_SYSTEM_NO_SESSION:t.errorAction={action:Ee.SendAlternateToPenaltyBox,flags:Re.MoveAllAlternatesMatchingKey};return;case R.BUFFER_ADD_CODEC_ERROR:case R.REMUX_ALLOC_ERROR:case R.BUFFER_APPEND_ERROR:if(!t.errorAction){var o;t.errorAction=this.getLevelSwitchAction(t,(o=t.level)!=null?o:i.loadLevel)}return;case R.INTERNAL_EXCEPTION:case R.BUFFER_APPENDING_ERROR:case R.BUFFER_FULL_ERROR:case R.LEVEL_SWITCH_ERROR:case R.BUFFER_STALLED_ERROR:case R.BUFFER_SEEK_OVER_HOLE:case R.BUFFER_NUDGE_ON_STALL:t.errorAction=_t();return}t.type===H.KEY_SYSTEM_ERROR&&(t.levelRetry=!1,t.errorAction=_t())}getPlaylistRetryOrSwitchAction(e,t){const s=this.hls,i=Xr(s.config.playlistLoadPolicy,e),r=this.playlistError++;if(ws(i,r,ks(e),e.response))return{action:Ee.RetryRequest,flags:Re.None,retryConfig:i,retryCount:r};const o=this.getLevelSwitchAction(e,t);return i&&(o.retryConfig=i,o.retryCount=r),o}getFragRetryOrSwitchAction(e){const t=this.hls,s=this.getVariantLevelIndex(e.frag),i=t.levels[s],{fragLoadPolicy:r,keyLoadPolicy:a}=t.config,o=Xr(Ba(e)?a:r,e),c=t.levels.reduce((h,u)=>h+u.fragmentError,0);if(i&&(e.details!==R.FRAG_GAP&&i.fragmentError++,!Ua(e)&&ws(o,c,ks(e),e.response)))return{action:Ee.RetryRequest,flags:Re.None,retryConfig:o,retryCount:c};const l=this.getLevelSwitchAction(e,s);return o&&(l.retryConfig=o,l.retryCount=c),l}getLevelSwitchAction(e,t){const s=this.hls;t==null&&(t=s.loadLevel);const i=this.hls.levels[t];if(i){var r,a;const l=e.details;i.loadError++,l===R.BUFFER_APPEND_ERROR&&i.fragmentError++;let h=-1;const{levels:u,loadLevel:d,minAutoLevel:f,maxAutoLevel:g}=s;!s.autoLevelEnabled&&!s.config.preserveManualLevelOnError&&(s.loadLevel=-1);const p=(r=e.frag)==null?void 0:r.type,E=(p===U.AUDIO&&l===R.FRAG_PARSING_ERROR||e.sourceBufferName==="audio"&&(l===R.BUFFER_ADD_CODEC_ERROR||l===R.BUFFER_APPEND_ERROR))&&u.some(({audioCodec:D})=>i.audioCodec!==D),S=e.sourceBufferName==="video"&&(l===R.BUFFER_ADD_CODEC_ERROR||l===R.BUFFER_APPEND_ERROR)&&u.some(({codecSet:D,audioCodec:A})=>i.codecSet!==D&&i.audioCodec===A),{type:v,groupId:x}=(a=e.context)!=null?a:{};for(let D=u.length;D--;){const A=(D+d)%u.length;if(A!==d&&A>=f&&A<=g&&u[A].loadError===0){var o,c;const b=u[A];if(l===R.FRAG_GAP&&p===U.MAIN&&e.frag){const I=u[A].details;if(I){const _=mt(e.frag,I.fragments,e.frag.start);if(_!=null&&_.gap)continue}}else{if(v===Q.AUDIO_TRACK&&b.hasAudioGroup(x)||v===Q.SUBTITLE_TRACK&&b.hasSubtitleGroup(x))continue;if(p===U.AUDIO&&(o=i.audioGroups)!=null&&o.some(I=>b.hasAudioGroup(I))||p===U.SUBTITLE&&(c=i.subtitleGroups)!=null&&c.some(I=>b.hasSubtitleGroup(I))||E&&i.audioCodec===b.audioCodec||S&&i.codecSet===b.codecSet||!E&&i.codecSet!==b.codecSet)continue}h=A;break}}if(h>-1&&s.loadLevel!==h)return e.levelRetry=!0,this.playlistError=0,{action:Ee.SendAlternateToPenaltyBox,flags:Re.None,nextAutoLevel:h}}return{action:Ee.SendAlternateToPenaltyBox,flags:Re.MoveAllAlternatesMatchingHost}}onErrorOut(e,t){var s;switch((s=t.errorAction)==null?void 0:s.action){case Ee.DoNothing:break;case Ee.SendAlternateToPenaltyBox:this.sendAlternateToPenaltyBox(t),!t.errorAction.resolved&&t.details!==R.FRAG_GAP?t.fatal=!0:/MediaSource readyState: ended/.test(t.error.message)&&(this.warn(`MediaSource ended after "${t.sourceBufferName}" sourceBuffer append error. Attempting to recover from media error.`),this.hls.recoverMediaError());break}if(t.fatal){this.hls.stopLoad();return}}sendAlternateToPenaltyBox(e){const t=this.hls,s=e.errorAction;if(!s)return;const{flags:i}=s,r=s.nextAutoLevel;switch(i){case Re.None:this.switchLevel(e,r);break;case Re.MoveAllAlternatesMatchingHDCP:{const c=this.getVariantLevelIndex(e.frag),l=t.levels[c],h=l==null?void 0:l.attrs["HDCP-LEVEL"];if(s.hdcpLevel=h,h==="NONE")this.warn("HDCP policy resticted output with HDCP-LEVEL=NONE");else if(h){t.maxHdcpLevel=Li[Li.indexOf(h)-1],s.resolved=!0,this.warn(`Restricting playback to HDCP-LEVEL of "${t.maxHdcpLevel}" or lower`);break}}case Re.MoveAllAlternatesMatchingKey:{const c=e.decryptdata;if(c){const l=this.hls.levels,h=l.length;for(let d=h;d--;)if(this.variantHasKey(l[d],c)){var a,o;this.log(`Banned key found in level ${d} (${l[d].bitrate}bps) or audio group "${(a=l[d].audioGroups)==null?void 0:a.join(",")}" (${(o=e.frag)==null?void 0:o.type} fragment) ${Te(c.keyId||[])}`),l[d].fragmentError++,l[d].loadError++,this.log(`Removing level ${d} with key error (${e.error})`),this.hls.removeLevel(d)}const u=e.frag;if(this.hls.levels.length<h)s.resolved=!0;else if(u&&u.type!==U.MAIN){const d=u.decryptdata;d&&!c.matches(d)&&(s.resolved=!0)}}break}}s.resolved||this.switchLevel(e,r)}switchLevel(e,t){if(t!==void 0&&e.errorAction&&(this.warn(`switching to level ${t} after ${e.details}`),this.hls.nextAutoLevel=t,e.errorAction.resolved=!0,this.hls.nextLoadLevel=this.hls.nextAutoLevel,e.details===R.BUFFER_ADD_CODEC_ERROR&&e.mimeType&&e.sourceBufferName!=="audiovideo")){const s=Ii(e.mimeType),i=this.hls.levels;for(let r=i.length;r--;)i[r][`${e.sourceBufferName}Codec`]===s&&(this.log(`Removing level ${r} for ${e.details} ("${s}" not supported)`),this.hls.removeLevel(r))}}}function _t(n){const e={action:Ee.DoNothing,flags:Re.None};return n&&(e.resolved=!0),e}var me={NOT_LOADED:"NOT_LOADED",APPENDING:"APPENDING",PARTIAL:"PARTIAL",OK:"OK"};class Gc{constructor(e){this.activePartLists=Object.create(null),this.endListFragments=Object.create(null),this.fragments=Object.create(null),this.timeRanges=Object.create(null),this.bufferPadding=.2,this.hls=void 0,this.hasGaps=!1,this.hls=e,this._registerListeners()}_registerListeners(){const{hls:e}=this;e&&(e.on(m.MANIFEST_LOADING,this.onManifestLoading,this),e.on(m.BUFFER_APPENDED,this.onBufferAppended,this),e.on(m.FRAG_BUFFERED,this.onFragBuffered,this),e.on(m.FRAG_LOADED,this.onFragLoaded,this))}_unregisterListeners(){const{hls:e}=this;e&&(e.off(m.MANIFEST_LOADING,this.onManifestLoading,this),e.off(m.BUFFER_APPENDED,this.onBufferAppended,this),e.off(m.FRAG_BUFFERED,this.onFragBuffered,this),e.off(m.FRAG_LOADED,this.onFragLoaded,this))}destroy(){this._unregisterListeners(),this.hls=this.fragments=this.activePartLists=this.endListFragments=this.timeRanges=null}getAppendedFrag(e,t){const s=this.activePartLists[t];if(s)for(let i=s.length;i--;){const r=s[i];if(!r)break;if(r.start<=e&&e<=r.end&&r.loaded)return r}return this.getBufferedFrag(e,t)}getBufferedFrag(e,t){return this.getFragAtPos(e,t,!0)}getFragAtPos(e,t,s){const{fragments:i}=this,r=Object.keys(i);for(let a=r.length;a--;){const o=i[r[a]];if((o==null?void 0:o.body.type)===t&&(!s||o.buffered)){const c=o.body;if(c.start<=e&&e<=c.end)return c}}return null}detectEvictedFragments(e,t,s,i,r){this.timeRanges&&(this.timeRanges[e]=t);const a=(i==null?void 0:i.fragment.sn)||-1;Object.keys(this.fragments).forEach(o=>{const c=this.fragments[o];if(!c||a>=c.body.sn)return;if(!c.buffered&&(!c.loaded||r)){c.body.type===s&&this.removeFragment(c.body);return}const l=c.range[e];if(l){if(l.time.length===0){this.removeFragment(c.body);return}l.time.some(h=>{const u=!this.isTimeBuffered(h.startPTS,h.endPTS,t);return u&&this.removeFragment(c.body),u})}})}detectPartialFragments(e){const t=this.timeRanges;if(!t||e.frag.sn==="initSegment")return;const s=e.frag,i=Et(s),r=this.fragments[i];if(!r||r.buffered&&s.gap)return;const a=!s.relurl;Object.keys(t).forEach(o=>{const c=s.elementaryStreams[o];if(!c)return;const l=t[o],h=a||c.partial===!0;r.range[o]=this.getBufferedTimes(s,e.part,h,l)}),r.loaded=null,Object.keys(r.range).length?(this.bufferedEnd(r,s),Jt(r)||this.removeParts(s.sn-1,s.type)):this.removeFragment(r.body)}bufferedEnd(e,t){e.buffered=!0,(e.body.endList=t.endList||e.body.endList)&&(this.endListFragments[e.body.type]=e)}removeParts(e,t){const s=this.activePartLists[t];s&&(this.activePartLists[t]=Qr(s,i=>i.fragment.sn>=e))}fragBuffered(e,t){const s=Et(e);let i=this.fragments[s];!i&&t&&(i=this.fragments[s]={body:e,appendedPTS:null,loaded:null,buffered:!1,range:Object.create(null)},e.gap&&(this.hasGaps=!0)),i&&(i.loaded=null,this.bufferedEnd(i,e))}getBufferedTimes(e,t,s,i){const r={time:[],partial:s},a=e.start,o=e.end,c=e.minEndPTS||o,l=e.maxStartPTS||a;for(let h=0;h<i.length;h++){const u=i.start(h)-this.bufferPadding,d=i.end(h)+this.bufferPadding;if(l>=u&&c<=d){r.time.push({startPTS:Math.max(a,i.start(h)),endPTS:Math.min(o,i.end(h))});break}else if(a<d&&o>u){const f=Math.max(a,i.start(h)),g=Math.min(o,i.end(h));g>f&&(r.partial=!0,r.time.push({startPTS:f,endPTS:g}))}else if(o<=u)break}return r}getPartialFragment(e){let t=null,s,i,r,a=0;const{bufferPadding:o,fragments:c}=this;return Object.keys(c).forEach(l=>{const h=c[l];h&&Jt(h)&&(i=h.body.start-o,r=h.body.end+o,e>=i&&e<=r&&(s=Math.min(e-i,r-e),a<=s&&(t=h.body,a=s)))}),t}isEndListAppended(e){const t=this.endListFragments[e];return t!==void 0&&(t.buffered||Jt(t))}getState(e){const t=Et(e),s=this.fragments[t];return s?s.buffered?Jt(s)?me.PARTIAL:me.OK:me.APPENDING:me.NOT_LOADED}isTimeBuffered(e,t,s){let i,r;for(let a=0;a<s.length;a++){if(i=s.start(a)-this.bufferPadding,r=s.end(a)+this.bufferPadding,e>=i&&t<=r)return!0;if(t<=i)return!1}return!1}onManifestLoading(){this.removeAllFragments()}onFragLoaded(e,t){if(t.frag.sn==="initSegment"||t.frag.bitrateTest)return;const s=t.frag,i=t.part?null:t,r=Et(s);this.fragments[r]={body:s,appendedPTS:null,loaded:i,buffered:!1,range:Object.create(null)}}onBufferAppended(e,t){const{frag:s,part:i,timeRanges:r,type:a}=t;if(s.sn==="initSegment")return;const o=s.type;if(i){let l=this.activePartLists[o];l||(this.activePartLists[o]=l=[]),l.push(i)}this.timeRanges=r;const c=r[a];this.detectEvictedFragments(a,c,o,i)}onFragBuffered(e,t){this.detectPartialFragments(t)}hasFragment(e){const t=Et(e);return!!this.fragments[t]}hasFragments(e){const{fragments:t}=this,s=Object.keys(t);if(!e)return s.length>0;for(let i=s.length;i--;){const r=t[s[i]];if((r==null?void 0:r.body.type)===e)return!0}return!1}hasParts(e){var t;return!!((t=this.activePartLists[e])!=null&&t.length)}removeFragmentsInRange(e,t,s,i,r){i&&!this.hasGaps||Object.keys(this.fragments).forEach(a=>{const o=this.fragments[a];if(!o)return;const c=o.body;c.type!==s||i&&!c.gap||c.start<t&&c.end>e&&(o.buffered||r)&&this.removeFragment(c)})}removeFragment(e){const t=Et(e);e.clearElementaryStreamInfo();const s=this.activePartLists[e.type];if(s){const i=e.sn;this.activePartLists[e.type]=Qr(s,r=>r.fragment.sn!==i)}delete this.fragments[t],e.endList&&delete this.endListFragments[e.type]}removeAllFragments(){var e;this.fragments=Object.create(null),this.endListFragments=Object.create(null),this.activePartLists=Object.create(null),this.hasGaps=!1;const t=(e=this.hls)==null||(e=e.latestLevelDetails)==null?void 0:e.partList;t&&t.forEach(s=>s.clearElementaryStreamInfo())}}function Jt(n){var e,t,s;return n.buffered&&!!(n.body.gap||(e=n.range.video)!=null&&e.partial||(t=n.range.audio)!=null&&t.partial||(s=n.range.audiovideo)!=null&&s.partial)}function Et(n){return`${n.type}_${n.level}_${n.sn}`}function Qr(n,e){return n.filter(t=>{const s=e(t);return s||t.clearElementaryStreamInfo(),s})}var ot={cbc:0,ctr:1};class Kc{constructor(e,t,s){this.subtle=void 0,this.aesIV=void 0,this.aesMode=void 0,this.subtle=e,this.aesIV=t,this.aesMode=s}decrypt(e,t){switch(this.aesMode){case ot.cbc:return this.subtle.decrypt({name:"AES-CBC",iv:this.aesIV},t,e);case ot.ctr:return this.subtle.decrypt({name:"AES-CTR",counter:this.aesIV,length:64},t,e);default:throw new Error(`[AESCrypto] invalid aes mode ${this.aesMode}`)}}}function Vc(n){const e=n.byteLength,t=e&&new DataView(n.buffer).getUint8(e-1);return t?n.slice(0,e-t):n}class Hc{constructor(){this.rcon=[0,1,2,4,8,16,32,64,128,27,54],this.subMix=[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)],this.invSubMix=[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)],this.sBox=new Uint32Array(256),this.invSBox=new Uint32Array(256),this.key=new Uint32Array(0),this.ksRows=0,this.keySize=0,this.keySchedule=void 0,this.invKeySchedule=void 0,this.initTable()}uint8ArrayToUint32Array_(e){const t=new DataView(e),s=new Uint32Array(4);for(let i=0;i<4;i++)s[i]=t.getUint32(i*4);return s}initTable(){const e=this.sBox,t=this.invSBox,s=this.subMix,i=s[0],r=s[1],a=s[2],o=s[3],c=this.invSubMix,l=c[0],h=c[1],u=c[2],d=c[3],f=new Uint32Array(256);let g=0,p=0,y=0;for(y=0;y<256;y++)y<128?f[y]=y<<1:f[y]=y<<1^283;for(y=0;y<256;y++){let E=p^p<<1^p<<2^p<<3^p<<4;E=E>>>8^E&255^99,e[g]=E,t[E]=g;const T=f[g],S=f[T],v=f[S];let x=f[E]*257^E*16843008;i[g]=x<<24|x>>>8,r[g]=x<<16|x>>>16,a[g]=x<<8|x>>>24,o[g]=x,x=v*16843009^S*65537^T*257^g*16843008,l[E]=x<<24|x>>>8,h[E]=x<<16|x>>>16,u[E]=x<<8|x>>>24,d[E]=x,g?(g=T^f[f[f[v^T]]],p^=f[f[p]]):g=p=1}}expandKey(e){const t=this.uint8ArrayToUint32Array_(e);let s=!0,i=0;for(;i<t.length&&s;)s=t[i]===this.key[i],i++;if(s)return;this.key=t;const r=this.keySize=t.length;if(r!==4&&r!==6&&r!==8)throw new Error("Invalid aes key size="+r);const a=this.ksRows=(r+6+1)*4;let o,c;const l=this.keySchedule=new Uint32Array(a),h=this.invKeySchedule=new Uint32Array(a),u=this.sBox,d=this.rcon,f=this.invSubMix,g=f[0],p=f[1],y=f[2],E=f[3];let T,S;for(o=0;o<a;o++){if(o<r){T=l[o]=t[o];continue}S=T,o%r===0?(S=S<<8|S>>>24,S=u[S>>>24]<<24|u[S>>>16&255]<<16|u[S>>>8&255]<<8|u[S&255],S^=d[o/r|0]<<24):r>6&&o%r===4&&(S=u[S>>>24]<<24|u[S>>>16&255]<<16|u[S>>>8&255]<<8|u[S&255]),l[o]=T=(l[o-r]^S)>>>0}for(c=0;c<a;c++)o=a-c,c&3?S=l[o]:S=l[o-4],c<4||o<=4?h[c]=S:h[c]=g[u[S>>>24]]^p[u[S>>>16&255]]^y[u[S>>>8&255]]^E[u[S&255]],h[c]=h[c]>>>0}networkToHostOrderSwap(e){return e<<24|(e&65280)<<8|(e&16711680)>>8|e>>>24}decrypt(e,t,s){const i=this.keySize+6,r=this.invKeySchedule,a=this.invSBox,o=this.invSubMix,c=o[0],l=o[1],h=o[2],u=o[3],d=this.uint8ArrayToUint32Array_(s);let f=d[0],g=d[1],p=d[2],y=d[3];const E=new Int32Array(e),T=new Int32Array(E.length);let S,v,x,D,A,b,I,_,C,k,B,K,$,w;const G=this.networkToHostOrderSwap;for(;t<E.length;){for(C=G(E[t]),k=G(E[t+1]),B=G(E[t+2]),K=G(E[t+3]),A=C^r[0],b=K^r[1],I=B^r[2],_=k^r[3],$=4,w=1;w<i;w++)S=c[A>>>24]^l[b>>16&255]^h[I>>8&255]^u[_&255]^r[$],v=c[b>>>24]^l[I>>16&255]^h[_>>8&255]^u[A&255]^r[$+1],x=c[I>>>24]^l[_>>16&255]^h[A>>8&255]^u[b&255]^r[$+2],D=c[_>>>24]^l[A>>16&255]^h[b>>8&255]^u[I&255]^r[$+3],A=S,b=v,I=x,_=D,$=$+4;S=a[A>>>24]<<24^a[b>>16&255]<<16^a[I>>8&255]<<8^a[_&255]^r[$],v=a[b>>>24]<<24^a[I>>16&255]<<16^a[_>>8&255]<<8^a[A&255]^r[$+1],x=a[I>>>24]<<24^a[_>>16&255]<<16^a[A>>8&255]<<8^a[b&255]^r[$+2],D=a[_>>>24]<<24^a[A>>16&255]<<16^a[b>>8&255]<<8^a[I&255]^r[$+3],T[t]=G(S^f),T[t+1]=G(D^g),T[t+2]=G(x^p),T[t+3]=G(v^y),f=C,g=k,p=B,y=K,t=t+4}return T.buffer}}class Wc{constructor(e,t,s){this.subtle=void 0,this.key=void 0,this.aesMode=void 0,this.subtle=e,this.key=t,this.aesMode=s}expandKey(){const e=Yc(this.aesMode);return this.subtle.importKey("raw",this.key,{name:e},!1,["encrypt","decrypt"])}}function Yc(n){switch(n){case ot.cbc:return"AES-CBC";case ot.ctr:return"AES-CTR";default:throw new Error(`[FastAESKey] invalid aes mode ${n}`)}}const qc=16;class Zi{constructor(e,{removePKCS7Padding:t=!0}={}){if(this.logEnabled=!0,this.removePKCS7Padding=void 0,this.subtle=null,this.softwareDecrypter=null,this.key=null,this.fastAesKey=null,this.remainderData=null,this.currentIV=null,this.currentResult=null,this.useSoftware=void 0,this.enableSoftwareAES=void 0,this.enableSoftwareAES=e.enableSoftwareAES,this.removePKCS7Padding=t,t)try{const s=self.crypto;s&&(this.subtle=s.subtle||s.webkitSubtle)}catch{}this.useSoftware=!this.subtle}destroy(){this.subtle=null,this.softwareDecrypter=null,this.key=null,this.fastAesKey=null,this.remainderData=null,this.currentIV=null,this.currentResult=null}isSync(){return this.useSoftware}flush(){const{currentResult:e,remainderData:t}=this;if(!e||t)return this.reset(),null;const s=new Uint8Array(e);return this.reset(),this.removePKCS7Padding?Vc(s):s}reset(){this.currentResult=null,this.currentIV=null,this.remainderData=null,this.softwareDecrypter&&(this.softwareDecrypter=null)}decrypt(e,t,s,i){return this.useSoftware?new Promise((r,a)=>{const o=ArrayBuffer.isView(e)?e:new Uint8Array(e);this.softwareDecrypt(o,t,s,i);const c=this.flush();c?r(c.buffer):a(new Error("[softwareDecrypt] Failed to decrypt data"))}):this.webCryptoDecrypt(new Uint8Array(e),t,s,i)}softwareDecrypt(e,t,s,i){const{currentIV:r,currentResult:a,remainderData:o}=this;if(i!==ot.cbc||t.byteLength!==16)return ie.warn("SoftwareDecrypt: can only handle AES-128-CBC"),null;this.logOnce("JS AES decrypt"),o&&(e=Oe(o,e),this.remainderData=null);const c=this.getValidChunk(e);if(!c.length)return null;r&&(s=r);let l=this.softwareDecrypter;l||(l=this.softwareDecrypter=new Hc),l.expandKey(t);const h=a;return this.currentResult=l.decrypt(c.buffer,0,s),this.currentIV=c.slice(-16).buffer,h||null}webCryptoDecrypt(e,t,s,i){if(this.key!==t||!this.fastAesKey){if(!this.subtle)return Promise.resolve(this.onWebCryptoError(e,t,s,i));this.key=t,this.fastAesKey=new Wc(this.subtle,t,i)}return this.fastAesKey.expandKey().then(r=>this.subtle?(this.logOnce("WebCrypto AES decrypt"),new Kc(this.subtle,new Uint8Array(s),i).decrypt(e.buffer,r)):Promise.reject(new Error("web crypto not initialized"))).catch(r=>(ie.warn(`[decrypter]: WebCrypto Error, disable WebCrypto API, ${r.name}: ${r.message}`),this.onWebCryptoError(e,t,s,i)))}onWebCryptoError(e,t,s,i){const r=this.enableSoftwareAES;if(r){this.useSoftware=!0,this.logEnabled=!0,this.softwareDecrypt(e,t,s,i);const a=this.flush();if(a)return a.buffer}throw new Error("WebCrypto"+(r?" and softwareDecrypt":"")+": failed to decrypt data")}getValidChunk(e){let t=e;const s=e.length-e.length%qc;return s!==e.length&&(t=e.slice(0,s),this.remainderData=e.slice(s)),t}logOnce(e){this.logEnabled&&(ie.log(`[decrypter]: ${e}`),this.logEnabled=!1)}}const Zr=Math.pow(2,17);class jc{constructor(e){this.config=void 0,this.loader=null,this.partLoadTimeout=-1,this.config=e}destroy(){this.loader&&(this.loader.destroy(),this.loader=null)}abort(){this.loader&&this.loader.abort()}load(e,t){const s=e.url;if(!s)return Promise.reject(new ze({type:H.NETWORK_ERROR,details:R.FRAG_LOAD_ERROR,fatal:!1,frag:e,error:new Error(`Fragment does not have a ${s?"part list":"url"}`),networkDetails:null}));this.abort();const i=this.config,r=i.fLoader,a=i.loader;return new Promise((o,c)=>{if(this.loader&&this.loader.destroy(),e.gap)if(e.tagList.some(g=>g[0]==="GAP")){c(en(e));return}else e.gap=!1;const l=this.loader=r?new r(i):new a(i),h=Jr(e);e.loader=l;const u=zr(i.fragLoadPolicy.default),d={loadPolicy:u,timeout:u.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:e.sn==="initSegment"?1/0:Zr};e.stats=l.stats;const f={onSuccess:(g,p,y,E)=>{this.resetLoader(e,l);let T=g.data;y.resetIV&&e.decryptdata&&(e.decryptdata.iv=new Uint8Array(T.slice(0,16)),T=T.slice(16)),o({frag:e,part:null,payload:T,networkDetails:E})},onError:(g,p,y,E)=>{this.resetLoader(e,l),c(new ze({type:H.NETWORK_ERROR,details:R.FRAG_LOAD_ERROR,fatal:!1,frag:e,response:se({url:s,data:void 0},g),error:new Error(`HTTP Error ${g.code} ${g.text}`),networkDetails:y,stats:E}))},onAbort:(g,p,y)=>{this.resetLoader(e,l),c(new ze({type:H.NETWORK_ERROR,details:R.INTERNAL_ABORTED,fatal:!1,frag:e,error:new Error("Aborted"),networkDetails:y,stats:g}))},onTimeout:(g,p,y)=>{this.resetLoader(e,l),c(new ze({type:H.NETWORK_ERROR,details:R.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,error:new Error(`Timeout after ${d.timeout}ms`),networkDetails:y,stats:g}))}};t&&(f.onProgress=(g,p,y,E)=>t({frag:e,part:null,payload:y,networkDetails:E})),l.load(h,d,f)})}loadPart(e,t,s){this.abort();const i=this.config,r=i.fLoader,a=i.loader;return new Promise((o,c)=>{if(this.loader&&this.loader.destroy(),e.gap||t.gap){c(en(e,t));return}const l=this.loader=r?new r(i):new a(i),h=Jr(e,t);e.loader=l;const u=zr(i.fragLoadPolicy.default),d={loadPolicy:u,timeout:u.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:Zr};t.stats=l.stats,l.load(h,d,{onSuccess:(f,g,p,y)=>{this.resetLoader(e,l),this.updateStatsFromPart(e,t);const E={frag:e,part:t,payload:f.data,networkDetails:y};s(E),o(E)},onError:(f,g,p,y)=>{this.resetLoader(e,l),c(new ze({type:H.NETWORK_ERROR,details:R.FRAG_LOAD_ERROR,fatal:!1,frag:e,part:t,response:se({url:h.url,data:void 0},f),error:new Error(`HTTP Error ${f.code} ${f.text}`),networkDetails:p,stats:y}))},onAbort:(f,g,p)=>{e.stats.aborted=t.stats.aborted,this.resetLoader(e,l),c(new ze({type:H.NETWORK_ERROR,details:R.INTERNAL_ABORTED,fatal:!1,frag:e,part:t,error:new Error("Aborted"),networkDetails:p,stats:f}))},onTimeout:(f,g,p)=>{this.resetLoader(e,l),c(new ze({type:H.NETWORK_ERROR,details:R.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,part:t,error:new Error(`Timeout after ${d.timeout}ms`),networkDetails:p,stats:f}))}})})}updateStatsFromPart(e,t){const s=e.stats,i=t.stats,r=i.total;if(s.loaded+=i.loaded,r){const c=Math.round(e.duration/t.duration),l=Math.min(Math.round(s.loaded/r),c),u=(c-l)*Math.round(s.loaded/l);s.total=s.loaded+u}else s.total=Math.max(s.loaded,s.total);const a=s.loading,o=i.loading;a.start?a.first+=o.first-o.start:(a.start=o.start,a.first=o.first),a.end=o.end}resetLoader(e,t){e.loader=null,this.loader===t&&(self.clearTimeout(this.partLoadTimeout),this.loader=null),t.destroy()}}function Jr(n,e=null){const t=e||n,s={frag:n,part:e,responseType:"arraybuffer",url:t.url,headers:{},rangeStart:0,rangeEnd:0},i=t.byteRangeStartOffset,r=t.byteRangeEndOffset;if(M(i)&&M(r)){var a;let o=i,c=r;if(n.sn==="initSegment"&&Xc((a=n.decryptdata)==null?void 0:a.method)){const l=r-i;l%16&&(c=r+(16-l%16)),i!==0&&(s.resetIV=!0,o=i-16)}s.rangeStart=o,s.rangeEnd=c}return s}function en(n,e){const t=new Error(`GAP ${n.gap?"tag":"attribute"} found`),s={type:H.MEDIA_ERROR,details:R.FRAG_GAP,fatal:!1,frag:n,error:t,networkDetails:null};return e&&(s.part=e),(e||n).stats.aborted=!0,new ze(s)}function Xc(n){return n==="AES-128"||n==="AES-256"}class ze extends Error{constructor(e){super(e.error.message),this.data=void 0,this.data=e}}class $a extends Fe{constructor(e,t){super(e,t),this._boundTick=void 0,this._tickTimer=null,this._tickInterval=null,this._tickCallCount=0,this._boundTick=this.tick.bind(this)}destroy(){this.onHandlerDestroying(),this.onHandlerDestroyed()}onHandlerDestroying(){this.clearNextTick(),this.clearInterval()}onHandlerDestroyed(){}hasInterval(){return!!this._tickInterval}hasNextTick(){return!!this._tickTimer}setInterval(e){return this._tickInterval?!1:(this._tickCallCount=0,this._tickInterval=self.setInterval(this._boundTick,e),!0)}clearInterval(){return this._tickInterval?(self.clearInterval(this._tickInterval),this._tickInterval=null,!0):!1}clearNextTick(){return this._tickTimer?(self.clearTimeout(this._tickTimer),this._tickTimer=null,!0):!1}tick(){this._tickCallCount++,this._tickCallCount===1&&(this.doTick(),this._tickCallCount>1&&this.tickImmediate(),this._tickCallCount=0)}tickImmediate(){this.clearNextTick(),this._tickTimer=self.setTimeout(this._boundTick,0)}doTick(){}}class Ji{constructor(e,t,s,i=0,r=-1,a=!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=es(),this.buffering={audio:es(),video:es(),audiovideo:es()},this.level=e,this.sn=t,this.id=s,this.size=i,this.part=r,this.partial=a}}function es(){return{start:0,executeStart:0,executeEnd:0,end:0}}const tn={length:0,start:()=>0,end:()=>0};class q{static isBuffered(e,t){if(e){const s=q.getBuffered(e);for(let i=s.length;i--;)if(t>=s.start(i)&&t<=s.end(i))return!0}return!1}static bufferedRanges(e){if(e){const t=q.getBuffered(e);return q.timeRangesToArray(t)}return[]}static timeRangesToArray(e){const t=[];for(let s=0;s<e.length;s++)t.push({start:e.start(s),end:e.end(s)});return t}static bufferInfo(e,t,s){if(e){const i=q.bufferedRanges(e);if(i.length)return q.bufferedInfo(i,t,s)}return{len:0,start:t,end:t,bufferedIndex:-1}}static bufferedInfo(e,t,s){t=Math.max(0,t),e.length>1&&e.sort((h,u)=>h.start-u.start||u.end-h.end);let i=-1,r=[];if(s)for(let h=0;h<e.length;h++){t>=e[h].start&&t<=e[h].end&&(i=h);const u=r.length;if(u){const d=r[u-1].end;e[h].start-d<s?e[h].end>d&&(r[u-1].end=e[h].end):r.push(e[h])}else r.push(e[h])}else r=e;let a=0,o,c=t,l=t;for(let h=0;h<r.length;h++){const u=r[h].start,d=r[h].end;if(i===-1&&t>=u&&t<=d&&(i=h),t+s>=u&&t<d)c=u,l=d,a=l-t;else if(t+s<u){o=u;break}}return{len:a,start:c||0,end:l||0,nextStart:o,buffered:e,bufferedIndex:i}}static getBuffered(e){try{return e.buffered||tn}catch(t){return ie.log("failed to get media.buffered",t),tn}}}const Ga=/\{\$([a-zA-Z0-9-_]+)\}/g;function sn(n){return Ga.test(n)}function bi(n,e){if(n.variableList!==null||n.hasVariableRefs){const t=n.variableList;return e.replace(Ga,s=>{const i=s.substring(2,s.length-1),r=t==null?void 0:t[i];return r===void 0?(n.playlistParsingError||(n.playlistParsingError=new Error(`Missing preceding EXT-X-DEFINE tag for Variable Reference: "${i}"`)),s):r})}return e}function rn(n,e,t){let s=n.variableList;s||(n.variableList=s={});let i,r;if("QUERYPARAM"in e){i=e.QUERYPARAM;try{const a=new self.URL(t).searchParams;if(a.has(i))r=a.get(i);else throw new Error(`"${i}" does not match any query parameter in URI: "${t}"`)}catch(a){n.playlistParsingError||(n.playlistParsingError=new Error(`EXT-X-DEFINE QUERYPARAM: ${a.message}`))}}else i=e.NAME,r=e.VALUE;i in s?n.playlistParsingError||(n.playlistParsingError=new Error(`EXT-X-DEFINE duplicate Variable Name declarations: "${i}"`)):s[i]=r||""}function zc(n,e,t){const s=e.IMPORT;if(t&&s in t){let i=n.variableList;i||(n.variableList=i={}),i[s]=t[s]}else n.playlistParsingError||(n.playlistParsingError=new Error(`EXT-X-DEFINE IMPORT attribute not found in Multivariant Playlist: "${s}"`))}const Qc=/^(\d+)x(\d+)$/,nn=/(.+?)=(".*?"|.*?)(?:,|$)/g;class le{constructor(e,t){typeof e=="string"&&(e=le.parseAttrList(e,t)),re(this,e)}get clientAttrs(){return Object.keys(this).filter(e=>e.substring(0,2)==="X-")}decimalInteger(e){const t=parseInt(this[e],10);return t>Number.MAX_SAFE_INTEGER?1/0:t}hexadecimalInteger(e){if(this[e]){let t=(this[e]||"0x").slice(2);t=(t.length&1?"0":"")+t;const s=new Uint8Array(t.length/2);for(let i=0;i<t.length/2;i++)s[i]=parseInt(t.slice(i*2,i*2+2),16);return s}return null}hexadecimalIntegerAsNumber(e){const t=parseInt(this[e],16);return t>Number.MAX_SAFE_INTEGER?1/0:t}decimalFloatingPoint(e){return parseFloat(this[e])}optionalFloat(e,t){const s=this[e];return s?parseFloat(s):t}enumeratedString(e){return this[e]}enumeratedStringList(e,t){const s=this[e];return(s?s.split(/[ ,]+/):[]).reduce((i,r)=>(i[r.toLowerCase()]=!0,i),t)}bool(e){return this[e]==="YES"}decimalResolution(e){const t=Qc.exec(this[e]);if(t!==null)return{width:parseInt(t[1],10),height:parseInt(t[2],10)}}static parseAttrList(e,t){let s;const i={},r='"';for(nn.lastIndex=0;(s=nn.exec(e))!==null;){const a=s[1].trim();let o=s[2];const c=o.indexOf(r)===0&&o.lastIndexOf(r)===o.length-1;let l=!1;if(c)o=o.slice(1,-1);else switch(a){case"IV":case"SCTE35-CMD":case"SCTE35-IN":case"SCTE35-OUT":l=!0}if(t&&(c||l))o=bi(t,o);else if(!l&&!c)switch(a){case"CLOSED-CAPTIONS":if(o==="NONE")break;case"ALLOWED-CPC":case"CLASS":case"ASSOC-LANGUAGE":case"AUDIO":case"BYTERANGE":case"CHANNELS":case"CHARACTERISTICS":case"CODECS":case"DATA-ID":case"END-DATE":case"GROUP-ID":case"ID":case"IMPORT":case"INSTREAM-ID":case"KEYFORMAT":case"KEYFORMATVERSIONS":case"LANGUAGE":case"NAME":case"PATHWAY-ID":case"QUERYPARAM":case"RECENTLY-REMOVED-DATERANGES":case"SERVER-URI":case"STABLE-RENDITION-ID":case"STABLE-VARIANT-ID":case"START-DATE":case"SUBTITLES":case"SUPPLEMENTAL-CODECS":case"URI":case"VALUE":case"VIDEO":case"X-ASSET-LIST":case"X-ASSET-URI":ie.warn(`${e}: attribute ${a} is missing quotes`)}i[a]=o}return i}}const Zc="com.apple.hls.interstitial";function Jc(n){return n!=="ID"&&n!=="CLASS"&&n!=="CUE"&&n!=="START-DATE"&&n!=="DURATION"&&n!=="END-DATE"&&n!=="END-ON-NEXT"}function eh(n){return n==="SCTE35-OUT"||n==="SCTE35-IN"||n==="SCTE35-CMD"}class Ka{constructor(e,t,s=0){var i;if(this.attr=void 0,this.tagAnchor=void 0,this.tagOrder=void 0,this._startDate=void 0,this._endDate=void 0,this._dateAtEnd=void 0,this._cue=void 0,this._badValueForSameId=void 0,this.tagAnchor=(t==null?void 0:t.tagAnchor)||null,this.tagOrder=(i=t==null?void 0:t.tagOrder)!=null?i:s,t){const r=t.attr;for(const a in r)if(Object.prototype.hasOwnProperty.call(e,a)&&e[a]!==r[a]){ie.warn(`DATERANGE tag attribute: "${a}" does not match for tags with ID: "${e.ID}"`),this._badValueForSameId=a;break}e=re(new le({}),r,e)}if(this.attr=e,t?(this._startDate=t._startDate,this._cue=t._cue,this._endDate=t._endDate,this._dateAtEnd=t._dateAtEnd):this._startDate=new Date(e["START-DATE"]),"END-DATE"in this.attr){const r=(t==null?void 0:t.endDate)||new Date(this.attr["END-DATE"]);M(r.getTime())&&(this._endDate=r)}}get id(){return this.attr.ID}get class(){return this.attr.CLASS}get cue(){const e=this._cue;return e===void 0?this._cue=this.attr.enumeratedStringList(this.attr.CUE?"CUE":"X-CUE",{pre:!1,post:!1,once:!1}):e}get startTime(){const{tagAnchor:e}=this;return e===null||e.programDateTime===null?(ie.warn(`Expected tagAnchor Fragment with PDT set for DateRange "${this.id}": ${e}`),NaN):e.start+(this.startDate.getTime()-e.programDateTime)/1e3}get startDate(){return this._startDate}get endDate(){const e=this._endDate||this._dateAtEnd;if(e)return e;const t=this.duration;return t!==null?this._dateAtEnd=new Date(this._startDate.getTime()+t*1e3):null}get duration(){if("DURATION"in this.attr){const e=this.attr.decimalFloatingPoint("DURATION");if(M(e))return e}else if(this._endDate)return(this._endDate.getTime()-this._startDate.getTime())/1e3;return null}get plannedDuration(){return"PLANNED-DURATION"in this.attr?this.attr.decimalFloatingPoint("PLANNED-DURATION"):null}get endOnNext(){return this.attr.bool("END-ON-NEXT")}get isInterstitial(){return this.class===Zc}get isValid(){return!!this.id&&!this._badValueForSameId&&M(this.startDate.getTime())&&(this.duration===null||this.duration>=0)&&(!this.endOnNext||!!this.class)&&(!this.attr.CUE||!this.cue.pre&&!this.cue.post||this.cue.pre!==this.cue.post)&&(!this.isInterstitial||"X-ASSET-URI"in this.attr||"X-ASSET-LIST"in this.attr)}}const th=10;class sh{constructor(e){this.PTSKnown=!1,this.alignedSliding=!1,this.averagetargetduration=void 0,this.endCC=0,this.endSN=0,this.fragments=void 0,this.fragmentHint=void 0,this.partList=null,this.dateRanges=void 0,this.dateRangeTagCount=0,this.live=!0,this.requestScheduled=-1,this.ageHeader=0,this.advancedDateTime=void 0,this.updated=!0,this.advanced=!0,this.misses=0,this.startCC=0,this.startSN=0,this.startTimeOffset=null,this.targetduration=0,this.totalduration=0,this.type=null,this.url=void 0,this.m3u8="",this.version=null,this.canBlockReload=!1,this.canSkipUntil=0,this.canSkipDateRanges=!1,this.skippedSegments=0,this.recentlyRemovedDateranges=void 0,this.partHoldBack=0,this.holdBack=0,this.partTarget=0,this.preloadHint=void 0,this.renditionReports=void 0,this.tuneInGoal=0,this.deltaUpdateFailed=void 0,this.driftStartTime=0,this.driftEndTime=0,this.driftStart=0,this.driftEnd=0,this.encryptedFragments=void 0,this.playlistParsingError=null,this.variableList=null,this.hasVariableRefs=!1,this.appliedTimelineOffset=void 0,this.fragments=[],this.encryptedFragments=[],this.dateRanges={},this.url=e}reloaded(e){if(!e){this.advanced=!0,this.updated=!0;return}const t=this.lastPartSn-e.lastPartSn,s=this.lastPartIndex-e.lastPartIndex;this.updated=this.endSN!==e.endSN||!!s||!!t||!this.live,this.advanced=this.endSN>e.endSN||t>0||t===0&&s>0,this.updated||this.advanced?this.misses=Math.floor(e.misses*.6):this.misses=e.misses+1}hasKey(e){return this.encryptedFragments.some(t=>{let s=t.decryptdata;return s||(t.setKeyFormat(e.keyFormat),s=t.decryptdata),!!s&&e.matches(s)})}get hasProgramDateTime(){return this.fragments.length?M(this.fragments[this.fragments.length-1].programDateTime):!1}get levelTargetDuration(){return this.averagetargetduration||this.targetduration||th}get drift(){const e=this.driftEndTime-this.driftStartTime;return e>0?(this.driftEnd-this.driftStart)*1e3/e:1}get edge(){return this.partEnd||this.fragmentEnd}get partEnd(){var e;return(e=this.partList)!=null&&e.length?this.partList[this.partList.length-1].end:this.fragmentEnd}get fragmentEnd(){return this.fragments.length?this.fragments[this.fragments.length-1].end:0}get fragmentStart(){return this.fragments.length?this.fragments[0].start:0}get age(){return this.advancedDateTime?Math.max(Date.now()-this.advancedDateTime,0)/1e3:0}get lastPartIndex(){var e;return(e=this.partList)!=null&&e.length?this.partList[this.partList.length-1].index:-1}get maxPartIndex(){const e=this.partList;if(e){const t=this.lastPartIndex;if(t!==-1){for(let s=e.length;s--;)if(e[s].index>t)return e[s].index;return t}}return 0}get lastPartSn(){var e;return(e=this.partList)!=null&&e.length?this.partList[this.partList.length-1].fragment.sn:this.endSN}get expired(){if(this.live&&this.age&&this.misses<3){const e=this.partEnd-this.fragmentStart;return this.age>Math.max(e,this.totalduration)+this.levelTargetDuration}return!1}}function Os(n,e){return n.length===e.length?!n.some((t,s)=>t!==e[s]):!1}function an(n,e){return!n&&!e?!0:!n||!e?!1:Os(n,e)}function It(n){return n==="AES-128"||n==="AES-256"||n==="AES-256-CTR"}function er(n){switch(n){case"AES-128":case"AES-256":return ot.cbc;case"AES-256-CTR":return ot.ctr;default:throw new Error(`invalid full segment method ${n}`)}}function tr(n){return Uint8Array.from(atob(n),e=>e.charCodeAt(0))}function Di(n){return Uint8Array.from(unescape(encodeURIComponent(n)),e=>e.charCodeAt(0))}function ih(n){const e=Di(n).subarray(0,16),t=new Uint8Array(16);return t.set(e,16-e.length),t}function Va(n){const e=function(s,i,r){const a=s[i];s[i]=s[r],s[r]=a};e(n,0,3),e(n,1,2),e(n,4,5),e(n,6,7)}function Ha(n){const e=n.split(":");let t=null;if(e[0]==="data"&&e.length===2){const s=e[1].split(";"),i=s[s.length-1].split(",");if(i.length===2){const r=i[0]==="base64",a=i[1];r?(s.splice(-1,1),t=tr(a)):t=ih(a)}}return t}const Fs=typeof self<"u"?self:void 0;var he={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.fps",PLAYREADY:"com.microsoft.playready",WIDEVINE:"com.widevine.alpha"},Se={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.streamingkeydelivery",PLAYREADY:"com.microsoft.playready",WIDEVINE:"urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed"};function ys(n){switch(n){case Se.FAIRPLAY:return he.FAIRPLAY;case Se.PLAYREADY:return he.PLAYREADY;case Se.WIDEVINE:return he.WIDEVINE;case Se.CLEARKEY:return he.CLEARKEY}}function Qs(n){switch(n){case he.FAIRPLAY:return Se.FAIRPLAY;case he.PLAYREADY:return Se.PLAYREADY;case he.WIDEVINE:return Se.WIDEVINE;case he.CLEARKEY:return Se.CLEARKEY}}function Ft(n){const{drmSystems:e,widevineLicenseUrl:t}=n,s=e?[he.FAIRPLAY,he.WIDEVINE,he.PLAYREADY,he.CLEARKEY].filter(i=>!!e[i]):[];return!s[he.WIDEVINE]&&t&&s.push(he.WIDEVINE),s}const Wa=function(n){return Fs!=null&&(n=Fs.navigator)!=null&&n.requestMediaKeySystemAccess?self.navigator.requestMediaKeySystemAccess.bind(self.navigator):null}();function rh(n,e,t,s){let i;switch(n){case he.FAIRPLAY:i=["cenc","sinf"];break;case he.WIDEVINE:case he.PLAYREADY:i=["cenc"];break;case he.CLEARKEY:i=["cenc","keyids"];break;default:throw new Error(`Unknown key-system: ${n}`)}return nh(i,e,t,s)}function nh(n,e,t,s){return[{initDataTypes:n,persistentState:s.persistentState||"optional",distinctiveIdentifier:s.distinctiveIdentifier||"optional",sessionTypes:s.sessionTypes||[s.sessionType||"temporary"],audioCapabilities:e.map(r=>({contentType:`audio/mp4; codecs=${r}`,robustness:s.audioRobustness||"",encryptionScheme:s.audioEncryptionScheme||null})),videoCapabilities:t.map(r=>({contentType:`video/mp4; codecs=${r}`,robustness:s.videoRobustness||"",encryptionScheme:s.videoEncryptionScheme||null}))}]}function ah(n){var e;return!!n&&(n.sessionType==="persistent-license"||!!((e=n.sessionTypes)!=null&&e.some(t=>t==="persistent-license")))}function Ya(n){const e=new Uint16Array(n.buffer,n.byteOffset,n.byteLength/2),t=String.fromCharCode.apply(null,Array.from(e)),s=t.substring(t.indexOf("<"),t.length),a=new DOMParser().parseFromString(s,"text/xml").getElementsByTagName("KID")[0];if(a){const o=a.childNodes[0]?a.childNodes[0].nodeValue:a.getAttribute("VALUE");if(o){const c=tr(o).subarray(0,16);return Va(c),c}}return null}let Tt={};class nt{static clearKeyUriToKeyIdMap(){Tt={}}static setKeyIdForUri(e,t){Tt[e]=t}static addKeyIdForUri(e){const t=Object.keys(Tt).length%Number.MAX_SAFE_INTEGER,s=new Uint8Array(16);return new DataView(s.buffer,12,4).setUint32(0,t),Tt[e]=s,s}constructor(e,t,s,i=[1],r=null,a){this.uri=void 0,this.method=void 0,this.keyFormat=void 0,this.keyFormatVersions=void 0,this.encrypted=void 0,this.isCommonEncryption=void 0,this.iv=null,this.key=null,this.keyId=null,this.pssh=null,this.method=e,this.uri=t,this.keyFormat=s,this.keyFormatVersions=i,this.iv=r,this.encrypted=e?e!=="NONE":!1,this.isCommonEncryption=this.encrypted&&!It(e),a!=null&&a.startsWith("0x")&&(this.keyId=new Uint8Array(Sa(a)))}matches(e){return e.uri===this.uri&&e.method===this.method&&e.encrypted===this.encrypted&&e.keyFormat===this.keyFormat&&Os(e.keyFormatVersions,this.keyFormatVersions)&&an(e.iv,this.iv)&&an(e.keyId,this.keyId)}isSupported(){if(this.method){if(It(this.method)||this.method==="NONE")return!0;if(this.keyFormat==="identity")return this.method==="SAMPLE-AES";switch(this.keyFormat){case Se.FAIRPLAY:case Se.WIDEVINE:case Se.PLAYREADY:case Se.CLEARKEY:return["SAMPLE-AES","SAMPLE-AES-CENC","SAMPLE-AES-CTR"].indexOf(this.method)!==-1}}return!1}getDecryptData(e,t){if(!this.encrypted||!this.uri)return null;if(It(this.method)){let r=this.iv;return r||(typeof e!="number"&&(ie.warn(`missing IV for initialization segment with method="${this.method}" - compliance issue`),e=0),r=lh(e)),new nt(this.method,this.uri,"identity",this.keyFormatVersions,r)}if(this.keyId){const r=Tt[this.uri];if(r&&!Os(this.keyId,r)&&nt.setKeyIdForUri(this.uri,this.keyId),this.pssh)return this}const s=Ha(this.uri);if(s)switch(this.keyFormat){case Se.WIDEVINE:if(this.pssh=s,!this.keyId){const r=uc(s.buffer);if(r.length){var i;const a=r[0];this.keyId=(i=a.kids)!=null&&i.length?a.kids[0]:null}}this.keyId||(this.keyId=on(t));break;case Se.PLAYREADY:{const r=new Uint8Array([154,4,240,121,152,64,66,134,171,146,230,91,224,136,95,149]);this.pssh=hc(r,null,s),this.keyId=Ya(s);break}default:{let r=s.subarray(0,16);if(r.length!==16){const a=new Uint8Array(16);a.set(r,16-r.length),r=a}this.keyId=r;break}}if(!this.keyId||this.keyId.byteLength!==16){let r;r=oh(t),r||(r=on(t),r||(r=Tt[this.uri])),r&&(this.keyId=r,nt.setKeyIdForUri(this.uri,r))}return this}}function oh(n){const e=n==null?void 0:n[Se.WIDEVINE];return e?e.keyId:null}function on(n){const e=n==null?void 0:n[Se.PLAYREADY];if(e){const t=Ha(e.uri);if(t)return Ya(t)}return null}function lh(n){const e=new Uint8Array(16);for(let t=12;t<16;t++)e[t]=n>>8*(15-t)&255;return e}const ln=/#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,cn=/#EXT-X-MEDIA:(.*)/g,ch=/^#EXT(?:INF|-X-TARGETDURATION):/m,Zs=new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,/(?!#) *(\S[^\r\n]*)/.source,/#.*/.source].join("|"),"g"),hh=new RegExp([/#EXT-X-(PROGRAM-DATE-TIME|BYTERANGE|DATERANGE|DEFINE|KEY|MAP|PART|PART-INF|PLAYLIST-TYPE|PRELOAD-HINT|RENDITION-REPORT|SERVER-CONTROL|SKIP|START):(.+)/.source,/#EXT-X-(BITRATE|DISCONTINUITY-SEQUENCE|MEDIA-SEQUENCE|TARGETDURATION|VERSION): *(\d+)/.source,/#EXT-X-(DISCONTINUITY|ENDLIST|GAP|INDEPENDENT-SEGMENTS)/.source,/(#)([^:]*):(.*)/.source,/(#)(.*)(?:.*)\r?\n?/.source].join("|"));class We{static findGroup(e,t){for(let s=0;s<e.length;s++){const i=e[s];if(i.id===t)return i}}static resolve(e,t){return Yi.buildAbsoluteURL(t,e,{alwaysNormalize:!0})}static isMediaPlaylist(e){return ch.test(e)}static parseMasterPlaylist(e,t){const s=sn(e),i={contentSteering:null,levels:[],playlistParsingError:null,sessionData:null,sessionKeys:null,startTimeOffset:null,variableList:null,hasVariableRefs:s},r=[];if(ln.lastIndex=0,!e.startsWith("#EXTM3U"))return i.playlistParsingError=new Error("no EXTM3U delimiter"),i;let a;for(;(a=ln.exec(e))!=null;)if(a[1]){var o;const l=new le(a[1],i),h=bi(i,a[2]),u={attrs:l,bitrate:l.decimalInteger("BANDWIDTH")||l.decimalInteger("AVERAGE-BANDWIDTH"),name:l.NAME,url:We.resolve(h,t)},d=l.decimalResolution("RESOLUTION");d&&(u.width=d.width,u.height=d.height),dn(l.CODECS,u);const f=l["SUPPLEMENTAL-CODECS"];f&&(u.supplemental={},dn(f,u.supplemental)),(o=u.unknownCodecs)!=null&&o.length||r.push(u),i.levels.push(u)}else if(a[3]){const l=a[3],h=a[4];switch(l){case"SESSION-DATA":{const u=new le(h,i),d=u["DATA-ID"];d&&(i.sessionData===null&&(i.sessionData={}),i.sessionData[d]=u);break}case"SESSION-KEY":{const u=hn(h,t,i);u.encrypted&&u.isSupported()?(i.sessionKeys===null&&(i.sessionKeys=[]),i.sessionKeys.push(u)):ie.warn(`[Keys] Ignoring invalid EXT-X-SESSION-KEY tag: "${h}"`);break}case"DEFINE":{{const u=new le(h,i);rn(i,u,t)}break}case"CONTENT-STEERING":{const u=new le(h,i);i.contentSteering={uri:We.resolve(u["SERVER-URI"],t),pathwayId:u["PATHWAY-ID"]||"."};break}case"START":{i.startTimeOffset=un(h);break}}}const c=r.length>0&&r.length<i.levels.length;return i.levels=c?r:i.levels,i.levels.length===0&&(i.playlistParsingError=new Error("no levels found in manifest")),i}static parseMasterPlaylistMedia(e,t,s){let i;const r={},a=s.levels,o={AUDIO:a.map(l=>({id:l.attrs.AUDIO,audioCodec:l.audioCodec})),SUBTITLES:a.map(l=>({id:l.attrs.SUBTITLES,textCodec:l.textCodec})),"CLOSED-CAPTIONS":[]};let c=0;for(cn.lastIndex=0;(i=cn.exec(e))!==null;){const l=new le(i[1],s),h=l.TYPE;if(h){const u=o[h],d=r[h]||[];r[h]=d;const f=l.LANGUAGE,g=l["ASSOC-LANGUAGE"],p=l.CHANNELS,y=l.CHARACTERISTICS,E=l["INSTREAM-ID"],T={attrs:l,bitrate:0,id:c++,groupId:l["GROUP-ID"]||"",name:l.NAME||f||"",type:h,default:l.bool("DEFAULT"),autoselect:l.bool("AUTOSELECT"),forced:l.bool("FORCED"),lang:f,url:l.URI?We.resolve(l.URI,t):""};if(g&&(T.assocLang=g),p&&(T.channels=p),y&&(T.characteristics=y),E&&(T.instreamId=E),u!=null&&u.length){const S=We.findGroup(u,T.groupId)||u[0];fn(T,S,"audioCodec"),fn(T,S,"textCodec")}d.push(T)}}return r}static parseLevelPlaylist(e,t,s,i,r,a){var o;const c={url:t},l=new sh(t),h=l.fragments,u=[];let d=null,f=0,g=0,p=0,y=0,E=0,T=null,S=new js(i,c),v,x,D,A=-1,b=!1,I=null,_;if(Zs.lastIndex=0,l.m3u8=e,l.hasVariableRefs=sn(e),((o=Zs.exec(e))==null?void 0:o[0])!=="#EXTM3U")return l.playlistParsingError=new Error("Missing format identifier #EXTM3U"),l;for(;(v=Zs.exec(e))!==null;){b&&(b=!1,S=new js(i,c),S.playlistOffset=p,S.setStart(p),S.sn=f,S.cc=y,E&&(S.bitrate=E),S.level=s,d&&(S.initSegment=d,d.rawProgramDateTime&&(S.rawProgramDateTime=d.rawProgramDateTime,d.rawProgramDateTime=null),I&&(S.setByteRange(I),I=null)));const K=v[1];if(K){S.duration=parseFloat(K);const $=(" "+v[2]).slice(1);S.title=$||null,S.tagList.push($?["INF",K,$]:["INF",K])}else if(v[3]){if(M(S.duration)){S.playlistOffset=p,S.setStart(p),D&&mn(S,D,l),S.sn=f,S.level=s,S.cc=y,h.push(S);const $=(" "+v[3]).slice(1);S.relurl=bi(l,$),Ci(S,T,u),T=S,p+=S.duration,f++,g=0,b=!0}}else{if(v=v[0].match(hh),!v){ie.warn("No matches on slow regex match for level playlist!");continue}for(x=1;x<v.length&&v[x]===void 0;x++);const $=(" "+v[x]).slice(1),w=(" "+v[x+1]).slice(1),G=v[x+2]?(" "+v[x+2]).slice(1):null;switch($){case"BYTERANGE":T?S.setByteRange(w,T):S.setByteRange(w);break;case"PROGRAM-DATE-TIME":S.rawProgramDateTime=w,S.tagList.push(["PROGRAM-DATE-TIME",w]),A===-1&&(A=h.length);break;case"PLAYLIST-TYPE":l.type&&je(l,$,v),l.type=w.toUpperCase();break;case"MEDIA-SEQUENCE":l.startSN!==0?je(l,$,v):h.length>0&&pn(l,$,v),f=l.startSN=parseInt(w);break;case"SKIP":{l.skippedSegments&&je(l,$,v);const N=new le(w,l),V=N.decimalInteger("SKIPPED-SEGMENTS");if(M(V)){l.skippedSegments+=V;for(let O=V;O--;)h.push(null);f+=V}const W=N.enumeratedString("RECENTLY-REMOVED-DATERANGES");W&&(l.recentlyRemovedDateranges=(l.recentlyRemovedDateranges||[]).concat(W.split(" ")));break}case"TARGETDURATION":l.targetduration!==0&&je(l,$,v),l.targetduration=Math.max(parseInt(w),1);break;case"VERSION":l.version!==null&&je(l,$,v),l.version=parseInt(w);break;case"INDEPENDENT-SEGMENTS":break;case"ENDLIST":l.live||je(l,$,v),l.live=!1;break;case"#":(w||G)&&S.tagList.push(G?[w,G]:[w]);break;case"DISCONTINUITY":y++,S.tagList.push(["DIS"]);break;case"GAP":S.gap=!0,S.tagList.push([$]);break;case"BITRATE":S.tagList.push([$,w]),E=parseInt(w)*1e3,M(E)?S.bitrate=E:E=0;break;case"DATERANGE":{const N=new le(w,l),V=new Ka(N,l.dateRanges[N.ID],l.dateRangeTagCount);l.dateRangeTagCount++,V.isValid||l.skippedSegments?l.dateRanges[V.id]=V:ie.warn(`Ignoring invalid DATERANGE tag: "${w}"`),S.tagList.push(["EXT-X-DATERANGE",w]);break}case"DEFINE":{{const N=new le(w,l);"IMPORT"in N?zc(l,N,a):rn(l,N,t)}break}case"DISCONTINUITY-SEQUENCE":l.startCC!==0?je(l,$,v):h.length>0&&pn(l,$,v),l.startCC=y=parseInt(w);break;case"KEY":{const N=hn(w,t,l);if(N.isSupported()){if(N.method==="NONE"){D=void 0;break}D||(D={});const V=D[N.keyFormat];V!=null&&V.matches(N)||(V&&(D=re({},D)),D[N.keyFormat]=N)}else ie.warn(`[Keys] Ignoring unsupported EXT-X-KEY tag: "${w}"`);break}case"START":l.startTimeOffset=un(w);break;case"MAP":{const N=new le(w,l);if(S.duration){const V=new js(i,c);gn(V,N,s,D),d=V,S.initSegment=d,d.rawProgramDateTime&&!S.rawProgramDateTime&&(S.rawProgramDateTime=d.rawProgramDateTime)}else{const V=S.byteRangeEndOffset;if(V){const W=S.byteRangeStartOffset;I=`${V-W}@${W}`}else I=null;gn(S,N,s,D),d=S,b=!0}d.cc=y;break}case"SERVER-CONTROL":{_&&je(l,$,v),_=new le(w),l.canBlockReload=_.bool("CAN-BLOCK-RELOAD"),l.canSkipUntil=_.optionalFloat("CAN-SKIP-UNTIL",0),l.canSkipDateRanges=l.canSkipUntil>0&&_.bool("CAN-SKIP-DATERANGES"),l.partHoldBack=_.optionalFloat("PART-HOLD-BACK",0),l.holdBack=_.optionalFloat("HOLD-BACK",0);break}case"PART-INF":{l.partTarget&&je(l,$,v);const N=new le(w);l.partTarget=N.decimalFloatingPoint("PART-TARGET");break}case"PART":{let N=l.partList;N||(N=l.partList=[]);const V=g>0?N[N.length-1]:void 0,W=g++,O=new le(w,l),F=new zl(O,S,c,W,V);N.push(F),S.duration+=F.duration;break}case"PRELOAD-HINT":{const N=new le(w,l);l.preloadHint=N;break}case"RENDITION-REPORT":{const N=new le(w,l);l.renditionReports=l.renditionReports||[],l.renditionReports.push(N);break}default:ie.warn(`line parsed but not handled: ${v}`);break}}}T&&!T.relurl?(h.pop(),p-=T.duration,l.partList&&(l.fragmentHint=T)):l.partList&&(Ci(S,T,u),S.cc=y,l.fragmentHint=S,D&&mn(S,D,l)),l.targetduration||(l.playlistParsingError=new Error("Missing Target Duration"));const C=h.length,k=h[0],B=h[C-1];if(p+=l.skippedSegments*l.targetduration,p>0&&C&&B){l.averagetargetduration=p/C;const K=B.sn;l.endSN=K!=="initSegment"?K:0,l.live||(B.endList=!0),A>0&&(dh(h,A),k&&u.unshift(k))}return l.fragmentHint&&(p+=l.fragmentHint.duration),l.totalduration=p,u.length&&l.dateRangeTagCount&&k&&qa(u,l),l.endCC=y,l}}function qa(n,e){let t=n.length;if(!t)if(e.hasProgramDateTime){const o=e.fragments[e.fragments.length-1];n.push(o),t++}else return;const s=n[t-1],i=e.live?1/0:e.totalduration,r=Object.keys(e.dateRanges);for(let o=r.length;o--;){const c=e.dateRanges[r[o]],l=c.startDate.getTime();c.tagAnchor=s.ref;for(let h=t;h--;){var a;if(((a=n[h])==null?void 0:a.sn)<e.startSN)break;const u=uh(e,l,n,h,i);if(u!==-1){c.tagAnchor=e.fragments[u].ref;break}}}}function uh(n,e,t,s,i){const r=t[s];if(r){const o=r.programDateTime;if(e>=o||s===0){var a;const c=(((a=t[s+1])==null?void 0:a.start)||i)-r.start;if(e<=o+c*1e3){const l=t[s].sn-n.startSN;if(l<0)return-1;const h=n.fragments;if(h.length>t.length){const d=(t[s+1]||h[h.length-1]).sn-n.startSN;for(let f=d;f>l;f--){const g=h[f].programDateTime;if(e>=g&&e<g+h[f].duration*1e3)return f}}return l}}}return-1}function hn(n,e,t){var s,i;const r=new le(n,t),a=(s=r.METHOD)!=null?s:"",o=r.URI,c=r.hexadecimalInteger("IV"),l=r.KEYFORMATVERSIONS,h=(i=r.KEYFORMAT)!=null?i:"identity";o&&r.IV&&!c&&ie.error(`Invalid IV: ${r.IV}`);const u=o?We.resolve(o,e):"",d=(l||"1").split("/").map(Number).filter(Number.isFinite);return new nt(a,u,h,d,c,r.KEYID)}function un(n){const t=new le(n).decimalFloatingPoint("TIME-OFFSET");return M(t)?t:null}function dn(n,e){let t=(n||"").split(/[ ,]+/).filter(s=>s);["video","audio","text"].forEach(s=>{const i=t.filter(r=>Xi(r,s));i.length&&(e[`${s}Codec`]=i.map(r=>r.split("/")[0]).join(","),t=t.filter(r=>i.indexOf(r)===-1))}),e.unknownCodecs=t}function fn(n,e,t){const s=e[t];s&&(n[t]=s)}function dh(n,e){let t=n[e];for(let s=e;s--;){const i=n[s];if(!i)return;i.programDateTime=t.programDateTime-i.duration*1e3,t=i}}function Ci(n,e,t){n.rawProgramDateTime?t.push(n):e!=null&&e.programDateTime&&(n.programDateTime=e.endProgramDateTime)}function gn(n,e,t,s){n.relurl=e.URI,e.BYTERANGE&&n.setByteRange(e.BYTERANGE),n.level=t,n.sn="initSegment",s&&(n.levelkeys=s),n.initSegment=null}function mn(n,e,t){n.levelkeys=e;const{encryptedFragments:s}=t;(!s.length||s[s.length-1].levelkeys!==e)&&Object.keys(e).some(i=>e[i].isCommonEncryption)&&s.push(n)}function je(n,e,t){n.playlistParsingError=new Error(`#EXT-X-${e} must not appear more than once (${t[0]})`)}function pn(n,e,t){n.playlistParsingError=new Error(`#EXT-X-${e} must appear before the first Media Segment (${t[0]})`)}function Js(n,e){const t=e.startPTS;if(M(t)){let s=0,i;e.sn>n.sn?(s=t-n.start,i=n):(s=n.start-t,i=e),i.duration!==s&&i.setDuration(s)}else e.sn>n.sn?n.cc===e.cc&&n.minEndPTS?e.setStart(n.start+(n.minEndPTS-n.start)):e.setStart(n.start+n.duration):e.setStart(Math.max(n.start-e.duration,0))}function ja(n,e,t,s,i,r,a){s-t<=0&&(a.warn("Fragment should have a positive duration",e),s=t+e.duration,r=i+e.duration);let c=t,l=s;const h=e.startPTS,u=e.endPTS;if(M(h)){const E=Math.abs(h-t);n&&E>n.totalduration?a.warn(`media timestamps and playlist times differ by ${E}s for level ${e.level} ${n.url}`):M(e.deltaPTS)?e.deltaPTS=Math.max(E,e.deltaPTS):e.deltaPTS=E,c=Math.max(t,h),t=Math.min(t,h),i=e.startDTS!==void 0?Math.min(i,e.startDTS):i,l=Math.min(s,u),s=Math.max(s,u),r=e.endDTS!==void 0?Math.max(r,e.endDTS):r}const d=t-e.start;e.start!==0&&e.setStart(t),e.setDuration(s-e.start),e.startPTS=t,e.maxStartPTS=c,e.startDTS=i,e.endPTS=s,e.minEndPTS=l,e.endDTS=r;const f=e.sn;if(!n||f<n.startSN||f>n.endSN)return 0;let g;const p=f-n.startSN,y=n.fragments;for(y[p]=e,g=p;g>0;g--)Js(y[g],y[g-1]);for(g=p;g<y.length-1;g++)Js(y[g],y[g+1]);return n.fragmentHint&&Js(y[y.length-1],n.fragmentHint),n.PTSKnown=n.alignedSliding=!0,d}function fh(n,e,t){if(n===e)return;let s=null;const i=n.fragments;for(let h=i.length-1;h>=0;h--){const u=i[h].initSegment;if(u){s=u;break}}n.fragmentHint&&delete n.fragmentHint.endPTS;let r;ph(n,e,(h,u,d,f)=>{if((!e.startCC||e.skippedSegments)&&u.cc!==h.cc){const g=h.cc-u.cc;for(let p=d;p<f.length;p++)f[p].cc+=g;e.endCC=f[f.length-1].cc}M(h.startPTS)&&M(h.endPTS)&&(u.setStart(u.startPTS=h.startPTS),u.startDTS=h.startDTS,u.maxStartPTS=h.maxStartPTS,u.endPTS=h.endPTS,u.endDTS=h.endDTS,u.minEndPTS=h.minEndPTS,u.setDuration(h.endPTS-h.startPTS),u.duration&&(r=u),e.PTSKnown=e.alignedSliding=!0),h.hasStreams&&(u.elementaryStreams=h.elementaryStreams),u.loader=h.loader,h.hasStats&&(u.stats=h.stats),h.initSegment&&(u.initSegment=h.initSegment,s=h.initSegment)});const a=e.fragments,o=e.fragmentHint?a.concat(e.fragmentHint):a;if(s&&o.forEach(h=>{var u;h&&(!h.initSegment||h.initSegment.relurl===((u=s)==null?void 0:u.relurl))&&(h.initSegment=s)}),e.skippedSegments){if(e.deltaUpdateFailed=a.some(h=>!h),e.deltaUpdateFailed){t.warn("[level-helper] Previous playlist missing segments skipped in delta playlist");for(let h=e.skippedSegments;h--;)a.shift();e.startSN=a[0].sn}else{e.canSkipDateRanges&&(e.dateRanges=gh(n.dateRanges,e,t));const h=n.fragments.filter(u=>u.rawProgramDateTime);if(n.hasProgramDateTime&&!e.hasProgramDateTime)for(let u=1;u<o.length;u++)o[u].programDateTime===null&&Ci(o[u],o[u-1],h);qa(h,e)}e.endCC=a[a.length-1].cc}if(!e.startCC){var c;const h=Qa(n,e.startSN-1);e.startCC=(c=h==null?void 0:h.cc)!=null?c:a[0].cc}mh(n.partList,e.partList,(h,u)=>{u.elementaryStreams=h.elementaryStreams,u.stats=h.stats}),r?ja(e,r,r.startPTS,r.endPTS,r.startDTS,r.endDTS,t):Xa(n,e),a.length&&(e.totalduration=e.edge-a[0].start),e.driftStartTime=n.driftStartTime,e.driftStart=n.driftStart;const l=e.advancedDateTime;if(e.advanced&&l){const h=e.edge;e.driftStart||(e.driftStartTime=l,e.driftStart=h),e.driftEndTime=l,e.driftEnd=h}else e.driftEndTime=n.driftEndTime,e.driftEnd=n.driftEnd,e.advancedDateTime=n.advancedDateTime;e.requestScheduled===-1&&(e.requestScheduled=n.requestScheduled)}function gh(n,e,t){const{dateRanges:s,recentlyRemovedDateranges:i}=e,r=re({},n);i&&i.forEach(c=>{delete r[c]});const o=Object.keys(r).length;return o?(Object.keys(s).forEach(c=>{const l=r[c],h=new Ka(s[c].attr,l);h.isValid?(r[c]=h,l||(h.tagOrder+=o)):t.warn(`Ignoring invalid Playlist Delta Update DATERANGE tag: "${oe(s[c].attr)}"`)}),r):s}function mh(n,e,t){if(n&&e){let s=0;for(let i=0,r=n.length;i<=r;i++){const a=n[i],o=e[i+s];a&&o&&a.index===o.index&&a.fragment.sn===o.fragment.sn?t(a,o):s--}}}function ph(n,e,t){const s=e.skippedSegments,i=Math.max(n.startSN,e.startSN)-e.startSN,r=(n.fragmentHint?1:0)+(s?e.endSN:Math.min(n.endSN,e.endSN))-e.startSN,a=e.startSN-n.startSN,o=e.fragmentHint?e.fragments.concat(e.fragmentHint):e.fragments,c=n.fragmentHint?n.fragments.concat(n.fragmentHint):n.fragments;for(let l=i;l<=r;l++){const h=c[a+l];let u=o[l];if(s&&!u&&h&&(u=e.fragments[l]=h),h&&u){t(h,u,l,o);const d=h.relurl,f=u.relurl;if(d&&yh(d,f)){e.playlistParsingError=yn(`media sequence mismatch ${u.sn}:`,n,e,h,u);return}else if(h.cc!==u.cc){e.playlistParsingError=yn(`discontinuity sequence mismatch (${h.cc}!=${u.cc})`,n,e,h,u);return}}}}function yn(n,e,t,s,i){return new Error(`${n} ${i.url}
235100Playlist starting @${e.startSN}
236101${e.m3u8}
237102238103Playlist starting @${t.startSN}
239239-${t.m3u8}`)}function zn(a,e,t=!0){const s=e.startSN+e.skippedSegments-a.startSN,i=a.fragments,r=s>=0;let n=0;if(r&&s<i.length)n=i[s].start;else if(r&&e.startSN===a.endSN+1)n=a.fragmentEnd;else if(r&&t)n=a.fragmentStart+s*e.levelTargetDuration;else if(!e.skippedSegments&&e.fragmentStart===0)n=a.fragmentStart;else return;ui(e,n)}function ui(a,e){if(e){const t=a.fragments;for(let s=a.skippedSegments;s<t.length;s++)t[s].addStart(e);a.fragmentHint&&a.fragmentHint.addStart(e)}}function Qn(a,e=1/0){let t=1e3*a.targetduration;if(a.updated){const s=a.fragments;if(s.length&&t*4>e){const r=s[s.length-1].duration*1e3;r<t&&(t=r)}}else t/=2;return Math.round(t)}function Zn(a,e,t){if(!a)return null;let s=a.fragments[e-a.startSN];return s||(s=a.fragmentHint,s&&s.sn===e)?s:e<a.startSN&&t&&t.sn===e?t:null}function Mr(a,e,t){return a?Jn(a.partList,e,t):null}function Jn(a,e,t){if(a)for(let s=a.length;s--;){const i=a[s];if(i.index===t&&i.fragment.sn===e)return i}return null}function ea(a){a.forEach((e,t)=>{var s;(s=e.details)==null||s.fragments.forEach(i=>{i.level=t,i.initSegment&&(i.initSegment.level=t)})})}function Ol(a,e){return a!==e&&e?Nr(a)!==Nr(e):!1}function Nr(a){return a.replace(/\?[^?]*$/,"")}function Ot(a,e){for(let s=0,i=a.length;s<i;s++){var t;if(((t=a[s])==null?void 0:t.cc)===e)return a[s]}return null}function Fl(a,e){return!!(a&&e.startCC<a.endCC&&e.endCC>a.startCC)}function Br(a,e){const t=a.start+e;a.startPTS=t,a.setStart(t),a.endPTS=t+a.duration}function ta(a,e){const t=e.fragments;for(let s=0,i=t.length;s<i;s++)Br(t[s],a);e.fragmentHint&&Br(e.fragmentHint,a),e.alignedSliding=!0}function Ml(a,e){a&&(sa(e,a),e.alignedSliding||Rs(e,a),!e.alignedSliding&&!e.skippedSegments&&zn(a,e,!1))}function sa(a,e){if(!Fl(e,a))return;const t=Math.min(e.endCC,a.endCC),s=Ot(e.fragments,t),i=Ot(a.fragments,t);if(!s||!i)return;se.log(`Aligning playlist at start of dicontinuity sequence ${t}`);const r=s.start-i.start;ta(r,a)}function Rs(a,e){if(!a.hasProgramDateTime||!e.hasProgramDateTime)return;const t=a.fragments,s=e.fragments;if(!t.length||!s.length)return;let i,r;const n=Math.min(e.endCC,a.endCC);e.startCC<n&&a.startCC<n&&(i=Ot(s,n),r=Ot(t,n)),(!i||!r)&&(i=s[Math.floor(s.length/2)],r=Ot(t,i.cc)||t[Math.floor(t.length/2)]);const o=i.programDateTime,c=r.programDateTime;if(!o||!c)return;const l=(c-o)/1e3-(r.start-i.start);ta(l,a)}function Te(a,e,t){ve(a,e,t),a.addEventListener(e,t)}function ve(a,e,t){a.removeEventListener(e,t)}const Nl={toString:function(a){let e="";const t=a.length;for(let s=0;s<t;s++)e+=`[${a.start(s).toFixed(3)}-${a.end(s).toFixed(3)}]`;return e}},C={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"};class Oi extends Gn{constructor(e,t,s,i,r){super(i,e.logger),this.hls=void 0,this.fragPrevious=null,this.fragCurrent=null,this.fragmentTracker=void 0,this.transmuxer=null,this._state=C.STOPPED,this.playlistType=void 0,this.media=null,this.mediaBuffer=null,this.config=void 0,this.bitrateTest=!1,this.lastCurrentTime=0,this.nextLoadPosition=0,this.startPosition=0,this.startTimeOffset=null,this.retryDate=0,this.levels=null,this.fragmentLoader=void 0,this.keyLoader=void 0,this.levelLastLoaded=null,this.startFragRequested=!1,this.decrypter=void 0,this.initPTS=[],this.buffering=!0,this.loadingParts=!1,this.loopSn=void 0,this.onMediaSeeking=()=>{const{config:n,fragCurrent:o,media:c,mediaBuffer:l,state:h}=this,d=c?c.currentTime:0,u=q.bufferInfo(l||c,d,n.maxBufferHole),f=!u.len;if(this.log(`Media seeking to ${M(d)?d.toFixed(3):d}, state: ${h}, ${f?"out of":"in"} buffer`),this.state===C.ENDED)this.resetLoadingState();else if(o){const g=n.maxFragLookUpTolerance,y=o.start-g,p=o.start+o.duration+g;if(f||p<u.start||y>u.end){const E=d>p;(d<y||E)&&(E&&o.loader&&(this.log(`Cancelling fragment load for seek (sn: ${o.sn})`),o.abortRequests(),this.resetLoadingState()),this.fragPrevious=null)}}if(c){this.fragmentTracker.removeFragmentsInRange(d,1/0,this.playlistType,!0);const g=this.lastCurrentTime;if(d>g&&(this.lastCurrentTime=d),!this.loadingParts){const y=Math.max(u.end,d),p=this.shouldLoadParts(this.getLevelDetails(),y);p&&(this.log(`LL-Part loading ON after seeking to ${d.toFixed(2)} with buffer @${y.toFixed(2)}`),this.loadingParts=p)}}this.hls.hasEnoughToStart||(this.log(`Setting ${f?"startPosition":"nextLoadPosition"} to ${d} for seek without enough to start`),this.nextLoadPosition=d,f&&(this.startPosition=d)),f&&this.state===C.IDLE&&this.tickImmediate()},this.onMediaEnded=()=>{this.log("setting startPosition to 0 because media ended"),this.startPosition=this.lastCurrentTime=0},this.playlistType=r,this.hls=e,this.fragmentLoader=new dl(e.config),this.keyLoader=s,this.fragmentTracker=t,this.config=e.config,this.decrypter=new Ci(e.config)}registerListeners(){const{hls:e}=this;e.on(m.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(m.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(m.MANIFEST_LOADING,this.onManifestLoading,this),e.on(m.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(m.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(m.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(m.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(m.MANIFEST_LOADING,this.onManifestLoading,this),e.off(m.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(m.ERROR,this.onError,this)}doTick(){this.onTickEnd()}onTickEnd(){}startLoad(e){}stopLoad(){if(this.state===C.STOPPED)return;this.fragmentLoader.abort(),this.keyLoader.abort(this.playlistType);const e=this.fragCurrent;e!=null&&e.loader&&(e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.resetTransmuxer(),this.fragCurrent=null,this.fragPrevious=null,this.clearInterval(),this.clearNextTick(),this.state=C.STOPPED}get startPositionValue(){const{nextLoadPosition:e,startPosition:t}=this;return t===-1&&e?e:t}get bufferingEnabled(){return this.buffering}pauseBuffering(){this.buffering=!1}resumeBuffering(){this.buffering=!0}get inFlightFrag(){return{frag:this.fragCurrent,state:this.state}}_streamEnded(e,t){if(t.live||!this.media)return!1;const s=e.end||0,i=this.config.timelineOffset||0;if(s<=i)return!1;const r=e.buffered;this.config.maxBufferHole&&r&&r.length>1&&(e=q.bufferedInfo(r,e.start,0));const n=e.nextStart;if(n&&n>i&&n<t.edge||this.media.currentTime<e.start)return!1;const c=t.partList;if(c!=null&&c.length){const h=c[c.length-1];return q.isBuffered(this.media,h.start+h.duration/2)}const l=t.fragments[t.fragments.length-1].type;return this.fragmentTracker.isEndListAppended(l)}getLevelDetails(){if(this.levels&&this.levelLastLoaded!==null)return this.levelLastLoaded.details}get timelineOffset(){const e=this.config.timelineOffset;if(e){var t;return((t=this.getLevelDetails())==null?void 0:t.appliedTimelineOffset)||e}return 0}onMediaAttached(e,t){const s=this.media=this.mediaBuffer=t.media;Te(s,"seeking",this.onMediaSeeking),Te(s,"ended",this.onMediaEnded);const i=this.config;this.levels&&i.autoStartLoad&&this.state===C.STOPPED&&this.startLoad(i.startPosition)}onMediaDetaching(e,t){const s=!!t.transferMedia,i=this.media;if(i!==null){if(i.ended&&(this.log("MSE detaching and video ended, reset startPosition"),this.startPosition=this.lastCurrentTime=0),ve(i,"seeking",this.onMediaSeeking),ve(i,"ended",this.onMediaEnded),this.keyLoader&&!s&&this.keyLoader.detach(),this.media=this.mediaBuffer=null,this.loopSn=void 0,s){this.resetLoadingState(),this.resetTransmuxer();return}this.loadingParts=!1,this.fragmentTracker.removeAllFragments(),this.stopLoad()}}onManifestLoading(){this.initPTS=[],this.levels=this.levelLastLoaded=this.fragCurrent=null,this.lastCurrentTime=this.startPosition=0,this.startFragRequested=!1}onError(e,t){}onManifestLoaded(e,t){this.startTimeOffset=t.startTimeOffset}onHandlerDestroying(){this.stopLoad(),this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null),super.onHandlerDestroying(),this.hls=this.onMediaSeeking=this.onMediaEnded=null}onHandlerDestroyed(){this.state=C.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,super.onHandlerDestroyed()}loadFragment(e,t,s){this.startFragRequested=!0,this._loadFragForPlayback(e,t,s)}_loadFragForPlayback(e,t,s){const i=r=>{const n=r.frag;if(this.fragContextChanged(n)){this.warn(`${n.type} sn: ${n.sn}${r.part?" part: "+r.part.index:""} of ${this.fragInfo(n,!1,r.part)}) was dropped during download.`),this.fragmentTracker.removeFragment(n);return}n.stats.chunkCount++,this._handleFragmentLoadProgress(r)};this._doFragLoad(e,t,s,i).then(r=>{if(!r)return;const n=this.state,o=r.frag;if(this.fragContextChanged(o)){(n===C.FRAG_LOADING||!this.fragCurrent&&n===C.PARSING)&&(this.fragmentTracker.removeFragment(o),this.state=C.IDLE);return}"payload"in r&&(this.log(`Loaded ${o.type} sn: ${o.sn} of ${this.playlistLabel()} ${o.level}`),this.hls.trigger(m.FRAG_LOADED,r)),this._handleFragmentLoadComplete(r)}).catch(r=>{this.state===C.STOPPED||this.state===C.ERROR||(this.warn(`Frag error: ${(r==null?void 0:r.message)||r}`),this.resetFragmentLoading(e))})}clearTrackerIfNeeded(e){var t;const{fragmentTracker:s}=this;if(s.getState(e)===de.APPENDING){const r=e.type,n=this.getFwdBufferInfo(this.mediaBuffer,r),o=Math.max(e.duration,n?n.len:this.config.maxBufferLength),c=this.backtrackFragment;((c?e.sn-c.sn:0)===1||this.reduceMaxBufferLength(o,e.duration))&&s.removeFragment(e)}else((t=this.mediaBuffer)==null?void 0:t.buffered.length)===0?s.removeAllFragments():s.hasParts(e.type)&&(s.detectPartialFragments({frag:e,part:null,stats:e.stats,id:e.type}),s.getState(e)===de.PARTIAL&&s.removeFragment(e))}checkLiveUpdate(e){if(e.updated&&!e.live){const t=e.fragments[e.fragments.length-1];this.fragmentTracker.detectPartialFragments({frag:t,part:null,stats:t.stats,id:t.type})}e.fragments[0]||(e.deltaUpdateFailed=!0)}waitForLive(e){const t=e.details;return(t==null?void 0:t.live)&&t.type!=="EVENT"&&(this.levelLastLoaded!==e||t.expired)}flushMainBuffer(e,t,s=null){if(!(e-t))return;const i={startOffset:e,endOffset:t,type:s};this.hls.trigger(m.BUFFER_FLUSHING,i)}_loadInitSegment(e,t){this._doFragLoad(e,t).then(s=>{const i=s==null?void 0:s.frag;if(!i||this.fragContextChanged(i)||!this.levels)throw new Error("init load aborted");return s}).then(s=>{const{hls:i}=this,{frag:r,payload:n}=s,o=r.decryptdata;if(n&&n.byteLength>0&&o!=null&&o.key&&o.iv&&Lt(o.method)){const c=self.performance.now();return this.decrypter.decrypt(new Uint8Array(n),o.key.buffer,o.iv.buffer,ki(o.method)).catch(l=>{throw i.trigger(m.ERROR,{type:V.MEDIA_ERROR,details:R.FRAG_DECRYPT_ERROR,fatal:!1,error:l,reason:l.message,frag:r}),l}).then(l=>{const h=self.performance.now();return i.trigger(m.FRAG_DECRYPTED,{frag:r,payload:l,stats:{tstart:c,tdecrypt:h}}),s.payload=l,this.completeInitSegmentLoad(s)})}return this.completeInitSegmentLoad(s)}).catch(s=>{this.state===C.STOPPED||this.state===C.ERROR||(this.warn(s),this.resetFragmentLoading(e))})}completeInitSegmentLoad(e){const{levels:t}=this;if(!t)throw new Error("init load aborted, missing levels");const s=e.frag.stats;this.state!==C.STOPPED&&(this.state=C.IDLE),e.frag.data=new Uint8Array(e.payload),s.parsing.start=s.buffering.start=self.performance.now(),s.parsing.end=s.buffering.end=self.performance.now(),this.tick()}unhandledEncryptionError(e,t){var s,i;const r=e.tracks;if(r&&!t.encrypted&&((s=r.audio)!=null&&s.encrypted||(i=r.video)!=null&&i.encrypted)&&(!this.config.emeEnabled||!this.keyLoader.emeController)){const n=this.media,o=new Error(`Encrypted track with no key in ${this.fragInfo(t)} (media ${n?"attached mediaKeys: "+n.mediaKeys:"detached"})`);return this.warn(o.message),!n||n.mediaKeys?!1:(this.hls.trigger(m.ERROR,{type:V.KEY_SYSTEM_ERROR,details:R.KEY_SYSTEM_NO_KEYS,fatal:!1,error:o,frag:t}),this.resetTransmuxer(),!0)}return!1}fragContextChanged(e){const{fragCurrent:t}=this;return!e||!t||e.sn!==t.sn||e.level!==t.level}fragBufferedComplete(e,t){const s=this.mediaBuffer?this.mediaBuffer:this.media;if(this.log(`Buffered ${e.type} sn: ${e.sn}${t?" part: "+t.index:""} of ${this.fragInfo(e,!1,t)} > buffer:${s?Nl.toString(q.getBuffered(s)):"(detached)"})`),ce(e)){var i;if(e.type!==B.SUBTITLE){const n=e.elementaryStreams;if(!Object.keys(n).some(o=>!!n[o])){this.state=C.IDLE;return}}const r=(i=this.levels)==null?void 0:i[e.level];r!=null&&r.fragmentError&&(this.log(`Resetting level fragment error count of ${r.fragmentError} on frag buffered`),r.fragmentError=0)}this.state=C.IDLE}_handleFragmentLoadComplete(e){const{transmuxer:t}=this;if(!t)return;const{frag:s,part:i,partsLoaded:r}=e,n=!r||r.length===0||r.some(c=>!c),o=new Pi(s.level,s.sn,s.stats.chunkCount+1,0,i?i.index:-1,!n);t.flush(o)}_handleFragmentLoadProgress(e){}_doFragLoad(e,t,s=null,i){var r;this.fragCurrent=e;const n=t.details;if(!this.levels||!n)throw new Error(`frag load aborted, missing level${n?"":" detail"}s`);let o=null;if(e.encrypted&&!((r=e.decryptdata)!=null&&r.key)){if(this.log(`Loading key for ${e.sn} of [${n.startSN}-${n.endSN}], ${this.playlistLabel()} ${e.level}`),this.state=C.KEY_LOADING,this.fragCurrent=e,o=this.keyLoader.load(e).then(u=>{if(!this.fragContextChanged(u.frag))return this.hls.trigger(m.KEY_LOADED,u),this.state===C.KEY_LOADING&&(this.state=C.IDLE),u}),this.hls.trigger(m.KEY_LOADING,{frag:e}),this.fragCurrent===null)return this.log("context changed in KEY_LOADING"),Promise.resolve(null)}else e.encrypted||(o=this.keyLoader.loadClear(e,n.encryptedFragments,this.startFragRequested),o&&this.log("[eme] blocking frag load until media-keys acquired"));const c=this.fragPrevious;if(ce(e)&&(!c||e.sn!==c.sn)){const u=this.shouldLoadParts(t.details,e.end);u!==this.loadingParts&&(this.log(`LL-Part loading ${u?"ON":"OFF"} loading sn ${c==null?void 0:c.sn}->${e.sn}`),this.loadingParts=u)}if(s=Math.max(e.start,s||0),this.loadingParts&&ce(e)){const u=n.partList;if(u&&i){s>n.fragmentEnd&&n.fragmentHint&&(e=n.fragmentHint);const f=this.getNextPart(u,e,s);if(f>-1){const g=u[f];e=this.fragCurrent=g.fragment,this.log(`Loading ${e.type} sn: ${e.sn} part: ${g.index} (${f}/${u.length-1}) of ${this.fragInfo(e,!1,g)}) cc: ${e.cc} [${n.startSN}-${n.endSN}], target: ${parseFloat(s.toFixed(3))}`),this.nextLoadPosition=g.start+g.duration,this.state=C.FRAG_LOADING;let y;return o?y=o.then(p=>!p||this.fragContextChanged(p.frag)?null:this.doFragPartsLoad(e,g,t,i)).catch(p=>this.handleFragLoadError(p)):y=this.doFragPartsLoad(e,g,t,i).catch(p=>this.handleFragLoadError(p)),this.hls.trigger(m.FRAG_LOADING,{frag:e,part:g,targetBufferTime:s}),this.fragCurrent===null?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING parts")):y}else if(!e.url||this.loadedEndOfParts(u,s))return Promise.resolve(null)}}if(ce(e)&&this.loadingParts){var l;this.log(`LL-Part loading OFF after next part miss @${s.toFixed(2)} Check buffer at sn: ${e.sn} loaded parts: ${(l=n.partList)==null?void 0:l.filter(u=>u.loaded).map(u=>`[${u.start}-${u.end}]`)}`),this.loadingParts=!1}else if(!e.url)return Promise.resolve(null);this.log(`Loading ${e.type} sn: ${e.sn} of ${this.fragInfo(e,!1)}) cc: ${e.cc} ${"["+n.startSN+"-"+n.endSN+"]"}, target: ${parseFloat(s.toFixed(3))}`),M(e.sn)&&!this.bitrateTest&&(this.nextLoadPosition=e.start+e.duration),this.state=C.FRAG_LOADING;const h=this.config.progressive&&e.type!==B.SUBTITLE;let d;return h&&o?d=o.then(u=>!u||this.fragContextChanged(u.frag)?null:this.fragmentLoader.load(e,i)).catch(u=>this.handleFragLoadError(u)):d=Promise.all([this.fragmentLoader.load(e,h?i:void 0),o]).then(([u])=>(!h&&i&&i(u),u)).catch(u=>this.handleFragLoadError(u)),this.hls.trigger(m.FRAG_LOADING,{frag:e,targetBufferTime:s}),this.fragCurrent===null?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING")):d}doFragPartsLoad(e,t,s,i){return new Promise((r,n)=>{var o;const c=[],l=(o=s.details)==null?void 0:o.partList,h=d=>{this.fragmentLoader.loadPart(e,d,i).then(u=>{c[d.index]=u;const f=u.part;this.hls.trigger(m.FRAG_LOADED,u);const g=Mr(s.details,e.sn,d.index+1)||Jn(l,e.sn,d.index+1);if(g)h(g);else return r({frag:e,part:f,partsLoaded:c})}).catch(n)};h(t)})}handleFragLoadError(e){if("data"in e){const t=e.data;t.frag&&t.details===R.INTERNAL_ABORTED?this.handleFragLoadAborted(t.frag,t.part):t.frag&&t.type===V.KEY_SYSTEM_ERROR?(t.frag.abortRequests(),this.resetStartWhenNotLoaded(),this.resetFragmentLoading(t.frag)):this.hls.trigger(m.ERROR,t)}else this.hls.trigger(m.ERROR,{type:V.OTHER_ERROR,details:R.INTERNAL_EXCEPTION,err:e,error:e,fatal:!0});return null}_handleTransmuxerFlush(e){const t=this.getCurrentContext(e);if(!t||this.state!==C.PARSING){!this.fragCurrent&&this.state!==C.STOPPED&&this.state!==C.ERROR&&(this.state=C.IDLE);return}const{frag:s,part:i,level:r}=t,n=self.performance.now();s.stats.parsing.end=n,i&&(i.stats.parsing.end=n);const o=this.getLevelDetails(),l=o&&s.sn>o.endSN||this.shouldLoadParts(o,s.end);l!==this.loadingParts&&(this.log(`LL-Part loading ${l?"ON":"OFF"} after parsing segment ending @${s.end.toFixed(2)}`),this.loadingParts=l),this.updateLevelTiming(s,i,r,e.partial)}shouldLoadParts(e,t){if(this.config.lowLatencyMode){if(!e)return this.loadingParts;if(e.partList){var s;const r=e.partList[0];if(r.fragment.type===B.SUBTITLE)return!1;const n=r.end+(((s=e.fragmentHint)==null?void 0:s.duration)||0);if(t>=n){var i;if((this.hls.hasEnoughToStart?((i=this.media)==null?void 0:i.currentTime)||this.lastCurrentTime:this.getLoadPosition())>r.start-r.fragment.duration)return!0}}}return!1}getCurrentContext(e){const{levels:t,fragCurrent:s}=this,{level:i,sn:r,part:n}=e;if(!(t!=null&&t[i]))return this.warn(`Levels object was unset while buffering fragment ${r} of ${this.playlistLabel()} ${i}. The current chunk will not be buffered.`),null;const o=t[i],c=o.details,l=n>-1?Mr(c,r,n):null,h=l?l.fragment:Zn(c,r,s);return h?(s&&s!==h&&(h.stats=s.stats),{frag:h,part:l,level:o}):null}bufferFragmentData(e,t,s,i,r){if(this.state!==C.PARSING)return;const{data1:n,data2:o}=e;let c=n;if(o&&(c=ke(n,o)),!c.length)return;const l=this.initPTS[t.cc],h=l?-l.baseTime/l.timescale:void 0,d={type:e.type,frag:t,part:s,chunkMeta:i,offset:h,parent:t.type,data:c};if(this.hls.trigger(m.BUFFER_APPENDING,d),e.dropped&&e.independent&&!s){if(r)return;this.flushBufferGap(t)}}flushBufferGap(e){const t=this.media;if(!t)return;if(!q.isBuffered(t,t.currentTime)){this.flushMainBuffer(0,e.start);return}const s=t.currentTime,i=q.bufferInfo(t,s,0),r=e.duration,n=Math.min(this.config.maxFragLookUpTolerance*2,r*.25),o=Math.max(Math.min(e.start-n,i.end-n),s+n);e.start-o>n&&this.flushMainBuffer(o,e.start)}getFwdBufferInfo(e,t){var s;const i=this.getLoadPosition();if(!M(i))return null;const n=this.lastCurrentTime>i||(s=this.media)!=null&&s.paused?0:this.config.maxBufferHole;return this.getFwdBufferInfoAtPos(e,i,t,n)}getFwdBufferInfoAtPos(e,t,s,i){const r=q.bufferInfo(e,t,i);if(r.len===0&&r.nextStart!==void 0){const n=this.fragmentTracker.getBufferedFrag(t,s);if(n&&(r.nextStart<=n.end||n.gap)){const o=Math.max(Math.min(r.nextStart,n.end)-t,i);return q.bufferInfo(e,t,o)}}return r}getMaxBufferLength(e){const{config:t}=this;let s;return e?s=Math.max(8*t.maxBufferSize/e,t.maxBufferLength):s=t.maxBufferLength,Math.min(s,t.maxMaxBufferLength)}reduceMaxBufferLength(e,t){const s=this.config,i=Math.max(Math.min(e-t,s.maxBufferLength),t),r=Math.max(e-t*3,s.maxMaxBufferLength/2,i);return r>=i?(s.maxMaxBufferLength=r,this.warn(`Reduce max buffer length to ${r}s`),!0):!1}getAppendedFrag(e,t=B.MAIN){const s=this.fragmentTracker?this.fragmentTracker.getAppendedFrag(e,t):null;return s&&"fragment"in s?s.fragment:s}getNextFragment(e,t){const s=t.fragments,i=s.length;if(!i)return null;const{config:r}=this,n=s[0].start,o=r.lowLatencyMode&&!!t.partList;let c=null;if(t.live){const d=r.initialLiveManifestSize;if(i<d)return this.warn(`Not enough fragments to start playback (have: ${i}, need: ${d})`),null;if(!t.PTSKnown&&!this.startFragRequested&&this.startPosition===-1||e<n){var l;o&&!this.loadingParts&&(this.log("LL-Part loading ON for initial live fragment"),this.loadingParts=!0),c=this.getInitialLiveFragment(t);const u=this.hls.startPosition,f=this.hls.liveSyncPosition,g=c?(u!==-1&&u>=n?u:f)||c.start:e;this.log(`Setting startPosition to ${g} to match start frag at live edge. mainStart: ${u} liveSyncPosition: ${f} frag.start: ${(l=c)==null?void 0:l.start}`),this.startPosition=this.nextLoadPosition=g}}else e<=n&&(c=s[0]);if(!c){const d=this.loadingParts?t.partEnd:t.fragmentEnd;c=this.getFragmentAtPosition(e,d,t)}let h=this.filterReplacedPrimary(c,t);if(!h&&c){const d=c.sn-t.startSN;h=this.filterReplacedPrimary(s[d+1]||null,t)}return this.mapToInitFragWhenRequired(h)}isLoopLoading(e,t){const s=this.fragmentTracker.getState(e);return(s===de.OK||s===de.PARTIAL&&!!e.gap)&&this.nextLoadPosition>t}getNextFragmentLoopLoading(e,t,s,i,r){let n=null;if(e.gap&&(n=this.getNextFragment(this.nextLoadPosition,t),n&&!n.gap&&s.nextStart)){const o=this.getFwdBufferInfoAtPos(this.mediaBuffer?this.mediaBuffer:this.media,s.nextStart,i,0);if(o!==null&&s.len+o.len>=r){const c=n.sn;return this.loopSn!==c&&(this.log(`buffer full after gaps in "${i}" playlist starting at sn: ${c}`),this.loopSn=c),null}}return this.loopSn=void 0,n}get primaryPrefetch(){if(Ur(this.config)){var e;if((e=this.hls.interstitialsManager)==null||(e=e.playingItem)==null?void 0:e.event)return!0}return!1}filterReplacedPrimary(e,t){if(!e)return e;if(Ur(this.config)&&e.type!==B.SUBTITLE){const s=this.hls.interstitialsManager,i=s==null?void 0:s.bufferingItem;if(i){const n=i.event;if(n){if(n.appendInPlace||Math.abs(e.start-i.start)>1||i.start===0)return null}else if(e.end<=i.start&&(t==null?void 0:t.live)===!1||e.start>i.end&&i.nextEvent&&(i.nextEvent.appendInPlace||e.start-i.end>1))return null}const r=s==null?void 0:s.playerQueue;if(r)for(let n=r.length;n--;){const o=r[n].interstitial;if(o.appendInPlace&&e.start>=o.startTime&&e.end<=o.resumeTime)return null}}return e}mapToInitFragWhenRequired(e){return e!=null&&e.initSegment&&!e.initSegment.data&&!this.bitrateTest?e.initSegment:e}getNextPart(e,t,s){let i=-1,r=!1,n=!0;for(let o=0,c=e.length;o<c;o++){const l=e[o];if(n=n&&!l.independent,i>-1&&s<l.start)break;const h=l.loaded;h?i=-1:(r||(l.independent||n)&&l.fragment===t)&&(l.fragment!==t&&this.warn(`Need buffer at ${s} but next unloaded part starts at ${l.start}`),i=o),r=h}return i}loadedEndOfParts(e,t){let s;for(let i=e.length;i--;){if(s=e[i],!s.loaded)return!1;if(t>s.start)return!0}return!1}getInitialLiveFragment(e){const t=e.fragments,s=this.fragPrevious;let i=null;if(s){if(e.hasProgramDateTime&&(this.log(`Live playlist, switching playlist, load frag with same PDT: ${s.programDateTime}`),i=Jo(t,s.endProgramDateTime,this.config.maxFragLookUpTolerance)),!i){const r=s.sn+1;if(r>=e.startSN&&r<=e.endSN){const n=t[r-e.startSN];s.cc===n.cc&&(i=n,this.log(`Live playlist, switching playlist, load frag with next SN: ${i.sn}`))}i||(i=Bn(e,s.cc,s.end),i&&this.log(`Live playlist, switching playlist, load frag with same CC: ${i.sn}`))}}else{const r=this.hls.liveSyncPosition;r!==null&&(i=this.getFragmentAtPosition(r,this.bitrateTest?e.fragmentEnd:e.edge,e))}return i}getFragmentAtPosition(e,t,s){const{config:i}=this;let{fragPrevious:r}=this,{fragments:n,endSN:o}=s;const{fragmentHint:c}=s,{maxFragLookUpTolerance:l}=i,h=s.partList,d=!!(this.loadingParts&&h!=null&&h.length&&c);d&&!this.bitrateTest&&h[h.length-1].fragment.sn===c.sn&&(n=n.concat(c),o=c.sn);let u;if(e<t){var f;const y=e<this.lastCurrentTime||e>t-l||(f=this.media)!=null&&f.paused||!this.startFragRequested?0:l;u=gt(r,n,e,y)}else u=n[n.length-1];if(u){const g=u.sn-s.startSN,y=this.fragmentTracker.getState(u);if((y===de.OK||y===de.PARTIAL&&u.gap)&&(r=u),r&&u.sn===r.sn&&(!d||h[0].fragment.sn>u.sn||!s.live)&&u.level===r.level){const E=n[g+1];u.sn<o&&this.fragmentTracker.getState(E)!==de.OK?u=E:u=null}}return u}alignPlaylists(e,t,s){const i=e.fragments.length;if(!i)return this.warn("No fragments in live playlist"),0;const r=e.fragmentStart,n=!t,o=e.alignedSliding&&M(r);if(n||!o&&!r){Ml(s,e);const c=e.fragmentStart;return this.log(`Live playlist sliding: ${c.toFixed(2)} start-sn: ${t?t.startSN:"na"}->${e.startSN} fragments: ${i}`),c}return r}waitForCdnTuneIn(e){return e.live&&e.canBlockReload&&e.partTarget&&e.tuneInGoal>Math.max(e.partHoldBack,e.partTarget*3)}setStartPosition(e,t){let s=this.startPosition;s<t&&(s=-1);const i=this.timelineOffset;if(s===-1){const r=this.startTimeOffset!==null,n=r?this.startTimeOffset:e.startTimeOffset;n!==null&&M(n)?(s=t+n,n<0&&(s+=e.edge),s=Math.min(Math.max(t,s),t+e.totalduration),this.log(`Setting startPosition to ${s} for start time offset ${n} found in ${r?"multivariant":"media"} playlist`),this.startPosition=s):e.live?(s=this.hls.liveSyncPosition||t,this.log(`Setting startPosition to -1 to start at live edge ${s}`),this.startPosition=-1):(this.log("setting startPosition to 0 by default"),this.startPosition=s=0),this.lastCurrentTime=s+i}this.nextLoadPosition=s+i}getLoadPosition(){var e;const{media:t}=this;let s=0;return(e=this.hls)!=null&&e.hasEnoughToStart&&t?s=t.currentTime:this.nextLoadPosition>=0&&(s=this.nextLoadPosition),s}handleFragLoadAborted(e,t){this.transmuxer&&e.type===this.playlistType&&ce(e)&&e.stats.aborted&&(this.log(`Fragment ${e.sn}${t?" part "+t.index:""} of ${this.playlistLabel()} ${e.level} was aborted`),this.resetFragmentLoading(e))}resetFragmentLoading(e){(!this.fragCurrent||!this.fragContextChanged(e)&&this.state!==C.FRAG_LOADING_WAITING_RETRY)&&(this.state=C.IDLE)}onFragmentOrKeyLoadError(e,t){var s;if(t.chunkMeta&&!t.frag){const E=this.getCurrentContext(t.chunkMeta);E&&(t.frag=E.frag)}const i=t.frag;if(!i||i.type!==e||!this.levels)return;if(this.fragContextChanged(i)){var r;this.warn(`Frag load error must match current frag to retry ${i.url} > ${(r=this.fragCurrent)==null?void 0:r.url}`);return}const n=t.details===R.FRAG_GAP;n&&this.fragmentTracker.fragBuffered(i,!0);const o=t.errorAction;if(!o){this.state=C.ERROR;return}const{action:c,flags:l,retryCount:h=0,retryConfig:d}=o,u=!!d,f=u&&c===ge.RetryRequest,g=u&&!o.resolved&&l===Ie.MoveAllAlternatesMatchingHost,y=(s=this.hls.latestLevelDetails)==null?void 0:s.live;if(!f&&g&&ce(i)&&!i.endList&&y&&!$n(t))this.resetFragmentErrors(e),this.treatAsGap(i),o.resolved=!0;else if((f||g)&&h<d.maxNumRetry){var p;const E=li((p=t.response)==null?void 0:p.code),T=Di(d,h);if(this.resetStartWhenNotLoaded(),this.retryDate=self.performance.now()+T,this.state=C.FRAG_LOADING_WAITING_RETRY,o.resolved=!0,E){this.log("Waiting for connection (offline)"),this.retryDate=1/0,t.reason="offline";return}this.warn(`Fragment ${i.sn} of ${e} ${i.level} errored with ${t.details}, retrying loading ${h+1}/${d.maxNumRetry} in ${T}ms`)}else if(d)if(this.resetFragmentErrors(e),h<d.maxNumRetry)!n&&c!==ge.RemoveAlternatePermanently&&(o.resolved=!0);else{this.warn(`${t.details} reached or exceeded max retry (${h})`);return}else c===ge.SendAlternateToPenaltyBox?this.state=C.WAITING_LEVEL:this.state=C.ERROR;this.tickImmediate()}checkRetryDate(){const e=self.performance.now(),t=this.retryDate,s=t===1/0;(!t||e>=t||s&&!li(0))&&(s&&this.log("Connection restored (online)"),this.resetStartWhenNotLoaded(),this.state=C.IDLE)}reduceLengthAndFlushBuffer(e){if(this.state===C.PARSING||this.state===C.PARSED){const t=e.frag,s=e.parent,i=this.getFwdBufferInfo(this.mediaBuffer,s),r=i&&i.len>.5;r&&this.reduceMaxBufferLength(i.len,(t==null?void 0:t.duration)||10);const n=!r;return n&&this.warn(`Buffer full error while media.currentTime (${this.getLoadPosition()}) is not buffered, flush ${s} buffer`),t&&(this.fragmentTracker.removeFragment(t),this.nextLoadPosition=t.start),this.resetLoadingState(),n}return!1}resetFragmentErrors(e){e===B.AUDIO&&(this.fragCurrent=null),this.hls.hasEnoughToStart||(this.startFragRequested=!1),this.state!==C.STOPPED&&(this.state=C.IDLE)}afterBufferFlushed(e,t,s){if(!e)return;const i=q.getBuffered(e);this.fragmentTracker.detectEvictedFragments(t,i,s),this.state===C.ENDED&&this.resetLoadingState()}resetLoadingState(){this.log("Reset loading state"),this.fragCurrent=null,this.fragPrevious=null,this.state!==C.STOPPED&&(this.state=C.IDLE)}resetStartWhenNotLoaded(){if(!this.hls.hasEnoughToStart){this.startFragRequested=!1;const e=this.levelLastLoaded,t=e?e.details:null;t!=null&&t.live?(this.log("resetting startPosition for live start"),this.startPosition=-1,this.setStartPosition(t,t.fragmentStart),this.resetLoadingState()):this.nextLoadPosition=this.startPosition}}resetWhenMissingContext(e){this.log(`Loading context changed while buffering sn ${e.sn} of ${this.playlistLabel()} ${e.level===-1?"<removed>":e.level}. This chunk will not be buffered.`),this.removeUnbufferedFrags(),this.resetStartWhenNotLoaded(),this.resetLoadingState()}removeUnbufferedFrags(e=0){this.fragmentTracker.removeFragmentsInRange(e,1/0,this.playlistType,!1,!0)}updateLevelTiming(e,t,s,i){const r=s.details;if(!r){this.warn("level.details undefined");return}if(!Object.keys(e.elementaryStreams).reduce((c,l)=>{const h=e.elementaryStreams[l];if(h){const d=h.endPTS-h.startPTS;if(d<=0)return this.warn(`Could not parse fragment ${e.sn} ${l} duration reliably (${d})`),c||!1;const u=i?0:Xn(r,e,h.startPTS,h.endPTS,h.startDTS,h.endDTS,this);return this.hls.trigger(m.LEVEL_PTS_UPDATED,{details:r,level:s,drift:u,type:l,frag:e,start:h.startPTS,end:h.endPTS}),!0}return c},!1)){var o;const c=((o=this.transmuxer)==null?void 0:o.error)===null;if((s.fragmentError===0||c&&(s.fragmentError<2||e.endList))&&this.treatAsGap(e,s),c){const l=new Error(`Found no media in fragment ${e.sn} of ${this.playlistLabel()} ${e.level} resetting transmuxer to fallback to playlist timing`);if(this.warn(l.message),this.hls.trigger(m.ERROR,{type:V.MEDIA_ERROR,details:R.FRAG_PARSING_ERROR,fatal:!1,error:l,frag:e,reason:`Found no media in msn ${e.sn} of ${this.playlistLabel()} "${s.url}"`}),!this.hls)return;this.resetTransmuxer()}}this.state=C.PARSED,this.log(`Parsed ${e.type} sn: ${e.sn}${t?" part: "+t.index:""} of ${this.fragInfo(e,!1,t)})`),this.hls.trigger(m.FRAG_PARSED,{frag:e,part:t})}playlistLabel(){return this.playlistType===B.MAIN?"level":"track"}fragInfo(e,t=!0,s){var i,r;return`${this.playlistLabel()} ${e.level} (${s?"part":"frag"}:[${((i=t&&!s?e.startPTS:(s||e).start)!=null?i:NaN).toFixed(3)}-${((r=t&&!s?e.endPTS:(s||e).end)!=null?r:NaN).toFixed(3)}]${s&&e.type==="main"?"INDEPENDENT="+(s.independent?"YES":"NO"):""}`}treatAsGap(e,t){t&&t.fragmentError++,e.gap=!0,this.fragmentTracker.removeFragment(e),this.fragmentTracker.fragBuffered(e,!0)}resetTransmuxer(){var e;(e=this.transmuxer)==null||e.reset()}recoverWorkerError(e){e.event==="demuxerWorker"&&(this.fragmentTracker.removeAllFragments(),this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null),this.resetStartWhenNotLoaded(),this.resetLoadingState())}set state(e){const t=this._state;t!==e&&(this._state=e,this.log(`${t}->${e}`))}get state(){return this._state}}function Ur(a){return!!a.interstitialsController&&a.enableInterstitialPlayback!==!1}class ia{constructor(){this.chunks=[],this.dataLength=0}push(e){this.chunks.push(e),this.dataLength+=e.length}flush(){const{chunks:e,dataLength:t}=this;let s;if(e.length)e.length===1?s=e[0]:s=Bl(e,t);else return new Uint8Array(0);return this.reset(),s}reset(){this.chunks.length=0,this.dataLength=0}}function Bl(a,e){const t=new Uint8Array(e);let s=0;for(let i=0;i<a.length;i++){const r=a[i];t.set(r,s),s+=r.length}return t}var Gs={exports:{}},$r;function Ul(){return $r||($r=1,function(a){var e=Object.prototype.hasOwnProperty,t="~";function s(){}Object.create&&(s.prototype=Object.create(null),new s().__proto__||(t=!1));function i(c,l,h){this.fn=c,this.context=l,this.once=h||!1}function r(c,l,h,d,u){if(typeof h!="function")throw new TypeError("The listener must be a function");var f=new i(h,d||c,u),g=t?t+l:l;return c._events[g]?c._events[g].fn?c._events[g]=[c._events[g],f]:c._events[g].push(f):(c._events[g]=f,c._eventsCount++),c}function n(c,l){--c._eventsCount===0?c._events=new s:delete c._events[l]}function o(){this._events=new s,this._eventsCount=0}o.prototype.eventNames=function(){var l=[],h,d;if(this._eventsCount===0)return l;for(d in h=this._events)e.call(h,d)&&l.push(t?d.slice(1):d);return Object.getOwnPropertySymbols?l.concat(Object.getOwnPropertySymbols(h)):l},o.prototype.listeners=function(l){var h=t?t+l:l,d=this._events[h];if(!d)return[];if(d.fn)return[d.fn];for(var u=0,f=d.length,g=new Array(f);u<f;u++)g[u]=d[u].fn;return g},o.prototype.listenerCount=function(l){var h=t?t+l:l,d=this._events[h];return d?d.fn?1:d.length:0},o.prototype.emit=function(l,h,d,u,f,g){var y=t?t+l:l;if(!this._events[y])return!1;var p=this._events[y],E=arguments.length,T,S;if(p.fn){switch(p.once&&this.removeListener(l,p.fn,void 0,!0),E){case 1:return p.fn.call(p.context),!0;case 2:return p.fn.call(p.context,h),!0;case 3:return p.fn.call(p.context,h,d),!0;case 4:return p.fn.call(p.context,h,d,u),!0;case 5:return p.fn.call(p.context,h,d,u,f),!0;case 6:return p.fn.call(p.context,h,d,u,f,g),!0}for(S=1,T=new Array(E-1);S<E;S++)T[S-1]=arguments[S];p.fn.apply(p.context,T)}else{var v=p.length,A;for(S=0;S<v;S++)switch(p[S].once&&this.removeListener(l,p[S].fn,void 0,!0),E){case 1:p[S].fn.call(p[S].context);break;case 2:p[S].fn.call(p[S].context,h);break;case 3:p[S].fn.call(p[S].context,h,d);break;case 4:p[S].fn.call(p[S].context,h,d,u);break;default:if(!T)for(A=1,T=new Array(E-1);A<E;A++)T[A-1]=arguments[A];p[S].fn.apply(p[S].context,T)}}return!0},o.prototype.on=function(l,h,d){return r(this,l,h,d,!1)},o.prototype.once=function(l,h,d){return r(this,l,h,d,!0)},o.prototype.removeListener=function(l,h,d,u){var f=t?t+l:l;if(!this._events[f])return this;if(!h)return n(this,f),this;var g=this._events[f];if(g.fn)g.fn===h&&(!u||g.once)&&(!d||g.context===d)&&n(this,f);else{for(var y=0,p=[],E=g.length;y<E;y++)(g[y].fn!==h||u&&!g[y].once||d&&g[y].context!==d)&&p.push(g[y]);p.length?this._events[f]=p.length===1?p[0]:p:n(this,f)}return this},o.prototype.removeAllListeners=function(l){var h;return l?(h=t?t+l:l,this._events[h]&&n(this,h)):(this._events=new s,this._eventsCount=0),this},o.prototype.off=o.prototype.removeListener,o.prototype.addListener=o.prototype.on,o.prefixed=t,o.EventEmitter=o,a.exports=o}(Gs)),Gs.exports}var $l=Ul(),Fi=ho($l);const Gt="1.6.15",Dt={};function Gl(){return typeof __HLS_WORKER_BUNDLE__=="function"}function Kl(){const a=Dt[Gt];if(a)return a.clientCount++,a;const e=new self.Blob([`var exports={};var module={exports:exports};function define(f){f()};define.amd=true;(${__HLS_WORKER_BUNDLE__.toString()})(true);`],{type:"text/javascript"}),t=self.URL.createObjectURL(e),i={worker:new self.Worker(t),objectURL:t,clientCount:1};return Dt[Gt]=i,i}function Vl(a){const e=Dt[a];if(e)return e.clientCount++,e;const t=new self.URL(a,self.location.href).href,i={worker:new self.Worker(t),scriptURL:t,clientCount:1};return Dt[a]=i,i}function Hl(a){const e=Dt[a||Gt];if(e&&e.clientCount--===1){const{worker:s,objectURL:i}=e;delete Dt[a||Gt],i&&self.URL.revokeObjectURL(i),s.terminate()}}function ra(a,e){return e+10<=a.length&&a[e]===51&&a[e+1]===68&&a[e+2]===73&&a[e+3]<255&&a[e+4]<255&&a[e+6]<128&&a[e+7]<128&&a[e+8]<128&&a[e+9]<128}function Mi(a,e){return e+10<=a.length&&a[e]===73&&a[e+1]===68&&a[e+2]===51&&a[e+3]<255&&a[e+4]<255&&a[e+6]<128&&a[e+7]<128&&a[e+8]<128&&a[e+9]<128}function Cs(a,e){let t=0;return t=(a[e]&127)<<21,t|=(a[e+1]&127)<<14,t|=(a[e+2]&127)<<7,t|=a[e+3]&127,t}function Kt(a,e){const t=e;let s=0;for(;Mi(a,e);){s+=10;const i=Cs(a,e+6);s+=i,ra(a,e+10)&&(s+=10),e+=s}if(s>0)return a.subarray(t,t+s)}function Yl(a,e,t,s){const i=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],r=e[t+2],n=r>>2&15;if(n>12){const f=new Error(`invalid ADTS sampling index:${n}`);a.emit(m.ERROR,m.ERROR,{type:V.MEDIA_ERROR,details:R.FRAG_PARSING_ERROR,fatal:!0,error:f,reason:f.message});return}const o=(r>>6&3)+1,c=e[t+3]>>6&3|(r&1)<<2,l="mp4a.40."+o,h=i[n];let d=n;(o===5||o===29)&&(d-=3);const u=[o<<3|(d&14)>>1,(d&1)<<7|c<<3];return se.log(`manifest codec:${s}, parsed codec:${l}, channels:${c}, rate:${h} (ADTS object type:${o} sampling index:${n})`),{config:u,samplerate:h,channelCount:c,codec:l,parsedCodec:l,manifestCodec:s}}function na(a,e){return a[e]===255&&(a[e+1]&246)===240}function aa(a,e){return a[e+1]&1?7:9}function Ni(a,e){return(a[e+3]&3)<<11|a[e+4]<<3|(a[e+5]&224)>>>5}function Wl(a,e){return e+5<a.length}function bs(a,e){return e+1<a.length&&na(a,e)}function ql(a,e){return Wl(a,e)&&na(a,e)&&Ni(a,e)<=a.length-e}function jl(a,e){if(bs(a,e)){const t=aa(a,e);if(e+t>=a.length)return!1;const s=Ni(a,e);if(s<=t)return!1;const i=e+s;return i===a.length||bs(a,i)}return!1}function oa(a,e,t,s,i){if(!a.samplerate){const r=Yl(e,t,s,i);if(!r)return;ie(a,r)}}function la(a){return 1024*9e4/a}function Xl(a,e){const t=aa(a,e);if(e+t<=a.length){const s=Ni(a,e)-t;if(s>0)return{headerLength:t,frameLength:s}}}function ca(a,e,t,s,i){const r=la(a.samplerate),n=s+i*r,o=Xl(e,t);let c;if(o){const{frameLength:d,headerLength:u}=o,f=u+d,g=Math.max(0,t+f-e.length);g?(c=new Uint8Array(f-u),c.set(e.subarray(t+u,e.length),0)):c=e.subarray(t+u,t+f);const y={unit:c,pts:n};return g||a.samples.push(y),{sample:y,length:f,missing:g}}const l=e.length-t;return c=new Uint8Array(l),c.set(e.subarray(t,e.length),0),{sample:{unit:c,pts:n},length:l,missing:-1}}function zl(a,e){return Mi(a,e)&&Cs(a,e+6)+10<=a.length-e}function Ql(a){return a instanceof ArrayBuffer?a:a.byteOffset==0&&a.byteLength==a.buffer.byteLength?a.buffer:new Uint8Array(a).buffer}function Ks(a,e=0,t=1/0){return Zl(a,e,t,Uint8Array)}function Zl(a,e,t,s){const i=Jl(a);let r=1;"BYTES_PER_ELEMENT"in s&&(r=s.BYTES_PER_ELEMENT);const n=ec(a)?a.byteOffset:0,o=(n+a.byteLength)/r,c=(n+e)/r,l=Math.floor(Math.max(0,Math.min(c,o))),h=Math.floor(Math.min(l+Math.max(t,0),o));return new s(i,l,h-l)}function Jl(a){return a instanceof ArrayBuffer?a:a.buffer}function ec(a){return a&&a.buffer instanceof ArrayBuffer&&a.byteLength!==void 0&&a.byteOffset!==void 0}function tc(a){const e={key:a.type,description:"",data:"",mimeType:null,pictureType:null},t=3;if(a.size<2)return;if(a.data[0]!==t){console.log("Ignore frame with unrecognized character encoding");return}const s=a.data.subarray(1).indexOf(0);if(s===-1)return;const i=be(Ks(a.data,1,s)),r=a.data[2+s],n=a.data.subarray(3+s).indexOf(0);if(n===-1)return;const o=be(Ks(a.data,3+s,n));let c;return i==="-->"?c=be(Ks(a.data,4+s+n)):c=Ql(a.data.subarray(4+s+n)),e.mimeType=i,e.pictureType=r,e.description=o,e.data=c,e}function sc(a){if(a.size<2)return;const e=be(a.data,!0),t=new Uint8Array(a.data.subarray(e.length+1));return{key:a.type,info:e,data:t.buffer}}function ic(a){if(a.size<2)return;if(a.type==="TXXX"){let t=1;const s=be(a.data.subarray(t),!0);t+=s.length+1;const i=be(a.data.subarray(t));return{key:a.type,info:s,data:i}}const e=be(a.data.subarray(1));return{key:a.type,info:"",data:e}}function rc(a){if(a.type==="WXXX"){if(a.size<2)return;let t=1;const s=be(a.data.subarray(t),!0);t+=s.length+1;const i=be(a.data.subarray(t));return{key:a.type,info:s,data:i}}const e=be(a.data);return{key:a.type,info:"",data:e}}function nc(a){return a.type==="PRIV"?sc(a):a.type[0]==="W"?rc(a):a.type==="APIC"?tc(a):ic(a)}function ac(a){const e=String.fromCharCode(a[0],a[1],a[2],a[3]),t=Cs(a,4),s=10;return{type:e,size:t,data:a.subarray(s,s+t)}}const zt=10,oc=10;function ha(a){let e=0;const t=[];for(;Mi(a,e);){const s=Cs(a,e+6);a[e+5]>>6&1&&(e+=zt),e+=zt;const i=e+s;for(;e+oc<i;){const r=ac(a.subarray(e)),n=nc(r);n&&t.push(n),e+=r.size+zt}ra(a,e)&&(e+=zt)}return t}function da(a){return a&&a.key==="PRIV"&&a.info==="com.apple.streaming.transportStreamTimestamp"}function lc(a){if(a.data.byteLength===8){const e=new Uint8Array(a.data),t=e[3]&1;let s=(e[4]<<23)+(e[5]<<15)+(e[6]<<7)+e[7];return s/=45,t&&(s+=4772185884e-2),Math.round(s)}}function Bi(a){const e=ha(a);for(let t=0;t<e.length;t++){const s=e[t];if(da(s))return lc(s)}}let Re=function(a){return a.audioId3="org.id3",a.dateRange="com.apple.quicktime.HLS",a.emsg="https://aomedia.org/emsg/ID3",a.misbklv="urn:misb:KLV:bin:1910.1",a}({});function Ke(a="",e=9e4){return{type:a,id:-1,pid:-1,inputTimeScale:e,sequenceNumber:-1,samples:[],dropped:0}}class Ui{constructor(){this._audioTrack=void 0,this._id3Track=void 0,this.frameIndex=0,this.cachedData=null,this.basePTS=null,this.initPTS=null,this.lastPTS=null}resetInitSegment(e,t,s,i){this._id3Track={type:"id3",id:3,pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0}}resetTimeStamp(e){this.initPTS=e,this.resetContiguity()}resetContiguity(){this.basePTS=null,this.lastPTS=null,this.frameIndex=0}canParse(e,t){return!1}appendFrame(e,t,s){}demux(e,t){this.cachedData&&(e=ke(this.cachedData,e),this.cachedData=null);let s=Kt(e,0),i=s?s.length:0,r;const n=this._audioTrack,o=this._id3Track,c=s?Bi(s):void 0,l=e.length;for((this.basePTS===null||this.frameIndex===0&&M(c))&&(this.basePTS=cc(c,t,this.initPTS),this.lastPTS=this.basePTS),this.lastPTS===null&&(this.lastPTS=this.basePTS),s&&s.length>0&&o.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:s,type:Re.audioId3,duration:Number.POSITIVE_INFINITY});i<l;){if(this.canParse(e,i)){const h=this.appendFrame(n,e,i);h?(this.frameIndex++,this.lastPTS=h.sample.pts,i+=h.length,r=i):i=l}else zl(e,i)?(s=Kt(e,i),o.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:s,type:Re.audioId3,duration:Number.POSITIVE_INFINITY}),i+=s.length,r=i):i++;if(i===l&&r!==l){const h=e.slice(r);this.cachedData?this.cachedData=ke(this.cachedData,h):this.cachedData=h}}return{audioTrack:n,videoTrack:Ke(),id3Track:o,textTrack:Ke()}}demuxSampleAes(e,t,s){return Promise.reject(new Error(`[${this}] This demuxer does not support Sample-AES decryption`))}flush(e){const t=this.cachedData;return t&&(this.cachedData=null,this.demux(t,0)),{audioTrack:this._audioTrack,videoTrack:Ke(),id3Track:this._id3Track,textTrack:Ke()}}destroy(){this.cachedData=null,this._audioTrack=this._id3Track=void 0}}const cc=(a,e,t)=>{if(M(a))return a*90;const s=t?t.baseTime*9e4/t.timescale:0;return e*9e4+s};let Qt=null;const hc=[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],dc=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],uc=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],fc=[0,1,1,4];function ua(a,e,t,s,i){if(t+24>e.length)return;const r=fa(e,t);if(r&&t+r.frameLength<=e.length){const n=r.samplesPerFrame*9e4/r.sampleRate,o=s+i*n,c={unit:e.subarray(t,t+r.frameLength),pts:o,dts:o};return a.config=[],a.channelCount=r.channelCount,a.samplerate=r.sampleRate,a.samples.push(c),{sample:c,length:r.frameLength,missing:0}}}function fa(a,e){const t=a[e+1]>>3&3,s=a[e+1]>>1&3,i=a[e+2]>>4&15,r=a[e+2]>>2&3;if(t!==1&&i!==0&&i!==15&&r!==3){const n=a[e+2]>>1&1,o=a[e+3]>>6,c=t===3?3-s:s===3?3:4,l=hc[c*14+i-1]*1e3,d=dc[(t===3?0:t===2?1:2)*3+r],u=o===3?1:2,f=uc[t][s],g=fc[s],y=f*8*g,p=Math.floor(f*l/d+n)*g;if(Qt===null){const S=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);Qt=S?parseInt(S[1]):0}return!!Qt&&Qt<=87&&s===2&&l>=224e3&&o===0&&(a[e+3]=a[e+3]|128),{sampleRate:d,channelCount:u,frameLength:p,samplesPerFrame:y}}}function $i(a,e){return a[e]===255&&(a[e+1]&224)===224&&(a[e+1]&6)!==0}function ga(a,e){return e+1<a.length&&$i(a,e)}function gc(a,e){return $i(a,e)&&4<=a.length-e}function ma(a,e){if(e+1<a.length&&$i(a,e)){const s=fa(a,e);let i=4;s!=null&&s.frameLength&&(i=s.frameLength);const r=e+i;return r===a.length||ga(a,r)}return!1}class mc extends Ui{constructor(e,t){super(),this.observer=void 0,this.config=void 0,this.observer=e,this.config=t}resetInitSegment(e,t,s,i){super.resetInitSegment(e,t,s,i),this._audioTrack={container:"audio/adts",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"aac",samples:[],manifestCodec:t,duration:i,inputTimeScale:9e4,dropped:0}}static probe(e,t){if(!e)return!1;const s=Kt(e,0);let i=(s==null?void 0:s.length)||0;if(ma(e,i))return!1;for(let r=e.length;i<r;i++)if(jl(e,i))return t.log("ADTS sync word found !"),!0;return!1}canParse(e,t){return ql(e,t)}appendFrame(e,t,s){oa(e,this.observer,t,s,e.manifestCodec);const i=ca(e,t,s,this.basePTS,this.frameIndex);if(i&&i.missing===0)return i}}const pa=(a,e)=>{let t=0,s=5;e+=s;const i=new Uint32Array(1),r=new Uint32Array(1),n=new Uint8Array(1);for(;s>0;){n[0]=a[e];const o=Math.min(s,8),c=8-o;r[0]=4278190080>>>24+c<<c,i[0]=(n[0]&r[0])>>c,t=t?t<<o|i[0]:i[0],e+=1,s-=o}return t};class pc extends Ui{constructor(e){super(),this.observer=void 0,this.observer=e}resetInitSegment(e,t,s,i){super.resetInitSegment(e,t,s,i),this._audioTrack={container:"audio/ac-3",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"ac3",samples:[],manifestCodec:t,duration:i,inputTimeScale:9e4,dropped:0}}canParse(e,t){return t+64<e.length}appendFrame(e,t,s){const i=ya(e,t,s,this.basePTS,this.frameIndex);if(i!==-1)return{sample:e.samples[e.samples.length-1],length:i,missing:0}}static probe(e){if(!e)return!1;const t=Kt(e,0);if(!t)return!1;const s=t.length;return e[s]===11&&e[s+1]===119&&Bi(t)!==void 0&&pa(e,s)<16}}function ya(a,e,t,s,i){if(t+8>e.length||e[t]!==11||e[t+1]!==119)return-1;const r=e[t+4]>>6;if(r>=3)return-1;const o=[48e3,44100,32e3][r],c=e[t+4]&63,h=[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][c*3+r]*2;if(t+h>e.length)return-1;const d=e[t+6]>>5;let u=0;d===2?u+=2:(d&1&&d!==1&&(u+=2),d&4&&(u+=2));const f=(e[t+6]<<8|e[t+7])>>12-u&1,y=[2,1,2,3,3,4,4,5][d]+f,p=e[t+5]>>3,E=e[t+5]&7,T=new Uint8Array([r<<6|p<<1|E>>2,(E&3)<<6|d<<3|f<<2|c>>4,c<<4&224]),S=1536/o*9e4,v=s+i*S,A=e.subarray(t,t+h);return a.config=T,a.channelCount=y,a.samplerate=o,a.samples.push({unit:A,pts:v}),h}class yc extends Ui{resetInitSegment(e,t,s,i){super.resetInitSegment(e,t,s,i),this._audioTrack={container:"audio/mpeg",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"mp3",samples:[],manifestCodec:t,duration:i,inputTimeScale:9e4,dropped:0}}static probe(e){if(!e)return!1;const t=Kt(e,0);let s=(t==null?void 0:t.length)||0;if(t&&e[s]===11&&e[s+1]===119&&Bi(t)!==void 0&&pa(e,s)<=16)return!1;for(let i=e.length;s<i;s++)if(ma(e,s))return se.log("MPEG Audio sync word found !"),!0;return!1}canParse(e,t){return gc(e,t)}appendFrame(e,t,s){if(this.basePTS!==null)return ua(e,t,s,this.basePTS,this.frameIndex)}}const Ec=/\/emsg[-/]ID3/i;class Tc{constructor(e,t){this.remainderData=null,this.timeOffset=0,this.config=void 0,this.videoTrack=void 0,this.audioTrack=void 0,this.id3Track=void 0,this.txtTrack=void 0,this.config=t}resetTimeStamp(){}resetInitSegment(e,t,s,i){const r=this.videoTrack=Ke("video",1),n=this.audioTrack=Ke("audio",1),o=this.txtTrack=Ke("text",1);if(this.id3Track=Ke("id3",1),this.timeOffset=0,!(e!=null&&e.byteLength))return;const c=bn(e);if(c.video){const{id:l,timescale:h,codec:d,supplemental:u}=c.video;r.id=l,r.timescale=o.timescale=h,r.codec=d,r.supplemental=u}if(c.audio){const{id:l,timescale:h,codec:d}=c.audio;n.id=l,n.timescale=h,n.codec=d}o.id=In.text,r.sampleDuration=0,r.duration=n.duration=i}resetContiguity(){this.remainderData=null}static probe(e){return po(e)}demux(e,t){this.timeOffset=t;let s=e;const i=this.videoTrack,r=this.txtTrack;if(this.config.progressive){this.remainderData&&(s=ke(this.remainderData,e));const o=Ao(s);this.remainderData=o.remainder,i.samples=o.valid||new Uint8Array}else i.samples=s;const n=this.extractID3Track(i,t);return r.samples=rr(t,i),{videoTrack:i,audioTrack:this.audioTrack,id3Track:n,textTrack:this.txtTrack}}flush(){const e=this.timeOffset,t=this.videoTrack,s=this.txtTrack;t.samples=this.remainderData||new Uint8Array,this.remainderData=null;const i=this.extractID3Track(t,this.timeOffset);return s.samples=rr(e,t),{videoTrack:t,audioTrack:Ke(),id3Track:i,textTrack:Ke()}}extractID3Track(e,t){const s=this.id3Track;if(e.samples.length){const i=z(e.samples,["emsg"]);i&&i.forEach(r=>{const n=Lo(r);if(Ec.test(n.schemeIdUri)){const o=Gr(n,t);let c=n.eventDuration===4294967295?Number.POSITIVE_INFINITY:n.eventDuration/n.timeScale;c<=.001&&(c=Number.POSITIVE_INFINITY);const l=n.payload;s.samples.push({data:l,len:l.byteLength,dts:o,pts:o,type:Re.emsg,duration:c})}else if(this.config.enableEmsgKLVMetadata&&n.schemeIdUri.startsWith("urn:misb:KLV:bin:1910.1")){const o=Gr(n,t);s.samples.push({data:n.payload,len:n.payload.byteLength,dts:o,pts:o,type:Re.misbklv,duration:Number.POSITIVE_INFINITY})}})}return s}demuxSampleAes(e,t,s){return Promise.reject(new Error("The MP4 demuxer does not support SAMPLE-AES decryption"))}destroy(){this.config=null,this.remainderData=null,this.videoTrack=this.audioTrack=this.id3Track=this.txtTrack=void 0}}function Gr(a,e){return M(a.presentationTime)?a.presentationTime/a.timeScale:e+a.presentationTimeDelta/a.timeScale}class Sc{constructor(e,t,s){this.keyData=void 0,this.decrypter=void 0,this.keyData=s,this.decrypter=new Ci(t,{removePKCS7Padding:!1})}decryptBuffer(e){return this.decrypter.decrypt(e,this.keyData.key.buffer,this.keyData.iv.buffer,nt.cbc)}decryptAacSample(e,t,s){const i=e[t].unit;if(i.length<=16)return;const r=i.subarray(16,i.length-i.length%16),n=r.buffer.slice(r.byteOffset,r.byteOffset+r.length);this.decryptBuffer(n).then(o=>{const c=new Uint8Array(o);i.set(c,16),this.decrypter.isSync()||this.decryptAacSamples(e,t+1,s)}).catch(s)}decryptAacSamples(e,t,s){for(;;t++){if(t>=e.length){s();return}if(!(e[t].unit.length<32)&&(this.decryptAacSample(e,t,s),!this.decrypter.isSync()))return}}getAvcEncryptedData(e){const t=Math.floor((e.length-48)/160)*16+16,s=new Int8Array(t);let i=0;for(let r=32;r<e.length-16;r+=160,i+=16)s.set(e.subarray(r,r+16),i);return s}getAvcDecryptedUnit(e,t){const s=new Uint8Array(t);let i=0;for(let r=32;r<e.length-16;r+=160,i+=16)e.set(s.subarray(i,i+16),r);return e}decryptAvcSample(e,t,s,i,r){const n=Cn(r.data),o=this.getAvcEncryptedData(n);this.decryptBuffer(o.buffer).then(c=>{r.data=this.getAvcDecryptedUnit(n,c),this.decrypter.isSync()||this.decryptAvcSamples(e,t,s+1,i)}).catch(i)}decryptAvcSamples(e,t,s,i){if(e instanceof Uint8Array)throw new Error("Cannot decrypt samples of type Uint8Array");for(;;t++,s=0){if(t>=e.length){i();return}const r=e[t].units;for(;!(s>=r.length);s++){const n=r[s];if(!(n.data.length<=48||n.type!==1&&n.type!==5)&&(this.decryptAvcSample(e,t,s,i,n),!this.decrypter.isSync()))return}}}}class Ea{constructor(){this.VideoSample=null}createVideoSample(e,t,s){return{key:e,frame:!1,pts:t,dts:s,units:[],length:0}}getLastNalUnit(e){var t;let s=this.VideoSample,i;if((!s||s.units.length===0)&&(s=e[e.length-1]),(t=s)!=null&&t.units){const r=s.units;i=r[r.length-1]}return i}pushAccessUnit(e,t){if(e.units.length&&e.frame){if(e.pts===void 0){const s=t.samples,i=s.length;if(i){const r=s[i-1];e.pts=r.pts,e.dts=r.dts}else{t.dropped++;return}}t.samples.push(e)}}parseNALu(e,t,s){const i=t.byteLength;let r=e.naluState||0;const n=r,o=[];let c=0,l,h,d,u=-1,f=0;for(r===-1&&(u=0,f=this.getNALuType(t,0),r=0,c=1);c<i;){if(l=t[c++],!r){r=l?0:1;continue}if(r===1){r=l?0:2;continue}if(!l)r=3;else if(l===1){if(h=c-r-1,u>=0){const g={data:t.subarray(u,h),type:f};o.push(g)}else{const g=this.getLastNalUnit(e.samples);g&&(n&&c<=4-n&&g.state&&(g.data=g.data.subarray(0,g.data.byteLength-n)),h>0&&(g.data=ke(g.data,t.subarray(0,h)),g.state=0))}c<i?(d=this.getNALuType(t,c),u=c,f=d,r=0):r=-1}else r=0}if(u>=0&&r>=0){const g={data:t.subarray(u,i),type:f,state:r};o.push(g)}if(o.length===0){const g=this.getLastNalUnit(e.samples);g&&(g.data=ke(g.data,t))}return e.naluState=r,o}}class Ft{constructor(e){this.data=void 0,this.bytesAvailable=void 0,this.word=void 0,this.bitsAvailable=void 0,this.data=e,this.bytesAvailable=e.byteLength,this.word=0,this.bitsAvailable=0}loadWord(){const e=this.data,t=this.bytesAvailable,s=e.byteLength-t,i=new Uint8Array(4),r=Math.min(4,t);if(r===0)throw new Error("no bytes available");i.set(e.subarray(s,s+r)),this.word=new DataView(i.buffer).getUint32(0),this.bitsAvailable=r*8,this.bytesAvailable-=r}skipBits(e){let t;e=Math.min(e,this.bytesAvailable*8+this.bitsAvailable),this.bitsAvailable>e?(this.word<<=e,this.bitsAvailable-=e):(e-=this.bitsAvailable,t=e>>3,e-=t<<3,this.bytesAvailable-=t,this.loadWord(),this.word<<=e,this.bitsAvailable-=e)}readBits(e){let t=Math.min(this.bitsAvailable,e);const s=this.word>>>32-t;if(e>32&&se.error("Cannot read more than 32 bits at a time"),this.bitsAvailable-=t,this.bitsAvailable>0)this.word<<=t;else if(this.bytesAvailable>0)this.loadWord();else throw new Error("no bits available");return t=e-t,t>0&&this.bitsAvailable?s<<t|this.readBits(t):s}skipLZ(){let e;for(e=0;e<this.bitsAvailable;++e)if(this.word&2147483648>>>e)return this.word<<=e,this.bitsAvailable-=e,e;return this.loadWord(),e+this.skipLZ()}skipUEG(){this.skipBits(1+this.skipLZ())}skipEG(){this.skipBits(1+this.skipLZ())}readUEG(){const e=this.skipLZ();return this.readBits(e+1)-1}readEG(){const e=this.readUEG();return 1&e?1+e>>>1:-1*(e>>>1)}readBoolean(){return this.readBits(1)===1}readUByte(){return this.readBits(8)}readUShort(){return this.readBits(16)}readUInt(){return this.readBits(32)}}class vc extends Ea{parsePES(e,t,s,i){const r=this.parseNALu(e,s.data,i);let n=this.VideoSample,o,c=!1;s.data=null,n&&r.length&&!e.audFound&&(this.pushAccessUnit(n,e),n=this.VideoSample=this.createVideoSample(!1,s.pts,s.dts)),r.forEach(l=>{var h,d;switch(l.type){case 1:{let y=!1;o=!0;const p=l.data;if(c&&p.length>4){const E=this.readSliceType(p);(E===2||E===4||E===7||E===9)&&(y=!0)}if(y){var u;(u=n)!=null&&u.frame&&!n.key&&(this.pushAccessUnit(n,e),n=this.VideoSample=null)}n||(n=this.VideoSample=this.createVideoSample(!0,s.pts,s.dts)),n.frame=!0,n.key=y;break}case 5:o=!0,(h=n)!=null&&h.frame&&!n.key&&(this.pushAccessUnit(n,e),n=this.VideoSample=null),n||(n=this.VideoSample=this.createVideoSample(!0,s.pts,s.dts)),n.key=!0,n.frame=!0;break;case 6:{o=!0,Ri(l.data,1,s.pts,t.samples);break}case 7:{var f,g;o=!0,c=!0;const y=l.data,p=this.readSPS(y);if(!e.sps||e.width!==p.width||e.height!==p.height||((f=e.pixelRatio)==null?void 0:f[0])!==p.pixelRatio[0]||((g=e.pixelRatio)==null?void 0:g[1])!==p.pixelRatio[1]){e.width=p.width,e.height=p.height,e.pixelRatio=p.pixelRatio,e.sps=[y];const E=y.subarray(1,4);let T="avc1.";for(let S=0;S<3;S++){let v=E[S].toString(16);v.length<2&&(v="0"+v),T+=v}e.codec=T}break}case 8:o=!0,e.pps=[l.data];break;case 9:o=!0,e.audFound=!0,(d=n)!=null&&d.frame&&(this.pushAccessUnit(n,e),n=null),n||(n=this.VideoSample=this.createVideoSample(!1,s.pts,s.dts));break;case 12:o=!0;break;default:o=!1;break}n&&o&&n.units.push(l)}),i&&n&&(this.pushAccessUnit(n,e),this.VideoSample=null)}getNALuType(e,t){return e[t]&31}readSliceType(e){const t=new Ft(e);return t.readUByte(),t.readUEG(),t.readUEG()}skipScalingList(e,t){let s=8,i=8,r;for(let n=0;n<e;n++)i!==0&&(r=t.readEG(),i=(s+r+256)%256),s=i===0?s:i}readSPS(e){const t=new Ft(e);let s=0,i=0,r=0,n=0,o,c,l;const h=t.readUByte.bind(t),d=t.readBits.bind(t),u=t.readUEG.bind(t),f=t.readBoolean.bind(t),g=t.skipBits.bind(t),y=t.skipEG.bind(t),p=t.skipUEG.bind(t),E=this.skipScalingList.bind(this);h();const T=h();if(d(5),g(3),h(),p(),T===100||T===110||T===122||T===244||T===44||T===83||T===86||T===118||T===128){const b=u();if(b===3&&g(1),p(),p(),g(1),f())for(c=b!==3?8:12,l=0;l<c;l++)f()&&(l<6?E(16,t):E(64,t))}p();const S=u();if(S===0)u();else if(S===1)for(g(1),y(),y(),o=u(),l=0;l<o;l++)y();p(),g(1);const v=u(),A=u(),D=d(1);D===0&&g(1),g(1),f()&&(s=u(),i=u(),r=u(),n=u());let x=[1,1];if(f()&&f())switch(h()){case 1:x=[1,1];break;case 2:x=[12,11];break;case 3:x=[10,11];break;case 4:x=[16,11];break;case 5:x=[40,33];break;case 6:x=[24,11];break;case 7:x=[20,11];break;case 8:x=[32,11];break;case 9:x=[80,33];break;case 10:x=[18,11];break;case 11:x=[15,11];break;case 12:x=[64,33];break;case 13:x=[160,99];break;case 14:x=[4,3];break;case 15:x=[3,2];break;case 16:x=[2,1];break;case 255:{x=[h()<<8|h(),h()<<8|h()];break}}return{width:Math.ceil((v+1)*16-s*2-i*2),height:(2-D)*(A+1)*16-(D?2:4)*(r+n),pixelRatio:x}}}class xc extends Ea{constructor(...e){super(...e),this.initVPS=null}parsePES(e,t,s,i){const r=this.parseNALu(e,s.data,i);let n=this.VideoSample,o,c=!1;s.data=null,n&&r.length&&!e.audFound&&(this.pushAccessUnit(n,e),n=this.VideoSample=this.createVideoSample(!1,s.pts,s.dts)),r.forEach(l=>{var h,d;switch(l.type){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:case 8:case 9:n||(n=this.VideoSample=this.createVideoSample(!1,s.pts,s.dts)),n.frame=!0,o=!0;break;case 16:case 17:case 18:case 21:if(o=!0,c){var u;(u=n)!=null&&u.frame&&!n.key&&(this.pushAccessUnit(n,e),n=this.VideoSample=null)}n||(n=this.VideoSample=this.createVideoSample(!0,s.pts,s.dts)),n.key=!0,n.frame=!0;break;case 19:case 20:o=!0,(h=n)!=null&&h.frame&&!n.key&&(this.pushAccessUnit(n,e),n=this.VideoSample=null),n||(n=this.VideoSample=this.createVideoSample(!0,s.pts,s.dts)),n.key=!0,n.frame=!0;break;case 39:o=!0,Ri(l.data,2,s.pts,t.samples);break;case 32:o=!0,e.vps||(typeof e.params!="object"&&(e.params={}),e.params=ie(e.params,this.readVPS(l.data)),this.initVPS=l.data),e.vps=[l.data];break;case 33:if(o=!0,c=!0,e.vps!==void 0&&e.vps[0]!==this.initVPS&&e.sps!==void 0&&!this.matchSPS(e.sps[0],l.data)&&(this.initVPS=e.vps[0],e.sps=e.pps=void 0),!e.sps){const f=this.readSPS(l.data);e.width=f.width,e.height=f.height,e.pixelRatio=f.pixelRatio,e.codec=f.codecString,e.sps=[],typeof e.params!="object"&&(e.params={});for(const g in f.params)e.params[g]=f.params[g]}this.pushParameterSet(e.sps,l.data,e.vps),n||(n=this.VideoSample=this.createVideoSample(!0,s.pts,s.dts)),n.key=!0;break;case 34:if(o=!0,typeof e.params=="object"){if(!e.pps){e.pps=[];const f=this.readPPS(l.data);for(const g in f)e.params[g]=f[g]}this.pushParameterSet(e.pps,l.data,e.vps)}break;case 35:o=!0,e.audFound=!0,(d=n)!=null&&d.frame&&(this.pushAccessUnit(n,e),n=null),n||(n=this.VideoSample=this.createVideoSample(!1,s.pts,s.dts));break;default:o=!1;break}n&&o&&n.units.push(l)}),i&&n&&(this.pushAccessUnit(n,e),this.VideoSample=null)}pushParameterSet(e,t,s){(s&&s[0]===this.initVPS||!s&&!e.length)&&e.push(t)}getNALuType(e,t){return(e[t]&126)>>>1}ebsp2rbsp(e){const t=new Uint8Array(e.byteLength);let s=0;for(let i=0;i<e.byteLength;i++)i>=2&&e[i]===3&&e[i-1]===0&&e[i-2]===0||(t[s]=e[i],s++);return new Uint8Array(t.buffer,0,s)}pushAccessUnit(e,t){super.pushAccessUnit(e,t),this.initVPS&&(this.initVPS=null)}readVPS(e){const t=new Ft(e);t.readUByte(),t.readUByte(),t.readBits(4),t.skipBits(2),t.readBits(6);const s=t.readBits(3),i=t.readBoolean();return{numTemporalLayers:s+1,temporalIdNested:i}}readSPS(e){const t=new Ft(this.ebsp2rbsp(e));t.readUByte(),t.readUByte(),t.readBits(4);const s=t.readBits(3);t.readBoolean();const i=t.readBits(2),r=t.readBoolean(),n=t.readBits(5),o=t.readUByte(),c=t.readUByte(),l=t.readUByte(),h=t.readUByte(),d=t.readUByte(),u=t.readUByte(),f=t.readUByte(),g=t.readUByte(),y=t.readUByte(),p=t.readUByte(),E=t.readUByte(),T=[],S=[];for(let J=0;J<s;J++)T.push(t.readBoolean()),S.push(t.readBoolean());if(s>0)for(let J=s;J<8;J++)t.readBits(2);for(let J=0;J<s;J++)T[J]&&(t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte()),S[J]&&t.readUByte();t.readUEG();const v=t.readUEG();v==3&&t.skipBits(1);const A=t.readUEG(),D=t.readUEG(),x=t.readBoolean();let b=0,_=0,I=0,P=0;x&&(b+=t.readUEG(),_+=t.readUEG(),I+=t.readUEG(),P+=t.readUEG());const F=t.readUEG(),U=t.readUEG(),H=t.readUEG(),$=t.readBoolean();for(let J=$?0:s;J<=s;J++)t.skipUEG(),t.skipUEG(),t.skipUEG();if(t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG(),t.readBoolean()&&t.readBoolean())for(let Ee=0;Ee<4;Ee++)for(let De=0;De<(Ee===3?2:6);De++)if(!t.readBoolean())t.readUEG();else{const Oe=Math.min(64,1<<4+(Ee<<1));Ee>1&&t.readEG();for(let mt=0;mt<Oe;mt++)t.readEG()}t.readBoolean(),t.readBoolean(),t.readBoolean()&&(t.readUByte(),t.skipUEG(),t.skipUEG(),t.readBoolean());const N=t.readUEG();let K=0;for(let J=0;J<N;J++){let Ee=!1;if(J!==0&&(Ee=t.readBoolean()),Ee){J===N&&t.readUEG(),t.readBoolean(),t.readUEG();let De=0;for(let ot=0;ot<=K;ot++){const Oe=t.readBoolean();let mt=!1;Oe||(mt=t.readBoolean()),(Oe||mt)&&De++}K=De}else{const De=t.readUEG(),ot=t.readUEG();K=De+ot;for(let Oe=0;Oe<De;Oe++)t.readUEG(),t.readBoolean();for(let Oe=0;Oe<ot;Oe++)t.readUEG(),t.readBoolean()}}if(t.readBoolean()){const J=t.readUEG();for(let Ee=0;Ee<J;Ee++){for(let De=0;De<H+4;De++)t.readBits(1);t.readBits(1)}}let w=0,O=1,j=1,ee=!0,X=1,Z=0;t.readBoolean(),t.readBoolean();let ye=!1;if(t.readBoolean()){if(t.readBoolean()){const lt=t.readUByte(),ji=[1,12,10,16,40,24,20,32,80,18,15,64,160,4,3,2],Yt=[1,11,11,11,33,11,11,11,33,11,11,33,99,3,2,1];lt>0&<<16?(O=ji[lt-1],j=Yt[lt-1]):lt===255&&(O=t.readBits(16),j=t.readBits(16))}if(t.readBoolean()&&t.readBoolean(),t.readBoolean()&&(t.readBits(3),t.readBoolean(),t.readBoolean()&&(t.readUByte(),t.readUByte(),t.readUByte())),t.readBoolean()&&(t.readUEG(),t.readUEG()),t.readBoolean(),t.readBoolean(),t.readBoolean(),ye=t.readBoolean(),ye&&(t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG()),t.readBoolean()&&(X=t.readBits(32),Z=t.readBits(32),t.readBoolean()&&t.readUEG(),t.readBoolean())){const Yt=t.readBoolean(),Xi=t.readBoolean();let Ct=!1;(Yt||Xi)&&(Ct=t.readBoolean(),Ct&&(t.readUByte(),t.readBits(5),t.readBoolean(),t.readBits(5)),t.readBits(4),t.readBits(4),Ct&&t.readBits(4),t.readBits(5),t.readBits(5),t.readBits(5));for(let zi=0;zi<=s;zi++){ee=t.readBoolean();const Ja=ee||t.readBoolean();let Qi=!1;Ja?t.readEG():Qi=t.readBoolean();const Zi=Qi?1:t.readUEG()+1;if(Yt)for(let Pt=0;Pt<Zi;Pt++)t.readUEG(),t.readUEG(),Ct&&(t.readUEG(),t.readUEG()),t.skipBits(1);if(Xi)for(let Pt=0;Pt<Zi;Pt++)t.readUEG(),t.readUEG(),Ct&&(t.readUEG(),t.readUEG()),t.skipBits(1)}}t.readBoolean()&&(t.readBoolean(),t.readBoolean(),t.readBoolean(),w=t.readUEG())}let _e=A,Be=D;if(x){let J=1,Ee=1;v===1?J=Ee=2:v==2&&(J=2),_e=A-J*_-J*b,Be=D-Ee*P-Ee*I}const at=i?["A","B","C"][i]:"",Za=o<<24|c<<16|l<<8|h;let ks=0;for(let J=0;J<32;J++)ks=(ks|(Za>>J&1)<<31-J)>>>0;let ws=ks.toString(16);return n===1&&ws==="2"&&(ws="6"),{codecString:`hvc1.${at}${n}.${ws}.${r?"H":"L"}${E}.B0`,params:{general_tier_flag:r,general_profile_idc:n,general_profile_space:i,general_profile_compatibility_flags:[o,c,l,h],general_constraint_indicator_flags:[d,u,f,g,y,p],general_level_idc:E,bit_depth:F+8,bit_depth_luma_minus8:F,bit_depth_chroma_minus8:U,min_spatial_segmentation_idc:w,chroma_format_idc:v,frame_rate:{fixed:ee,fps:Z/X}},width:_e,height:Be,pixelRatio:[O,j]}}readPPS(e){const t=new Ft(this.ebsp2rbsp(e));t.readUByte(),t.readUByte(),t.skipUEG(),t.skipUEG(),t.skipBits(2),t.skipBits(3),t.skipBits(2),t.skipUEG(),t.skipUEG(),t.skipEG(),t.skipBits(2),t.readBoolean()&&t.skipUEG(),t.skipEG(),t.skipEG(),t.skipBits(4);const i=t.readBoolean(),r=t.readBoolean();let n=1;return r&&i?n=0:r?n=3:i&&(n=2),{parallelismType:n}}matchSPS(e,t){return String.fromCharCode.apply(null,e).substr(3)===String.fromCharCode.apply(null,t).substr(3)}}const ue=188;class tt{constructor(e,t,s,i){this.logger=void 0,this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.sampleAes=null,this.pmtParsed=!1,this.audioCodec=void 0,this.videoCodec=void 0,this._pmtId=-1,this._videoTrack=void 0,this._audioTrack=void 0,this._id3Track=void 0,this._txtTrack=void 0,this.aacOverFlow=null,this.remainderData=null,this.videoParser=void 0,this.observer=e,this.config=t,this.typeSupported=s,this.logger=i,this.videoParser=null}static probe(e,t){const s=tt.syncOffset(e);return s>0&&t.warn(`MPEG2-TS detected but first sync word found @ offset ${s}`),s!==-1}static syncOffset(e){const t=e.length;let s=Math.min(ue*5,t-ue)+1,i=0;for(;i<s;){let r=!1,n=-1,o=0;for(let c=i;c<t;c+=ue)if(e[c]===71&&(t-c===ue||e[c+ue]===71)){if(o++,n===-1&&(n=c,n!==0&&(s=Math.min(n+ue*99,e.length-ue)+1)),r||(r=fi(e,c)===0),r&&o>1&&(n===0&&o>2||c+ue>s))return n}else{if(o)return-1;break}i++}return-1}static createTrack(e,t){return{container:e==="video"||e==="audio"?"video/mp2t":void 0,type:e,id:In[e],pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0,duration:e==="audio"?t:void 0}}resetInitSegment(e,t,s,i){this.pmtParsed=!1,this._pmtId=-1,this._videoTrack=tt.createTrack("video"),this._videoTrack.duration=i,this._audioTrack=tt.createTrack("audio",i),this._id3Track=tt.createTrack("id3"),this._txtTrack=tt.createTrack("text"),this._audioTrack.segmentCodec="aac",this.videoParser=null,this.aacOverFlow=null,this.remainderData=null,this.audioCodec=t,this.videoCodec=s}resetTimeStamp(){}resetContiguity(){const{_audioTrack:e,_videoTrack:t,_id3Track:s}=this;e&&(e.pesData=null),t&&(t.pesData=null),s&&(s.pesData=null),this.aacOverFlow=null,this.remainderData=null}demux(e,t,s=!1,i=!1){s||(this.sampleAes=null);let r;const n=this._videoTrack,o=this._audioTrack,c=this._id3Track,l=this._txtTrack;let h=n.pid,d=n.pesData,u=o.pid,f=c.pid,g=o.pesData,y=c.pesData,p=null,E=this.pmtParsed,T=this._pmtId,S=e.length;if(this.remainderData&&(e=ke(this.remainderData,e),S=e.length,this.remainderData=null),S<ue&&!i)return this.remainderData=e,{audioTrack:o,videoTrack:n,id3Track:c,textTrack:l};const v=Math.max(0,tt.syncOffset(e));S-=(S-v)%ue,S<e.byteLength&&!i&&(this.remainderData=new Uint8Array(e.buffer,S,e.buffer.byteLength-S));let A=0;for(let x=v;x<S;x+=ue)if(e[x]===71){const b=!!(e[x+1]&64),_=fi(e,x),I=(e[x+3]&48)>>4;let P;if(I>1){if(P=x+5+e[x+4],P===x+ue)continue}else P=x+4;switch(_){case h:b&&(d&&(r=Tt(d,this.logger))&&(this.readyVideoParser(n.segmentCodec),this.videoParser!==null&&this.videoParser.parsePES(n,l,r,!1)),d={data:[],size:0}),d&&(d.data.push(e.subarray(P,x+ue)),d.size+=x+ue-P);break;case u:if(b){if(g&&(r=Tt(g,this.logger)))switch(o.segmentCodec){case"aac":this.parseAACPES(o,r);break;case"mp3":this.parseMPEGPES(o,r);break;case"ac3":this.parseAC3PES(o,r);break}g={data:[],size:0}}g&&(g.data.push(e.subarray(P,x+ue)),g.size+=x+ue-P);break;case f:b&&(y&&(r=Tt(y,this.logger))&&this.parseID3PES(c,r),y={data:[],size:0}),y&&(y.data.push(e.subarray(P,x+ue)),y.size+=x+ue-P);break;case 0:b&&(P+=e[P]+1),T=this._pmtId=Ac(e,P);break;case T:{b&&(P+=e[P]+1);const F=Ic(e,P,this.typeSupported,s,this.observer,this.logger);h=F.videoPid,h>0&&(n.pid=h,n.segmentCodec=F.segmentVideoCodec),u=F.audioPid,u>0&&(o.pid=u,o.segmentCodec=F.segmentAudioCodec),f=F.id3Pid,f>0&&(c.pid=f),p!==null&&!E&&(this.logger.warn(`MPEG-TS PMT found at ${x} after unknown PID '${p}'. Backtracking to sync byte @${v} to parse all TS packets.`),p=null,x=v-188),E=this.pmtParsed=!0;break}case 17:case 8191:break;default:p=_;break}}else A++;A>0&&gi(this.observer,new Error(`Found ${A} TS packet/s that do not start with 0x47`),void 0,this.logger),n.pesData=d,o.pesData=g,c.pesData=y;const D={audioTrack:o,videoTrack:n,id3Track:c,textTrack:l};return i&&this.extractRemainingSamples(D),D}flush(){const{remainderData:e}=this;this.remainderData=null;let t;return e?t=this.demux(e,-1,!1,!0):t={videoTrack:this._videoTrack,audioTrack:this._audioTrack,id3Track:this._id3Track,textTrack:this._txtTrack},this.extractRemainingSamples(t),this.sampleAes?this.decrypt(t,this.sampleAes):t}extractRemainingSamples(e){const{audioTrack:t,videoTrack:s,id3Track:i,textTrack:r}=e,n=s.pesData,o=t.pesData,c=i.pesData;let l;if(n&&(l=Tt(n,this.logger))?(this.readyVideoParser(s.segmentCodec),this.videoParser!==null&&(this.videoParser.parsePES(s,r,l,!0),s.pesData=null)):s.pesData=n,o&&(l=Tt(o,this.logger))){switch(t.segmentCodec){case"aac":this.parseAACPES(t,l);break;case"mp3":this.parseMPEGPES(t,l);break;case"ac3":this.parseAC3PES(t,l);break}t.pesData=null}else o!=null&&o.size&&this.logger.log("last AAC PES packet truncated,might overlap between fragments"),t.pesData=o;c&&(l=Tt(c,this.logger))?(this.parseID3PES(i,l),i.pesData=null):i.pesData=c}demuxSampleAes(e,t,s){const i=this.demux(e,s,!0,!this.config.progressive),r=this.sampleAes=new Sc(this.observer,this.config,t);return this.decrypt(i,r)}readyVideoParser(e){this.videoParser===null&&(e==="avc"?this.videoParser=new vc:e==="hevc"&&(this.videoParser=new xc))}decrypt(e,t){return new Promise(s=>{const{audioTrack:i,videoTrack:r}=e;i.samples&&i.segmentCodec==="aac"?t.decryptAacSamples(i.samples,0,()=>{r.samples?t.decryptAvcSamples(r.samples,0,0,()=>{s(e)}):s(e)}):r.samples&&t.decryptAvcSamples(r.samples,0,0,()=>{s(e)})})}destroy(){this.observer&&this.observer.removeAllListeners(),this.config=this.logger=this.observer=null,this.aacOverFlow=this.videoParser=this.remainderData=this.sampleAes=null,this._videoTrack=this._audioTrack=this._id3Track=this._txtTrack=void 0}parseAACPES(e,t){let s=0;const i=this.aacOverFlow;let r=t.data;if(i){this.aacOverFlow=null;const d=i.missing,u=i.sample.unit.byteLength;if(d===-1)r=ke(i.sample.unit,r);else{const f=u-d;i.sample.unit.set(r.subarray(0,d),f),e.samples.push(i.sample),s=i.missing}}let n,o;for(n=s,o=r.length;n<o-1&&!bs(r,n);n++);if(n!==s){let d;const u=n<o-1;if(u?d=`AAC PES did not start with ADTS header,offset:${n}`:d="No ADTS header found in AAC PES",gi(this.observer,new Error(d),u,this.logger),!u)return}oa(e,this.observer,r,n,this.audioCodec);let c;if(t.pts!==void 0)c=t.pts;else if(i){const d=la(e.samplerate);c=i.sample.pts+d}else{this.logger.warn("[tsdemuxer]: AAC PES unknown PTS");return}let l=0,h;for(;n<o;)if(h=ca(e,r,n,c,l),n+=h.length,h.missing){this.aacOverFlow=h;break}else for(l++;n<o-1&&!bs(r,n);n++);}parseMPEGPES(e,t){const s=t.data,i=s.length;let r=0,n=0;const o=t.pts;if(o===void 0){this.logger.warn("[tsdemuxer]: MPEG PES unknown PTS");return}for(;n<i;)if(ga(s,n)){const c=ua(e,s,n,o,r);if(c)n+=c.length,r++;else break}else n++}parseAC3PES(e,t){{const s=t.data,i=t.pts;if(i===void 0){this.logger.warn("[tsdemuxer]: AC3 PES unknown PTS");return}const r=s.length;let n=0,o=0,c;for(;o<r&&(c=ya(e,s,o,i,n++))>0;)o+=c}}parseID3PES(e,t){if(t.pts===void 0){this.logger.warn("[tsdemuxer]: ID3 PES unknown PTS");return}const s=ie({},t,{type:this._videoTrack?Re.emsg:Re.audioId3,duration:Number.POSITIVE_INFINITY});e.samples.push(s)}}function fi(a,e){return((a[e+1]&31)<<8)+a[e+2]}function Ac(a,e){return(a[e+10]&31)<<8|a[e+11]}function Ic(a,e,t,s,i,r){const n={audioPid:-1,videoPid:-1,id3Pid:-1,segmentVideoCodec:"avc",segmentAudioCodec:"aac"},o=(a[e+1]&15)<<8|a[e+2],c=e+3+o-4,l=(a[e+10]&15)<<8|a[e+11];for(e+=12+l;e<c;){const h=fi(a,e),d=(a[e+3]&15)<<8|a[e+4];switch(a[e]){case 207:if(!s){Vs("ADTS AAC",r);break}case 15:n.audioPid===-1&&(n.audioPid=h);break;case 21:n.id3Pid===-1&&(n.id3Pid=h);break;case 219:if(!s){Vs("H.264",r);break}case 27:n.videoPid===-1&&(n.videoPid=h);break;case 3:case 4:!t.mpeg&&!t.mp3?r.log("MPEG audio found, not supported in this browser"):n.audioPid===-1&&(n.audioPid=h,n.segmentAudioCodec="mp3");break;case 193:if(!s){Vs("AC-3",r);break}case 129:t.ac3?n.audioPid===-1&&(n.audioPid=h,n.segmentAudioCodec="ac3"):r.log("AC-3 audio found, not supported in this browser");break;case 6:if(n.audioPid===-1&&d>0){let u=e+5,f=d;for(;f>2;){switch(a[u]){case 106:t.ac3!==!0?r.log("AC-3 audio found, not supported in this browser for now"):(n.audioPid=h,n.segmentAudioCodec="ac3");break}const y=a[u+1]+2;u+=y,f-=y}}break;case 194:case 135:return gi(i,new Error("Unsupported EC-3 in M2TS found"),void 0,r),n;case 36:n.videoPid===-1&&(n.videoPid=h,n.segmentVideoCodec="hevc",r.log("HEVC in M2TS found"));break}e+=d+5}return n}function gi(a,e,t,s){s.warn(`parsing error: ${e.message}`),a.emit(m.ERROR,m.ERROR,{type:V.MEDIA_ERROR,details:R.FRAG_PARSING_ERROR,fatal:!1,levelRetry:t,error:e,reason:e.message})}function Vs(a,e){e.log(`${a} with AES-128-CBC encryption found in unencrypted stream`)}function Tt(a,e){let t=0,s,i,r,n,o;const c=a.data;if(!a||a.size===0)return null;for(;c[0].length<19&&c.length>1;)c[0]=ke(c[0],c[1]),c.splice(1,1);if(s=c[0],(s[0]<<16)+(s[1]<<8)+s[2]===1){if(i=(s[4]<<8)+s[5],i&&i>a.size-6)return null;const h=s[7];h&192&&(n=(s[9]&14)*536870912+(s[10]&255)*4194304+(s[11]&254)*16384+(s[12]&255)*128+(s[13]&254)/2,h&64?(o=(s[14]&14)*536870912+(s[15]&255)*4194304+(s[16]&254)*16384+(s[17]&255)*128+(s[18]&254)/2,n-o>60*9e4&&(e.warn(`${Math.round((n-o)/9e4)}s delta between PTS and DTS, align them`),n=o)):o=n),r=s[8];let d=r+9;if(a.size<=d)return null;a.size-=d;const u=new Uint8Array(a.size);for(let f=0,g=c.length;f<g;f++){s=c[f];let y=s.byteLength;if(d)if(d>y){d-=y;continue}else s=s.subarray(d),y-=d,d=0;u.set(s,t),t+=y}return i&&(i-=r+3),{data:u,pts:n,dts:o,len:i}}return null}class Lc{static getSilentFrame(e,t){switch(e){case"mp4a.40.2":if(t===1)return new Uint8Array([0,200,0,128,35,128]);if(t===2)return new Uint8Array([33,0,73,144,2,25,0,35,128]);if(t===3)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,142]);if(t===4)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,128,44,128,8,2,56]);if(t===5)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(t===6)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]);break;default:if(t===1)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(t===2)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(t===3)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]);break}}}const Ze=Math.pow(2,32)-1;class L{static init(){L.types={avc1:[],avcC:[],hvc1:[],hvcC:[],btrt:[],dinf:[],dref:[],esds:[],ftyp:[],hdlr:[],mdat:[],mdhd:[],mdia:[],mfhd:[],minf:[],moof:[],moov:[],mp4a:[],".mp3":[],dac3:[],"ac-3":[],mvex:[],mvhd:[],pasp:[],sdtp:[],stbl:[],stco:[],stsc:[],stsd:[],stsz:[],stts:[],tfdt:[],tfhd:[],traf:[],trak:[],trun:[],trex:[],tkhd:[],vmhd:[],smhd:[]};let e;for(e in L.types)L.types.hasOwnProperty(e)&&(L.types[e]=[e.charCodeAt(0),e.charCodeAt(1),e.charCodeAt(2),e.charCodeAt(3)]);const t=new Uint8Array([0,0,0,0,0,0,0,0,118,105,100,101,0,0,0,0,0,0,0,0,0,0,0,0,86,105,100,101,111,72,97,110,100,108,101,114,0]),s=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]);L.HDLR_TYPES={video:t,audio:s};const i=new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,12,117,114,108,32,0,0,0,1]),r=new Uint8Array([0,0,0,0,0,0,0,0]);L.STTS=L.STSC=L.STCO=r,L.STSZ=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),L.VMHD=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0]),L.SMHD=new Uint8Array([0,0,0,0,0,0,0,0]),L.STSD=new Uint8Array([0,0,0,0,0,0,0,1]);const n=new Uint8Array([105,115,111,109]),o=new Uint8Array([97,118,99,49]),c=new Uint8Array([0,0,0,1]);L.FTYP=L.box(L.types.ftyp,n,c,n,o),L.DINF=L.box(L.types.dinf,L.box(L.types.dref,i))}static box(e,...t){let s=8,i=t.length;const r=i;for(;i--;)s+=t[i].byteLength;const n=new Uint8Array(s);for(n[0]=s>>24&255,n[1]=s>>16&255,n[2]=s>>8&255,n[3]=s&255,n.set(e,4),i=0,s=8;i<r;i++)n.set(t[i],s),s+=t[i].byteLength;return n}static hdlr(e){return L.box(L.types.hdlr,L.HDLR_TYPES[e])}static mdat(e){return L.box(L.types.mdat,e)}static mdhd(e,t){t*=e;const s=Math.floor(t/(Ze+1)),i=Math.floor(t%(Ze+1));return L.box(L.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,e&255,s>>24,s>>16&255,s>>8&255,s&255,i>>24,i>>16&255,i>>8&255,i&255,85,196,0,0]))}static mdia(e){return L.box(L.types.mdia,L.mdhd(e.timescale||0,e.duration||0),L.hdlr(e.type),L.minf(e))}static mfhd(e){return L.box(L.types.mfhd,new Uint8Array([0,0,0,0,e>>24,e>>16&255,e>>8&255,e&255]))}static minf(e){return e.type==="audio"?L.box(L.types.minf,L.box(L.types.smhd,L.SMHD),L.DINF,L.stbl(e)):L.box(L.types.minf,L.box(L.types.vmhd,L.VMHD),L.DINF,L.stbl(e))}static moof(e,t,s){return L.box(L.types.moof,L.mfhd(e),L.traf(s,t))}static moov(e){let t=e.length;const s=[];for(;t--;)s[t]=L.trak(e[t]);return L.box.apply(null,[L.types.moov,L.mvhd(e[0].timescale||0,e[0].duration||0)].concat(s).concat(L.mvex(e)))}static mvex(e){let t=e.length;const s=[];for(;t--;)s[t]=L.trex(e[t]);return L.box.apply(null,[L.types.mvex,...s])}static mvhd(e,t){t*=e;const s=Math.floor(t/(Ze+1)),i=Math.floor(t%(Ze+1)),r=new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,e>>24&255,e>>16&255,e>>8&255,e&255,s>>24,s>>16&255,s>>8&255,s&255,i>>24,i>>16&255,i>>8&255,i&255,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 L.box(L.types.mvhd,r)}static sdtp(e){const t=e.samples||[],s=new Uint8Array(4+t.length);let i,r;for(i=0;i<t.length;i++)r=t[i].flags,s[i+4]=r.dependsOn<<4|r.isDependedOn<<2|r.hasRedundancy;return L.box(L.types.sdtp,s)}static stbl(e){return L.box(L.types.stbl,L.stsd(e),L.box(L.types.stts,L.STTS),L.box(L.types.stsc,L.STSC),L.box(L.types.stsz,L.STSZ),L.box(L.types.stco,L.STCO))}static avc1(e){let t=[],s=[],i,r,n;for(i=0;i<e.sps.length;i++)r=e.sps[i],n=r.byteLength,t.push(n>>>8&255),t.push(n&255),t=t.concat(Array.prototype.slice.call(r));for(i=0;i<e.pps.length;i++)r=e.pps[i],n=r.byteLength,s.push(n>>>8&255),s.push(n&255),s=s.concat(Array.prototype.slice.call(r));const o=L.box(L.types.avcC,new Uint8Array([1,t[3],t[4],t[5],255,224|e.sps.length].concat(t).concat([e.pps.length]).concat(s))),c=e.width,l=e.height,h=e.pixelRatio[0],d=e.pixelRatio[1];return L.box(L.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,c>>8&255,c&255,l>>8&255,l&255,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,L.box(L.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),L.box(L.types.pasp,new Uint8Array([h>>24,h>>16&255,h>>8&255,h&255,d>>24,d>>16&255,d>>8&255,d&255])))}static esds(e){const t=e.config;return new Uint8Array([0,0,0,0,3,25,0,1,0,4,17,64,21,0,0,0,0,0,0,0,0,0,0,0,5,2,...t,6,1,2])}static audioStsd(e){const t=e.samplerate||0;return new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,e.channelCount||0,0,16,0,0,0,0,t>>8&255,t&255,0,0])}static mp4a(e){return L.box(L.types.mp4a,L.audioStsd(e),L.box(L.types.esds,L.esds(e)))}static mp3(e){return L.box(L.types[".mp3"],L.audioStsd(e))}static ac3(e){return L.box(L.types["ac-3"],L.audioStsd(e),L.box(L.types.dac3,e.config))}static stsd(e){const{segmentCodec:t}=e;if(e.type==="audio"){if(t==="aac")return L.box(L.types.stsd,L.STSD,L.mp4a(e));if(t==="ac3"&&e.config)return L.box(L.types.stsd,L.STSD,L.ac3(e));if(t==="mp3"&&e.codec==="mp3")return L.box(L.types.stsd,L.STSD,L.mp3(e))}else if(e.pps&&e.sps){if(t==="avc")return L.box(L.types.stsd,L.STSD,L.avc1(e));if(t==="hevc"&&e.vps)return L.box(L.types.stsd,L.STSD,L.hvc1(e))}else throw new Error("video track missing pps or sps");throw new Error(`unsupported ${e.type} segment codec (${t}/${e.codec})`)}static tkhd(e){const t=e.id,s=(e.duration||0)*(e.timescale||0),i=e.width||0,r=e.height||0,n=Math.floor(s/(Ze+1)),o=Math.floor(s%(Ze+1));return L.box(L.types.tkhd,new Uint8Array([1,0,0,7,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,t>>24&255,t>>16&255,t>>8&255,t&255,0,0,0,0,n>>24,n>>16&255,n>>8&255,n&255,o>>24,o>>16&255,o>>8&255,o&255,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,i>>8&255,i&255,0,0,r>>8&255,r&255,0,0]))}static traf(e,t){const s=L.sdtp(e),i=e.id,r=Math.floor(t/(Ze+1)),n=Math.floor(t%(Ze+1));return L.box(L.types.traf,L.box(L.types.tfhd,new Uint8Array([0,0,0,0,i>>24,i>>16&255,i>>8&255,i&255])),L.box(L.types.tfdt,new Uint8Array([1,0,0,0,r>>24,r>>16&255,r>>8&255,r&255,n>>24,n>>16&255,n>>8&255,n&255])),L.trun(e,s.length+16+20+8+16+8+8),s)}static trak(e){return e.duration=e.duration||4294967295,L.box(L.types.trak,L.tkhd(e),L.mdia(e))}static trex(e){const t=e.id;return L.box(L.types.trex,new Uint8Array([0,0,0,0,t>>24,t>>16&255,t>>8&255,t&255,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,1]))}static trun(e,t){const s=e.samples||[],i=s.length,r=12+16*i,n=new Uint8Array(r);let o,c,l,h,d,u;for(t+=8+r,n.set([e.type==="video"?1:0,0,15,1,i>>>24&255,i>>>16&255,i>>>8&255,i&255,t>>>24&255,t>>>16&255,t>>>8&255,t&255],0),o=0;o<i;o++)c=s[o],l=c.duration,h=c.size,d=c.flags,u=c.cts,n.set([l>>>24&255,l>>>16&255,l>>>8&255,l&255,h>>>24&255,h>>>16&255,h>>>8&255,h&255,d.isLeading<<2|d.dependsOn,d.isDependedOn<<6|d.hasRedundancy<<4|d.paddingValue<<1|d.isNonSync,d.degradPrio&61440,d.degradPrio&15,u>>>24&255,u>>>16&255,u>>>8&255,u&255],12+16*o);return L.box(L.types.trun,n)}static initSegment(e){L.types||L.init();const t=L.moov(e);return ke(L.FTYP,t)}static hvc1(e){const t=e.params,s=[e.vps,e.sps,e.pps],i=4,r=new Uint8Array([1,t.general_profile_space<<6|(t.general_tier_flag?32:0)|t.general_profile_idc,t.general_profile_compatibility_flags[0],t.general_profile_compatibility_flags[1],t.general_profile_compatibility_flags[2],t.general_profile_compatibility_flags[3],t.general_constraint_indicator_flags[0],t.general_constraint_indicator_flags[1],t.general_constraint_indicator_flags[2],t.general_constraint_indicator_flags[3],t.general_constraint_indicator_flags[4],t.general_constraint_indicator_flags[5],t.general_level_idc,240|t.min_spatial_segmentation_idc>>8,255&t.min_spatial_segmentation_idc,252|t.parallelismType,252|t.chroma_format_idc,248|t.bit_depth_luma_minus8,248|t.bit_depth_chroma_minus8,0,parseInt(t.frame_rate.fps),i-1|t.temporal_id_nested<<2|t.num_temporal_layers<<3|(t.frame_rate.fixed?64:0),s.length]);let n=r.length;for(let g=0;g<s.length;g+=1){n+=3;for(let y=0;y<s[g].length;y+=1)n+=2+s[g][y].length}const o=new Uint8Array(n);o.set(r,0),n=r.length;const c=s.length-1;for(let g=0;g<s.length;g+=1){o.set(new Uint8Array([32+g|(g===c?128:0),0,s[g].length]),n),n+=3;for(let y=0;y<s[g].length;y+=1)o.set(new Uint8Array([s[g][y].length>>8,s[g][y].length&255]),n),n+=2,o.set(s[g][y],n),n+=s[g][y].length}const l=L.box(L.types.hvcC,o),h=e.width,d=e.height,u=e.pixelRatio[0],f=e.pixelRatio[1];return L.box(L.types.hvc1,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,h>>8&255,h&255,d>>8&255,d&255,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]),l,L.box(L.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),L.box(L.types.pasp,new Uint8Array([u>>24,u>>16&255,u>>8&255,u&255,f>>24,f>>16&255,f>>8&255,f&255])))}}L.types=void 0;L.HDLR_TYPES=void 0;L.STTS=void 0;L.STSC=void 0;L.STCO=void 0;L.STSZ=void 0;L.VMHD=void 0;L.SMHD=void 0;L.STSD=void 0;L.FTYP=void 0;L.DINF=void 0;const Ta=9e4;function Gi(a,e,t=1,s=!1){const i=a*e*t;return s?Math.round(i):i}function Rc(a,e,t=1,s=!1){return Gi(a,e,1/t,s)}function kt(a,e=!1){return Gi(a,1e3,1/Ta,e)}function bc(a,e=1){return Gi(a,Ta,1/e)}function Kr(a){const{baseTime:e,timescale:t,trackId:s}=a;return`${e/t} (${e}/${t}) trackId: ${s}`}const _c=10*1e3,Dc=1024,Cc=1152,Pc=1536;let St=null,Hs=null;function Vr(a,e,t,s){return{duration:e,size:t,cts:s,flags:{isLeading:0,isDependedOn:0,hasRedundancy:0,degradPrio:0,dependsOn:a?2:1,isNonSync:a?0:1}}}class us extends we{constructor(e,t,s,i){if(super("mp4-remuxer",i),this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.ISGenerated=!1,this._initPTS=null,this._initDTS=null,this.nextVideoTs=null,this.nextAudioTs=null,this.videoSampleDuration=null,this.isAudioContiguous=!1,this.isVideoContiguous=!1,this.videoTrackConfig=void 0,this.observer=e,this.config=t,this.typeSupported=s,this.ISGenerated=!1,St===null){const n=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);St=n?parseInt(n[1]):0}if(Hs===null){const r=navigator.userAgent.match(/Safari\/(\d+)/i);Hs=r?parseInt(r[1]):0}}destroy(){this.config=this.videoTrackConfig=this._initPTS=this._initDTS=null}resetTimeStamp(e){const t=this._initPTS;(!t||!e||e.trackId!==t.trackId||e.baseTime!==t.baseTime||e.timescale!==t.timescale)&&this.log(`Reset initPTS: ${t&&Kr(t)} > ${e&&Kr(e)}`),this._initPTS=this._initDTS=e}resetNextTimestamp(){this.log("reset next timestamp"),this.isVideoContiguous=!1,this.isAudioContiguous=!1}resetInitSegment(){this.log("ISGenerated flag reset"),this.ISGenerated=!1,this.videoTrackConfig=void 0}getVideoStartPts(e){let t=!1;const s=e[0].pts,i=e.reduce((r,n)=>{let o=n.pts,c=o-r;return c<-4294967296&&(t=!0,o=Le(o,s),c=o-r),c>0?r:o},s);return t&&this.debug("PTS rollover detected"),i}remux(e,t,s,i,r,n,o,c){let l,h,d,u,f,g,y=r,p=r;const E=e.pid>-1,T=t.pid>-1,S=t.samples.length,v=e.samples.length>0,A=o&&S>0||S>1;if((!E||v)&&(!T||A)||this.ISGenerated||o){if(this.ISGenerated){var x,b,_,I;const H=this.videoTrackConfig;(H&&(t.width!==H.width||t.height!==H.height||((x=t.pixelRatio)==null?void 0:x[0])!==((b=H.pixelRatio)==null?void 0:b[0])||((_=t.pixelRatio)==null?void 0:_[1])!==((I=H.pixelRatio)==null?void 0:I[1]))||!H&&A||this.nextAudioTs===null&&v)&&this.resetInitSegment()}this.ISGenerated||(d=this.generateIS(e,t,r,n));const P=this.isVideoContiguous;let F=-1,U;if(A&&(F=kc(t.samples),!P&&this.config.forceKeyFrameOnDiscontinuity))if(g=!0,F>0){this.warn(`Dropped ${F} out of ${S} video samples due to a missing keyframe`);const H=this.getVideoStartPts(t.samples);t.samples=t.samples.slice(F),t.dropped+=F,p+=(t.samples[0].pts-H)/t.inputTimeScale,U=p}else F===-1&&(this.warn(`No keyframe found out of ${S} video samples`),g=!1);if(this.ISGenerated){if(v&&A){const H=this.getVideoStartPts(t.samples),k=(Le(e.samples[0].pts,H)-H)/t.inputTimeScale;y+=Math.max(0,k),p+=Math.max(0,-k)}if(v){if(e.samplerate||(this.warn("regenerate InitSegment as audio detected"),d=this.generateIS(e,t,r,n)),h=this.remuxAudio(e,y,this.isAudioContiguous,n,T||A||c===B.AUDIO?p:void 0),A){const H=h?h.endPTS-h.startPTS:0;t.inputTimeScale||(this.warn("regenerate InitSegment as video detected"),d=this.generateIS(e,t,r,n)),l=this.remuxVideo(t,p,P,H)}}else A&&(l=this.remuxVideo(t,p,P,0));l&&(l.firstKeyFrame=F,l.independent=F!==-1,l.firstKeyFramePTS=U)}}return this.ISGenerated&&this._initPTS&&this._initDTS&&(s.samples.length&&(f=Sa(s,r,this._initPTS,this._initDTS)),i.samples.length&&(u=va(i,r,this._initPTS))),{audio:h,video:l,initSegment:d,independent:g,text:u,id3:f}}computeInitPts(e,t,s,i){const r=Math.round(s*t);let n=Le(e,r);if(n<r+t)for(this.log(`Adjusting PTS for rollover in timeline near ${(r-n)/t} ${i}`);n<r+t;)n+=8589934592;return n-r}generateIS(e,t,s,i){const r=e.samples,n=t.samples,o=this.typeSupported,c={},l=this._initPTS;let h=!l||i,d="audio/mp4",u,f,g,y=-1;if(h&&(u=f=1/0),e.config&&r.length){switch(e.timescale=e.samplerate,e.segmentCodec){case"mp3":o.mpeg?(d="audio/mpeg",e.codec=""):o.mp3&&(e.codec="mp3");break;case"ac3":e.codec="ac-3";break}c.audio={id:"audio",container:d,codec:e.codec,initSegment:e.segmentCodec==="mp3"&&o.mpeg?new Uint8Array(0):L.initSegment([e]),metadata:{channelCount:e.channelCount}},h&&(y=e.id,g=e.inputTimeScale,!l||g!==l.timescale?u=f=this.computeInitPts(r[0].pts,g,s,"audio"):h=!1)}if(t.sps&&t.pps&&n.length){if(t.timescale=t.inputTimeScale,c.video={id:"main",container:"video/mp4",codec:t.codec,initSegment:L.initSegment([t]),metadata:{width:t.width,height:t.height}},h)if(y=t.id,g=t.inputTimeScale,!l||g!==l.timescale){const p=this.getVideoStartPts(n),E=Le(n[0].dts,p),T=this.computeInitPts(E,g,s,"video"),S=this.computeInitPts(p,g,s,"video");f=Math.min(f,T),u=Math.min(u,S)}else h=!1;this.videoTrackConfig={width:t.width,height:t.height,pixelRatio:t.pixelRatio}}if(Object.keys(c).length)return this.ISGenerated=!0,h?(l&&this.warn(`Timestamps at playlist time: ${i?"":"~"}${s} ${u/g} != initPTS: ${l.baseTime/l.timescale} (${l.baseTime}/${l.timescale}) trackId: ${l.trackId}`),this.log(`Found initPTS at playlist time: ${s} offset: ${u/g} (${u}/${g}) trackId: ${y}`),this._initPTS={baseTime:u,timescale:g,trackId:y},this._initDTS={baseTime:f,timescale:g,trackId:y}):u=g=void 0,{tracks:c,initPTS:u,timescale:g,trackId:y}}remuxVideo(e,t,s,i){const r=e.inputTimeScale,n=e.samples,o=[],c=n.length,l=this._initPTS,h=l.baseTime*r/l.timescale;let d=this.nextVideoTs,u=8,f=this.videoSampleDuration,g,y,p=Number.POSITIVE_INFINITY,E=Number.NEGATIVE_INFINITY,T=!1;if(!s||d===null){const w=h+t*r,O=n[0].pts-Le(n[0].dts,n[0].pts);St&&d!==null&&Math.abs(w-O-(d+h))<15e3?s=!0:d=w-O-h}const S=d+h;for(let w=0;w<c;w++){const O=n[w];O.pts=Le(O.pts,S),O.dts=Le(O.dts,S),O.dts<n[w>0?w-1:w].dts&&(T=!0)}T&&n.sort(function(w,O){const j=w.dts-O.dts,ee=w.pts-O.pts;return j||ee}),g=n[0].dts,y=n[n.length-1].dts;const v=y-g,A=v?Math.round(v/(c-1)):f||e.inputTimeScale/30;if(s){const w=g-S,O=w>A,j=w<-1;if((O||j)&&(O?this.warn(`${(e.segmentCodec||"").toUpperCase()}: ${kt(w,!0)} ms (${w}dts) hole between fragments detected at ${t.toFixed(3)}`):this.warn(`${(e.segmentCodec||"").toUpperCase()}: ${kt(-w,!0)} ms (${w}dts) overlapping between fragments detected at ${t.toFixed(3)}`),!j||S>=n[0].pts||St)){g=S;const ee=n[0].pts-w;if(O)n[0].dts=g,n[0].pts=ee;else{let X=!0;for(let Z=0;Z<n.length&&!(n[Z].dts>ee&&X);Z++){const ye=n[Z].pts;if(n[Z].dts-=w,n[Z].pts-=w,Z<n.length-1){const fe=n[Z+1].pts,_e=n[Z].pts,Be=fe<=_e,at=fe<=ye;X=Be==at}}}this.log(`Video: Initial PTS/DTS adjusted: ${kt(ee,!0)}/${kt(g,!0)}, delta: ${kt(w,!0)} ms`)}}g=Math.max(0,g);let D=0,x=0,b=g;for(let w=0;w<c;w++){const O=n[w],j=O.units,ee=j.length;let X=0;for(let Z=0;Z<ee;Z++)X+=j[Z].data.length;x+=X,D+=ee,O.length=X,O.dts<b?(O.dts=b,b+=A/4|0||1):b=O.dts,p=Math.min(O.pts,p),E=Math.max(O.pts,E)}y=n[c-1].dts;const _=x+4*D+8;let I;try{I=new Uint8Array(_)}catch(w){this.observer.emit(m.ERROR,m.ERROR,{type:V.MUX_ERROR,details:R.REMUX_ALLOC_ERROR,fatal:!1,error:w,bytes:_,reason:`fail allocating video mdat ${_}`});return}const P=new DataView(I.buffer);P.setUint32(0,_),I.set(L.types.mdat,4);let F=!1,U=Number.POSITIVE_INFINITY,H=Number.POSITIVE_INFINITY,$=Number.NEGATIVE_INFINITY,k=Number.NEGATIVE_INFINITY;for(let w=0;w<c;w++){const O=n[w],j=O.units;let ee=0;for(let ye=0,fe=j.length;ye<fe;ye++){const _e=j[ye],Be=_e.data,at=_e.data.byteLength;P.setUint32(u,at),u+=4,I.set(Be,u),u+=at,ee+=4+at}let X;if(w<c-1)f=n[w+1].dts-O.dts,X=n[w+1].pts-O.pts;else{const ye=this.config,fe=w>0?O.dts-n[w-1].dts:A;if(X=w>0?O.pts-n[w-1].pts:A,ye.stretchShortVideoTrack&&this.nextAudioTs!==null){const _e=Math.floor(ye.maxBufferHole*r),Be=(i?p+i*r:this.nextAudioTs+h)-O.pts;Be>_e?(f=Be-fe,f<0?f=fe:F=!0,this.log(`It is approximately ${Be/90} ms to the next segment; using duration ${f/90} ms for the last video frame.`)):f=fe}else f=fe}const Z=Math.round(O.pts-O.dts);U=Math.min(U,f),$=Math.max($,f),H=Math.min(H,X),k=Math.max(k,X),o.push(Vr(O.key,f,ee,Z))}if(o.length){if(St){if(St<70){const w=o[0].flags;w.dependsOn=2,w.isNonSync=0}}else if(Hs&&k-H<$-U&&A/$<.025&&o[0].cts===0){this.warn("Found irregular gaps in sample duration. Using PTS instead of DTS to determine MP4 sample duration.");let w=g;for(let O=0,j=o.length;O<j;O++){const ee=w+o[O].duration,X=w+o[O].cts;if(O<j-1){const Z=ee+o[O+1].cts;o[O].duration=Z-X}else o[O].duration=O?o[O-1].duration:A;o[O].cts=0,w=ee}}}f=F||!f?A:f;const G=y+f;this.nextVideoTs=d=G-h,this.videoSampleDuration=f,this.isVideoContiguous=!0;const Y={data1:L.moof(e.sequenceNumber++,g,ie(e,{samples:o})),data2:I,startPTS:(p-h)/r,endPTS:(E+f-h)/r,startDTS:(g-h)/r,endDTS:d/r,type:"video",hasAudio:!1,hasVideo:!0,nb:o.length,dropped:e.dropped};return e.samples=[],e.dropped=0,Y}getSamplesPerFrame(e){switch(e.segmentCodec){case"mp3":return Cc;case"ac3":return Pc;default:return Dc}}remuxAudio(e,t,s,i,r){const n=e.inputTimeScale,o=e.samplerate?e.samplerate:n,c=n/o,l=this.getSamplesPerFrame(e),h=l*c,d=this._initPTS,u=e.segmentCodec==="mp3"&&this.typeSupported.mpeg,f=[],g=r!==void 0;let y=e.samples,p=u?0:8,E=this.nextAudioTs||-1;const T=d.baseTime*n/d.timescale,S=T+t*n;if(this.isAudioContiguous=s=s||y.length&&E>0&&(i&&Math.abs(S-(E+T))<9e3||Math.abs(Le(y[0].pts,S)-(E+T))<20*h),y.forEach(function(k){k.pts=Le(k.pts,S)}),!s||E<0){const k=y.length;if(y=y.filter(G=>G.pts>=0),k!==y.length&&this.warn(`Removed ${y.length-k} of ${k} samples (initPTS ${T} / ${n})`),!y.length)return;r===0?E=0:i&&!g?E=Math.max(0,S-T):E=y[0].pts-T}if(e.segmentCodec==="aac"){const k=this.config.maxAudioFramesDrift;for(let G=0,N=E+T;G<y.length;G++){const K=y[G],Y=K.pts,w=Y-N,O=Math.abs(1e3*w/n);if(w<=-k*h&&g)G===0&&(this.warn(`Audio frame @ ${(Y/n).toFixed(3)}s overlaps marker by ${Math.round(1e3*w/n)} ms.`),this.nextAudioTs=E=Y-T,N=Y);else if(w>=k*h&&O<_c&&g){let j=Math.round(w/h);for(N=Y-j*h;N<0&&j&&h;)j--,N+=h;G===0&&(this.nextAudioTs=E=N-T),this.warn(`Injecting ${j} audio frames @ ${((N-T)/n).toFixed(3)}s due to ${Math.round(1e3*w/n)} ms gap.`);for(let ee=0;ee<j;ee++){let X=Lc.getSilentFrame(e.parsedCodec||e.manifestCodec||e.codec,e.channelCount);X||(this.log("Unable to get silent frame for given audio codec; duplicating last frame instead."),X=K.unit.subarray()),y.splice(G,0,{unit:X,pts:N}),N+=h,G++}}K.pts=N,N+=h}}let v=null,A=null,D,x=0,b=y.length;for(;b--;)x+=y[b].unit.byteLength;for(let k=0,G=y.length;k<G;k++){const N=y[k],K=N.unit;let Y=N.pts;if(A!==null){const O=f[k-1];O.duration=Math.round((Y-A)/c)}else if(s&&e.segmentCodec==="aac"&&(Y=E+T),v=Y,x>0){x+=p;try{D=new Uint8Array(x)}catch(O){this.observer.emit(m.ERROR,m.ERROR,{type:V.MUX_ERROR,details:R.REMUX_ALLOC_ERROR,fatal:!1,error:O,bytes:x,reason:`fail allocating audio mdat ${x}`});return}u||(new DataView(D.buffer).setUint32(0,x),D.set(L.types.mdat,4))}else return;D.set(K,p);const w=K.byteLength;p+=w,f.push(Vr(!0,l,w,0)),A=Y}const _=f.length;if(!_)return;const I=f[f.length-1];E=A-T,this.nextAudioTs=E+c*I.duration;const P=u?new Uint8Array(0):L.moof(e.sequenceNumber++,v/c,ie({},e,{samples:f}));e.samples=[];const F=(v-T)/n,U=this.nextAudioTs/n,$={data1:P,data2:D,startPTS:F,endPTS:U,startDTS:F,endDTS:U,type:"audio",hasAudio:!0,hasVideo:!1,nb:_};return this.isAudioContiguous=!0,$}}function Le(a,e){let t;if(e===null)return a;for(e<a?t=-8589934592:t=8589934592;Math.abs(a-e)>4294967296;)a+=t;return a}function kc(a){for(let e=0;e<a.length;e++)if(a[e].key)return e;return-1}function Sa(a,e,t,s){const i=a.samples.length;if(!i)return;const r=a.inputTimeScale;for(let o=0;o<i;o++){const c=a.samples[o];c.pts=Le(c.pts-t.baseTime*r/t.timescale,e*r)/r,c.dts=Le(c.dts-s.baseTime*r/s.timescale,e*r)/r}const n=a.samples;return a.samples=[],{samples:n}}function va(a,e,t){const s=a.samples.length;if(!s)return;const i=a.inputTimeScale;for(let n=0;n<s;n++){const o=a.samples[n];o.pts=Le(o.pts-t.baseTime*i/t.timescale,e*i)/i}a.samples.sort((n,o)=>n.pts-o.pts);const r=a.samples;return a.samples=[],{samples:r}}class wc extends we{constructor(e,t,s,i){super("passthrough-remuxer",i),this.emitInitSegment=!1,this.audioCodec=void 0,this.videoCodec=void 0,this.initData=void 0,this.initPTS=null,this.initTracks=void 0,this.lastEndTime=null,this.isVideoContiguous=!1}destroy(){}resetTimeStamp(e){this.lastEndTime=null;const t=this.initPTS;t&&e&&t.baseTime===e.baseTime&&t.timescale===e.timescale||(this.initPTS=e)}resetNextTimestamp(){this.isVideoContiguous=!1,this.lastEndTime=null}resetInitSegment(e,t,s,i){this.audioCodec=t,this.videoCodec=s,this.generateInitSegment(e,i),this.emitInitSegment=!0}generateInitSegment(e,t){let{audioCodec:s,videoCodec:i}=this;if(!(e!=null&&e.byteLength)){this.initTracks=void 0,this.initData=void 0;return}const{audio:r,video:n}=this.initData=bn(e);if(t)So(e,t);else{const c=r||n;c!=null&&c.encrypted&&this.warn(`Init segment with encrypted track with has no key ("${c.codec}")!`)}r&&(s=Hr(r,re.AUDIO,this)),n&&(i=Hr(n,re.VIDEO,this));const o={};r&&n?o.audiovideo={container:"video/mp4",codec:s+","+i,supplemental:n.supplemental,encrypted:n.encrypted,initSegment:e,id:"main"}:r?o.audio={container:"audio/mp4",codec:s,encrypted:r.encrypted,initSegment:e,id:"audio"}:n?o.video={container:"video/mp4",codec:i,supplemental:n.supplemental,encrypted:n.encrypted,initSegment:e,id:"main"}:this.warn("initSegment does not contain moov or trak boxes."),this.initTracks=o}remux(e,t,s,i,r,n){var o,c;let{initPTS:l,lastEndTime:h}=this;const d={audio:void 0,video:void 0,text:i,id3:s,initSegment:void 0};M(h)||(h=this.lastEndTime=r||0);const u=t.samples;if(!u.length)return d;const f={initPTS:void 0,timescale:void 0,trackId:void 0};let g=this.initData;if((o=g)!=null&&o.length||(this.generateInitSegment(u),g=this.initData),!((c=g)!=null&&c.length))return this.warn("Failed to generate initSegment."),d;this.emitInitSegment&&(f.tracks=this.initTracks,this.emitInitSegment=!1);const y=xo(u,g,this),p=g.audio?y[g.audio.id]:null,E=g.video?y[g.video.id]:null,T=Zt(E,1/0),S=Zt(p,1/0),v=Zt(E,0,!0),A=Zt(p,0,!0);let D=r,x=0;const b=p&&(!E||!l&&S<T||l&&l.trackId===g.audio.id),_=b?p:E;if(_){const N=_.timescale,K=_.start-r*N,Y=b?g.audio.id:g.video.id;D=_.start/N,x=b?A-S:v-T,(n||!l)&&(Oc(l,D,r,x)||N!==l.timescale)&&(l&&this.warn(`Timestamps at playlist time: ${n?"":"~"}${r} ${K/N} != initPTS: ${l.baseTime/l.timescale} (${l.baseTime}/${l.timescale}) trackId: ${l.trackId}`),this.log(`Found initPTS at playlist time: ${r} offset: ${D-r} (${K}/${N}) trackId: ${Y}`),l=null,f.initPTS=K,f.timescale=N,f.trackId=Y)}else this.warn(`No audio or video samples found for initPTS at playlist time: ${r}`);l?(f.initPTS=l.baseTime,f.timescale=l.timescale,f.trackId=l.trackId):((!f.timescale||f.trackId===void 0||f.initPTS===void 0)&&(this.warn("Could not set initPTS"),f.initPTS=D,f.timescale=1,f.trackId=-1),this.initPTS=l={baseTime:f.initPTS,timescale:f.timescale,trackId:f.trackId});const I=D-l.baseTime/l.timescale,P=I+x;x>0?this.lastEndTime=P:(this.warn("Duration parsed from mp4 should be greater than zero"),this.resetNextTimestamp());const F=!!g.audio,U=!!g.video;let H="";F&&(H+="audio"),U&&(H+="video");const $=(g.audio?g.audio.encrypted:!1)||(g.video?g.video.encrypted:!1),k={data1:u,startPTS:I,startDTS:I,endPTS:P,endDTS:P,type:H,hasAudio:F,hasVideo:U,nb:1,dropped:0,encrypted:$};d.audio=F&&!U?k:void 0,d.video=U?k:void 0;const G=E==null?void 0:E.sampleCount;if(G){const N=E.keyFrameIndex,K=N!==-1;k.nb=G,k.dropped=N===0||this.isVideoContiguous?0:K?N:G,k.independent=K,k.firstKeyFrame=N,K&&E.keyFrameStart&&(k.firstKeyFramePTS=(E.keyFrameStart-l.baseTime)/l.timescale),this.isVideoContiguous||(d.independent=K),this.isVideoContiguous||(this.isVideoContiguous=K),k.dropped&&this.warn(`fmp4 does not start with IDR: firstIDR ${N}/${G} dropped: ${k.dropped} start: ${k.firstKeyFramePTS||"NA"}`)}return d.initSegment=f,d.id3=Sa(s,r,l,l),i.samples.length&&(d.text=va(i,r,l)),d}}function Zt(a,e,t=!1){return(a==null?void 0:a.start)!==void 0?(a.start+(t?a.duration:0))/a.timescale:e}function Oc(a,e,t,s){if(a===null)return!0;const i=Math.max(s,1),r=e-a.baseTime/a.timescale;return Math.abs(r-t)>i}function Hr(a,e,t){const s=a.codec;return s&&s.length>4?s:e===re.AUDIO?s==="ec-3"||s==="ac-3"||s==="alac"?s:s==="fLaC"||s==="Opus"?Ts(s,!1):(t.warn(`Unhandled audio codec "${s}" in mp4 MAP`),s||"mp4a"):(t.warn(`Unhandled video codec "${s}" in mp4 MAP`),s||"avc1")}let ze;try{ze=self.performance.now.bind(self.performance)}catch{ze=Date.now}const fs=[{demux:Tc,remux:wc},{demux:tt,remux:us},{demux:mc,remux:us},{demux:yc,remux:us}];fs.splice(2,0,{demux:pc,remux:us});class Yr{constructor(e,t,s,i,r,n){this.asyncResult=!1,this.logger=void 0,this.observer=void 0,this.typeSupported=void 0,this.config=void 0,this.id=void 0,this.demuxer=void 0,this.remuxer=void 0,this.decrypter=void 0,this.probe=void 0,this.decryptionPromise=null,this.transmuxConfig=void 0,this.currentTransmuxState=void 0,this.observer=e,this.typeSupported=t,this.config=s,this.id=r,this.logger=n}configure(e){this.transmuxConfig=e,this.decrypter&&this.decrypter.reset()}push(e,t,s,i){const r=s.transmuxing;r.executeStart=ze();let n=new Uint8Array(e);const{currentTransmuxState:o,transmuxConfig:c}=this;i&&(this.currentTransmuxState=i);const{contiguous:l,discontinuity:h,trackSwitch:d,accurateTimeOffset:u,timeOffset:f,initSegmentChange:g}=i||o,{audioCodec:y,videoCodec:p,defaultInitPts:E,duration:T,initSegmentData:S}=c,v=Fc(n,t);if(v&&Lt(v.method)){const b=this.getDecrypter(),_=ki(v.method);if(b.isSync()){let I=b.softwareDecrypt(n,v.key.buffer,v.iv.buffer,_);if(s.part>-1){const F=b.flush();I=F&&F.buffer}if(!I)return r.executeEnd=ze(),Ys(s);n=new Uint8Array(I)}else return this.asyncResult=!0,this.decryptionPromise=b.webCryptoDecrypt(n,v.key.buffer,v.iv.buffer,_).then(I=>{const P=this.push(I,null,s);return this.decryptionPromise=null,P}),this.decryptionPromise}const A=this.needsProbing(h,d);if(A){const b=this.configureTransmuxer(n);if(b)return this.logger.warn(`[transmuxer] ${b.message}`),this.observer.emit(m.ERROR,m.ERROR,{type:V.MEDIA_ERROR,details:R.FRAG_PARSING_ERROR,fatal:!1,error:b,reason:b.message}),r.executeEnd=ze(),Ys(s)}(h||d||g||A)&&this.resetInitSegment(S,y,p,T,t),(h||g||A)&&this.resetInitialTimestamp(E),l||this.resetContiguity();const D=this.transmux(n,v,f,u,s);this.asyncResult=Vt(D);const x=this.currentTransmuxState;return x.contiguous=!0,x.discontinuity=!1,x.trackSwitch=!1,r.executeEnd=ze(),D}flush(e){const t=e.transmuxing;t.executeStart=ze();const{decrypter:s,currentTransmuxState:i,decryptionPromise:r}=this;if(r)return this.asyncResult=!0,r.then(()=>this.flush(e));const n=[],{timeOffset:o}=i;if(s){const d=s.flush();d&&n.push(this.push(d.buffer,null,e))}const{demuxer:c,remuxer:l}=this;if(!c||!l){t.executeEnd=ze();const d=[Ys(e)];return this.asyncResult?Promise.resolve(d):d}const h=c.flush(o);return Vt(h)?(this.asyncResult=!0,h.then(d=>(this.flushRemux(n,d,e),n))):(this.flushRemux(n,h,e),this.asyncResult?Promise.resolve(n):n)}flushRemux(e,t,s){const{audioTrack:i,videoTrack:r,id3Track:n,textTrack:o}=t,{accurateTimeOffset:c,timeOffset:l}=this.currentTransmuxState;this.logger.log(`[transmuxer.ts]: Flushed ${this.id} sn: ${s.sn}${s.part>-1?" part: "+s.part:""} of ${this.id===B.MAIN?"level":"track"} ${s.level}`);const h=this.remuxer.remux(i,r,n,o,l,c,!0,this.id);e.push({remuxResult:h,chunkMeta:s}),s.transmuxing.executeEnd=ze()}resetInitialTimestamp(e){const{demuxer:t,remuxer:s}=this;!t||!s||(t.resetTimeStamp(e),s.resetTimeStamp(e))}resetContiguity(){const{demuxer:e,remuxer:t}=this;!e||!t||(e.resetContiguity(),t.resetNextTimestamp())}resetInitSegment(e,t,s,i,r){const{demuxer:n,remuxer:o}=this;!n||!o||(n.resetInitSegment(e,t,s,i),o.resetInitSegment(e,t,s,r))}destroy(){this.demuxer&&(this.demuxer.destroy(),this.demuxer=void 0),this.remuxer&&(this.remuxer.destroy(),this.remuxer=void 0)}transmux(e,t,s,i,r){let n;return t&&t.method==="SAMPLE-AES"?n=this.transmuxSampleAes(e,t,s,i,r):n=this.transmuxUnencrypted(e,s,i,r),n}transmuxUnencrypted(e,t,s,i){const{audioTrack:r,videoTrack:n,id3Track:o,textTrack:c}=this.demuxer.demux(e,t,!1,!this.config.progressive);return{remuxResult:this.remuxer.remux(r,n,o,c,t,s,!1,this.id),chunkMeta:i}}transmuxSampleAes(e,t,s,i,r){return this.demuxer.demuxSampleAes(e,t,s).then(n=>({remuxResult:this.remuxer.remux(n.audioTrack,n.videoTrack,n.id3Track,n.textTrack,s,i,!1,this.id),chunkMeta:r}))}configureTransmuxer(e){const{config:t,observer:s,typeSupported:i}=this;let r;for(let d=0,u=fs.length;d<u;d++){var n;if((n=fs[d].demux)!=null&&n.probe(e,this.logger)){r=fs[d];break}}if(!r)return new Error("Failed to find demuxer by probing fragment data");const o=this.demuxer,c=this.remuxer,l=r.remux,h=r.demux;(!c||!(c instanceof l))&&(this.remuxer=new l(s,t,i,this.logger)),(!o||!(o instanceof h))&&(this.demuxer=new h(s,t,i,this.logger),this.probe=h.probe)}needsProbing(e,t){return!this.demuxer||!this.remuxer||e||t}getDecrypter(){let e=this.decrypter;return e||(e=this.decrypter=new Ci(this.config)),e}}function Fc(a,e){let t=null;return a.byteLength>0&&(e==null?void 0:e.key)!=null&&e.iv!==null&&e.method!=null&&(t=e),t}const Ys=a=>({remuxResult:{},chunkMeta:a});function Vt(a){return"then"in a&&a.then instanceof Function}class Mc{constructor(e,t,s,i,r){this.audioCodec=void 0,this.videoCodec=void 0,this.initSegmentData=void 0,this.duration=void 0,this.defaultInitPts=void 0,this.audioCodec=e,this.videoCodec=t,this.initSegmentData=s,this.duration=i,this.defaultInitPts=r||null}}class Nc{constructor(e,t,s,i,r,n){this.discontinuity=void 0,this.contiguous=void 0,this.accurateTimeOffset=void 0,this.trackSwitch=void 0,this.timeOffset=void 0,this.initSegmentChange=void 0,this.discontinuity=e,this.contiguous=t,this.accurateTimeOffset=s,this.trackSwitch=i,this.timeOffset=r,this.initSegmentChange=n}}let Wr=0;class xa{constructor(e,t,s,i){this.error=null,this.hls=void 0,this.id=void 0,this.instanceNo=Wr++,this.observer=void 0,this.frag=null,this.part=null,this.useWorker=void 0,this.workerContext=null,this.transmuxer=null,this.onTransmuxComplete=void 0,this.onFlush=void 0,this.onWorkerMessage=c=>{const l=c.data,h=this.hls;if(!(!h||!(l!=null&&l.event)||l.instanceNo!==this.instanceNo))switch(l.event){case"init":{var d;const u=(d=this.workerContext)==null?void 0:d.objectURL;u&&self.URL.revokeObjectURL(u);break}case"transmuxComplete":{this.handleTransmuxComplete(l.data);break}case"flush":{this.onFlush(l.data);break}case"workerLog":{h.logger[l.data.logType]&&h.logger[l.data.logType](l.data.message);break}default:{l.data=l.data||{},l.data.frag=this.frag,l.data.part=this.part,l.data.id=this.id,h.trigger(l.event,l.data);break}}},this.onWorkerError=c=>{if(!this.hls)return;const l=new Error(`${c.message} (${c.filename}:${c.lineno})`);this.hls.config.enableWorker=!1,this.hls.logger.warn(`Error in "${this.id}" Web Worker, fallback to inline`),this.hls.trigger(m.ERROR,{type:V.OTHER_ERROR,details:R.INTERNAL_EXCEPTION,fatal:!1,event:"demuxerWorker",error:l})};const r=e.config;this.hls=e,this.id=t,this.useWorker=!!r.enableWorker,this.onTransmuxComplete=s,this.onFlush=i;const n=(c,l)=>{l=l||{},l.frag=this.frag||void 0,c===m.ERROR&&(l=l,l.parent=this.id,l.part=this.part,this.error=l.error),this.hls.trigger(c,l)};this.observer=new Fi,this.observer.on(m.FRAG_DECRYPTED,n),this.observer.on(m.ERROR,n);const o=or(r.preferManagedMediaSource);if(this.useWorker&&typeof Worker<"u"){const c=this.hls.logger;if(r.workerPath||Gl()){try{r.workerPath?(c.log(`loading Web Worker ${r.workerPath} for "${t}"`),this.workerContext=Vl(r.workerPath)):(c.log(`injecting Web Worker for "${t}"`),this.workerContext=Kl());const{worker:h}=this.workerContext;h.addEventListener("message",this.onWorkerMessage),h.addEventListener("error",this.onWorkerError),h.postMessage({instanceNo:this.instanceNo,cmd:"init",typeSupported:o,id:t,config:ne(r)})}catch(h){c.warn(`Error setting up "${t}" Web Worker, fallback to inline`,h),this.terminateWorker(),this.error=null,this.transmuxer=new Yr(this.observer,o,r,"",t,e.logger)}return}}this.transmuxer=new Yr(this.observer,o,r,"",t,e.logger)}reset(){if(this.frag=null,this.part=null,this.workerContext){const e=this.instanceNo;this.instanceNo=Wr++;const t=this.hls.config,s=or(t.preferManagedMediaSource);this.workerContext.worker.postMessage({instanceNo:this.instanceNo,cmd:"reset",resetNo:e,typeSupported:s,id:this.id,config:ne(t)})}}terminateWorker(){if(this.workerContext){const{worker:e}=this.workerContext;this.workerContext=null,e.removeEventListener("message",this.onWorkerMessage),e.removeEventListener("error",this.onWorkerError),Hl(this.hls.config.workerPath)}}destroy(){if(this.workerContext)this.terminateWorker(),this.onWorkerMessage=this.onWorkerError=null;else{const t=this.transmuxer;t&&(t.destroy(),this.transmuxer=null)}const e=this.observer;e&&e.removeAllListeners(),this.frag=null,this.part=null,this.observer=null,this.hls=null}push(e,t,s,i,r,n,o,c,l,h){var d,u;l.transmuxing.start=self.performance.now();const{instanceNo:f,transmuxer:g}=this,y=n?n.start:r.start,p=r.decryptdata,E=this.frag,T=!(E&&r.cc===E.cc),S=!(E&&l.level===E.level),v=E?l.sn-E.sn:-1,A=this.part?l.part-this.part.index:-1,D=v===0&&l.id>1&&l.id===(E==null?void 0:E.stats.chunkCount),x=!S&&(v===1||v===0&&(A===1||D&&A<=0)),b=self.performance.now();(S||v||r.stats.parsing.start===0)&&(r.stats.parsing.start=b),n&&(A||!x)&&(n.stats.parsing.start=b);const _=!(E&&((d=r.initSegment)==null?void 0:d.url)===((u=E.initSegment)==null?void 0:u.url)),I=new Nc(T,x,c,S,y,_);if(!x||T||_){this.hls.logger.log(`[transmuxer-interface]: Starting new transmux session for ${r.type} sn: ${l.sn}${l.part>-1?" part: "+l.part:""} ${this.id===B.MAIN?"level":"track"}: ${l.level} id: ${l.id}
104104+${t.m3u8}`)}function Xa(n,e,t=!0){const s=e.startSN+e.skippedSegments-n.startSN,i=n.fragments,r=s>=0;let a=0;if(r&&s<i.length)a=i[s].start;else if(r&&e.startSN===n.endSN+1)a=n.fragmentEnd;else if(r&&t)a=n.fragmentStart+s*e.levelTargetDuration;else if(!e.skippedSegments&&e.fragmentStart===0)a=n.fragmentStart;else return;Pi(e,a)}function Pi(n,e){if(e){const t=n.fragments;for(let s=n.skippedSegments;s<t.length;s++)t[s].addStart(e);n.fragmentHint&&n.fragmentHint.addStart(e)}}function za(n,e=1/0){let t=1e3*n.targetduration;if(n.updated){const s=n.fragments;if(s.length&&t*4>e){const r=s[s.length-1].duration*1e3;r<t&&(t=r)}}else t/=2;return Math.round(t)}function Qa(n,e,t){if(!n)return null;let s=n.fragments[e-n.startSN];return s||(s=n.fragmentHint,s&&s.sn===e)?s:e<n.startSN&&t&&t.sn===e?t:null}function En(n,e,t){return n?Za(n.partList,e,t):null}function Za(n,e,t){if(n)for(let s=n.length;s--;){const i=n[s];if(i.index===t&&i.fragment.sn===e)return i}return null}function Ja(n){n.forEach((e,t)=>{var s;(s=e.details)==null||s.fragments.forEach(i=>{i.level=t,i.initSegment&&(i.initSegment.level=t)})})}function yh(n,e){return n!==e&&e?Tn(n)!==Tn(e):!1}function Tn(n){return n.replace(/\?[^?]*$/,"")}function Nt(n,e){for(let s=0,i=n.length;s<i;s++){var t;if(((t=n[s])==null?void 0:t.cc)===e)return n[s]}return null}function Eh(n,e){return!!(n&&e.startCC<n.endCC&&e.endCC>n.startCC)}function Sn(n,e){const t=n.start+e;n.startPTS=t,n.setStart(t),n.endPTS=t+n.duration}function eo(n,e){const t=e.fragments;for(let s=0,i=t.length;s<i;s++)Sn(t[s],n);e.fragmentHint&&Sn(e.fragmentHint,n),e.alignedSliding=!0}function Th(n,e){n&&(to(e,n),e.alignedSliding||Ms(e,n),!e.alignedSliding&&!e.skippedSegments&&Xa(n,e,!1))}function to(n,e){if(!Eh(e,n))return;const t=Math.min(e.endCC,n.endCC),s=Nt(e.fragments,t),i=Nt(n.fragments,t);if(!s||!i)return;ie.log(`Aligning playlist at start of dicontinuity sequence ${t}`);const r=s.start-i.start;eo(r,n)}function Ms(n,e){if(!n.hasProgramDateTime||!e.hasProgramDateTime)return;const t=n.fragments,s=e.fragments;if(!t.length||!s.length)return;let i,r;const a=Math.min(e.endCC,n.endCC);e.startCC<a&&n.startCC<a&&(i=Nt(s,a),r=Nt(t,a)),(!i||!r)&&(i=s[Math.floor(s.length/2)],r=Nt(t,i.cc)||t[Math.floor(t.length/2)]);const o=i.programDateTime,c=r.programDateTime;if(!o||!c)return;const l=(c-o)/1e3-(r.start-i.start);eo(l,n)}function Ae(n,e,t){Ie(n,e,t),n.addEventListener(e,t)}function Ie(n,e,t){n.removeEventListener(e,t)}const Sh={toString:function(n){let e="";const t=n.length;for(let s=0;s<t;s++)e+=`[${n.start(s).toFixed(3)}-${n.end(s).toFixed(3)}]`;return e}},P={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"};class sr extends $a{constructor(e,t,s,i,r){super(i,e.logger),this.hls=void 0,this.fragPrevious=null,this.fragCurrent=null,this.fragmentTracker=void 0,this.transmuxer=null,this._state=P.STOPPED,this.playlistType=void 0,this.media=null,this.mediaBuffer=null,this.config=void 0,this.bitrateTest=!1,this.lastCurrentTime=0,this.nextLoadPosition=0,this.startPosition=0,this.startTimeOffset=null,this.retryDate=0,this.levels=null,this.fragmentLoader=void 0,this.keyLoader=void 0,this.levelLastLoaded=null,this.startFragRequested=!1,this.decrypter=void 0,this.initPTS=[],this.buffering=!0,this.loadingParts=!1,this.loopSn=void 0,this.onMediaSeeking=()=>{const{config:a,fragCurrent:o,media:c,mediaBuffer:l,state:h}=this,u=c?c.currentTime:0,d=q.bufferInfo(l||c,u,a.maxBufferHole),f=!d.len;if(this.log(`Media seeking to ${M(u)?u.toFixed(3):u}, state: ${h}, ${f?"out of":"in"} buffer`),this.state===P.ENDED)this.resetLoadingState();else if(o){const g=a.maxFragLookUpTolerance,p=o.start-g,y=o.start+o.duration+g;if(f||y<d.start||p>d.end){const E=u>y;(u<p||E)&&(E&&o.loader&&(this.log(`Cancelling fragment load for seek (sn: ${o.sn})`),o.abortRequests(),this.resetLoadingState()),this.fragPrevious=null)}}if(c){this.fragmentTracker.removeFragmentsInRange(u,1/0,this.playlistType,!0);const g=this.lastCurrentTime;if(u>g&&(this.lastCurrentTime=u),!this.loadingParts){const p=Math.max(d.end,u),y=this.shouldLoadParts(this.getLevelDetails(),p);y&&(this.log(`LL-Part loading ON after seeking to ${u.toFixed(2)} with buffer @${p.toFixed(2)}`),this.loadingParts=y)}}this.hls.hasEnoughToStart||(this.log(`Setting ${f?"startPosition":"nextLoadPosition"} to ${u} for seek without enough to start`),this.nextLoadPosition=u,f&&(this.startPosition=u)),f&&this.state===P.IDLE&&this.tickImmediate()},this.onMediaEnded=()=>{this.log("setting startPosition to 0 because media ended"),this.startPosition=this.lastCurrentTime=0},this.playlistType=r,this.hls=e,this.fragmentLoader=new jc(e.config),this.keyLoader=s,this.fragmentTracker=t,this.config=e.config,this.decrypter=new Zi(e.config)}registerListeners(){const{hls:e}=this;e.on(m.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(m.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(m.MANIFEST_LOADING,this.onManifestLoading,this),e.on(m.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(m.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(m.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(m.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(m.MANIFEST_LOADING,this.onManifestLoading,this),e.off(m.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(m.ERROR,this.onError,this)}doTick(){this.onTickEnd()}onTickEnd(){}startLoad(e){}stopLoad(){if(this.state===P.STOPPED)return;this.fragmentLoader.abort(),this.keyLoader.abort(this.playlistType);const e=this.fragCurrent;e!=null&&e.loader&&(e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.resetTransmuxer(),this.fragCurrent=null,this.fragPrevious=null,this.clearInterval(),this.clearNextTick(),this.state=P.STOPPED}get startPositionValue(){const{nextLoadPosition:e,startPosition:t}=this;return t===-1&&e?e:t}get bufferingEnabled(){return this.buffering}pauseBuffering(){this.buffering=!1}resumeBuffering(){this.buffering=!0}get inFlightFrag(){return{frag:this.fragCurrent,state:this.state}}_streamEnded(e,t){if(t.live||!this.media)return!1;const s=e.end||0,i=this.config.timelineOffset||0;if(s<=i)return!1;const r=e.buffered;this.config.maxBufferHole&&r&&r.length>1&&(e=q.bufferedInfo(r,e.start,0));const a=e.nextStart;if(a&&a>i&&a<t.edge||this.media.currentTime<e.start)return!1;const c=t.partList;if(c!=null&&c.length){const h=c[c.length-1];return q.isBuffered(this.media,h.start+h.duration/2)}const l=t.fragments[t.fragments.length-1].type;return this.fragmentTracker.isEndListAppended(l)}getLevelDetails(){if(this.levels&&this.levelLastLoaded!==null)return this.levelLastLoaded.details}get timelineOffset(){const e=this.config.timelineOffset;if(e){var t;return((t=this.getLevelDetails())==null?void 0:t.appliedTimelineOffset)||e}return 0}onMediaAttached(e,t){const s=this.media=this.mediaBuffer=t.media;Ae(s,"seeking",this.onMediaSeeking),Ae(s,"ended",this.onMediaEnded);const i=this.config;this.levels&&i.autoStartLoad&&this.state===P.STOPPED&&this.startLoad(i.startPosition)}onMediaDetaching(e,t){const s=!!t.transferMedia,i=this.media;if(i!==null){if(i.ended&&(this.log("MSE detaching and video ended, reset startPosition"),this.startPosition=this.lastCurrentTime=0),Ie(i,"seeking",this.onMediaSeeking),Ie(i,"ended",this.onMediaEnded),this.keyLoader&&!s&&this.keyLoader.detach(),this.media=this.mediaBuffer=null,this.loopSn=void 0,s){this.resetLoadingState(),this.resetTransmuxer();return}this.loadingParts=!1,this.fragmentTracker.removeAllFragments(),this.stopLoad()}}onManifestLoading(){this.initPTS=[],this.levels=this.levelLastLoaded=this.fragCurrent=null,this.lastCurrentTime=this.startPosition=0,this.startFragRequested=!1}onError(e,t){}onManifestLoaded(e,t){this.startTimeOffset=t.startTimeOffset}onHandlerDestroying(){this.stopLoad(),this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null),super.onHandlerDestroying(),this.hls=this.onMediaSeeking=this.onMediaEnded=null}onHandlerDestroyed(){this.state=P.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,super.onHandlerDestroyed()}loadFragment(e,t,s){this.startFragRequested=!0,this._loadFragForPlayback(e,t,s)}_loadFragForPlayback(e,t,s){const i=r=>{const a=r.frag;if(this.fragContextChanged(a)){this.warn(`${a.type} sn: ${a.sn}${r.part?" part: "+r.part.index:""} of ${this.fragInfo(a,!1,r.part)}) was dropped during download.`),this.fragmentTracker.removeFragment(a);return}a.stats.chunkCount++,this._handleFragmentLoadProgress(r)};this._doFragLoad(e,t,s,i).then(r=>{if(!r)return;const a=this.state,o=r.frag;if(this.fragContextChanged(o)){(a===P.FRAG_LOADING||!this.fragCurrent&&a===P.PARSING)&&(this.fragmentTracker.removeFragment(o),this.state=P.IDLE);return}"payload"in r&&(this.log(`Loaded ${o.type} sn: ${o.sn} of ${this.playlistLabel()} ${o.level}`),this.hls.trigger(m.FRAG_LOADED,r)),this._handleFragmentLoadComplete(r)}).catch(r=>{this.state===P.STOPPED||this.state===P.ERROR||(this.warn(`Frag error: ${(r==null?void 0:r.message)||r}`),this.resetFragmentLoading(e))})}clearTrackerIfNeeded(e){var t;const{fragmentTracker:s}=this;if(s.getState(e)===me.APPENDING){const r=e.type,a=this.getFwdBufferInfo(this.mediaBuffer,r),o=Math.max(e.duration,a?a.len:this.config.maxBufferLength),c=this.backtrackFragment;((c?e.sn-c.sn:0)===1||this.reduceMaxBufferLength(o,e.duration))&&s.removeFragment(e)}else((t=this.mediaBuffer)==null?void 0:t.buffered.length)===0?s.removeAllFragments():s.hasParts(e.type)&&(s.detectPartialFragments({frag:e,part:null,stats:e.stats,id:e.type}),s.getState(e)===me.PARTIAL&&s.removeFragment(e))}checkLiveUpdate(e){if(e.updated&&!e.live){const t=e.fragments[e.fragments.length-1];this.fragmentTracker.detectPartialFragments({frag:t,part:null,stats:t.stats,id:t.type})}e.fragments[0]||(e.deltaUpdateFailed=!0)}waitForLive(e){const t=e.details;return(t==null?void 0:t.live)&&t.type!=="EVENT"&&(this.levelLastLoaded!==e||t.expired)}flushMainBuffer(e,t,s=null){if(!(e-t))return;const i={startOffset:e,endOffset:t,type:s};this.hls.trigger(m.BUFFER_FLUSHING,i)}_loadInitSegment(e,t){this._doFragLoad(e,t).then(s=>{const i=s==null?void 0:s.frag;if(!i||this.fragContextChanged(i)||!this.levels)throw new Error("init load aborted");return s}).then(s=>{const{hls:i}=this,{frag:r,payload:a}=s,o=r.decryptdata;if(a&&a.byteLength>0&&o!=null&&o.key&&o.iv&&It(o.method)){const c=self.performance.now();return this.decrypter.decrypt(new Uint8Array(a),o.key.buffer,o.iv.buffer,er(o.method)).catch(l=>{throw i.trigger(m.ERROR,{type:H.MEDIA_ERROR,details:R.FRAG_DECRYPT_ERROR,fatal:!1,error:l,reason:l.message,frag:r}),l}).then(l=>{const h=self.performance.now();return i.trigger(m.FRAG_DECRYPTED,{frag:r,payload:l,stats:{tstart:c,tdecrypt:h}}),s.payload=l,this.completeInitSegmentLoad(s)})}return this.completeInitSegmentLoad(s)}).catch(s=>{this.state===P.STOPPED||this.state===P.ERROR||(this.warn(s),this.resetFragmentLoading(e))})}completeInitSegmentLoad(e){const{levels:t}=this;if(!t)throw new Error("init load aborted, missing levels");const s=e.frag.stats;this.state!==P.STOPPED&&(this.state=P.IDLE),e.frag.data=new Uint8Array(e.payload),s.parsing.start=s.buffering.start=self.performance.now(),s.parsing.end=s.buffering.end=self.performance.now(),this.tick()}unhandledEncryptionError(e,t){var s,i;const r=e.tracks;if(r&&!t.encrypted&&((s=r.audio)!=null&&s.encrypted||(i=r.video)!=null&&i.encrypted)&&(!this.config.emeEnabled||!this.keyLoader.emeController)){const a=this.media,o=new Error(`Encrypted track with no key in ${this.fragInfo(t)} (media ${a?"attached mediaKeys: "+a.mediaKeys:"detached"})`);return this.warn(o.message),!a||a.mediaKeys?!1:(this.hls.trigger(m.ERROR,{type:H.KEY_SYSTEM_ERROR,details:R.KEY_SYSTEM_NO_KEYS,fatal:!1,error:o,frag:t}),this.resetTransmuxer(),!0)}return!1}fragContextChanged(e){const{fragCurrent:t}=this;return!e||!t||e.sn!==t.sn||e.level!==t.level}fragBufferedComplete(e,t){const s=this.mediaBuffer?this.mediaBuffer:this.media;if(this.log(`Buffered ${e.type} sn: ${e.sn}${t?" part: "+t.index:""} of ${this.fragInfo(e,!1,t)} > buffer:${s?Sh.toString(q.getBuffered(s)):"(detached)"})`),de(e)){var i;if(e.type!==U.SUBTITLE){const a=e.elementaryStreams;if(!Object.keys(a).some(o=>!!a[o])){this.state=P.IDLE;return}}const r=(i=this.levels)==null?void 0:i[e.level];r!=null&&r.fragmentError&&(this.log(`Resetting level fragment error count of ${r.fragmentError} on frag buffered`),r.fragmentError=0)}this.state=P.IDLE}_handleFragmentLoadComplete(e){const{transmuxer:t}=this;if(!t)return;const{frag:s,part:i,partsLoaded:r}=e,a=!r||r.length===0||r.some(c=>!c),o=new Ji(s.level,s.sn,s.stats.chunkCount+1,0,i?i.index:-1,!a);t.flush(o)}_handleFragmentLoadProgress(e){}_doFragLoad(e,t,s=null,i){var r;this.fragCurrent=e;const a=t.details;if(!this.levels||!a)throw new Error(`frag load aborted, missing level${a?"":" detail"}s`);let o=null;if(e.encrypted&&!((r=e.decryptdata)!=null&&r.key)){if(this.log(`Loading key for ${e.sn} of [${a.startSN}-${a.endSN}], ${this.playlistLabel()} ${e.level}`),this.state=P.KEY_LOADING,this.fragCurrent=e,o=this.keyLoader.load(e).then(d=>{if(!this.fragContextChanged(d.frag))return this.hls.trigger(m.KEY_LOADED,d),this.state===P.KEY_LOADING&&(this.state=P.IDLE),d}),this.hls.trigger(m.KEY_LOADING,{frag:e}),this.fragCurrent===null)return this.log("context changed in KEY_LOADING"),Promise.resolve(null)}else e.encrypted||(o=this.keyLoader.loadClear(e,a.encryptedFragments,this.startFragRequested),o&&this.log("[eme] blocking frag load until media-keys acquired"));const c=this.fragPrevious;if(de(e)&&(!c||e.sn!==c.sn)){const d=this.shouldLoadParts(t.details,e.end);d!==this.loadingParts&&(this.log(`LL-Part loading ${d?"ON":"OFF"} loading sn ${c==null?void 0:c.sn}->${e.sn}`),this.loadingParts=d)}if(s=Math.max(e.start,s||0),this.loadingParts&&de(e)){const d=a.partList;if(d&&i){s>a.fragmentEnd&&a.fragmentHint&&(e=a.fragmentHint);const f=this.getNextPart(d,e,s);if(f>-1){const g=d[f];e=this.fragCurrent=g.fragment,this.log(`Loading ${e.type} sn: ${e.sn} part: ${g.index} (${f}/${d.length-1}) of ${this.fragInfo(e,!1,g)}) cc: ${e.cc} [${a.startSN}-${a.endSN}], target: ${parseFloat(s.toFixed(3))}`),this.nextLoadPosition=g.start+g.duration,this.state=P.FRAG_LOADING;let p;return o?p=o.then(y=>!y||this.fragContextChanged(y.frag)?null:this.doFragPartsLoad(e,g,t,i)).catch(y=>this.handleFragLoadError(y)):p=this.doFragPartsLoad(e,g,t,i).catch(y=>this.handleFragLoadError(y)),this.hls.trigger(m.FRAG_LOADING,{frag:e,part:g,targetBufferTime:s}),this.fragCurrent===null?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING parts")):p}else if(!e.url||this.loadedEndOfParts(d,s))return Promise.resolve(null)}}if(de(e)&&this.loadingParts){var l;this.log(`LL-Part loading OFF after next part miss @${s.toFixed(2)} Check buffer at sn: ${e.sn} loaded parts: ${(l=a.partList)==null?void 0:l.filter(d=>d.loaded).map(d=>`[${d.start}-${d.end}]`)}`),this.loadingParts=!1}else if(!e.url)return Promise.resolve(null);this.log(`Loading ${e.type} sn: ${e.sn} of ${this.fragInfo(e,!1)}) cc: ${e.cc} ${"["+a.startSN+"-"+a.endSN+"]"}, target: ${parseFloat(s.toFixed(3))}`),M(e.sn)&&!this.bitrateTest&&(this.nextLoadPosition=e.start+e.duration),this.state=P.FRAG_LOADING;const h=this.config.progressive&&e.type!==U.SUBTITLE;let u;return h&&o?u=o.then(d=>!d||this.fragContextChanged(d.frag)?null:this.fragmentLoader.load(e,i)).catch(d=>this.handleFragLoadError(d)):u=Promise.all([this.fragmentLoader.load(e,h?i:void 0),o]).then(([d])=>(!h&&i&&i(d),d)).catch(d=>this.handleFragLoadError(d)),this.hls.trigger(m.FRAG_LOADING,{frag:e,targetBufferTime:s}),this.fragCurrent===null?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING")):u}doFragPartsLoad(e,t,s,i){return new Promise((r,a)=>{var o;const c=[],l=(o=s.details)==null?void 0:o.partList,h=u=>{this.fragmentLoader.loadPart(e,u,i).then(d=>{c[u.index]=d;const f=d.part;this.hls.trigger(m.FRAG_LOADED,d);const g=En(s.details,e.sn,u.index+1)||Za(l,e.sn,u.index+1);if(g)h(g);else return r({frag:e,part:f,partsLoaded:c})}).catch(a)};h(t)})}handleFragLoadError(e){if("data"in e){const t=e.data;t.frag&&t.details===R.INTERNAL_ABORTED?this.handleFragLoadAborted(t.frag,t.part):t.frag&&t.type===H.KEY_SYSTEM_ERROR?(t.frag.abortRequests(),this.resetStartWhenNotLoaded(),this.resetFragmentLoading(t.frag)):this.hls.trigger(m.ERROR,t)}else this.hls.trigger(m.ERROR,{type:H.OTHER_ERROR,details:R.INTERNAL_EXCEPTION,err:e,error:e,fatal:!0});return null}_handleTransmuxerFlush(e){const t=this.getCurrentContext(e);if(!t||this.state!==P.PARSING){!this.fragCurrent&&this.state!==P.STOPPED&&this.state!==P.ERROR&&(this.state=P.IDLE);return}const{frag:s,part:i,level:r}=t,a=self.performance.now();s.stats.parsing.end=a,i&&(i.stats.parsing.end=a);const o=this.getLevelDetails(),l=o&&s.sn>o.endSN||this.shouldLoadParts(o,s.end);l!==this.loadingParts&&(this.log(`LL-Part loading ${l?"ON":"OFF"} after parsing segment ending @${s.end.toFixed(2)}`),this.loadingParts=l),this.updateLevelTiming(s,i,r,e.partial)}shouldLoadParts(e,t){if(this.config.lowLatencyMode){if(!e)return this.loadingParts;if(e.partList){var s;const r=e.partList[0];if(r.fragment.type===U.SUBTITLE)return!1;const a=r.end+(((s=e.fragmentHint)==null?void 0:s.duration)||0);if(t>=a){var i;if((this.hls.hasEnoughToStart?((i=this.media)==null?void 0:i.currentTime)||this.lastCurrentTime:this.getLoadPosition())>r.start-r.fragment.duration)return!0}}}return!1}getCurrentContext(e){const{levels:t,fragCurrent:s}=this,{level:i,sn:r,part:a}=e;if(!(t!=null&&t[i]))return this.warn(`Levels object was unset while buffering fragment ${r} of ${this.playlistLabel()} ${i}. The current chunk will not be buffered.`),null;const o=t[i],c=o.details,l=a>-1?En(c,r,a):null,h=l?l.fragment:Qa(c,r,s);return h?(s&&s!==h&&(h.stats=s.stats),{frag:h,part:l,level:o}):null}bufferFragmentData(e,t,s,i,r){if(this.state!==P.PARSING)return;const{data1:a,data2:o}=e;let c=a;if(o&&(c=Oe(a,o)),!c.length)return;const l=this.initPTS[t.cc],h=l?-l.baseTime/l.timescale:void 0,u={type:e.type,frag:t,part:s,chunkMeta:i,offset:h,parent:t.type,data:c};if(this.hls.trigger(m.BUFFER_APPENDING,u),e.dropped&&e.independent&&!s){if(r)return;this.flushBufferGap(t)}}flushBufferGap(e){const t=this.media;if(!t)return;if(!q.isBuffered(t,t.currentTime)){this.flushMainBuffer(0,e.start);return}const s=t.currentTime,i=q.bufferInfo(t,s,0),r=e.duration,a=Math.min(this.config.maxFragLookUpTolerance*2,r*.25),o=Math.max(Math.min(e.start-a,i.end-a),s+a);e.start-o>a&&this.flushMainBuffer(o,e.start)}getFwdBufferInfo(e,t){var s;const i=this.getLoadPosition();if(!M(i))return null;const a=this.lastCurrentTime>i||(s=this.media)!=null&&s.paused?0:this.config.maxBufferHole;return this.getFwdBufferInfoAtPos(e,i,t,a)}getFwdBufferInfoAtPos(e,t,s,i){const r=q.bufferInfo(e,t,i);if(r.len===0&&r.nextStart!==void 0){const a=this.fragmentTracker.getBufferedFrag(t,s);if(a&&(r.nextStart<=a.end||a.gap)){const o=Math.max(Math.min(r.nextStart,a.end)-t,i);return q.bufferInfo(e,t,o)}}return r}getMaxBufferLength(e){const{config:t}=this;let s;return e?s=Math.max(8*t.maxBufferSize/e,t.maxBufferLength):s=t.maxBufferLength,Math.min(s,t.maxMaxBufferLength)}reduceMaxBufferLength(e,t){const s=this.config,i=Math.max(Math.min(e-t,s.maxBufferLength),t),r=Math.max(e-t*3,s.maxMaxBufferLength/2,i);return r>=i?(s.maxMaxBufferLength=r,this.warn(`Reduce max buffer length to ${r}s`),!0):!1}getAppendedFrag(e,t=U.MAIN){const s=this.fragmentTracker?this.fragmentTracker.getAppendedFrag(e,t):null;return s&&"fragment"in s?s.fragment:s}getNextFragment(e,t){const s=t.fragments,i=s.length;if(!i)return null;const{config:r}=this,a=s[0].start,o=r.lowLatencyMode&&!!t.partList;let c=null;if(t.live){const u=r.initialLiveManifestSize;if(i<u)return this.warn(`Not enough fragments to start playback (have: ${i}, need: ${u})`),null;if(!t.PTSKnown&&!this.startFragRequested&&this.startPosition===-1||e<a){var l;o&&!this.loadingParts&&(this.log("LL-Part loading ON for initial live fragment"),this.loadingParts=!0),c=this.getInitialLiveFragment(t);const d=this.hls.startPosition,f=this.hls.liveSyncPosition,g=c?(d!==-1&&d>=a?d:f)||c.start:e;this.log(`Setting startPosition to ${g} to match start frag at live edge. mainStart: ${d} liveSyncPosition: ${f} frag.start: ${(l=c)==null?void 0:l.start}`),this.startPosition=this.nextLoadPosition=g}}else e<=a&&(c=s[0]);if(!c){const u=this.loadingParts?t.partEnd:t.fragmentEnd;c=this.getFragmentAtPosition(e,u,t)}let h=this.filterReplacedPrimary(c,t);if(!h&&c){const u=c.sn-t.startSN;h=this.filterReplacedPrimary(s[u+1]||null,t)}return this.mapToInitFragWhenRequired(h)}isLoopLoading(e,t){const s=this.fragmentTracker.getState(e);return(s===me.OK||s===me.PARTIAL&&!!e.gap)&&this.nextLoadPosition>t}getNextFragmentLoopLoading(e,t,s,i,r){let a=null;if(e.gap&&(a=this.getNextFragment(this.nextLoadPosition,t),a&&!a.gap&&s.nextStart)){const o=this.getFwdBufferInfoAtPos(this.mediaBuffer?this.mediaBuffer:this.media,s.nextStart,i,0);if(o!==null&&s.len+o.len>=r){const c=a.sn;return this.loopSn!==c&&(this.log(`buffer full after gaps in "${i}" playlist starting at sn: ${c}`),this.loopSn=c),null}}return this.loopSn=void 0,a}get primaryPrefetch(){if(vn(this.config)){var e;if((e=this.hls.interstitialsManager)==null||(e=e.playingItem)==null?void 0:e.event)return!0}return!1}filterReplacedPrimary(e,t){if(!e)return e;if(vn(this.config)&&e.type!==U.SUBTITLE){const s=this.hls.interstitialsManager,i=s==null?void 0:s.bufferingItem;if(i){const a=i.event;if(a){if(a.appendInPlace||Math.abs(e.start-i.start)>1||i.start===0)return null}else if(e.end<=i.start&&(t==null?void 0:t.live)===!1||e.start>i.end&&i.nextEvent&&(i.nextEvent.appendInPlace||e.start-i.end>1))return null}const r=s==null?void 0:s.playerQueue;if(r)for(let a=r.length;a--;){const o=r[a].interstitial;if(o.appendInPlace&&e.start>=o.startTime&&e.end<=o.resumeTime)return null}}return e}mapToInitFragWhenRequired(e){return e!=null&&e.initSegment&&!e.initSegment.data&&!this.bitrateTest?e.initSegment:e}getNextPart(e,t,s){let i=-1,r=!1,a=!0;for(let o=0,c=e.length;o<c;o++){const l=e[o];if(a=a&&!l.independent,i>-1&&s<l.start)break;const h=l.loaded;h?i=-1:(r||(l.independent||a)&&l.fragment===t)&&(l.fragment!==t&&this.warn(`Need buffer at ${s} but next unloaded part starts at ${l.start}`),i=o),r=h}return i}loadedEndOfParts(e,t){let s;for(let i=e.length;i--;){if(s=e[i],!s.loaded)return!1;if(t>s.start)return!0}return!1}getInitialLiveFragment(e){const t=e.fragments,s=this.fragPrevious;let i=null;if(s){if(e.hasProgramDateTime&&(this.log(`Live playlist, switching playlist, load frag with same PDT: ${s.programDateTime}`),i=Mc(t,s.endProgramDateTime,this.config.maxFragLookUpTolerance)),!i){const r=s.sn+1;if(r>=e.startSN&&r<=e.endSN){const a=t[r-e.startSN];s.cc===a.cc&&(i=a,this.log(`Live playlist, switching playlist, load frag with next SN: ${i.sn}`))}i||(i=Na(e,s.cc,s.end),i&&this.log(`Live playlist, switching playlist, load frag with same CC: ${i.sn}`))}}else{const r=this.hls.liveSyncPosition;r!==null&&(i=this.getFragmentAtPosition(r,this.bitrateTest?e.fragmentEnd:e.edge,e))}return i}getFragmentAtPosition(e,t,s){const{config:i}=this;let{fragPrevious:r}=this,{fragments:a,endSN:o}=s;const{fragmentHint:c}=s,{maxFragLookUpTolerance:l}=i,h=s.partList,u=!!(this.loadingParts&&h!=null&&h.length&&c);u&&!this.bitrateTest&&h[h.length-1].fragment.sn===c.sn&&(a=a.concat(c),o=c.sn);let d;if(e<t){var f;const p=e<this.lastCurrentTime||e>t-l||(f=this.media)!=null&&f.paused||!this.startFragRequested?0:l;d=mt(r,a,e,p)}else d=a[a.length-1];if(d){const g=d.sn-s.startSN,p=this.fragmentTracker.getState(d);if((p===me.OK||p===me.PARTIAL&&d.gap)&&(r=d),r&&d.sn===r.sn&&(!u||h[0].fragment.sn>d.sn||!s.live)&&d.level===r.level){const E=a[g+1];d.sn<o&&this.fragmentTracker.getState(E)!==me.OK?d=E:d=null}}return d}alignPlaylists(e,t,s){const i=e.fragments.length;if(!i)return this.warn("No fragments in live playlist"),0;const r=e.fragmentStart,a=!t,o=e.alignedSliding&&M(r);if(a||!o&&!r){Th(s,e);const c=e.fragmentStart;return this.log(`Live playlist sliding: ${c.toFixed(2)} start-sn: ${t?t.startSN:"na"}->${e.startSN} fragments: ${i}`),c}return r}waitForCdnTuneIn(e){return e.live&&e.canBlockReload&&e.partTarget&&e.tuneInGoal>Math.max(e.partHoldBack,e.partTarget*3)}setStartPosition(e,t){let s=this.startPosition;s<t&&(s=-1);const i=this.timelineOffset;if(s===-1){const r=this.startTimeOffset!==null,a=r?this.startTimeOffset:e.startTimeOffset;a!==null&&M(a)?(s=t+a,a<0&&(s+=e.edge),s=Math.min(Math.max(t,s),t+e.totalduration),this.log(`Setting startPosition to ${s} for start time offset ${a} found in ${r?"multivariant":"media"} playlist`),this.startPosition=s):e.live?(s=this.hls.liveSyncPosition||t,this.log(`Setting startPosition to -1 to start at live edge ${s}`),this.startPosition=-1):(this.log("setting startPosition to 0 by default"),this.startPosition=s=0),this.lastCurrentTime=s+i}this.nextLoadPosition=s+i}getLoadPosition(){var e;const{media:t}=this;let s=0;return(e=this.hls)!=null&&e.hasEnoughToStart&&t?s=t.currentTime:this.nextLoadPosition>=0&&(s=this.nextLoadPosition),s}handleFragLoadAborted(e,t){this.transmuxer&&e.type===this.playlistType&&de(e)&&e.stats.aborted&&(this.log(`Fragment ${e.sn}${t?" part "+t.index:""} of ${this.playlistLabel()} ${e.level} was aborted`),this.resetFragmentLoading(e))}resetFragmentLoading(e){(!this.fragCurrent||!this.fragContextChanged(e)&&this.state!==P.FRAG_LOADING_WAITING_RETRY)&&(this.state=P.IDLE)}onFragmentOrKeyLoadError(e,t){var s;if(t.chunkMeta&&!t.frag){const E=this.getCurrentContext(t.chunkMeta);E&&(t.frag=E.frag)}const i=t.frag;if(!i||i.type!==e||!this.levels)return;if(this.fragContextChanged(i)){var r;this.warn(`Frag load error must match current frag to retry ${i.url} > ${(r=this.fragCurrent)==null?void 0:r.url}`);return}const a=t.details===R.FRAG_GAP;a&&this.fragmentTracker.fragBuffered(i,!0);const o=t.errorAction;if(!o){this.state=P.ERROR;return}const{action:c,flags:l,retryCount:h=0,retryConfig:u}=o,d=!!u,f=d&&c===Ee.RetryRequest,g=d&&!o.resolved&&l===Re.MoveAllAlternatesMatchingHost,p=(s=this.hls.latestLevelDetails)==null?void 0:s.live;if(!f&&g&&de(i)&&!i.endList&&p&&!Ua(t))this.resetFragmentErrors(e),this.treatAsGap(i),o.resolved=!0;else if((f||g)&&h<u.maxNumRetry){var y;const E=Ri((y=t.response)==null?void 0:y.code),T=Qi(u,h);if(this.resetStartWhenNotLoaded(),this.retryDate=self.performance.now()+T,this.state=P.FRAG_LOADING_WAITING_RETRY,o.resolved=!0,E){this.log("Waiting for connection (offline)"),this.retryDate=1/0,t.reason="offline";return}this.warn(`Fragment ${i.sn} of ${e} ${i.level} errored with ${t.details}, retrying loading ${h+1}/${u.maxNumRetry} in ${T}ms`)}else if(u)if(this.resetFragmentErrors(e),h<u.maxNumRetry)!a&&c!==Ee.RemoveAlternatePermanently&&(o.resolved=!0);else{this.warn(`${t.details} reached or exceeded max retry (${h})`);return}else c===Ee.SendAlternateToPenaltyBox?this.state=P.WAITING_LEVEL:this.state=P.ERROR;this.tickImmediate()}checkRetryDate(){const e=self.performance.now(),t=this.retryDate,s=t===1/0;(!t||e>=t||s&&!Ri(0))&&(s&&this.log("Connection restored (online)"),this.resetStartWhenNotLoaded(),this.state=P.IDLE)}reduceLengthAndFlushBuffer(e){if(this.state===P.PARSING||this.state===P.PARSED){const t=e.frag,s=e.parent,i=this.getFwdBufferInfo(this.mediaBuffer,s),r=i&&i.len>.5;r&&this.reduceMaxBufferLength(i.len,(t==null?void 0:t.duration)||10);const a=!r;return a&&this.warn(`Buffer full error while media.currentTime (${this.getLoadPosition()}) is not buffered, flush ${s} buffer`),t&&(this.fragmentTracker.removeFragment(t),this.nextLoadPosition=t.start),this.resetLoadingState(),a}return!1}resetFragmentErrors(e){e===U.AUDIO&&(this.fragCurrent=null),this.hls.hasEnoughToStart||(this.startFragRequested=!1),this.state!==P.STOPPED&&(this.state=P.IDLE)}afterBufferFlushed(e,t,s){if(!e)return;const i=q.getBuffered(e);this.fragmentTracker.detectEvictedFragments(t,i,s),this.state===P.ENDED&&this.resetLoadingState()}resetLoadingState(){this.log("Reset loading state"),this.fragCurrent=null,this.fragPrevious=null,this.state!==P.STOPPED&&(this.state=P.IDLE)}resetStartWhenNotLoaded(){if(!this.hls.hasEnoughToStart){this.startFragRequested=!1;const e=this.levelLastLoaded,t=e?e.details:null;t!=null&&t.live?(this.log("resetting startPosition for live start"),this.startPosition=-1,this.setStartPosition(t,t.fragmentStart),this.resetLoadingState()):this.nextLoadPosition=this.startPosition}}resetWhenMissingContext(e){this.log(`Loading context changed while buffering sn ${e.sn} of ${this.playlistLabel()} ${e.level===-1?"<removed>":e.level}. This chunk will not be buffered.`),this.removeUnbufferedFrags(),this.resetStartWhenNotLoaded(),this.resetLoadingState()}removeUnbufferedFrags(e=0){this.fragmentTracker.removeFragmentsInRange(e,1/0,this.playlistType,!1,!0)}updateLevelTiming(e,t,s,i){const r=s.details;if(!r){this.warn("level.details undefined");return}if(!Object.keys(e.elementaryStreams).reduce((c,l)=>{const h=e.elementaryStreams[l];if(h){const u=h.endPTS-h.startPTS;if(u<=0)return this.warn(`Could not parse fragment ${e.sn} ${l} duration reliably (${u})`),c||!1;const d=i?0:ja(r,e,h.startPTS,h.endPTS,h.startDTS,h.endDTS,this);return this.hls.trigger(m.LEVEL_PTS_UPDATED,{details:r,level:s,drift:d,type:l,frag:e,start:h.startPTS,end:h.endPTS}),!0}return c},!1)){var o;const c=((o=this.transmuxer)==null?void 0:o.error)===null;if((s.fragmentError===0||c&&(s.fragmentError<2||e.endList))&&this.treatAsGap(e,s),c){const l=new Error(`Found no media in fragment ${e.sn} of ${this.playlistLabel()} ${e.level} resetting transmuxer to fallback to playlist timing`);if(this.warn(l.message),this.hls.trigger(m.ERROR,{type:H.MEDIA_ERROR,details:R.FRAG_PARSING_ERROR,fatal:!1,error:l,frag:e,reason:`Found no media in msn ${e.sn} of ${this.playlistLabel()} "${s.url}"`}),!this.hls)return;this.resetTransmuxer()}}this.state=P.PARSED,this.log(`Parsed ${e.type} sn: ${e.sn}${t?" part: "+t.index:""} of ${this.fragInfo(e,!1,t)})`),this.hls.trigger(m.FRAG_PARSED,{frag:e,part:t})}playlistLabel(){return this.playlistType===U.MAIN?"level":"track"}fragInfo(e,t=!0,s){var i,r;return`${this.playlistLabel()} ${e.level} (${s?"part":"frag"}:[${((i=t&&!s?e.startPTS:(s||e).start)!=null?i:NaN).toFixed(3)}-${((r=t&&!s?e.endPTS:(s||e).end)!=null?r:NaN).toFixed(3)}]${s&&e.type==="main"?"INDEPENDENT="+(s.independent?"YES":"NO"):""}`}treatAsGap(e,t){t&&t.fragmentError++,e.gap=!0,this.fragmentTracker.removeFragment(e),this.fragmentTracker.fragBuffered(e,!0)}resetTransmuxer(){var e;(e=this.transmuxer)==null||e.reset()}recoverWorkerError(e){e.event==="demuxerWorker"&&(this.fragmentTracker.removeAllFragments(),this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null),this.resetStartWhenNotLoaded(),this.resetLoadingState())}set state(e){const t=this._state;t!==e&&(this._state=e,this.log(`${t}->${e}`))}get state(){return this._state}}function vn(n){return!!n.interstitialsController&&n.enableInterstitialPlayback!==!1}class so{constructor(){this.chunks=[],this.dataLength=0}push(e){this.chunks.push(e),this.dataLength+=e.length}flush(){const{chunks:e,dataLength:t}=this;let s;if(e.length)e.length===1?s=e[0]:s=vh(e,t);else return new Uint8Array(0);return this.reset(),s}reset(){this.chunks.length=0,this.dataLength=0}}function vh(n,e){const t=new Uint8Array(e);let s=0;for(let i=0;i<n.length;i++){const r=n[i];t.set(r,s),s+=r.length}return t}var ei={exports:{}},xn;function xh(){return xn||(xn=1,function(n){var e=Object.prototype.hasOwnProperty,t="~";function s(){}Object.create&&(s.prototype=Object.create(null),new s().__proto__||(t=!1));function i(c,l,h){this.fn=c,this.context=l,this.once=h||!1}function r(c,l,h,u,d){if(typeof h!="function")throw new TypeError("The listener must be a function");var f=new i(h,u||c,d),g=t?t+l:l;return c._events[g]?c._events[g].fn?c._events[g]=[c._events[g],f]:c._events[g].push(f):(c._events[g]=f,c._eventsCount++),c}function a(c,l){--c._eventsCount===0?c._events=new s:delete c._events[l]}function o(){this._events=new s,this._eventsCount=0}o.prototype.eventNames=function(){var l=[],h,u;if(this._eventsCount===0)return l;for(u in h=this._events)e.call(h,u)&&l.push(t?u.slice(1):u);return Object.getOwnPropertySymbols?l.concat(Object.getOwnPropertySymbols(h)):l},o.prototype.listeners=function(l){var h=t?t+l:l,u=this._events[h];if(!u)return[];if(u.fn)return[u.fn];for(var d=0,f=u.length,g=new Array(f);d<f;d++)g[d]=u[d].fn;return g},o.prototype.listenerCount=function(l){var h=t?t+l:l,u=this._events[h];return u?u.fn?1:u.length:0},o.prototype.emit=function(l,h,u,d,f,g){var p=t?t+l:l;if(!this._events[p])return!1;var y=this._events[p],E=arguments.length,T,S;if(y.fn){switch(y.once&&this.removeListener(l,y.fn,void 0,!0),E){case 1:return y.fn.call(y.context),!0;case 2:return y.fn.call(y.context,h),!0;case 3:return y.fn.call(y.context,h,u),!0;case 4:return y.fn.call(y.context,h,u,d),!0;case 5:return y.fn.call(y.context,h,u,d,f),!0;case 6:return y.fn.call(y.context,h,u,d,f,g),!0}for(S=1,T=new Array(E-1);S<E;S++)T[S-1]=arguments[S];y.fn.apply(y.context,T)}else{var v=y.length,x;for(S=0;S<v;S++)switch(y[S].once&&this.removeListener(l,y[S].fn,void 0,!0),E){case 1:y[S].fn.call(y[S].context);break;case 2:y[S].fn.call(y[S].context,h);break;case 3:y[S].fn.call(y[S].context,h,u);break;case 4:y[S].fn.call(y[S].context,h,u,d);break;default:if(!T)for(x=1,T=new Array(E-1);x<E;x++)T[x-1]=arguments[x];y[S].fn.apply(y[S].context,T)}}return!0},o.prototype.on=function(l,h,u){return r(this,l,h,u,!1)},o.prototype.once=function(l,h,u){return r(this,l,h,u,!0)},o.prototype.removeListener=function(l,h,u,d){var f=t?t+l:l;if(!this._events[f])return this;if(!h)return a(this,f),this;var g=this._events[f];if(g.fn)g.fn===h&&(!d||g.once)&&(!u||g.context===u)&&a(this,f);else{for(var p=0,y=[],E=g.length;p<E;p++)(g[p].fn!==h||d&&!g[p].once||u&&g[p].context!==u)&&y.push(g[p]);y.length?this._events[f]=y.length===1?y[0]:y:a(this,f)}return this},o.prototype.removeAllListeners=function(l){var h;return l?(h=t?t+l:l,this._events[h]&&a(this,h)):(this._events=new s,this._eventsCount=0),this},o.prototype.off=o.prototype.removeListener,o.prototype.addListener=o.prototype.on,o.prefixed=t,o.EventEmitter=o,n.exports=o}(ei)),ei.exports}var Ah=xh(),ir=jl(Ah);const Vt="1.6.15",Pt={};function _h(){return typeof __HLS_WORKER_BUNDLE__=="function"}function Ih(){const n=Pt[Vt];if(n)return n.clientCount++,n;const e=new self.Blob([`var exports={};var module={exports:exports};function define(f){f()};define.amd=true;(${__HLS_WORKER_BUNDLE__.toString()})(true);`],{type:"text/javascript"}),t=self.URL.createObjectURL(e),i={worker:new self.Worker(t),objectURL:t,clientCount:1};return Pt[Vt]=i,i}function Lh(n){const e=Pt[n];if(e)return e.clientCount++,e;const t=new self.URL(n,self.location.href).href,i={worker:new self.Worker(t),scriptURL:t,clientCount:1};return Pt[n]=i,i}function Rh(n){const e=Pt[n||Vt];if(e&&e.clientCount--===1){const{worker:s,objectURL:i}=e;delete Pt[n||Vt],i&&self.URL.revokeObjectURL(i),s.terminate()}}function io(n,e){return e+10<=n.length&&n[e]===51&&n[e+1]===68&&n[e+2]===73&&n[e+3]<255&&n[e+4]<255&&n[e+6]<128&&n[e+7]<128&&n[e+8]<128&&n[e+9]<128}function rr(n,e){return e+10<=n.length&&n[e]===73&&n[e+1]===68&&n[e+2]===51&&n[e+3]<255&&n[e+4]<255&&n[e+6]<128&&n[e+7]<128&&n[e+8]<128&&n[e+9]<128}function Ks(n,e){let t=0;return t=(n[e]&127)<<21,t|=(n[e+1]&127)<<14,t|=(n[e+2]&127)<<7,t|=n[e+3]&127,t}function Ht(n,e){const t=e;let s=0;for(;rr(n,e);){s+=10;const i=Ks(n,e+6);s+=i,io(n,e+10)&&(s+=10),e+=s}if(s>0)return n.subarray(t,t+s)}function bh(n,e,t,s){const i=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],r=e[t+2],a=r>>2&15;if(a>12){const f=new Error(`invalid ADTS sampling index:${a}`);n.emit(m.ERROR,m.ERROR,{type:H.MEDIA_ERROR,details:R.FRAG_PARSING_ERROR,fatal:!0,error:f,reason:f.message});return}const o=(r>>6&3)+1,c=e[t+3]>>6&3|(r&1)<<2,l="mp4a.40."+o,h=i[a];let u=a;(o===5||o===29)&&(u-=3);const d=[o<<3|(u&14)>>1,(u&1)<<7|c<<3];return ie.log(`manifest codec:${s}, parsed codec:${l}, channels:${c}, rate:${h} (ADTS object type:${o} sampling index:${a})`),{config:d,samplerate:h,channelCount:c,codec:l,parsedCodec:l,manifestCodec:s}}function ro(n,e){return n[e]===255&&(n[e+1]&246)===240}function no(n,e){return n[e+1]&1?7:9}function nr(n,e){return(n[e+3]&3)<<11|n[e+4]<<3|(n[e+5]&224)>>>5}function Dh(n,e){return e+5<n.length}function Ns(n,e){return e+1<n.length&&ro(n,e)}function Ch(n,e){return Dh(n,e)&&ro(n,e)&&nr(n,e)<=n.length-e}function Ph(n,e){if(Ns(n,e)){const t=no(n,e);if(e+t>=n.length)return!1;const s=nr(n,e);if(s<=t)return!1;const i=e+s;return i===n.length||Ns(n,i)}return!1}function ao(n,e,t,s,i){if(!n.samplerate){const r=bh(e,t,s,i);if(!r)return;re(n,r)}}function oo(n){return 1024*9e4/n}function kh(n,e){const t=no(n,e);if(e+t<=n.length){const s=nr(n,e)-t;if(s>0)return{headerLength:t,frameLength:s}}}function lo(n,e,t,s,i){const r=oo(n.samplerate),a=s+i*r,o=kh(e,t);let c;if(o){const{frameLength:u,headerLength:d}=o,f=d+u,g=Math.max(0,t+f-e.length);g?(c=new Uint8Array(f-d),c.set(e.subarray(t+d,e.length),0)):c=e.subarray(t+d,t+f);const p={unit:c,pts:a};return g||n.samples.push(p),{sample:p,length:f,missing:g}}const l=e.length-t;return c=new Uint8Array(l),c.set(e.subarray(t,e.length),0),{sample:{unit:c,pts:a},length:l,missing:-1}}function wh(n,e){return rr(n,e)&&Ks(n,e+6)+10<=n.length-e}function Oh(n){return n instanceof ArrayBuffer?n:n.byteOffset==0&&n.byteLength==n.buffer.byteLength?n.buffer:new Uint8Array(n).buffer}function ti(n,e=0,t=1/0){return Fh(n,e,t,Uint8Array)}function Fh(n,e,t,s){const i=Mh(n);let r=1;"BYTES_PER_ELEMENT"in s&&(r=s.BYTES_PER_ELEMENT);const a=Nh(n)?n.byteOffset:0,o=(a+n.byteLength)/r,c=(a+e)/r,l=Math.floor(Math.max(0,Math.min(c,o))),h=Math.floor(Math.min(l+Math.max(t,0),o));return new s(i,l,h-l)}function Mh(n){return n instanceof ArrayBuffer?n:n.buffer}function Nh(n){return n&&n.buffer instanceof ArrayBuffer&&n.byteLength!==void 0&&n.byteOffset!==void 0}function Bh(n){const e={key:n.type,description:"",data:"",mimeType:null,pictureType:null},t=3;if(n.size<2)return;if(n.data[0]!==t){console.log("Ignore frame with unrecognized character encoding");return}const s=n.data.subarray(1).indexOf(0);if(s===-1)return;const i=Ce(ti(n.data,1,s)),r=n.data[2+s],a=n.data.subarray(3+s).indexOf(0);if(a===-1)return;const o=Ce(ti(n.data,3+s,a));let c;return i==="-->"?c=Ce(ti(n.data,4+s+a)):c=Oh(n.data.subarray(4+s+a)),e.mimeType=i,e.pictureType=r,e.description=o,e.data=c,e}function Uh(n){if(n.size<2)return;const e=Ce(n.data,!0),t=new Uint8Array(n.data.subarray(e.length+1));return{key:n.type,info:e,data:t.buffer}}function $h(n){if(n.size<2)return;if(n.type==="TXXX"){let t=1;const s=Ce(n.data.subarray(t),!0);t+=s.length+1;const i=Ce(n.data.subarray(t));return{key:n.type,info:s,data:i}}const e=Ce(n.data.subarray(1));return{key:n.type,info:"",data:e}}function Gh(n){if(n.type==="WXXX"){if(n.size<2)return;let t=1;const s=Ce(n.data.subarray(t),!0);t+=s.length+1;const i=Ce(n.data.subarray(t));return{key:n.type,info:s,data:i}}const e=Ce(n.data);return{key:n.type,info:"",data:e}}function Kh(n){return n.type==="PRIV"?Uh(n):n.type[0]==="W"?Gh(n):n.type==="APIC"?Bh(n):$h(n)}function Vh(n){const e=String.fromCharCode(n[0],n[1],n[2],n[3]),t=Ks(n,4),s=10;return{type:e,size:t,data:n.subarray(s,s+t)}}const ts=10,Hh=10;function co(n){let e=0;const t=[];for(;rr(n,e);){const s=Ks(n,e+6);n[e+5]>>6&1&&(e+=ts),e+=ts;const i=e+s;for(;e+Hh<i;){const r=Vh(n.subarray(e)),a=Kh(r);a&&t.push(a),e+=r.size+ts}io(n,e)&&(e+=ts)}return t}function ho(n){return n&&n.key==="PRIV"&&n.info==="com.apple.streaming.transportStreamTimestamp"}function Wh(n){if(n.data.byteLength===8){const e=new Uint8Array(n.data),t=e[3]&1;let s=(e[4]<<23)+(e[5]<<15)+(e[6]<<7)+e[7];return s/=45,t&&(s+=4772185884e-2),Math.round(s)}}function ar(n){const e=co(n);for(let t=0;t<e.length;t++){const s=e[t];if(ho(s))return Wh(s)}}let De=function(n){return n.audioId3="org.id3",n.dateRange="com.apple.quicktime.HLS",n.emsg="https://aomedia.org/emsg/ID3",n.misbklv="urn:misb:KLV:bin:1910.1",n}({});function Ve(n="",e=9e4){return{type:n,id:-1,pid:-1,inputTimeScale:e,sequenceNumber:-1,samples:[],dropped:0}}class or{constructor(){this._audioTrack=void 0,this._id3Track=void 0,this.frameIndex=0,this.cachedData=null,this.basePTS=null,this.initPTS=null,this.lastPTS=null}resetInitSegment(e,t,s,i){this._id3Track={type:"id3",id:3,pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0}}resetTimeStamp(e){this.initPTS=e,this.resetContiguity()}resetContiguity(){this.basePTS=null,this.lastPTS=null,this.frameIndex=0}canParse(e,t){return!1}appendFrame(e,t,s){}demux(e,t){this.cachedData&&(e=Oe(this.cachedData,e),this.cachedData=null);let s=Ht(e,0),i=s?s.length:0,r;const a=this._audioTrack,o=this._id3Track,c=s?ar(s):void 0,l=e.length;for((this.basePTS===null||this.frameIndex===0&&M(c))&&(this.basePTS=Yh(c,t,this.initPTS),this.lastPTS=this.basePTS),this.lastPTS===null&&(this.lastPTS=this.basePTS),s&&s.length>0&&o.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:s,type:De.audioId3,duration:Number.POSITIVE_INFINITY});i<l;){if(this.canParse(e,i)){const h=this.appendFrame(a,e,i);h?(this.frameIndex++,this.lastPTS=h.sample.pts,i+=h.length,r=i):i=l}else wh(e,i)?(s=Ht(e,i),o.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:s,type:De.audioId3,duration:Number.POSITIVE_INFINITY}),i+=s.length,r=i):i++;if(i===l&&r!==l){const h=e.slice(r);this.cachedData?this.cachedData=Oe(this.cachedData,h):this.cachedData=h}}return{audioTrack:a,videoTrack:Ve(),id3Track:o,textTrack:Ve()}}demuxSampleAes(e,t,s){return Promise.reject(new Error(`[${this}] This demuxer does not support Sample-AES decryption`))}flush(e){const t=this.cachedData;return t&&(this.cachedData=null,this.demux(t,0)),{audioTrack:this._audioTrack,videoTrack:Ve(),id3Track:this._id3Track,textTrack:Ve()}}destroy(){this.cachedData=null,this._audioTrack=this._id3Track=void 0}}const Yh=(n,e,t)=>{if(M(n))return n*90;const s=t?t.baseTime*9e4/t.timescale:0;return e*9e4+s};let ss=null;const qh=[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],jh=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],Xh=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],zh=[0,1,1,4];function uo(n,e,t,s,i){if(t+24>e.length)return;const r=fo(e,t);if(r&&t+r.frameLength<=e.length){const a=r.samplesPerFrame*9e4/r.sampleRate,o=s+i*a,c={unit:e.subarray(t,t+r.frameLength),pts:o,dts:o};return n.config=[],n.channelCount=r.channelCount,n.samplerate=r.sampleRate,n.samples.push(c),{sample:c,length:r.frameLength,missing:0}}}function fo(n,e){const t=n[e+1]>>3&3,s=n[e+1]>>1&3,i=n[e+2]>>4&15,r=n[e+2]>>2&3;if(t!==1&&i!==0&&i!==15&&r!==3){const a=n[e+2]>>1&1,o=n[e+3]>>6,c=t===3?3-s:s===3?3:4,l=qh[c*14+i-1]*1e3,u=jh[(t===3?0:t===2?1:2)*3+r],d=o===3?1:2,f=Xh[t][s],g=zh[s],p=f*8*g,y=Math.floor(f*l/u+a)*g;if(ss===null){const S=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);ss=S?parseInt(S[1]):0}return!!ss&&ss<=87&&s===2&&l>=224e3&&o===0&&(n[e+3]=n[e+3]|128),{sampleRate:u,channelCount:d,frameLength:y,samplesPerFrame:p}}}function lr(n,e){return n[e]===255&&(n[e+1]&224)===224&&(n[e+1]&6)!==0}function go(n,e){return e+1<n.length&&lr(n,e)}function Qh(n,e){return lr(n,e)&&4<=n.length-e}function mo(n,e){if(e+1<n.length&&lr(n,e)){const s=fo(n,e);let i=4;s!=null&&s.frameLength&&(i=s.frameLength);const r=e+i;return r===n.length||go(n,r)}return!1}class Zh extends or{constructor(e,t){super(),this.observer=void 0,this.config=void 0,this.observer=e,this.config=t}resetInitSegment(e,t,s,i){super.resetInitSegment(e,t,s,i),this._audioTrack={container:"audio/adts",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"aac",samples:[],manifestCodec:t,duration:i,inputTimeScale:9e4,dropped:0}}static probe(e,t){if(!e)return!1;const s=Ht(e,0);let i=(s==null?void 0:s.length)||0;if(mo(e,i))return!1;for(let r=e.length;i<r;i++)if(Ph(e,i))return t.log("ADTS sync word found !"),!0;return!1}canParse(e,t){return Ch(e,t)}appendFrame(e,t,s){ao(e,this.observer,t,s,e.manifestCodec);const i=lo(e,t,s,this.basePTS,this.frameIndex);if(i&&i.missing===0)return i}}const po=(n,e)=>{let t=0,s=5;e+=s;const i=new Uint32Array(1),r=new Uint32Array(1),a=new Uint8Array(1);for(;s>0;){a[0]=n[e];const o=Math.min(s,8),c=8-o;r[0]=4278190080>>>24+c<<c,i[0]=(a[0]&r[0])>>c,t=t?t<<o|i[0]:i[0],e+=1,s-=o}return t};class Jh extends or{constructor(e){super(),this.observer=void 0,this.observer=e}resetInitSegment(e,t,s,i){super.resetInitSegment(e,t,s,i),this._audioTrack={container:"audio/ac-3",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"ac3",samples:[],manifestCodec:t,duration:i,inputTimeScale:9e4,dropped:0}}canParse(e,t){return t+64<e.length}appendFrame(e,t,s){const i=yo(e,t,s,this.basePTS,this.frameIndex);if(i!==-1)return{sample:e.samples[e.samples.length-1],length:i,missing:0}}static probe(e){if(!e)return!1;const t=Ht(e,0);if(!t)return!1;const s=t.length;return e[s]===11&&e[s+1]===119&&ar(t)!==void 0&&po(e,s)<16}}function yo(n,e,t,s,i){if(t+8>e.length||e[t]!==11||e[t+1]!==119)return-1;const r=e[t+4]>>6;if(r>=3)return-1;const o=[48e3,44100,32e3][r],c=e[t+4]&63,h=[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][c*3+r]*2;if(t+h>e.length)return-1;const u=e[t+6]>>5;let d=0;u===2?d+=2:(u&1&&u!==1&&(d+=2),u&4&&(d+=2));const f=(e[t+6]<<8|e[t+7])>>12-d&1,p=[2,1,2,3,3,4,4,5][u]+f,y=e[t+5]>>3,E=e[t+5]&7,T=new Uint8Array([r<<6|y<<1|E>>2,(E&3)<<6|u<<3|f<<2|c>>4,c<<4&224]),S=1536/o*9e4,v=s+i*S,x=e.subarray(t,t+h);return n.config=T,n.channelCount=p,n.samplerate=o,n.samples.push({unit:x,pts:v}),h}class eu extends or{resetInitSegment(e,t,s,i){super.resetInitSegment(e,t,s,i),this._audioTrack={container:"audio/mpeg",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"mp3",samples:[],manifestCodec:t,duration:i,inputTimeScale:9e4,dropped:0}}static probe(e){if(!e)return!1;const t=Ht(e,0);let s=(t==null?void 0:t.length)||0;if(t&&e[s]===11&&e[s+1]===119&&ar(t)!==void 0&&po(e,s)<=16)return!1;for(let i=e.length;s<i;s++)if(mo(e,s))return ie.log("MPEG Audio sync word found !"),!0;return!1}canParse(e,t){return Qh(e,t)}appendFrame(e,t,s){if(this.basePTS!==null)return uo(e,t,s,this.basePTS,this.frameIndex)}}const tu=/\/emsg[-/]ID3/i;class su{constructor(e,t){this.remainderData=null,this.timeOffset=0,this.config=void 0,this.videoTrack=void 0,this.audioTrack=void 0,this.id3Track=void 0,this.txtTrack=void 0,this.config=t}resetTimeStamp(){}resetInitSegment(e,t,s,i){const r=this.videoTrack=Ve("video",1),a=this.audioTrack=Ve("audio",1),o=this.txtTrack=Ve("text",1);if(this.id3Track=Ve("id3",1),this.timeOffset=0,!(e!=null&&e.byteLength))return;const c=La(e);if(c.video){const{id:l,timescale:h,codec:u,supplemental:d}=c.video;r.id=l,r.timescale=o.timescale=h,r.codec=u,r.supplemental=d}if(c.audio){const{id:l,timescale:h,codec:u}=c.audio;a.id=l,a.timescale=h,a.codec=u}o.id=Aa.text,r.sampleDuration=0,r.duration=a.duration=i}resetContiguity(){this.remainderData=null}static probe(e){return Jl(e)}demux(e,t){this.timeOffset=t;let s=e;const i=this.videoTrack,r=this.txtTrack;if(this.config.progressive){this.remainderData&&(s=Oe(this.remainderData,e));const o=ac(s);this.remainderData=o.remainder,i.samples=o.valid||new Uint8Array}else i.samples=s;const a=this.extractID3Track(i,t);return r.samples=Ur(t,i),{videoTrack:i,audioTrack:this.audioTrack,id3Track:a,textTrack:this.txtTrack}}flush(){const e=this.timeOffset,t=this.videoTrack,s=this.txtTrack;t.samples=this.remainderData||new Uint8Array,this.remainderData=null;const i=this.extractID3Track(t,this.timeOffset);return s.samples=Ur(e,t),{videoTrack:t,audioTrack:Ve(),id3Track:i,textTrack:Ve()}}extractID3Track(e,t){const s=this.id3Track;if(e.samples.length){const i=z(e.samples,["emsg"]);i&&i.forEach(r=>{const a=lc(r);if(tu.test(a.schemeIdUri)){const o=An(a,t);let c=a.eventDuration===4294967295?Number.POSITIVE_INFINITY:a.eventDuration/a.timeScale;c<=.001&&(c=Number.POSITIVE_INFINITY);const l=a.payload;s.samples.push({data:l,len:l.byteLength,dts:o,pts:o,type:De.emsg,duration:c})}else if(this.config.enableEmsgKLVMetadata&&a.schemeIdUri.startsWith("urn:misb:KLV:bin:1910.1")){const o=An(a,t);s.samples.push({data:a.payload,len:a.payload.byteLength,dts:o,pts:o,type:De.misbklv,duration:Number.POSITIVE_INFINITY})}})}return s}demuxSampleAes(e,t,s){return Promise.reject(new Error("The MP4 demuxer does not support SAMPLE-AES decryption"))}destroy(){this.config=null,this.remainderData=null,this.videoTrack=this.audioTrack=this.id3Track=this.txtTrack=void 0}}function An(n,e){return M(n.presentationTime)?n.presentationTime/n.timeScale:e+n.presentationTimeDelta/n.timeScale}class iu{constructor(e,t,s){this.keyData=void 0,this.decrypter=void 0,this.keyData=s,this.decrypter=new Zi(t,{removePKCS7Padding:!1})}decryptBuffer(e){return this.decrypter.decrypt(e,this.keyData.key.buffer,this.keyData.iv.buffer,ot.cbc)}decryptAacSample(e,t,s){const i=e[t].unit;if(i.length<=16)return;const r=i.subarray(16,i.length-i.length%16),a=r.buffer.slice(r.byteOffset,r.byteOffset+r.length);this.decryptBuffer(a).then(o=>{const c=new Uint8Array(o);i.set(c,16),this.decrypter.isSync()||this.decryptAacSamples(e,t+1,s)}).catch(s)}decryptAacSamples(e,t,s){for(;;t++){if(t>=e.length){s();return}if(!(e[t].unit.length<32)&&(this.decryptAacSample(e,t,s),!this.decrypter.isSync()))return}}getAvcEncryptedData(e){const t=Math.floor((e.length-48)/160)*16+16,s=new Int8Array(t);let i=0;for(let r=32;r<e.length-16;r+=160,i+=16)s.set(e.subarray(r,r+16),i);return s}getAvcDecryptedUnit(e,t){const s=new Uint8Array(t);let i=0;for(let r=32;r<e.length-16;r+=160,i+=16)e.set(s.subarray(i,i+16),r);return e}decryptAvcSample(e,t,s,i,r){const a=Da(r.data),o=this.getAvcEncryptedData(a);this.decryptBuffer(o.buffer).then(c=>{r.data=this.getAvcDecryptedUnit(a,c),this.decrypter.isSync()||this.decryptAvcSamples(e,t,s+1,i)}).catch(i)}decryptAvcSamples(e,t,s,i){if(e instanceof Uint8Array)throw new Error("Cannot decrypt samples of type Uint8Array");for(;;t++,s=0){if(t>=e.length){i();return}const r=e[t].units;for(;!(s>=r.length);s++){const a=r[s];if(!(a.data.length<=48||a.type!==1&&a.type!==5)&&(this.decryptAvcSample(e,t,s,i,a),!this.decrypter.isSync()))return}}}}class Eo{constructor(){this.VideoSample=null}createVideoSample(e,t,s){return{key:e,frame:!1,pts:t,dts:s,units:[],length:0}}getLastNalUnit(e){var t;let s=this.VideoSample,i;if((!s||s.units.length===0)&&(s=e[e.length-1]),(t=s)!=null&&t.units){const r=s.units;i=r[r.length-1]}return i}pushAccessUnit(e,t){if(e.units.length&&e.frame){if(e.pts===void 0){const s=t.samples,i=s.length;if(i){const r=s[i-1];e.pts=r.pts,e.dts=r.dts}else{t.dropped++;return}}t.samples.push(e)}}parseNALu(e,t,s){const i=t.byteLength;let r=e.naluState||0;const a=r,o=[];let c=0,l,h,u,d=-1,f=0;for(r===-1&&(d=0,f=this.getNALuType(t,0),r=0,c=1);c<i;){if(l=t[c++],!r){r=l?0:1;continue}if(r===1){r=l?0:2;continue}if(!l)r=3;else if(l===1){if(h=c-r-1,d>=0){const g={data:t.subarray(d,h),type:f};o.push(g)}else{const g=this.getLastNalUnit(e.samples);g&&(a&&c<=4-a&&g.state&&(g.data=g.data.subarray(0,g.data.byteLength-a)),h>0&&(g.data=Oe(g.data,t.subarray(0,h)),g.state=0))}c<i?(u=this.getNALuType(t,c),d=c,f=u,r=0):r=-1}else r=0}if(d>=0&&r>=0){const g={data:t.subarray(d,i),type:f,state:r};o.push(g)}if(o.length===0){const g=this.getLastNalUnit(e.samples);g&&(g.data=Oe(g.data,t))}return e.naluState=r,o}}class Bt{constructor(e){this.data=void 0,this.bytesAvailable=void 0,this.word=void 0,this.bitsAvailable=void 0,this.data=e,this.bytesAvailable=e.byteLength,this.word=0,this.bitsAvailable=0}loadWord(){const e=this.data,t=this.bytesAvailable,s=e.byteLength-t,i=new Uint8Array(4),r=Math.min(4,t);if(r===0)throw new Error("no bytes available");i.set(e.subarray(s,s+r)),this.word=new DataView(i.buffer).getUint32(0),this.bitsAvailable=r*8,this.bytesAvailable-=r}skipBits(e){let t;e=Math.min(e,this.bytesAvailable*8+this.bitsAvailable),this.bitsAvailable>e?(this.word<<=e,this.bitsAvailable-=e):(e-=this.bitsAvailable,t=e>>3,e-=t<<3,this.bytesAvailable-=t,this.loadWord(),this.word<<=e,this.bitsAvailable-=e)}readBits(e){let t=Math.min(this.bitsAvailable,e);const s=this.word>>>32-t;if(e>32&&ie.error("Cannot read more than 32 bits at a time"),this.bitsAvailable-=t,this.bitsAvailable>0)this.word<<=t;else if(this.bytesAvailable>0)this.loadWord();else throw new Error("no bits available");return t=e-t,t>0&&this.bitsAvailable?s<<t|this.readBits(t):s}skipLZ(){let e;for(e=0;e<this.bitsAvailable;++e)if(this.word&2147483648>>>e)return this.word<<=e,this.bitsAvailable-=e,e;return this.loadWord(),e+this.skipLZ()}skipUEG(){this.skipBits(1+this.skipLZ())}skipEG(){this.skipBits(1+this.skipLZ())}readUEG(){const e=this.skipLZ();return this.readBits(e+1)-1}readEG(){const e=this.readUEG();return 1&e?1+e>>>1:-1*(e>>>1)}readBoolean(){return this.readBits(1)===1}readUByte(){return this.readBits(8)}readUShort(){return this.readBits(16)}readUInt(){return this.readBits(32)}}class ru extends Eo{parsePES(e,t,s,i){const r=this.parseNALu(e,s.data,i);let a=this.VideoSample,o,c=!1;s.data=null,a&&r.length&&!e.audFound&&(this.pushAccessUnit(a,e),a=this.VideoSample=this.createVideoSample(!1,s.pts,s.dts)),r.forEach(l=>{var h,u;switch(l.type){case 1:{let p=!1;o=!0;const y=l.data;if(c&&y.length>4){const E=this.readSliceType(y);(E===2||E===4||E===7||E===9)&&(p=!0)}if(p){var d;(d=a)!=null&&d.frame&&!a.key&&(this.pushAccessUnit(a,e),a=this.VideoSample=null)}a||(a=this.VideoSample=this.createVideoSample(!0,s.pts,s.dts)),a.frame=!0,a.key=p;break}case 5:o=!0,(h=a)!=null&&h.frame&&!a.key&&(this.pushAccessUnit(a,e),a=this.VideoSample=null),a||(a=this.VideoSample=this.createVideoSample(!0,s.pts,s.dts)),a.key=!0,a.frame=!0;break;case 6:{o=!0,ji(l.data,1,s.pts,t.samples);break}case 7:{var f,g;o=!0,c=!0;const p=l.data,y=this.readSPS(p);if(!e.sps||e.width!==y.width||e.height!==y.height||((f=e.pixelRatio)==null?void 0:f[0])!==y.pixelRatio[0]||((g=e.pixelRatio)==null?void 0:g[1])!==y.pixelRatio[1]){e.width=y.width,e.height=y.height,e.pixelRatio=y.pixelRatio,e.sps=[p];const E=p.subarray(1,4);let T="avc1.";for(let S=0;S<3;S++){let v=E[S].toString(16);v.length<2&&(v="0"+v),T+=v}e.codec=T}break}case 8:o=!0,e.pps=[l.data];break;case 9:o=!0,e.audFound=!0,(u=a)!=null&&u.frame&&(this.pushAccessUnit(a,e),a=null),a||(a=this.VideoSample=this.createVideoSample(!1,s.pts,s.dts));break;case 12:o=!0;break;default:o=!1;break}a&&o&&a.units.push(l)}),i&&a&&(this.pushAccessUnit(a,e),this.VideoSample=null)}getNALuType(e,t){return e[t]&31}readSliceType(e){const t=new Bt(e);return t.readUByte(),t.readUEG(),t.readUEG()}skipScalingList(e,t){let s=8,i=8,r;for(let a=0;a<e;a++)i!==0&&(r=t.readEG(),i=(s+r+256)%256),s=i===0?s:i}readSPS(e){const t=new Bt(e);let s=0,i=0,r=0,a=0,o,c,l;const h=t.readUByte.bind(t),u=t.readBits.bind(t),d=t.readUEG.bind(t),f=t.readBoolean.bind(t),g=t.skipBits.bind(t),p=t.skipEG.bind(t),y=t.skipUEG.bind(t),E=this.skipScalingList.bind(this);h();const T=h();if(u(5),g(3),h(),y(),T===100||T===110||T===122||T===244||T===44||T===83||T===86||T===118||T===128){const b=d();if(b===3&&g(1),y(),y(),g(1),f())for(c=b!==3?8:12,l=0;l<c;l++)f()&&(l<6?E(16,t):E(64,t))}y();const S=d();if(S===0)d();else if(S===1)for(g(1),p(),p(),o=d(),l=0;l<o;l++)p();y(),g(1);const v=d(),x=d(),D=u(1);D===0&&g(1),g(1),f()&&(s=d(),i=d(),r=d(),a=d());let A=[1,1];if(f()&&f())switch(h()){case 1:A=[1,1];break;case 2:A=[12,11];break;case 3:A=[10,11];break;case 4:A=[16,11];break;case 5:A=[40,33];break;case 6:A=[24,11];break;case 7:A=[20,11];break;case 8:A=[32,11];break;case 9:A=[80,33];break;case 10:A=[18,11];break;case 11:A=[15,11];break;case 12:A=[64,33];break;case 13:A=[160,99];break;case 14:A=[4,3];break;case 15:A=[3,2];break;case 16:A=[2,1];break;case 255:{A=[h()<<8|h(),h()<<8|h()];break}}return{width:Math.ceil((v+1)*16-s*2-i*2),height:(2-D)*(x+1)*16-(D?2:4)*(r+a),pixelRatio:A}}}class nu extends Eo{constructor(...e){super(...e),this.initVPS=null}parsePES(e,t,s,i){const r=this.parseNALu(e,s.data,i);let a=this.VideoSample,o,c=!1;s.data=null,a&&r.length&&!e.audFound&&(this.pushAccessUnit(a,e),a=this.VideoSample=this.createVideoSample(!1,s.pts,s.dts)),r.forEach(l=>{var h,u;switch(l.type){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:case 8:case 9:a||(a=this.VideoSample=this.createVideoSample(!1,s.pts,s.dts)),a.frame=!0,o=!0;break;case 16:case 17:case 18:case 21:if(o=!0,c){var d;(d=a)!=null&&d.frame&&!a.key&&(this.pushAccessUnit(a,e),a=this.VideoSample=null)}a||(a=this.VideoSample=this.createVideoSample(!0,s.pts,s.dts)),a.key=!0,a.frame=!0;break;case 19:case 20:o=!0,(h=a)!=null&&h.frame&&!a.key&&(this.pushAccessUnit(a,e),a=this.VideoSample=null),a||(a=this.VideoSample=this.createVideoSample(!0,s.pts,s.dts)),a.key=!0,a.frame=!0;break;case 39:o=!0,ji(l.data,2,s.pts,t.samples);break;case 32:o=!0,e.vps||(typeof e.params!="object"&&(e.params={}),e.params=re(e.params,this.readVPS(l.data)),this.initVPS=l.data),e.vps=[l.data];break;case 33:if(o=!0,c=!0,e.vps!==void 0&&e.vps[0]!==this.initVPS&&e.sps!==void 0&&!this.matchSPS(e.sps[0],l.data)&&(this.initVPS=e.vps[0],e.sps=e.pps=void 0),!e.sps){const f=this.readSPS(l.data);e.width=f.width,e.height=f.height,e.pixelRatio=f.pixelRatio,e.codec=f.codecString,e.sps=[],typeof e.params!="object"&&(e.params={});for(const g in f.params)e.params[g]=f.params[g]}this.pushParameterSet(e.sps,l.data,e.vps),a||(a=this.VideoSample=this.createVideoSample(!0,s.pts,s.dts)),a.key=!0;break;case 34:if(o=!0,typeof e.params=="object"){if(!e.pps){e.pps=[];const f=this.readPPS(l.data);for(const g in f)e.params[g]=f[g]}this.pushParameterSet(e.pps,l.data,e.vps)}break;case 35:o=!0,e.audFound=!0,(u=a)!=null&&u.frame&&(this.pushAccessUnit(a,e),a=null),a||(a=this.VideoSample=this.createVideoSample(!1,s.pts,s.dts));break;default:o=!1;break}a&&o&&a.units.push(l)}),i&&a&&(this.pushAccessUnit(a,e),this.VideoSample=null)}pushParameterSet(e,t,s){(s&&s[0]===this.initVPS||!s&&!e.length)&&e.push(t)}getNALuType(e,t){return(e[t]&126)>>>1}ebsp2rbsp(e){const t=new Uint8Array(e.byteLength);let s=0;for(let i=0;i<e.byteLength;i++)i>=2&&e[i]===3&&e[i-1]===0&&e[i-2]===0||(t[s]=e[i],s++);return new Uint8Array(t.buffer,0,s)}pushAccessUnit(e,t){super.pushAccessUnit(e,t),this.initVPS&&(this.initVPS=null)}readVPS(e){const t=new Bt(e);t.readUByte(),t.readUByte(),t.readBits(4),t.skipBits(2),t.readBits(6);const s=t.readBits(3),i=t.readBoolean();return{numTemporalLayers:s+1,temporalIdNested:i}}readSPS(e){const t=new Bt(this.ebsp2rbsp(e));t.readUByte(),t.readUByte(),t.readBits(4);const s=t.readBits(3);t.readBoolean();const i=t.readBits(2),r=t.readBoolean(),a=t.readBits(5),o=t.readUByte(),c=t.readUByte(),l=t.readUByte(),h=t.readUByte(),u=t.readUByte(),d=t.readUByte(),f=t.readUByte(),g=t.readUByte(),p=t.readUByte(),y=t.readUByte(),E=t.readUByte(),T=[],S=[];for(let ee=0;ee<s;ee++)T.push(t.readBoolean()),S.push(t.readBoolean());if(s>0)for(let ee=s;ee<8;ee++)t.readBits(2);for(let ee=0;ee<s;ee++)T[ee]&&(t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte()),S[ee]&&t.readUByte();t.readUEG();const v=t.readUEG();v==3&&t.skipBits(1);const x=t.readUEG(),D=t.readUEG(),A=t.readBoolean();let b=0,I=0,_=0,C=0;A&&(b+=t.readUEG(),I+=t.readUEG(),_+=t.readUEG(),C+=t.readUEG());const k=t.readUEG(),B=t.readUEG(),K=t.readUEG(),$=t.readBoolean();for(let ee=$?0:s;ee<=s;ee++)t.skipUEG(),t.skipUEG(),t.skipUEG();if(t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG(),t.readBoolean()&&t.readBoolean())for(let xe=0;xe<4;xe++)for(let ke=0;ke<(xe===3?2:6);ke++)if(!t.readBoolean())t.readUEG();else{const Me=Math.min(64,1<<4+(xe<<1));xe>1&&t.readEG();for(let pt=0;pt<Me;pt++)t.readEG()}t.readBoolean(),t.readBoolean(),t.readBoolean()&&(t.readUByte(),t.skipUEG(),t.skipUEG(),t.readBoolean());const N=t.readUEG();let V=0;for(let ee=0;ee<N;ee++){let xe=!1;if(ee!==0&&(xe=t.readBoolean()),xe){ee===N&&t.readUEG(),t.readBoolean(),t.readUEG();let ke=0;for(let ct=0;ct<=V;ct++){const Me=t.readBoolean();let pt=!1;Me||(pt=t.readBoolean()),(Me||pt)&&ke++}V=ke}else{const ke=t.readUEG(),ct=t.readUEG();V=ke+ct;for(let Me=0;Me<ke;Me++)t.readUEG(),t.readBoolean();for(let Me=0;Me<ct;Me++)t.readUEG(),t.readBoolean()}}if(t.readBoolean()){const ee=t.readUEG();for(let xe=0;xe<ee;xe++){for(let ke=0;ke<K+4;ke++)t.readBits(1);t.readBits(1)}}let O=0,F=1,j=1,te=!0,X=1,J=0;t.readBoolean(),t.readBoolean();let ve=!1;if(t.readBoolean()){if(t.readBoolean()){const ht=t.readUByte(),pr=[1,12,10,16,40,24,20,32,80,18,15,64,160,4,3,2],Xt=[1,11,11,11,33,11,11,11,33,11,11,33,99,3,2,1];ht>0&&ht<16?(F=pr[ht-1],j=Xt[ht-1]):ht===255&&(F=t.readBits(16),j=t.readBits(16))}if(t.readBoolean()&&t.readBoolean(),t.readBoolean()&&(t.readBits(3),t.readBoolean(),t.readBoolean()&&(t.readUByte(),t.readUByte(),t.readUByte())),t.readBoolean()&&(t.readUEG(),t.readUEG()),t.readBoolean(),t.readBoolean(),t.readBoolean(),ve=t.readBoolean(),ve&&(t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG()),t.readBoolean()&&(X=t.readBits(32),J=t.readBits(32),t.readBoolean()&&t.readUEG(),t.readBoolean())){const Xt=t.readBoolean(),yr=t.readBoolean();let kt=!1;(Xt||yr)&&(kt=t.readBoolean(),kt&&(t.readUByte(),t.readBits(5),t.readBoolean(),t.readBits(5)),t.readBits(4),t.readBits(4),kt&&t.readBits(4),t.readBits(5),t.readBits(5),t.readBits(5));for(let Er=0;Er<=s;Er++){te=t.readBoolean();const tl=te||t.readBoolean();let Tr=!1;tl?t.readEG():Tr=t.readBoolean();const Sr=Tr?1:t.readUEG()+1;if(Xt)for(let wt=0;wt<Sr;wt++)t.readUEG(),t.readUEG(),kt&&(t.readUEG(),t.readUEG()),t.skipBits(1);if(yr)for(let wt=0;wt<Sr;wt++)t.readUEG(),t.readUEG(),kt&&(t.readUEG(),t.readUEG()),t.skipBits(1)}}t.readBoolean()&&(t.readBoolean(),t.readBoolean(),t.readBoolean(),O=t.readUEG())}let Pe=x,Ue=D;if(A){let ee=1,xe=1;v===1?ee=xe=2:v==2&&(ee=2),Pe=x-ee*I-ee*b,Ue=D-xe*C-xe*_}const lt=i?["A","B","C"][i]:"",el=o<<24|c<<16|l<<8|h;let Hs=0;for(let ee=0;ee<32;ee++)Hs=(Hs|(el>>ee&1)<<31-ee)>>>0;let Ws=Hs.toString(16);return a===1&&Ws==="2"&&(Ws="6"),{codecString:`hvc1.${lt}${a}.${Ws}.${r?"H":"L"}${E}.B0`,params:{general_tier_flag:r,general_profile_idc:a,general_profile_space:i,general_profile_compatibility_flags:[o,c,l,h],general_constraint_indicator_flags:[u,d,f,g,p,y],general_level_idc:E,bit_depth:k+8,bit_depth_luma_minus8:k,bit_depth_chroma_minus8:B,min_spatial_segmentation_idc:O,chroma_format_idc:v,frame_rate:{fixed:te,fps:J/X}},width:Pe,height:Ue,pixelRatio:[F,j]}}readPPS(e){const t=new Bt(this.ebsp2rbsp(e));t.readUByte(),t.readUByte(),t.skipUEG(),t.skipUEG(),t.skipBits(2),t.skipBits(3),t.skipBits(2),t.skipUEG(),t.skipUEG(),t.skipEG(),t.skipBits(2),t.readBoolean()&&t.skipUEG(),t.skipEG(),t.skipEG(),t.skipBits(4);const i=t.readBoolean(),r=t.readBoolean();let a=1;return r&&i?a=0:r?a=3:i&&(a=2),{parallelismType:a}}matchSPS(e,t){return String.fromCharCode.apply(null,e).substr(3)===String.fromCharCode.apply(null,t).substr(3)}}const pe=188;class it{constructor(e,t,s,i){this.logger=void 0,this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.sampleAes=null,this.pmtParsed=!1,this.audioCodec=void 0,this.videoCodec=void 0,this._pmtId=-1,this._videoTrack=void 0,this._audioTrack=void 0,this._id3Track=void 0,this._txtTrack=void 0,this.aacOverFlow=null,this.remainderData=null,this.videoParser=void 0,this.observer=e,this.config=t,this.typeSupported=s,this.logger=i,this.videoParser=null}static probe(e,t){const s=it.syncOffset(e);return s>0&&t.warn(`MPEG2-TS detected but first sync word found @ offset ${s}`),s!==-1}static syncOffset(e){const t=e.length;let s=Math.min(pe*5,t-pe)+1,i=0;for(;i<s;){let r=!1,a=-1,o=0;for(let c=i;c<t;c+=pe)if(e[c]===71&&(t-c===pe||e[c+pe]===71)){if(o++,a===-1&&(a=c,a!==0&&(s=Math.min(a+pe*99,e.length-pe)+1)),r||(r=ki(e,c)===0),r&&o>1&&(a===0&&o>2||c+pe>s))return a}else{if(o)return-1;break}i++}return-1}static createTrack(e,t){return{container:e==="video"||e==="audio"?"video/mp2t":void 0,type:e,id:Aa[e],pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0,duration:e==="audio"?t:void 0}}resetInitSegment(e,t,s,i){this.pmtParsed=!1,this._pmtId=-1,this._videoTrack=it.createTrack("video"),this._videoTrack.duration=i,this._audioTrack=it.createTrack("audio",i),this._id3Track=it.createTrack("id3"),this._txtTrack=it.createTrack("text"),this._audioTrack.segmentCodec="aac",this.videoParser=null,this.aacOverFlow=null,this.remainderData=null,this.audioCodec=t,this.videoCodec=s}resetTimeStamp(){}resetContiguity(){const{_audioTrack:e,_videoTrack:t,_id3Track:s}=this;e&&(e.pesData=null),t&&(t.pesData=null),s&&(s.pesData=null),this.aacOverFlow=null,this.remainderData=null}demux(e,t,s=!1,i=!1){s||(this.sampleAes=null);let r;const a=this._videoTrack,o=this._audioTrack,c=this._id3Track,l=this._txtTrack;let h=a.pid,u=a.pesData,d=o.pid,f=c.pid,g=o.pesData,p=c.pesData,y=null,E=this.pmtParsed,T=this._pmtId,S=e.length;if(this.remainderData&&(e=Oe(this.remainderData,e),S=e.length,this.remainderData=null),S<pe&&!i)return this.remainderData=e,{audioTrack:o,videoTrack:a,id3Track:c,textTrack:l};const v=Math.max(0,it.syncOffset(e));S-=(S-v)%pe,S<e.byteLength&&!i&&(this.remainderData=new Uint8Array(e.buffer,S,e.buffer.byteLength-S));let x=0;for(let A=v;A<S;A+=pe)if(e[A]===71){const b=!!(e[A+1]&64),I=ki(e,A),_=(e[A+3]&48)>>4;let C;if(_>1){if(C=A+5+e[A+4],C===A+pe)continue}else C=A+4;switch(I){case h:b&&(u&&(r=St(u,this.logger))&&(this.readyVideoParser(a.segmentCodec),this.videoParser!==null&&this.videoParser.parsePES(a,l,r,!1)),u={data:[],size:0}),u&&(u.data.push(e.subarray(C,A+pe)),u.size+=A+pe-C);break;case d:if(b){if(g&&(r=St(g,this.logger)))switch(o.segmentCodec){case"aac":this.parseAACPES(o,r);break;case"mp3":this.parseMPEGPES(o,r);break;case"ac3":this.parseAC3PES(o,r);break}g={data:[],size:0}}g&&(g.data.push(e.subarray(C,A+pe)),g.size+=A+pe-C);break;case f:b&&(p&&(r=St(p,this.logger))&&this.parseID3PES(c,r),p={data:[],size:0}),p&&(p.data.push(e.subarray(C,A+pe)),p.size+=A+pe-C);break;case 0:b&&(C+=e[C]+1),T=this._pmtId=au(e,C);break;case T:{b&&(C+=e[C]+1);const k=ou(e,C,this.typeSupported,s,this.observer,this.logger);h=k.videoPid,h>0&&(a.pid=h,a.segmentCodec=k.segmentVideoCodec),d=k.audioPid,d>0&&(o.pid=d,o.segmentCodec=k.segmentAudioCodec),f=k.id3Pid,f>0&&(c.pid=f),y!==null&&!E&&(this.logger.warn(`MPEG-TS PMT found at ${A} after unknown PID '${y}'. Backtracking to sync byte @${v} to parse all TS packets.`),y=null,A=v-188),E=this.pmtParsed=!0;break}case 17:case 8191:break;default:y=I;break}}else x++;x>0&&wi(this.observer,new Error(`Found ${x} TS packet/s that do not start with 0x47`),void 0,this.logger),a.pesData=u,o.pesData=g,c.pesData=p;const D={audioTrack:o,videoTrack:a,id3Track:c,textTrack:l};return i&&this.extractRemainingSamples(D),D}flush(){const{remainderData:e}=this;this.remainderData=null;let t;return e?t=this.demux(e,-1,!1,!0):t={videoTrack:this._videoTrack,audioTrack:this._audioTrack,id3Track:this._id3Track,textTrack:this._txtTrack},this.extractRemainingSamples(t),this.sampleAes?this.decrypt(t,this.sampleAes):t}extractRemainingSamples(e){const{audioTrack:t,videoTrack:s,id3Track:i,textTrack:r}=e,a=s.pesData,o=t.pesData,c=i.pesData;let l;if(a&&(l=St(a,this.logger))?(this.readyVideoParser(s.segmentCodec),this.videoParser!==null&&(this.videoParser.parsePES(s,r,l,!0),s.pesData=null)):s.pesData=a,o&&(l=St(o,this.logger))){switch(t.segmentCodec){case"aac":this.parseAACPES(t,l);break;case"mp3":this.parseMPEGPES(t,l);break;case"ac3":this.parseAC3PES(t,l);break}t.pesData=null}else o!=null&&o.size&&this.logger.log("last AAC PES packet truncated,might overlap between fragments"),t.pesData=o;c&&(l=St(c,this.logger))?(this.parseID3PES(i,l),i.pesData=null):i.pesData=c}demuxSampleAes(e,t,s){const i=this.demux(e,s,!0,!this.config.progressive),r=this.sampleAes=new iu(this.observer,this.config,t);return this.decrypt(i,r)}readyVideoParser(e){this.videoParser===null&&(e==="avc"?this.videoParser=new ru:e==="hevc"&&(this.videoParser=new nu))}decrypt(e,t){return new Promise(s=>{const{audioTrack:i,videoTrack:r}=e;i.samples&&i.segmentCodec==="aac"?t.decryptAacSamples(i.samples,0,()=>{r.samples?t.decryptAvcSamples(r.samples,0,0,()=>{s(e)}):s(e)}):r.samples&&t.decryptAvcSamples(r.samples,0,0,()=>{s(e)})})}destroy(){this.observer&&this.observer.removeAllListeners(),this.config=this.logger=this.observer=null,this.aacOverFlow=this.videoParser=this.remainderData=this.sampleAes=null,this._videoTrack=this._audioTrack=this._id3Track=this._txtTrack=void 0}parseAACPES(e,t){let s=0;const i=this.aacOverFlow;let r=t.data;if(i){this.aacOverFlow=null;const u=i.missing,d=i.sample.unit.byteLength;if(u===-1)r=Oe(i.sample.unit,r);else{const f=d-u;i.sample.unit.set(r.subarray(0,u),f),e.samples.push(i.sample),s=i.missing}}let a,o;for(a=s,o=r.length;a<o-1&&!Ns(r,a);a++);if(a!==s){let u;const d=a<o-1;if(d?u=`AAC PES did not start with ADTS header,offset:${a}`:u="No ADTS header found in AAC PES",wi(this.observer,new Error(u),d,this.logger),!d)return}ao(e,this.observer,r,a,this.audioCodec);let c;if(t.pts!==void 0)c=t.pts;else if(i){const u=oo(e.samplerate);c=i.sample.pts+u}else{this.logger.warn("[tsdemuxer]: AAC PES unknown PTS");return}let l=0,h;for(;a<o;)if(h=lo(e,r,a,c,l),a+=h.length,h.missing){this.aacOverFlow=h;break}else for(l++;a<o-1&&!Ns(r,a);a++);}parseMPEGPES(e,t){const s=t.data,i=s.length;let r=0,a=0;const o=t.pts;if(o===void 0){this.logger.warn("[tsdemuxer]: MPEG PES unknown PTS");return}for(;a<i;)if(go(s,a)){const c=uo(e,s,a,o,r);if(c)a+=c.length,r++;else break}else a++}parseAC3PES(e,t){{const s=t.data,i=t.pts;if(i===void 0){this.logger.warn("[tsdemuxer]: AC3 PES unknown PTS");return}const r=s.length;let a=0,o=0,c;for(;o<r&&(c=yo(e,s,o,i,a++))>0;)o+=c}}parseID3PES(e,t){if(t.pts===void 0){this.logger.warn("[tsdemuxer]: ID3 PES unknown PTS");return}const s=re({},t,{type:this._videoTrack?De.emsg:De.audioId3,duration:Number.POSITIVE_INFINITY});e.samples.push(s)}}function ki(n,e){return((n[e+1]&31)<<8)+n[e+2]}function au(n,e){return(n[e+10]&31)<<8|n[e+11]}function ou(n,e,t,s,i,r){const a={audioPid:-1,videoPid:-1,id3Pid:-1,segmentVideoCodec:"avc",segmentAudioCodec:"aac"},o=(n[e+1]&15)<<8|n[e+2],c=e+3+o-4,l=(n[e+10]&15)<<8|n[e+11];for(e+=12+l;e<c;){const h=ki(n,e),u=(n[e+3]&15)<<8|n[e+4];switch(n[e]){case 207:if(!s){si("ADTS AAC",r);break}case 15:a.audioPid===-1&&(a.audioPid=h);break;case 21:a.id3Pid===-1&&(a.id3Pid=h);break;case 219:if(!s){si("H.264",r);break}case 27:a.videoPid===-1&&(a.videoPid=h);break;case 3:case 4:!t.mpeg&&!t.mp3?r.log("MPEG audio found, not supported in this browser"):a.audioPid===-1&&(a.audioPid=h,a.segmentAudioCodec="mp3");break;case 193:if(!s){si("AC-3",r);break}case 129:t.ac3?a.audioPid===-1&&(a.audioPid=h,a.segmentAudioCodec="ac3"):r.log("AC-3 audio found, not supported in this browser");break;case 6:if(a.audioPid===-1&&u>0){let d=e+5,f=u;for(;f>2;){switch(n[d]){case 106:t.ac3!==!0?r.log("AC-3 audio found, not supported in this browser for now"):(a.audioPid=h,a.segmentAudioCodec="ac3");break}const p=n[d+1]+2;d+=p,f-=p}}break;case 194:case 135:return wi(i,new Error("Unsupported EC-3 in M2TS found"),void 0,r),a;case 36:a.videoPid===-1&&(a.videoPid=h,a.segmentVideoCodec="hevc",r.log("HEVC in M2TS found"));break}e+=u+5}return a}function wi(n,e,t,s){s.warn(`parsing error: ${e.message}`),n.emit(m.ERROR,m.ERROR,{type:H.MEDIA_ERROR,details:R.FRAG_PARSING_ERROR,fatal:!1,levelRetry:t,error:e,reason:e.message})}function si(n,e){e.log(`${n} with AES-128-CBC encryption found in unencrypted stream`)}function St(n,e){let t=0,s,i,r,a,o;const c=n.data;if(!n||n.size===0)return null;for(;c[0].length<19&&c.length>1;)c[0]=Oe(c[0],c[1]),c.splice(1,1);if(s=c[0],(s[0]<<16)+(s[1]<<8)+s[2]===1){if(i=(s[4]<<8)+s[5],i&&i>n.size-6)return null;const h=s[7];h&192&&(a=(s[9]&14)*536870912+(s[10]&255)*4194304+(s[11]&254)*16384+(s[12]&255)*128+(s[13]&254)/2,h&64?(o=(s[14]&14)*536870912+(s[15]&255)*4194304+(s[16]&254)*16384+(s[17]&255)*128+(s[18]&254)/2,a-o>60*9e4&&(e.warn(`${Math.round((a-o)/9e4)}s delta between PTS and DTS, align them`),a=o)):o=a),r=s[8];let u=r+9;if(n.size<=u)return null;n.size-=u;const d=new Uint8Array(n.size);for(let f=0,g=c.length;f<g;f++){s=c[f];let p=s.byteLength;if(u)if(u>p){u-=p;continue}else s=s.subarray(u),p-=u,u=0;d.set(s,t),t+=p}return i&&(i-=r+3),{data:d,pts:a,dts:o,len:i}}return null}class lu{static getSilentFrame(e,t){switch(e){case"mp4a.40.2":if(t===1)return new Uint8Array([0,200,0,128,35,128]);if(t===2)return new Uint8Array([33,0,73,144,2,25,0,35,128]);if(t===3)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,142]);if(t===4)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,128,44,128,8,2,56]);if(t===5)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(t===6)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]);break;default:if(t===1)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(t===2)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(t===3)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]);break}}}const Je=Math.pow(2,32)-1;class L{static init(){L.types={avc1:[],avcC:[],hvc1:[],hvcC:[],btrt:[],dinf:[],dref:[],esds:[],ftyp:[],hdlr:[],mdat:[],mdhd:[],mdia:[],mfhd:[],minf:[],moof:[],moov:[],mp4a:[],".mp3":[],dac3:[],"ac-3":[],mvex:[],mvhd:[],pasp:[],sdtp:[],stbl:[],stco:[],stsc:[],stsd:[],stsz:[],stts:[],tfdt:[],tfhd:[],traf:[],trak:[],trun:[],trex:[],tkhd:[],vmhd:[],smhd:[]};let e;for(e in L.types)L.types.hasOwnProperty(e)&&(L.types[e]=[e.charCodeAt(0),e.charCodeAt(1),e.charCodeAt(2),e.charCodeAt(3)]);const t=new Uint8Array([0,0,0,0,0,0,0,0,118,105,100,101,0,0,0,0,0,0,0,0,0,0,0,0,86,105,100,101,111,72,97,110,100,108,101,114,0]),s=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]);L.HDLR_TYPES={video:t,audio:s};const i=new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,12,117,114,108,32,0,0,0,1]),r=new Uint8Array([0,0,0,0,0,0,0,0]);L.STTS=L.STSC=L.STCO=r,L.STSZ=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),L.VMHD=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0]),L.SMHD=new Uint8Array([0,0,0,0,0,0,0,0]),L.STSD=new Uint8Array([0,0,0,0,0,0,0,1]);const a=new Uint8Array([105,115,111,109]),o=new Uint8Array([97,118,99,49]),c=new Uint8Array([0,0,0,1]);L.FTYP=L.box(L.types.ftyp,a,c,a,o),L.DINF=L.box(L.types.dinf,L.box(L.types.dref,i))}static box(e,...t){let s=8,i=t.length;const r=i;for(;i--;)s+=t[i].byteLength;const a=new Uint8Array(s);for(a[0]=s>>24&255,a[1]=s>>16&255,a[2]=s>>8&255,a[3]=s&255,a.set(e,4),i=0,s=8;i<r;i++)a.set(t[i],s),s+=t[i].byteLength;return a}static hdlr(e){return L.box(L.types.hdlr,L.HDLR_TYPES[e])}static mdat(e){return L.box(L.types.mdat,e)}static mdhd(e,t){t*=e;const s=Math.floor(t/(Je+1)),i=Math.floor(t%(Je+1));return L.box(L.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,e&255,s>>24,s>>16&255,s>>8&255,s&255,i>>24,i>>16&255,i>>8&255,i&255,85,196,0,0]))}static mdia(e){return L.box(L.types.mdia,L.mdhd(e.timescale||0,e.duration||0),L.hdlr(e.type),L.minf(e))}static mfhd(e){return L.box(L.types.mfhd,new Uint8Array([0,0,0,0,e>>24,e>>16&255,e>>8&255,e&255]))}static minf(e){return e.type==="audio"?L.box(L.types.minf,L.box(L.types.smhd,L.SMHD),L.DINF,L.stbl(e)):L.box(L.types.minf,L.box(L.types.vmhd,L.VMHD),L.DINF,L.stbl(e))}static moof(e,t,s){return L.box(L.types.moof,L.mfhd(e),L.traf(s,t))}static moov(e){let t=e.length;const s=[];for(;t--;)s[t]=L.trak(e[t]);return L.box.apply(null,[L.types.moov,L.mvhd(e[0].timescale||0,e[0].duration||0)].concat(s).concat(L.mvex(e)))}static mvex(e){let t=e.length;const s=[];for(;t--;)s[t]=L.trex(e[t]);return L.box.apply(null,[L.types.mvex,...s])}static mvhd(e,t){t*=e;const s=Math.floor(t/(Je+1)),i=Math.floor(t%(Je+1)),r=new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,e>>24&255,e>>16&255,e>>8&255,e&255,s>>24,s>>16&255,s>>8&255,s&255,i>>24,i>>16&255,i>>8&255,i&255,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 L.box(L.types.mvhd,r)}static sdtp(e){const t=e.samples||[],s=new Uint8Array(4+t.length);let i,r;for(i=0;i<t.length;i++)r=t[i].flags,s[i+4]=r.dependsOn<<4|r.isDependedOn<<2|r.hasRedundancy;return L.box(L.types.sdtp,s)}static stbl(e){return L.box(L.types.stbl,L.stsd(e),L.box(L.types.stts,L.STTS),L.box(L.types.stsc,L.STSC),L.box(L.types.stsz,L.STSZ),L.box(L.types.stco,L.STCO))}static avc1(e){let t=[],s=[],i,r,a;for(i=0;i<e.sps.length;i++)r=e.sps[i],a=r.byteLength,t.push(a>>>8&255),t.push(a&255),t=t.concat(Array.prototype.slice.call(r));for(i=0;i<e.pps.length;i++)r=e.pps[i],a=r.byteLength,s.push(a>>>8&255),s.push(a&255),s=s.concat(Array.prototype.slice.call(r));const o=L.box(L.types.avcC,new Uint8Array([1,t[3],t[4],t[5],255,224|e.sps.length].concat(t).concat([e.pps.length]).concat(s))),c=e.width,l=e.height,h=e.pixelRatio[0],u=e.pixelRatio[1];return L.box(L.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,c>>8&255,c&255,l>>8&255,l&255,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,L.box(L.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),L.box(L.types.pasp,new Uint8Array([h>>24,h>>16&255,h>>8&255,h&255,u>>24,u>>16&255,u>>8&255,u&255])))}static esds(e){const t=e.config;return new Uint8Array([0,0,0,0,3,25,0,1,0,4,17,64,21,0,0,0,0,0,0,0,0,0,0,0,5,2,...t,6,1,2])}static audioStsd(e){const t=e.samplerate||0;return new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,e.channelCount||0,0,16,0,0,0,0,t>>8&255,t&255,0,0])}static mp4a(e){return L.box(L.types.mp4a,L.audioStsd(e),L.box(L.types.esds,L.esds(e)))}static mp3(e){return L.box(L.types[".mp3"],L.audioStsd(e))}static ac3(e){return L.box(L.types["ac-3"],L.audioStsd(e),L.box(L.types.dac3,e.config))}static stsd(e){const{segmentCodec:t}=e;if(e.type==="audio"){if(t==="aac")return L.box(L.types.stsd,L.STSD,L.mp4a(e));if(t==="ac3"&&e.config)return L.box(L.types.stsd,L.STSD,L.ac3(e));if(t==="mp3"&&e.codec==="mp3")return L.box(L.types.stsd,L.STSD,L.mp3(e))}else if(e.pps&&e.sps){if(t==="avc")return L.box(L.types.stsd,L.STSD,L.avc1(e));if(t==="hevc"&&e.vps)return L.box(L.types.stsd,L.STSD,L.hvc1(e))}else throw new Error("video track missing pps or sps");throw new Error(`unsupported ${e.type} segment codec (${t}/${e.codec})`)}static tkhd(e){const t=e.id,s=(e.duration||0)*(e.timescale||0),i=e.width||0,r=e.height||0,a=Math.floor(s/(Je+1)),o=Math.floor(s%(Je+1));return L.box(L.types.tkhd,new Uint8Array([1,0,0,7,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,t>>24&255,t>>16&255,t>>8&255,t&255,0,0,0,0,a>>24,a>>16&255,a>>8&255,a&255,o>>24,o>>16&255,o>>8&255,o&255,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,i>>8&255,i&255,0,0,r>>8&255,r&255,0,0]))}static traf(e,t){const s=L.sdtp(e),i=e.id,r=Math.floor(t/(Je+1)),a=Math.floor(t%(Je+1));return L.box(L.types.traf,L.box(L.types.tfhd,new Uint8Array([0,0,0,0,i>>24,i>>16&255,i>>8&255,i&255])),L.box(L.types.tfdt,new Uint8Array([1,0,0,0,r>>24,r>>16&255,r>>8&255,r&255,a>>24,a>>16&255,a>>8&255,a&255])),L.trun(e,s.length+16+20+8+16+8+8),s)}static trak(e){return e.duration=e.duration||4294967295,L.box(L.types.trak,L.tkhd(e),L.mdia(e))}static trex(e){const t=e.id;return L.box(L.types.trex,new Uint8Array([0,0,0,0,t>>24,t>>16&255,t>>8&255,t&255,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,1]))}static trun(e,t){const s=e.samples||[],i=s.length,r=12+16*i,a=new Uint8Array(r);let o,c,l,h,u,d;for(t+=8+r,a.set([e.type==="video"?1:0,0,15,1,i>>>24&255,i>>>16&255,i>>>8&255,i&255,t>>>24&255,t>>>16&255,t>>>8&255,t&255],0),o=0;o<i;o++)c=s[o],l=c.duration,h=c.size,u=c.flags,d=c.cts,a.set([l>>>24&255,l>>>16&255,l>>>8&255,l&255,h>>>24&255,h>>>16&255,h>>>8&255,h&255,u.isLeading<<2|u.dependsOn,u.isDependedOn<<6|u.hasRedundancy<<4|u.paddingValue<<1|u.isNonSync,u.degradPrio&61440,u.degradPrio&15,d>>>24&255,d>>>16&255,d>>>8&255,d&255],12+16*o);return L.box(L.types.trun,a)}static initSegment(e){L.types||L.init();const t=L.moov(e);return Oe(L.FTYP,t)}static hvc1(e){const t=e.params,s=[e.vps,e.sps,e.pps],i=4,r=new Uint8Array([1,t.general_profile_space<<6|(t.general_tier_flag?32:0)|t.general_profile_idc,t.general_profile_compatibility_flags[0],t.general_profile_compatibility_flags[1],t.general_profile_compatibility_flags[2],t.general_profile_compatibility_flags[3],t.general_constraint_indicator_flags[0],t.general_constraint_indicator_flags[1],t.general_constraint_indicator_flags[2],t.general_constraint_indicator_flags[3],t.general_constraint_indicator_flags[4],t.general_constraint_indicator_flags[5],t.general_level_idc,240|t.min_spatial_segmentation_idc>>8,255&t.min_spatial_segmentation_idc,252|t.parallelismType,252|t.chroma_format_idc,248|t.bit_depth_luma_minus8,248|t.bit_depth_chroma_minus8,0,parseInt(t.frame_rate.fps),i-1|t.temporal_id_nested<<2|t.num_temporal_layers<<3|(t.frame_rate.fixed?64:0),s.length]);let a=r.length;for(let g=0;g<s.length;g+=1){a+=3;for(let p=0;p<s[g].length;p+=1)a+=2+s[g][p].length}const o=new Uint8Array(a);o.set(r,0),a=r.length;const c=s.length-1;for(let g=0;g<s.length;g+=1){o.set(new Uint8Array([32+g|(g===c?128:0),0,s[g].length]),a),a+=3;for(let p=0;p<s[g].length;p+=1)o.set(new Uint8Array([s[g][p].length>>8,s[g][p].length&255]),a),a+=2,o.set(s[g][p],a),a+=s[g][p].length}const l=L.box(L.types.hvcC,o),h=e.width,u=e.height,d=e.pixelRatio[0],f=e.pixelRatio[1];return L.box(L.types.hvc1,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,h>>8&255,h&255,u>>8&255,u&255,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]),l,L.box(L.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),L.box(L.types.pasp,new Uint8Array([d>>24,d>>16&255,d>>8&255,d&255,f>>24,f>>16&255,f>>8&255,f&255])))}}L.types=void 0;L.HDLR_TYPES=void 0;L.STTS=void 0;L.STSC=void 0;L.STCO=void 0;L.STSZ=void 0;L.VMHD=void 0;L.SMHD=void 0;L.STSD=void 0;L.FTYP=void 0;L.DINF=void 0;const To=9e4;function cr(n,e,t=1,s=!1){const i=n*e*t;return s?Math.round(i):i}function cu(n,e,t=1,s=!1){return cr(n,e,1/t,s)}function Ot(n,e=!1){return cr(n,1e3,1/To,e)}function hu(n,e=1){return cr(n,To,1/e)}function _n(n){const{baseTime:e,timescale:t,trackId:s}=n;return`${e/t} (${e}/${t}) trackId: ${s}`}const uu=10*1e3,du=1024,fu=1152,gu=1536;let vt=null,ii=null;function In(n,e,t,s){return{duration:e,size:t,cts:s,flags:{isLeading:0,isDependedOn:0,hasRedundancy:0,degradPrio:0,dependsOn:n?2:1,isNonSync:n?0:1}}}class Es extends Fe{constructor(e,t,s,i){if(super("mp4-remuxer",i),this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.ISGenerated=!1,this._initPTS=null,this._initDTS=null,this.nextVideoTs=null,this.nextAudioTs=null,this.videoSampleDuration=null,this.isAudioContiguous=!1,this.isVideoContiguous=!1,this.videoTrackConfig=void 0,this.observer=e,this.config=t,this.typeSupported=s,this.ISGenerated=!1,vt===null){const a=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);vt=a?parseInt(a[1]):0}if(ii===null){const r=navigator.userAgent.match(/Safari\/(\d+)/i);ii=r?parseInt(r[1]):0}}destroy(){this.config=this.videoTrackConfig=this._initPTS=this._initDTS=null}resetTimeStamp(e){const t=this._initPTS;(!t||!e||e.trackId!==t.trackId||e.baseTime!==t.baseTime||e.timescale!==t.timescale)&&this.log(`Reset initPTS: ${t&&_n(t)} > ${e&&_n(e)}`),this._initPTS=this._initDTS=e}resetNextTimestamp(){this.log("reset next timestamp"),this.isVideoContiguous=!1,this.isAudioContiguous=!1}resetInitSegment(){this.log("ISGenerated flag reset"),this.ISGenerated=!1,this.videoTrackConfig=void 0}getVideoStartPts(e){let t=!1;const s=e[0].pts,i=e.reduce((r,a)=>{let o=a.pts,c=o-r;return c<-4294967296&&(t=!0,o=be(o,s),c=o-r),c>0?r:o},s);return t&&this.debug("PTS rollover detected"),i}remux(e,t,s,i,r,a,o,c){let l,h,u,d,f,g,p=r,y=r;const E=e.pid>-1,T=t.pid>-1,S=t.samples.length,v=e.samples.length>0,x=o&&S>0||S>1;if((!E||v)&&(!T||x)||this.ISGenerated||o){if(this.ISGenerated){var A,b,I,_;const K=this.videoTrackConfig;(K&&(t.width!==K.width||t.height!==K.height||((A=t.pixelRatio)==null?void 0:A[0])!==((b=K.pixelRatio)==null?void 0:b[0])||((I=t.pixelRatio)==null?void 0:I[1])!==((_=K.pixelRatio)==null?void 0:_[1]))||!K&&x||this.nextAudioTs===null&&v)&&this.resetInitSegment()}this.ISGenerated||(u=this.generateIS(e,t,r,a));const C=this.isVideoContiguous;let k=-1,B;if(x&&(k=mu(t.samples),!C&&this.config.forceKeyFrameOnDiscontinuity))if(g=!0,k>0){this.warn(`Dropped ${k} out of ${S} video samples due to a missing keyframe`);const K=this.getVideoStartPts(t.samples);t.samples=t.samples.slice(k),t.dropped+=k,y+=(t.samples[0].pts-K)/t.inputTimeScale,B=y}else k===-1&&(this.warn(`No keyframe found out of ${S} video samples`),g=!1);if(this.ISGenerated){if(v&&x){const K=this.getVideoStartPts(t.samples),w=(be(e.samples[0].pts,K)-K)/t.inputTimeScale;p+=Math.max(0,w),y+=Math.max(0,-w)}if(v){if(e.samplerate||(this.warn("regenerate InitSegment as audio detected"),u=this.generateIS(e,t,r,a)),h=this.remuxAudio(e,p,this.isAudioContiguous,a,T||x||c===U.AUDIO?y:void 0),x){const K=h?h.endPTS-h.startPTS:0;t.inputTimeScale||(this.warn("regenerate InitSegment as video detected"),u=this.generateIS(e,t,r,a)),l=this.remuxVideo(t,y,C,K)}}else x&&(l=this.remuxVideo(t,y,C,0));l&&(l.firstKeyFrame=k,l.independent=k!==-1,l.firstKeyFramePTS=B)}}return this.ISGenerated&&this._initPTS&&this._initDTS&&(s.samples.length&&(f=So(s,r,this._initPTS,this._initDTS)),i.samples.length&&(d=vo(i,r,this._initPTS))),{audio:h,video:l,initSegment:u,independent:g,text:d,id3:f}}computeInitPts(e,t,s,i){const r=Math.round(s*t);let a=be(e,r);if(a<r+t)for(this.log(`Adjusting PTS for rollover in timeline near ${(r-a)/t} ${i}`);a<r+t;)a+=8589934592;return a-r}generateIS(e,t,s,i){const r=e.samples,a=t.samples,o=this.typeSupported,c={},l=this._initPTS;let h=!l||i,u="audio/mp4",d,f,g,p=-1;if(h&&(d=f=1/0),e.config&&r.length){switch(e.timescale=e.samplerate,e.segmentCodec){case"mp3":o.mpeg?(u="audio/mpeg",e.codec=""):o.mp3&&(e.codec="mp3");break;case"ac3":e.codec="ac-3";break}c.audio={id:"audio",container:u,codec:e.codec,initSegment:e.segmentCodec==="mp3"&&o.mpeg?new Uint8Array(0):L.initSegment([e]),metadata:{channelCount:e.channelCount}},h&&(p=e.id,g=e.inputTimeScale,!l||g!==l.timescale?d=f=this.computeInitPts(r[0].pts,g,s,"audio"):h=!1)}if(t.sps&&t.pps&&a.length){if(t.timescale=t.inputTimeScale,c.video={id:"main",container:"video/mp4",codec:t.codec,initSegment:L.initSegment([t]),metadata:{width:t.width,height:t.height}},h)if(p=t.id,g=t.inputTimeScale,!l||g!==l.timescale){const y=this.getVideoStartPts(a),E=be(a[0].dts,y),T=this.computeInitPts(E,g,s,"video"),S=this.computeInitPts(y,g,s,"video");f=Math.min(f,T),d=Math.min(d,S)}else h=!1;this.videoTrackConfig={width:t.width,height:t.height,pixelRatio:t.pixelRatio}}if(Object.keys(c).length)return this.ISGenerated=!0,h?(l&&this.warn(`Timestamps at playlist time: ${i?"":"~"}${s} ${d/g} != initPTS: ${l.baseTime/l.timescale} (${l.baseTime}/${l.timescale}) trackId: ${l.trackId}`),this.log(`Found initPTS at playlist time: ${s} offset: ${d/g} (${d}/${g}) trackId: ${p}`),this._initPTS={baseTime:d,timescale:g,trackId:p},this._initDTS={baseTime:f,timescale:g,trackId:p}):d=g=void 0,{tracks:c,initPTS:d,timescale:g,trackId:p}}remuxVideo(e,t,s,i){const r=e.inputTimeScale,a=e.samples,o=[],c=a.length,l=this._initPTS,h=l.baseTime*r/l.timescale;let u=this.nextVideoTs,d=8,f=this.videoSampleDuration,g,p,y=Number.POSITIVE_INFINITY,E=Number.NEGATIVE_INFINITY,T=!1;if(!s||u===null){const O=h+t*r,F=a[0].pts-be(a[0].dts,a[0].pts);vt&&u!==null&&Math.abs(O-F-(u+h))<15e3?s=!0:u=O-F-h}const S=u+h;for(let O=0;O<c;O++){const F=a[O];F.pts=be(F.pts,S),F.dts=be(F.dts,S),F.dts<a[O>0?O-1:O].dts&&(T=!0)}T&&a.sort(function(O,F){const j=O.dts-F.dts,te=O.pts-F.pts;return j||te}),g=a[0].dts,p=a[a.length-1].dts;const v=p-g,x=v?Math.round(v/(c-1)):f||e.inputTimeScale/30;if(s){const O=g-S,F=O>x,j=O<-1;if((F||j)&&(F?this.warn(`${(e.segmentCodec||"").toUpperCase()}: ${Ot(O,!0)} ms (${O}dts) hole between fragments detected at ${t.toFixed(3)}`):this.warn(`${(e.segmentCodec||"").toUpperCase()}: ${Ot(-O,!0)} ms (${O}dts) overlapping between fragments detected at ${t.toFixed(3)}`),!j||S>=a[0].pts||vt)){g=S;const te=a[0].pts-O;if(F)a[0].dts=g,a[0].pts=te;else{let X=!0;for(let J=0;J<a.length&&!(a[J].dts>te&&X);J++){const ve=a[J].pts;if(a[J].dts-=O,a[J].pts-=O,J<a.length-1){const ye=a[J+1].pts,Pe=a[J].pts,Ue=ye<=Pe,lt=ye<=ve;X=Ue==lt}}}this.log(`Video: Initial PTS/DTS adjusted: ${Ot(te,!0)}/${Ot(g,!0)}, delta: ${Ot(O,!0)} ms`)}}g=Math.max(0,g);let D=0,A=0,b=g;for(let O=0;O<c;O++){const F=a[O],j=F.units,te=j.length;let X=0;for(let J=0;J<te;J++)X+=j[J].data.length;A+=X,D+=te,F.length=X,F.dts<b?(F.dts=b,b+=x/4|0||1):b=F.dts,y=Math.min(F.pts,y),E=Math.max(F.pts,E)}p=a[c-1].dts;const I=A+4*D+8;let _;try{_=new Uint8Array(I)}catch(O){this.observer.emit(m.ERROR,m.ERROR,{type:H.MUX_ERROR,details:R.REMUX_ALLOC_ERROR,fatal:!1,error:O,bytes:I,reason:`fail allocating video mdat ${I}`});return}const C=new DataView(_.buffer);C.setUint32(0,I),_.set(L.types.mdat,4);let k=!1,B=Number.POSITIVE_INFINITY,K=Number.POSITIVE_INFINITY,$=Number.NEGATIVE_INFINITY,w=Number.NEGATIVE_INFINITY;for(let O=0;O<c;O++){const F=a[O],j=F.units;let te=0;for(let ve=0,ye=j.length;ve<ye;ve++){const Pe=j[ve],Ue=Pe.data,lt=Pe.data.byteLength;C.setUint32(d,lt),d+=4,_.set(Ue,d),d+=lt,te+=4+lt}let X;if(O<c-1)f=a[O+1].dts-F.dts,X=a[O+1].pts-F.pts;else{const ve=this.config,ye=O>0?F.dts-a[O-1].dts:x;if(X=O>0?F.pts-a[O-1].pts:x,ve.stretchShortVideoTrack&&this.nextAudioTs!==null){const Pe=Math.floor(ve.maxBufferHole*r),Ue=(i?y+i*r:this.nextAudioTs+h)-F.pts;Ue>Pe?(f=Ue-ye,f<0?f=ye:k=!0,this.log(`It is approximately ${Ue/90} ms to the next segment; using duration ${f/90} ms for the last video frame.`)):f=ye}else f=ye}const J=Math.round(F.pts-F.dts);B=Math.min(B,f),$=Math.max($,f),K=Math.min(K,X),w=Math.max(w,X),o.push(In(F.key,f,te,J))}if(o.length){if(vt){if(vt<70){const O=o[0].flags;O.dependsOn=2,O.isNonSync=0}}else if(ii&&w-K<$-B&&x/$<.025&&o[0].cts===0){this.warn("Found irregular gaps in sample duration. Using PTS instead of DTS to determine MP4 sample duration.");let O=g;for(let F=0,j=o.length;F<j;F++){const te=O+o[F].duration,X=O+o[F].cts;if(F<j-1){const J=te+o[F+1].cts;o[F].duration=J-X}else o[F].duration=F?o[F-1].duration:x;o[F].cts=0,O=te}}}f=k||!f?x:f;const G=p+f;this.nextVideoTs=u=G-h,this.videoSampleDuration=f,this.isVideoContiguous=!0;const W={data1:L.moof(e.sequenceNumber++,g,re(e,{samples:o})),data2:_,startPTS:(y-h)/r,endPTS:(E+f-h)/r,startDTS:(g-h)/r,endDTS:u/r,type:"video",hasAudio:!1,hasVideo:!0,nb:o.length,dropped:e.dropped};return e.samples=[],e.dropped=0,W}getSamplesPerFrame(e){switch(e.segmentCodec){case"mp3":return fu;case"ac3":return gu;default:return du}}remuxAudio(e,t,s,i,r){const a=e.inputTimeScale,o=e.samplerate?e.samplerate:a,c=a/o,l=this.getSamplesPerFrame(e),h=l*c,u=this._initPTS,d=e.segmentCodec==="mp3"&&this.typeSupported.mpeg,f=[],g=r!==void 0;let p=e.samples,y=d?0:8,E=this.nextAudioTs||-1;const T=u.baseTime*a/u.timescale,S=T+t*a;if(this.isAudioContiguous=s=s||p.length&&E>0&&(i&&Math.abs(S-(E+T))<9e3||Math.abs(be(p[0].pts,S)-(E+T))<20*h),p.forEach(function(w){w.pts=be(w.pts,S)}),!s||E<0){const w=p.length;if(p=p.filter(G=>G.pts>=0),w!==p.length&&this.warn(`Removed ${p.length-w} of ${w} samples (initPTS ${T} / ${a})`),!p.length)return;r===0?E=0:i&&!g?E=Math.max(0,S-T):E=p[0].pts-T}if(e.segmentCodec==="aac"){const w=this.config.maxAudioFramesDrift;for(let G=0,N=E+T;G<p.length;G++){const V=p[G],W=V.pts,O=W-N,F=Math.abs(1e3*O/a);if(O<=-w*h&&g)G===0&&(this.warn(`Audio frame @ ${(W/a).toFixed(3)}s overlaps marker by ${Math.round(1e3*O/a)} ms.`),this.nextAudioTs=E=W-T,N=W);else if(O>=w*h&&F<uu&&g){let j=Math.round(O/h);for(N=W-j*h;N<0&&j&&h;)j--,N+=h;G===0&&(this.nextAudioTs=E=N-T),this.warn(`Injecting ${j} audio frames @ ${((N-T)/a).toFixed(3)}s due to ${Math.round(1e3*O/a)} ms gap.`);for(let te=0;te<j;te++){let X=lu.getSilentFrame(e.parsedCodec||e.manifestCodec||e.codec,e.channelCount);X||(this.log("Unable to get silent frame for given audio codec; duplicating last frame instead."),X=V.unit.subarray()),p.splice(G,0,{unit:X,pts:N}),N+=h,G++}}V.pts=N,N+=h}}let v=null,x=null,D,A=0,b=p.length;for(;b--;)A+=p[b].unit.byteLength;for(let w=0,G=p.length;w<G;w++){const N=p[w],V=N.unit;let W=N.pts;if(x!==null){const F=f[w-1];F.duration=Math.round((W-x)/c)}else if(s&&e.segmentCodec==="aac"&&(W=E+T),v=W,A>0){A+=y;try{D=new Uint8Array(A)}catch(F){this.observer.emit(m.ERROR,m.ERROR,{type:H.MUX_ERROR,details:R.REMUX_ALLOC_ERROR,fatal:!1,error:F,bytes:A,reason:`fail allocating audio mdat ${A}`});return}d||(new DataView(D.buffer).setUint32(0,A),D.set(L.types.mdat,4))}else return;D.set(V,y);const O=V.byteLength;y+=O,f.push(In(!0,l,O,0)),x=W}const I=f.length;if(!I)return;const _=f[f.length-1];E=x-T,this.nextAudioTs=E+c*_.duration;const C=d?new Uint8Array(0):L.moof(e.sequenceNumber++,v/c,re({},e,{samples:f}));e.samples=[];const k=(v-T)/a,B=this.nextAudioTs/a,$={data1:C,data2:D,startPTS:k,endPTS:B,startDTS:k,endDTS:B,type:"audio",hasAudio:!0,hasVideo:!1,nb:I};return this.isAudioContiguous=!0,$}}function be(n,e){let t;if(e===null)return n;for(e<n?t=-8589934592:t=8589934592;Math.abs(n-e)>4294967296;)n+=t;return n}function mu(n){for(let e=0;e<n.length;e++)if(n[e].key)return e;return-1}function So(n,e,t,s){const i=n.samples.length;if(!i)return;const r=n.inputTimeScale;for(let o=0;o<i;o++){const c=n.samples[o];c.pts=be(c.pts-t.baseTime*r/t.timescale,e*r)/r,c.dts=be(c.dts-s.baseTime*r/s.timescale,e*r)/r}const a=n.samples;return n.samples=[],{samples:a}}function vo(n,e,t){const s=n.samples.length;if(!s)return;const i=n.inputTimeScale;for(let a=0;a<s;a++){const o=n.samples[a];o.pts=be(o.pts-t.baseTime*i/t.timescale,e*i)/i}n.samples.sort((a,o)=>a.pts-o.pts);const r=n.samples;return n.samples=[],{samples:r}}class pu extends Fe{constructor(e,t,s,i){super("passthrough-remuxer",i),this.emitInitSegment=!1,this.audioCodec=void 0,this.videoCodec=void 0,this.initData=void 0,this.initPTS=null,this.initTracks=void 0,this.lastEndTime=null,this.isVideoContiguous=!1}destroy(){}resetTimeStamp(e){this.lastEndTime=null;const t=this.initPTS;t&&e&&t.baseTime===e.baseTime&&t.timescale===e.timescale||(this.initPTS=e)}resetNextTimestamp(){this.isVideoContiguous=!1,this.lastEndTime=null}resetInitSegment(e,t,s,i){this.audioCodec=t,this.videoCodec=s,this.generateInitSegment(e,i),this.emitInitSegment=!0}generateInitSegment(e,t){let{audioCodec:s,videoCodec:i}=this;if(!(e!=null&&e.byteLength)){this.initTracks=void 0,this.initData=void 0;return}const{audio:r,video:a}=this.initData=La(e);if(t)ic(e,t);else{const c=r||a;c!=null&&c.encrypted&&this.warn(`Init segment with encrypted track with has no key ("${c.codec}")!`)}r&&(s=Ln(r,ne.AUDIO,this)),a&&(i=Ln(a,ne.VIDEO,this));const o={};r&&a?o.audiovideo={container:"video/mp4",codec:s+","+i,supplemental:a.supplemental,encrypted:a.encrypted,initSegment:e,id:"main"}:r?o.audio={container:"audio/mp4",codec:s,encrypted:r.encrypted,initSegment:e,id:"audio"}:a?o.video={container:"video/mp4",codec:i,supplemental:a.supplemental,encrypted:a.encrypted,initSegment:e,id:"main"}:this.warn("initSegment does not contain moov or trak boxes."),this.initTracks=o}remux(e,t,s,i,r,a){var o,c;let{initPTS:l,lastEndTime:h}=this;const u={audio:void 0,video:void 0,text:i,id3:s,initSegment:void 0};M(h)||(h=this.lastEndTime=r||0);const d=t.samples;if(!d.length)return u;const f={initPTS:void 0,timescale:void 0,trackId:void 0};let g=this.initData;if((o=g)!=null&&o.length||(this.generateInitSegment(d),g=this.initData),!((c=g)!=null&&c.length))return this.warn("Failed to generate initSegment."),u;this.emitInitSegment&&(f.tracks=this.initTracks,this.emitInitSegment=!1);const p=nc(d,g,this),y=g.audio?p[g.audio.id]:null,E=g.video?p[g.video.id]:null,T=is(E,1/0),S=is(y,1/0),v=is(E,0,!0),x=is(y,0,!0);let D=r,A=0;const b=y&&(!E||!l&&S<T||l&&l.trackId===g.audio.id),I=b?y:E;if(I){const N=I.timescale,V=I.start-r*N,W=b?g.audio.id:g.video.id;D=I.start/N,A=b?x-S:v-T,(a||!l)&&(yu(l,D,r,A)||N!==l.timescale)&&(l&&this.warn(`Timestamps at playlist time: ${a?"":"~"}${r} ${V/N} != initPTS: ${l.baseTime/l.timescale} (${l.baseTime}/${l.timescale}) trackId: ${l.trackId}`),this.log(`Found initPTS at playlist time: ${r} offset: ${D-r} (${V}/${N}) trackId: ${W}`),l=null,f.initPTS=V,f.timescale=N,f.trackId=W)}else this.warn(`No audio or video samples found for initPTS at playlist time: ${r}`);l?(f.initPTS=l.baseTime,f.timescale=l.timescale,f.trackId=l.trackId):((!f.timescale||f.trackId===void 0||f.initPTS===void 0)&&(this.warn("Could not set initPTS"),f.initPTS=D,f.timescale=1,f.trackId=-1),this.initPTS=l={baseTime:f.initPTS,timescale:f.timescale,trackId:f.trackId});const _=D-l.baseTime/l.timescale,C=_+A;A>0?this.lastEndTime=C:(this.warn("Duration parsed from mp4 should be greater than zero"),this.resetNextTimestamp());const k=!!g.audio,B=!!g.video;let K="";k&&(K+="audio"),B&&(K+="video");const $=(g.audio?g.audio.encrypted:!1)||(g.video?g.video.encrypted:!1),w={data1:d,startPTS:_,startDTS:_,endPTS:C,endDTS:C,type:K,hasAudio:k,hasVideo:B,nb:1,dropped:0,encrypted:$};u.audio=k&&!B?w:void 0,u.video=B?w:void 0;const G=E==null?void 0:E.sampleCount;if(G){const N=E.keyFrameIndex,V=N!==-1;w.nb=G,w.dropped=N===0||this.isVideoContiguous?0:V?N:G,w.independent=V,w.firstKeyFrame=N,V&&E.keyFrameStart&&(w.firstKeyFramePTS=(E.keyFrameStart-l.baseTime)/l.timescale),this.isVideoContiguous||(u.independent=V),this.isVideoContiguous||(this.isVideoContiguous=V),w.dropped&&this.warn(`fmp4 does not start with IDR: firstIDR ${N}/${G} dropped: ${w.dropped} start: ${w.firstKeyFramePTS||"NA"}`)}return u.initSegment=f,u.id3=So(s,r,l,l),i.samples.length&&(u.text=vo(i,r,l)),u}}function is(n,e,t=!1){return(n==null?void 0:n.start)!==void 0?(n.start+(t?n.duration:0))/n.timescale:e}function yu(n,e,t,s){if(n===null)return!0;const i=Math.max(s,1),r=e-n.baseTime/n.timescale;return Math.abs(r-t)>i}function Ln(n,e,t){const s=n.codec;return s&&s.length>4?s:e===ne.AUDIO?s==="ec-3"||s==="ac-3"||s==="alac"?s:s==="fLaC"||s==="Opus"?Ds(s,!1):(t.warn(`Unhandled audio codec "${s}" in mp4 MAP`),s||"mp4a"):(t.warn(`Unhandled video codec "${s}" in mp4 MAP`),s||"avc1")}let Qe;try{Qe=self.performance.now.bind(self.performance)}catch{Qe=Date.now}const Ts=[{demux:su,remux:pu},{demux:it,remux:Es},{demux:Zh,remux:Es},{demux:eu,remux:Es}];Ts.splice(2,0,{demux:Jh,remux:Es});class Rn{constructor(e,t,s,i,r,a){this.asyncResult=!1,this.logger=void 0,this.observer=void 0,this.typeSupported=void 0,this.config=void 0,this.id=void 0,this.demuxer=void 0,this.remuxer=void 0,this.decrypter=void 0,this.probe=void 0,this.decryptionPromise=null,this.transmuxConfig=void 0,this.currentTransmuxState=void 0,this.observer=e,this.typeSupported=t,this.config=s,this.id=r,this.logger=a}configure(e){this.transmuxConfig=e,this.decrypter&&this.decrypter.reset()}push(e,t,s,i){const r=s.transmuxing;r.executeStart=Qe();let a=new Uint8Array(e);const{currentTransmuxState:o,transmuxConfig:c}=this;i&&(this.currentTransmuxState=i);const{contiguous:l,discontinuity:h,trackSwitch:u,accurateTimeOffset:d,timeOffset:f,initSegmentChange:g}=i||o,{audioCodec:p,videoCodec:y,defaultInitPts:E,duration:T,initSegmentData:S}=c,v=Eu(a,t);if(v&&It(v.method)){const b=this.getDecrypter(),I=er(v.method);if(b.isSync()){let _=b.softwareDecrypt(a,v.key.buffer,v.iv.buffer,I);if(s.part>-1){const k=b.flush();_=k&&k.buffer}if(!_)return r.executeEnd=Qe(),ri(s);a=new Uint8Array(_)}else return this.asyncResult=!0,this.decryptionPromise=b.webCryptoDecrypt(a,v.key.buffer,v.iv.buffer,I).then(_=>{const C=this.push(_,null,s);return this.decryptionPromise=null,C}),this.decryptionPromise}const x=this.needsProbing(h,u);if(x){const b=this.configureTransmuxer(a);if(b)return this.logger.warn(`[transmuxer] ${b.message}`),this.observer.emit(m.ERROR,m.ERROR,{type:H.MEDIA_ERROR,details:R.FRAG_PARSING_ERROR,fatal:!1,error:b,reason:b.message}),r.executeEnd=Qe(),ri(s)}(h||u||g||x)&&this.resetInitSegment(S,p,y,T,t),(h||g||x)&&this.resetInitialTimestamp(E),l||this.resetContiguity();const D=this.transmux(a,v,f,d,s);this.asyncResult=Wt(D);const A=this.currentTransmuxState;return A.contiguous=!0,A.discontinuity=!1,A.trackSwitch=!1,r.executeEnd=Qe(),D}flush(e){const t=e.transmuxing;t.executeStart=Qe();const{decrypter:s,currentTransmuxState:i,decryptionPromise:r}=this;if(r)return this.asyncResult=!0,r.then(()=>this.flush(e));const a=[],{timeOffset:o}=i;if(s){const u=s.flush();u&&a.push(this.push(u.buffer,null,e))}const{demuxer:c,remuxer:l}=this;if(!c||!l){t.executeEnd=Qe();const u=[ri(e)];return this.asyncResult?Promise.resolve(u):u}const h=c.flush(o);return Wt(h)?(this.asyncResult=!0,h.then(u=>(this.flushRemux(a,u,e),a))):(this.flushRemux(a,h,e),this.asyncResult?Promise.resolve(a):a)}flushRemux(e,t,s){const{audioTrack:i,videoTrack:r,id3Track:a,textTrack:o}=t,{accurateTimeOffset:c,timeOffset:l}=this.currentTransmuxState;this.logger.log(`[transmuxer.ts]: Flushed ${this.id} sn: ${s.sn}${s.part>-1?" part: "+s.part:""} of ${this.id===U.MAIN?"level":"track"} ${s.level}`);const h=this.remuxer.remux(i,r,a,o,l,c,!0,this.id);e.push({remuxResult:h,chunkMeta:s}),s.transmuxing.executeEnd=Qe()}resetInitialTimestamp(e){const{demuxer:t,remuxer:s}=this;!t||!s||(t.resetTimeStamp(e),s.resetTimeStamp(e))}resetContiguity(){const{demuxer:e,remuxer:t}=this;!e||!t||(e.resetContiguity(),t.resetNextTimestamp())}resetInitSegment(e,t,s,i,r){const{demuxer:a,remuxer:o}=this;!a||!o||(a.resetInitSegment(e,t,s,i),o.resetInitSegment(e,t,s,r))}destroy(){this.demuxer&&(this.demuxer.destroy(),this.demuxer=void 0),this.remuxer&&(this.remuxer.destroy(),this.remuxer=void 0)}transmux(e,t,s,i,r){let a;return t&&t.method==="SAMPLE-AES"?a=this.transmuxSampleAes(e,t,s,i,r):a=this.transmuxUnencrypted(e,s,i,r),a}transmuxUnencrypted(e,t,s,i){const{audioTrack:r,videoTrack:a,id3Track:o,textTrack:c}=this.demuxer.demux(e,t,!1,!this.config.progressive);return{remuxResult:this.remuxer.remux(r,a,o,c,t,s,!1,this.id),chunkMeta:i}}transmuxSampleAes(e,t,s,i,r){return this.demuxer.demuxSampleAes(e,t,s).then(a=>({remuxResult:this.remuxer.remux(a.audioTrack,a.videoTrack,a.id3Track,a.textTrack,s,i,!1,this.id),chunkMeta:r}))}configureTransmuxer(e){const{config:t,observer:s,typeSupported:i}=this;let r;for(let u=0,d=Ts.length;u<d;u++){var a;if((a=Ts[u].demux)!=null&&a.probe(e,this.logger)){r=Ts[u];break}}if(!r)return new Error("Failed to find demuxer by probing fragment data");const o=this.demuxer,c=this.remuxer,l=r.remux,h=r.demux;(!c||!(c instanceof l))&&(this.remuxer=new l(s,t,i,this.logger)),(!o||!(o instanceof h))&&(this.demuxer=new h(s,t,i,this.logger),this.probe=h.probe)}needsProbing(e,t){return!this.demuxer||!this.remuxer||e||t}getDecrypter(){let e=this.decrypter;return e||(e=this.decrypter=new Zi(this.config)),e}}function Eu(n,e){let t=null;return n.byteLength>0&&(e==null?void 0:e.key)!=null&&e.iv!==null&&e.method!=null&&(t=e),t}const ri=n=>({remuxResult:{},chunkMeta:n});function Wt(n){return"then"in n&&n.then instanceof Function}class Tu{constructor(e,t,s,i,r){this.audioCodec=void 0,this.videoCodec=void 0,this.initSegmentData=void 0,this.duration=void 0,this.defaultInitPts=void 0,this.audioCodec=e,this.videoCodec=t,this.initSegmentData=s,this.duration=i,this.defaultInitPts=r||null}}class Su{constructor(e,t,s,i,r,a){this.discontinuity=void 0,this.contiguous=void 0,this.accurateTimeOffset=void 0,this.trackSwitch=void 0,this.timeOffset=void 0,this.initSegmentChange=void 0,this.discontinuity=e,this.contiguous=t,this.accurateTimeOffset=s,this.trackSwitch=i,this.timeOffset=r,this.initSegmentChange=a}}let bn=0;class xo{constructor(e,t,s,i){this.error=null,this.hls=void 0,this.id=void 0,this.instanceNo=bn++,this.observer=void 0,this.frag=null,this.part=null,this.useWorker=void 0,this.workerContext=null,this.transmuxer=null,this.onTransmuxComplete=void 0,this.onFlush=void 0,this.onWorkerMessage=c=>{const l=c.data,h=this.hls;if(!(!h||!(l!=null&&l.event)||l.instanceNo!==this.instanceNo))switch(l.event){case"init":{var u;const d=(u=this.workerContext)==null?void 0:u.objectURL;d&&self.URL.revokeObjectURL(d);break}case"transmuxComplete":{this.handleTransmuxComplete(l.data);break}case"flush":{this.onFlush(l.data);break}case"workerLog":{h.logger[l.data.logType]&&h.logger[l.data.logType](l.data.message);break}default:{l.data=l.data||{},l.data.frag=this.frag,l.data.part=this.part,l.data.id=this.id,h.trigger(l.event,l.data);break}}},this.onWorkerError=c=>{if(!this.hls)return;const l=new Error(`${c.message} (${c.filename}:${c.lineno})`);this.hls.config.enableWorker=!1,this.hls.logger.warn(`Error in "${this.id}" Web Worker, fallback to inline`),this.hls.trigger(m.ERROR,{type:H.OTHER_ERROR,details:R.INTERNAL_EXCEPTION,fatal:!1,event:"demuxerWorker",error:l})};const r=e.config;this.hls=e,this.id=t,this.useWorker=!!r.enableWorker,this.onTransmuxComplete=s,this.onFlush=i;const a=(c,l)=>{l=l||{},l.frag=this.frag||void 0,c===m.ERROR&&(l=l,l.parent=this.id,l.part=this.part,this.error=l.error),this.hls.trigger(c,l)};this.observer=new ir,this.observer.on(m.FRAG_DECRYPTED,a),this.observer.on(m.ERROR,a);const o=Kr(r.preferManagedMediaSource);if(this.useWorker&&typeof Worker<"u"){const c=this.hls.logger;if(r.workerPath||_h()){try{r.workerPath?(c.log(`loading Web Worker ${r.workerPath} for "${t}"`),this.workerContext=Lh(r.workerPath)):(c.log(`injecting Web Worker for "${t}"`),this.workerContext=Ih());const{worker:h}=this.workerContext;h.addEventListener("message",this.onWorkerMessage),h.addEventListener("error",this.onWorkerError),h.postMessage({instanceNo:this.instanceNo,cmd:"init",typeSupported:o,id:t,config:oe(r)})}catch(h){c.warn(`Error setting up "${t}" Web Worker, fallback to inline`,h),this.terminateWorker(),this.error=null,this.transmuxer=new Rn(this.observer,o,r,"",t,e.logger)}return}}this.transmuxer=new Rn(this.observer,o,r,"",t,e.logger)}reset(){if(this.frag=null,this.part=null,this.workerContext){const e=this.instanceNo;this.instanceNo=bn++;const t=this.hls.config,s=Kr(t.preferManagedMediaSource);this.workerContext.worker.postMessage({instanceNo:this.instanceNo,cmd:"reset",resetNo:e,typeSupported:s,id:this.id,config:oe(t)})}}terminateWorker(){if(this.workerContext){const{worker:e}=this.workerContext;this.workerContext=null,e.removeEventListener("message",this.onWorkerMessage),e.removeEventListener("error",this.onWorkerError),Rh(this.hls.config.workerPath)}}destroy(){if(this.workerContext)this.terminateWorker(),this.onWorkerMessage=this.onWorkerError=null;else{const t=this.transmuxer;t&&(t.destroy(),this.transmuxer=null)}const e=this.observer;e&&e.removeAllListeners(),this.frag=null,this.part=null,this.observer=null,this.hls=null}push(e,t,s,i,r,a,o,c,l,h){var u,d;l.transmuxing.start=self.performance.now();const{instanceNo:f,transmuxer:g}=this,p=a?a.start:r.start,y=r.decryptdata,E=this.frag,T=!(E&&r.cc===E.cc),S=!(E&&l.level===E.level),v=E?l.sn-E.sn:-1,x=this.part?l.part-this.part.index:-1,D=v===0&&l.id>1&&l.id===(E==null?void 0:E.stats.chunkCount),A=!S&&(v===1||v===0&&(x===1||D&&x<=0)),b=self.performance.now();(S||v||r.stats.parsing.start===0)&&(r.stats.parsing.start=b),a&&(x||!A)&&(a.stats.parsing.start=b);const I=!(E&&((u=r.initSegment)==null?void 0:u.url)===((d=E.initSegment)==null?void 0:d.url)),_=new Su(T,A,c,S,p,I);if(!A||T||I){this.hls.logger.log(`[transmuxer-interface]: Starting new transmux session for ${r.type} sn: ${l.sn}${l.part>-1?" part: "+l.part:""} ${this.id===U.MAIN?"level":"track"}: ${l.level} id: ${l.id}
240105 discontinuity: ${T}
241106 trackSwitch: ${S}
242242- contiguous: ${x}
107107+ contiguous: ${A}
243108 accurateTimeOffset: ${c}
244244- timeOffset: ${y}
245245- initSegmentChange: ${_}`);const P=new Mc(s,i,t,o,h);this.configureTransmuxer(P)}if(this.frag=r,this.part=n,this.workerContext)this.workerContext.worker.postMessage({instanceNo:f,cmd:"demux",data:e,decryptdata:p,chunkMeta:l,state:I},e instanceof ArrayBuffer?[e]:[]);else if(g){const P=g.push(e,p,l,I);Vt(P)?P.then(F=>{this.handleTransmuxComplete(F)}).catch(F=>{this.transmuxerError(F,l,"transmuxer-interface push error")}):this.handleTransmuxComplete(P)}}flush(e){e.transmuxing.start=self.performance.now();const{instanceNo:t,transmuxer:s}=this;if(this.workerContext)this.workerContext.worker.postMessage({instanceNo:t,cmd:"flush",chunkMeta:e});else if(s){const i=s.flush(e);Vt(i)?i.then(r=>{this.handleFlushResult(r,e)}).catch(r=>{this.transmuxerError(r,e,"transmuxer-interface flush error")}):this.handleFlushResult(i,e)}}transmuxerError(e,t,s){this.hls&&(this.error=e,this.hls.trigger(m.ERROR,{type:V.MEDIA_ERROR,details:R.FRAG_PARSING_ERROR,chunkMeta:t,frag:this.frag||void 0,part:this.part||void 0,fatal:!1,error:e,err:e,reason:s}))}handleFlushResult(e,t){e.forEach(s=>{this.handleTransmuxComplete(s)}),this.onFlush(t)}configureTransmuxer(e){const{instanceNo:t,transmuxer:s}=this;this.workerContext?this.workerContext.worker.postMessage({instanceNo:t,cmd:"configure",config:e}):s&&s.configure(e)}handleTransmuxComplete(e){e.chunkMeta.transmuxing.end=self.performance.now(),this.onTransmuxComplete(e)}}const qr=100;class Bc extends Oi{constructor(e,t,s){super(e,t,s,"audio-stream-controller",B.AUDIO),this.mainAnchor=null,this.mainFragLoading=null,this.audioOnly=!1,this.bufferedTrack=null,this.switchingTrack=null,this.trackId=-1,this.waitingData=null,this.mainDetails=null,this.flushing=!1,this.bufferFlushed=!1,this.cachedTrackLoadedData=null,this.registerListeners()}onHandlerDestroying(){this.unregisterListeners(),super.onHandlerDestroying(),this.resetItem()}resetItem(){this.mainDetails=this.mainAnchor=this.mainFragLoading=this.bufferedTrack=this.switchingTrack=this.waitingData=this.cachedTrackLoadedData=null}registerListeners(){super.registerListeners();const{hls:e}=this;e.on(m.LEVEL_LOADED,this.onLevelLoaded,this),e.on(m.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.on(m.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(m.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(m.BUFFER_RESET,this.onBufferReset,this),e.on(m.BUFFER_CREATED,this.onBufferCreated,this),e.on(m.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(m.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(m.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(m.FRAG_LOADING,this.onFragLoading,this),e.on(m.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){const{hls:e}=this;e&&(super.unregisterListeners(),e.off(m.LEVEL_LOADED,this.onLevelLoaded,this),e.off(m.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.off(m.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(m.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(m.BUFFER_RESET,this.onBufferReset,this),e.off(m.BUFFER_CREATED,this.onBufferCreated,this),e.off(m.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(m.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(m.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(m.FRAG_LOADING,this.onFragLoading,this),e.off(m.FRAG_BUFFERED,this.onFragBuffered,this))}onInitPtsFound(e,{frag:t,id:s,initPTS:i,timescale:r,trackId:n}){if(s===B.MAIN){const o=t.cc,c=this.fragCurrent;if(this.initPTS[o]={baseTime:i,timescale:r,trackId:n},this.log(`InitPTS for cc: ${o} found from main: ${i/r} (${i}/${r}) trackId: ${n}`),this.mainAnchor=t,this.state===C.WAITING_INIT_PTS){const l=this.waitingData;(!l&&!this.loadingParts||l&&l.frag.cc!==o)&&this.syncWithAnchor(t,l==null?void 0:l.frag)}else!this.hls.hasEnoughToStart&&c&&c.cc!==o?(c.abortRequests(),this.syncWithAnchor(t,c)):this.state===C.IDLE&&this.tick()}}getLoadPosition(){return!this.startFragRequested&&this.nextLoadPosition>=0?this.nextLoadPosition:super.getLoadPosition()}syncWithAnchor(e,t){var s;const i=((s=this.mainFragLoading)==null?void 0:s.frag)||null;if(t&&(i==null?void 0:i.cc)===t.cc)return;const r=(i||e).cc,n=this.getLevelDetails(),o=this.getLoadPosition(),c=Bn(n,r,o);c&&(this.log(`Syncing with main frag at ${c.start} cc ${c.cc}`),this.startFragRequested=!1,this.nextLoadPosition=c.start,this.resetLoadingState(),this.state===C.IDLE&&this.doTickIdle())}startLoad(e,t){if(!this.levels){this.startPosition=e,this.state=C.STOPPED;return}const s=this.lastCurrentTime;this.stopLoad(),this.setInterval(qr),s>0&&e===-1?(this.log(`Override startPosition with lastCurrentTime @${s.toFixed(3)}`),e=s,this.state=C.IDLE):this.state=C.WAITING_TRACK,this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,this.tick()}doTick(){switch(this.state){case C.IDLE:this.doTickIdle();break;case C.WAITING_TRACK:{const{levels:e,trackId:t}=this,s=e==null?void 0:e[t],i=s==null?void 0:s.details;if(i&&!this.waitForLive(s)){if(this.waitForCdnTuneIn(i))break;this.state=C.WAITING_INIT_PTS}break}case C.FRAG_LOADING_WAITING_RETRY:{this.checkRetryDate();break}case C.WAITING_INIT_PTS:{const e=this.waitingData;if(e){const{frag:t,part:s,cache:i,complete:r}=e,n=this.mainAnchor;if(this.initPTS[t.cc]!==void 0){this.waitingData=null,this.state=C.FRAG_LOADING;const o=i.flush().buffer,c={frag:t,part:s,payload:o,networkDetails:null};this._handleFragmentLoadProgress(c),r&&super._handleFragmentLoadComplete(c)}else n&&n.cc!==e.frag.cc&&this.syncWithAnchor(n,e.frag)}else this.state=C.IDLE}}this.onTickEnd()}resetLoadingState(){const e=this.waitingData;e&&(this.fragmentTracker.removeFragment(e.frag),this.waitingData=null),super.resetLoadingState()}onTickEnd(){const{media:e}=this;e!=null&&e.readyState&&(this.lastCurrentTime=e.currentTime)}doTickIdle(){var e;const{hls:t,levels:s,media:i,trackId:r}=this,n=t.config;if(!this.buffering||!i&&!this.primaryPrefetch&&(this.startFragRequested||!n.startFragPrefetch)||!(s!=null&&s[r]))return;const o=s[r],c=o.details;if(!c||this.waitForLive(o)||this.waitForCdnTuneIn(c)){this.state=C.WAITING_TRACK,this.startFragRequested=!1;return}const l=this.mediaBuffer?this.mediaBuffer:this.media;this.bufferFlushed&&l&&(this.bufferFlushed=!1,this.afterBufferFlushed(l,re.AUDIO,B.AUDIO));const h=this.getFwdBufferInfo(l,B.AUDIO);if(h===null)return;if(!this.switchingTrack&&this._streamEnded(h,c)){t.trigger(m.BUFFER_EOS,{type:"audio"}),this.state=C.ENDED;return}const d=h.len,u=t.maxBufferLength,f=c.fragments,g=f[0].start,y=this.getLoadPosition(),p=this.flushing?y:h.end;if(this.switchingTrack&&i){const S=y;c.PTSKnown&&S<g&&(h.end>g||h.nextStart)&&(this.log("Alt audio track ahead of main track, seek to start of alt audio track"),i.currentTime=g+.05)}if(d>=u&&!this.switchingTrack&&p<f[f.length-1].start)return;let E=this.getNextFragment(p,c);if(E&&this.isLoopLoading(E,p)&&(E=this.getNextFragmentLoopLoading(E,c,h,B.MAIN,u)),!E){this.bufferFlushed=!0;return}let T=((e=this.mainFragLoading)==null?void 0:e.frag)||null;if(!this.audioOnly&&this.startFragRequested&&T&&ce(E)&&!E.endList&&(!c.live||!this.loadingParts&&p<this.hls.liveSyncPosition)&&(this.fragmentTracker.getState(T)===de.OK&&(this.mainFragLoading=T=null),T&&ce(T))){if(E.start>T.end){const v=this.fragmentTracker.getFragAtPos(p,B.MAIN);v&&v.end>T.end&&(T=v,this.mainFragLoading={frag:v,targetBufferTime:null})}if(E.start>T.end)return}this.loadFragment(E,o,p)}onMediaDetaching(e,t){this.bufferFlushed=this.flushing=!1,super.onMediaDetaching(e,t)}onAudioTracksUpdated(e,{audioTracks:t}){this.resetTransmuxer(),this.levels=t.map(s=>new $t(s))}onAudioTrackSwitching(e,t){const s=!!t.url;this.trackId=t.id;const{fragCurrent:i}=this;i&&(i.abortRequests(),this.removeUnbufferedFrags(i.start)),this.resetLoadingState(),s?(this.switchingTrack=t,this.flushAudioIfNeeded(t),this.state!==C.STOPPED&&(this.setInterval(qr),this.state=C.IDLE,this.tick())):(this.resetTransmuxer(),this.switchingTrack=null,this.bufferedTrack=t,this.clearInterval())}onManifestLoading(){super.onManifestLoading(),this.bufferFlushed=this.flushing=this.audioOnly=!1,this.resetItem(),this.trackId=-1}onLevelLoaded(e,t){this.mainDetails=t.details;const s=this.cachedTrackLoadedData;s&&(this.cachedTrackLoadedData=null,this.onAudioTrackLoaded(m.AUDIO_TRACK_LOADED,s))}onAudioTrackLoaded(e,t){var s;const{levels:i}=this,{details:r,id:n,groupId:o,track:c}=t;if(!i){this.warn(`Audio tracks reset while loading track ${n} "${c.name}" of "${o}"`);return}const l=this.mainDetails;if(!l||r.endCC>l.endCC||l.expired){this.cachedTrackLoadedData=t,this.state!==C.STOPPED&&(this.state=C.WAITING_TRACK);return}this.cachedTrackLoadedData=null,this.log(`Audio track ${n} "${c.name}" of "${o}" loaded [${r.startSN},${r.endSN}]${r.lastPartSn?`[part-${r.lastPartSn}-${r.lastPartIndex}]`:""},duration:${r.totalduration}`);const h=i[n];let d=0;if(r.live||(s=h.details)!=null&&s.live){if(this.checkLiveUpdate(r),r.deltaUpdateFailed)return;if(h.details){var u;d=this.alignPlaylists(r,h.details,(u=this.levelLastLoaded)==null?void 0:u.details)}r.alignedSliding||(sa(r,l),r.alignedSliding||Rs(r,l),d=r.fragmentStart)}h.details=r,this.levelLastLoaded=h,this.startFragRequested||this.setStartPosition(l,d),this.hls.trigger(m.AUDIO_TRACK_UPDATED,{details:r,id:n,groupId:t.groupId}),this.state===C.WAITING_TRACK&&!this.waitForCdnTuneIn(r)&&(this.state=C.IDLE),this.tick()}_handleFragmentLoadProgress(e){var t;const s=e.frag,{part:i,payload:r}=e,{config:n,trackId:o,levels:c}=this;if(!c){this.warn(`Audio tracks were reset while fragment load was in progress. Fragment ${s.sn} of level ${s.level} will not be buffered`);return}const l=c[o];if(!l){this.warn("Audio track is undefined on fragment load progress");return}const h=l.details;if(!h){this.warn("Audio track details undefined on fragment load progress"),this.removeUnbufferedFrags(s.start);return}const d=n.defaultAudioCodec||l.audioCodec||"mp4a.40.2";let u=this.transmuxer;u||(u=this.transmuxer=new xa(this.hls,B.AUDIO,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)));const f=this.initPTS[s.cc],g=(t=s.initSegment)==null?void 0:t.data;if(f!==void 0){const p=i?i.index:-1,E=p!==-1,T=new Pi(s.level,s.sn,s.stats.chunkCount,r.byteLength,p,E);u.push(r,g,d,"",s,i,h.totalduration,!1,T,f)}else{this.log(`Unknown video PTS for cc ${s.cc}, waiting for video PTS before demuxing audio frag ${s.sn} of [${h.startSN} ,${h.endSN}],track ${o}`);const{cache:y}=this.waitingData=this.waitingData||{frag:s,part:i,cache:new ia,complete:!1};y.push(new Uint8Array(r)),this.state!==C.STOPPED&&(this.state=C.WAITING_INIT_PTS)}}_handleFragmentLoadComplete(e){if(this.waitingData){this.waitingData.complete=!0;return}super._handleFragmentLoadComplete(e)}onBufferReset(){this.mediaBuffer=null}onBufferCreated(e,t){this.bufferFlushed=this.flushing=!1;const s=t.tracks.audio;s&&(this.mediaBuffer=s.buffer||null)}onFragLoading(e,t){!this.audioOnly&&t.frag.type===B.MAIN&&ce(t.frag)&&(this.mainFragLoading=t,this.state===C.IDLE&&this.tick())}onFragBuffered(e,t){const{frag:s,part:i}=t;if(s.type!==B.AUDIO){!this.audioOnly&&s.type===B.MAIN&&!s.elementaryStreams.video&&!s.elementaryStreams.audiovideo&&(this.audioOnly=!0,this.mainFragLoading=null);return}if(this.fragContextChanged(s)){this.warn(`Fragment ${s.sn}${i?" p: "+i.index:""} of level ${s.level} finished buffering, but was aborted. state: ${this.state}, audioSwitch: ${this.switchingTrack?this.switchingTrack.name:"false"}`);return}if(ce(s)){this.fragPrevious=s;const r=this.switchingTrack;r&&(this.bufferedTrack=r,this.switchingTrack=null,this.hls.trigger(m.AUDIO_TRACK_SWITCHED,te({},r)))}this.fragBufferedComplete(s,i),this.media&&this.tick()}onError(e,t){var s;if(t.fatal){this.state=C.ERROR;return}switch(t.details){case R.FRAG_GAP:case R.FRAG_PARSING_ERROR:case R.FRAG_DECRYPT_ERROR:case R.FRAG_LOAD_ERROR:case R.FRAG_LOAD_TIMEOUT:case R.KEY_LOAD_ERROR:case R.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(B.AUDIO,t);break;case R.AUDIO_TRACK_LOAD_ERROR:case R.AUDIO_TRACK_LOAD_TIMEOUT:case R.LEVEL_PARSING_ERROR:!t.levelRetry&&this.state===C.WAITING_TRACK&&((s=t.context)==null?void 0:s.type)===Q.AUDIO_TRACK&&(this.state=C.IDLE);break;case R.BUFFER_ADD_CODEC_ERROR:case R.BUFFER_APPEND_ERROR:if(t.parent!=="audio")return;this.reduceLengthAndFlushBuffer(t)||this.resetLoadingState();break;case R.BUFFER_FULL_ERROR:if(t.parent!=="audio")return;this.reduceLengthAndFlushBuffer(t)&&(this.bufferedTrack=null,super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"));break;case R.INTERNAL_EXCEPTION:this.recoverWorkerError(t);break}}onBufferFlushing(e,{type:t}){t!==re.VIDEO&&(this.flushing=!0)}onBufferFlushed(e,{type:t}){if(t!==re.VIDEO){this.flushing=!1,this.bufferFlushed=!0,this.state===C.ENDED&&(this.state=C.IDLE);const s=this.mediaBuffer||this.media;s&&(this.afterBufferFlushed(s,t,B.AUDIO),this.tick())}}_handleTransmuxComplete(e){var t;const s="audio",{hls:i}=this,{remuxResult:r,chunkMeta:n}=e,o=this.getCurrentContext(n);if(!o){this.resetWhenMissingContext(n);return}const{frag:c,part:l,level:h}=o,{details:d}=h,{audio:u,text:f,id3:g,initSegment:y}=r;if(this.fragContextChanged(c)||!d){this.fragmentTracker.removeFragment(c);return}if(this.state=C.PARSING,this.switchingTrack&&u&&this.completeAudioSwitch(this.switchingTrack),y!=null&&y.tracks){const p=c.initSegment||c;if(this.unhandledEncryptionError(y,c))return;this._bufferInitSegment(h,y.tracks,p,n),i.trigger(m.FRAG_PARSING_INIT_SEGMENT,{frag:p,id:s,tracks:y.tracks})}if(u){const{startPTS:p,endPTS:E,startDTS:T,endDTS:S}=u;l&&(l.elementaryStreams[re.AUDIO]={startPTS:p,endPTS:E,startDTS:T,endDTS:S}),c.setElementaryStreamInfo(re.AUDIO,p,E,T,S),this.bufferFragmentData(u,c,l,n)}if(g!=null&&(t=g.samples)!=null&&t.length){const p=ie({id:s,frag:c,details:d},g);i.trigger(m.FRAG_PARSING_METADATA,p)}if(f){const p=ie({id:s,frag:c,details:d},f);i.trigger(m.FRAG_PARSING_USERDATA,p)}}_bufferInitSegment(e,t,s,i){if(this.state!==C.PARSING||(t.video&&delete t.video,t.audiovideo&&delete t.audiovideo,!t.audio))return;const r=t.audio;r.id=B.AUDIO;const n=e.audioCodec;this.log(`Init audio buffer, container:${r.container}, codecs[level/parsed]=[${n}/${r.codec}]`),n&&n.split(",").length===1&&(r.levelCodec=n),this.hls.trigger(m.BUFFER_CODECS,t);const o=r.initSegment;if(o!=null&&o.byteLength){const c={type:"audio",frag:s,part:null,chunkMeta:i,parent:s.type,data:o};this.hls.trigger(m.BUFFER_APPENDING,c)}this.tickImmediate()}loadFragment(e,t,s){const i=this.fragmentTracker.getState(e);if(this.switchingTrack||i===de.NOT_LOADED||i===de.PARTIAL){var r;if(!ce(e))this._loadInitSegment(e,t);else if((r=t.details)!=null&&r.live&&!this.initPTS[e.cc]){this.log(`Waiting for video PTS in continuity counter ${e.cc} of live stream before loading audio fragment ${e.sn} of level ${this.trackId}`),this.state=C.WAITING_INIT_PTS;const n=this.mainDetails;n&&n.fragmentStart!==t.details.fragmentStart&&Rs(t.details,n)}else super.loadFragment(e,t,s)}else this.clearTrackerIfNeeded(e)}flushAudioIfNeeded(e){if(this.media&&this.bufferedTrack){const{name:t,lang:s,assocLang:i,characteristics:r,audioCodec:n,channels:o}=this.bufferedTrack;ft({name:t,lang:s,assocLang:i,characteristics:r,audioCodec:n,channels:o},e,ut)||(vs(e.url,this.hls)?(this.log("Switching audio track : flushing all audio"),super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"),this.bufferedTrack=null):this.bufferedTrack=e)}}completeAudioSwitch(e){const{hls:t}=this;this.flushAudioIfNeeded(e),this.bufferedTrack=e,this.switchingTrack=null,t.trigger(m.AUDIO_TRACK_SWITCHED,te({},e))}}class Ki extends we{constructor(e,t){super(t,e.logger),this.hls=void 0,this.canLoad=!1,this.timer=-1,this.hls=e}destroy(){this.clearTimer(),this.hls=this.log=this.warn=null}clearTimer(){this.timer!==-1&&(self.clearTimeout(this.timer),this.timer=-1)}startLoad(){this.canLoad=!0,this.loadPlaylist()}stopLoad(){this.canLoad=!1,this.clearTimer()}switchParams(e,t,s){const i=t==null?void 0:t.renditionReports;if(i){let r=-1;for(let n=0;n<i.length;n++){const o=i[n];let c;try{c=new self.URL(o.URI,t.url).href}catch(l){this.warn(`Could not construct new URL for Rendition Report: ${l}`),c=o.URI||""}if(c===e){r=n;break}else c===e.substring(0,c.length)&&(r=n)}if(r!==-1){const n=i[r],o=parseInt(n["LAST-MSN"])||t.lastPartSn;let c=parseInt(n["LAST-PART"])||t.lastPartIndex;if(this.hls.config.lowLatencyMode){const h=Math.min(t.age-t.partTarget,t.targetduration);c>=0&&h>t.partTarget&&(c+=1)}const l=s&&lr(s);return new cr(o,c>=0?c:void 0,l)}}}loadPlaylist(e){this.clearTimer()}loadingPlaylist(e,t){this.clearTimer()}shouldLoadPlaylist(e){return this.canLoad&&!!e&&!!e.url&&(!e.details||e.details.live)}getUrlWithDirectives(e,t){if(t)try{return t.addDirectives(e)}catch(s){this.warn(`Could not construct new URL with HLS Delivery Directives: ${s}`)}return e}playlistLoaded(e,t,s){const{details:i,stats:r}=t,n=self.performance.now(),o=r.loading.first?Math.max(0,n-r.loading.first):0;i.advancedDateTime=Date.now()-o;const c=this.hls.config.timelineOffset;if(c!==i.appliedTimelineOffset){const h=Math.max(c||0,0);i.appliedTimelineOffset=h,i.fragments.forEach(d=>{d.setStart(d.playlistOffset+h)})}if(i.live||s!=null&&s.live){const h="levelInfo"in t?t.levelInfo:t.track;if(i.reloaded(s),s&&i.fragments.length>0){Cl(s,i,this);const T=i.playlistParsingError;if(T){this.warn(T);const S=this.hls;if(!S.config.ignorePlaylistParsingErrors){var l;const{networkDetails:v}=t;S.trigger(m.ERROR,{type:V.NETWORK_ERROR,details:R.LEVEL_PARSING_ERROR,fatal:!1,url:i.url,error:T,reason:T.message,level:t.level||void 0,parent:(l=i.fragments[0])==null?void 0:l.type,networkDetails:v,stats:r});return}i.playlistParsingError=null}}i.requestScheduled===-1&&(i.requestScheduled=r.loading.start);const d=this.hls.mainForwardBufferInfo,u=d?d.end-d.len:0,f=(i.edge-u)*1e3,g=Qn(i,f);if(i.requestScheduled+g<n?i.requestScheduled=n:i.requestScheduled+=g,this.log(`live playlist ${e} ${i.advanced?"REFRESHED "+i.lastPartSn+"-"+i.lastPartIndex:i.updated?"UPDATED":"MISSED"}`),!this.canLoad||!i.live)return;let y,p,E;if(i.canBlockReload&&i.endSN&&i.advanced){const T=this.hls.config.lowLatencyMode,S=i.lastPartSn,v=i.endSN,A=i.lastPartIndex,D=A!==-1,x=S===v;D?x?(p=v+1,E=T?0:A):(p=S,E=T?A+1:i.maxPartIndex):p=v+1;const b=i.age,_=b+i.ageHeader;let I=Math.min(_-i.partTarget,i.targetduration*1.5);if(I>0){if(_>i.targetduration*3)this.log(`Playlist last advanced ${b.toFixed(2)}s ago. Omitting segment and part directives.`),p=void 0,E=void 0;else if(s!=null&&s.tuneInGoal&&_-i.partTarget>s.tuneInGoal)this.warn(`CDN Tune-in goal increased from: ${s.tuneInGoal} to: ${I} with playlist age: ${i.age}`),I=0;else{const P=Math.floor(I/i.targetduration);if(p+=P,E!==void 0){const F=Math.round(I%i.targetduration/i.partTarget);E+=F}this.log(`CDN Tune-in age: ${i.ageHeader}s last advanced ${b.toFixed(2)}s goal: ${I} skip sn ${P} to part ${E}`)}i.tuneInGoal=I}if(y=this.getDeliveryDirectives(i,t.deliveryDirectives,p,E),T||!x){i.requestScheduled=n,this.loadingPlaylist(h,y);return}}else(i.canBlockReload||i.canSkipUntil)&&(y=this.getDeliveryDirectives(i,t.deliveryDirectives,p,E));y&&p!==void 0&&i.canBlockReload&&(i.requestScheduled=r.loading.first+Math.max(g-o*2,g/2)),this.scheduleLoading(h,y,i)}else this.clearTimer()}scheduleLoading(e,t,s){const i=s||e.details;if(!i){this.loadingPlaylist(e,t);return}const r=self.performance.now(),n=i.requestScheduled;if(r>=n){this.loadingPlaylist(e,t);return}const o=n-r;this.log(`reload live playlist ${e.name||e.bitrate+"bps"} in ${Math.round(o)} ms`),this.clearTimer(),this.timer=self.setTimeout(()=>this.loadingPlaylist(e,t),o)}getDeliveryDirectives(e,t,s,i){let r=lr(e);return t!=null&&t.skip&&e.deltaUpdateFailed&&(s=t.msn,i=t.part,r=hs.No),new cr(s,i,r)}checkRetry(e){const t=e.details,s=xs(e),i=e.errorAction,{action:r,retryCount:n=0,retryConfig:o}=i||{},c=!!i&&!!o&&(r===ge.RetryRequest||!i.resolved&&r===ge.SendAlternateToPenaltyBox);if(c){var l;if(n>=o.maxNumRetry)return!1;if(s&&(l=e.context)!=null&&l.deliveryDirectives)this.warn(`Retrying playlist loading ${n+1}/${o.maxNumRetry} after "${t}" without delivery-directives`),this.loadPlaylist();else{const h=Di(o,n);this.clearTimer(),this.timer=self.setTimeout(()=>this.loadPlaylist(),h),this.warn(`Retrying playlist loading ${n+1}/${o.maxNumRetry} after "${t}" in ${h}ms`)}e.levelRetry=!0,i.resolved=!0}return c}}function Aa(a,e){if(a.length!==e.length)return!1;for(let t=0;t<a.length;t++)if(!Ht(a[t].attrs,e[t].attrs))return!1;return!0}function Ht(a,e,t){const s=a["STABLE-RENDITION-ID"];return s&&!t?s===e["STABLE-RENDITION-ID"]:!(t||["LANGUAGE","NAME","CHARACTERISTICS","AUTOSELECT","DEFAULT","FORCED","ASSOC-LANGUAGE"]).some(i=>a[i]!==e[i])}function mi(a,e){return e.label.toLowerCase()===a.name.toLowerCase()&&(!e.language||e.language.toLowerCase()===(a.lang||"").toLowerCase())}class Uc extends Ki{constructor(e){super(e,"audio-track-controller"),this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0,this.registerListeners()}registerListeners(){const{hls:e}=this;e.on(m.MANIFEST_LOADING,this.onManifestLoading,this),e.on(m.MANIFEST_PARSED,this.onManifestParsed,this),e.on(m.LEVEL_LOADING,this.onLevelLoading,this),e.on(m.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(m.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(m.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(m.MANIFEST_LOADING,this.onManifestLoading,this),e.off(m.MANIFEST_PARSED,this.onManifestParsed,this),e.off(m.LEVEL_LOADING,this.onLevelLoading,this),e.off(m.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(m.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(m.ERROR,this.onError,this)}destroy(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.currentTrack=null,super.destroy()}onManifestLoading(){this.tracks=[],this.tracksInGroup=[],this.groupIds=null,this.currentTrack=null,this.trackId=-1,this.selectDefaultTrack=!0}onManifestParsed(e,t){this.tracks=t.audioTracks||[]}onAudioTrackLoaded(e,t){const{id:s,groupId:i,details:r}=t,n=this.tracksInGroup[s];if(!n||n.groupId!==i){this.warn(`Audio track with id:${s} and group:${i} not found in active group ${n==null?void 0:n.groupId}`);return}const o=n.details;n.details=t.details,this.log(`Audio track ${s} "${n.name}" lang:${n.lang} group:${i} loaded [${r.startSN}-${r.endSN}]`),s===this.trackId&&this.playlistLoaded(s,t,o)}onLevelLoading(e,t){this.switchLevel(t.level)}onLevelSwitching(e,t){this.switchLevel(t.level)}switchLevel(e){const t=this.hls.levels[e];if(!t)return;const s=t.audioGroups||null,i=this.groupIds;let r=this.currentTrack;if(!s||(i==null?void 0:i.length)!==(s==null?void 0:s.length)||s!=null&&s.some(o=>(i==null?void 0:i.indexOf(o))===-1)){this.groupIds=s,this.trackId=-1,this.currentTrack=null;const o=this.tracks.filter(u=>!s||s.indexOf(u.groupId)!==-1);if(o.length)this.selectDefaultTrack&&!o.some(u=>u.default)&&(this.selectDefaultTrack=!1),o.forEach((u,f)=>{u.id=f});else if(!r&&!this.tracksInGroup.length)return;this.tracksInGroup=o;const c=this.hls.config.audioPreference;if(!r&&c){const u=Ve(c,o,ut);if(u>-1)r=o[u];else{const f=Ve(c,this.tracks);r=this.tracks[f]}}let l=this.findTrackId(r);l===-1&&r&&(l=this.findTrackId(null));const h={audioTracks:o};this.log(`Updating audio tracks, ${o.length} track(s) found in group(s): ${s==null?void 0:s.join(",")}`),this.hls.trigger(m.AUDIO_TRACKS_UPDATED,h);const d=this.trackId;if(l!==-1&&d===-1)this.setAudioTrack(l);else if(o.length&&d===-1){var n;const u=new Error(`No audio track selected for current audio group-ID(s): ${(n=this.groupIds)==null?void 0:n.join(",")} track count: ${o.length}`);this.warn(u.message),this.hls.trigger(m.ERROR,{type:V.MEDIA_ERROR,details:R.AUDIO_TRACK_LOAD_ERROR,fatal:!0,error:u})}}}onError(e,t){t.fatal||!t.context||t.context.type===Q.AUDIO_TRACK&&t.context.id===this.trackId&&(!this.groupIds||this.groupIds.indexOf(t.context.groupId)!==-1)&&this.checkRetry(t)}get allAudioTracks(){return this.tracks}get audioTracks(){return this.tracksInGroup}get audioTrack(){return this.trackId}set audioTrack(e){this.selectDefaultTrack=!1,this.setAudioTrack(e)}setAudioOption(e){const t=this.hls;if(t.config.audioPreference=e,e){const s=this.allAudioTracks;if(this.selectDefaultTrack=!1,s.length){const i=this.currentTrack;if(i&&ft(e,i,ut))return i;const r=Ve(e,this.tracksInGroup,ut);if(r>-1){const n=this.tracksInGroup[r];return this.setAudioTrack(r),n}else if(i){let n=t.loadLevel;n===-1&&(n=t.firstAutoLevel);const o=Qo(e,t.levels,s,n,ut);if(o===-1)return null;t.nextLoadLevel=o}if(e.channels||e.audioCodec){const n=Ve(e,s);if(n>-1)return s[n]}}}return null}setAudioTrack(e){const t=this.tracksInGroup;if(e<0||e>=t.length){this.warn(`Invalid audio track id: ${e}`);return}this.selectDefaultTrack=!1;const s=this.currentTrack,i=t[e],r=i.details&&!i.details.live;if(e===this.trackId&&i===s&&r||(this.log(`Switching to audio-track ${e} "${i.name}" lang:${i.lang} group:${i.groupId} channels:${i.channels}`),this.trackId=e,this.currentTrack=i,this.hls.trigger(m.AUDIO_TRACK_SWITCHING,te({},i)),r))return;const n=this.switchParams(i.url,s==null?void 0:s.details,i.details);this.loadPlaylist(n)}findTrackId(e){const t=this.tracksInGroup;for(let s=0;s<t.length;s++){const i=t[s];if(!(this.selectDefaultTrack&&!i.default)&&(!e||ft(e,i,ut)))return s}if(e){const{name:s,lang:i,assocLang:r,characteristics:n,audioCodec:o,channels:c}=e;for(let l=0;l<t.length;l++){const h=t[l];if(ft({name:s,lang:i,assocLang:r,characteristics:n,audioCodec:o,channels:c},h,ut))return l}for(let l=0;l<t.length;l++){const h=t[l];if(Ht(e.attrs,h.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return l}for(let l=0;l<t.length;l++){const h=t[l];if(Ht(e.attrs,h.attrs,["LANGUAGE"]))return l}}return-1}loadPlaylist(e){super.loadPlaylist();const t=this.currentTrack;this.shouldLoadPlaylist(t)&&vs(t.url,this.hls)&&this.scheduleLoading(t,e)}loadingPlaylist(e,t){super.loadingPlaylist(e,t);const s=e.id,i=e.groupId,r=this.getUrlWithDirectives(e.url,t),n=e.details,o=n==null?void 0:n.age;this.log(`Loading audio-track ${s} "${e.name}" lang:${e.lang} group:${i}${(t==null?void 0:t.msn)!==void 0?" at sn "+t.msn+" part "+t.part:""}${o&&n.live?" age "+o.toFixed(1)+(n.type&&" "+n.type||""):""} ${r}`),this.hls.trigger(m.AUDIO_TRACK_LOADING,{url:r,id:s,groupId:i,deliveryDirectives:t||null,track:e})}}class $c{constructor(e){this.tracks=void 0,this.queues={video:[],audio:[],audiovideo:[]},this.tracks=e}destroy(){this.tracks=this.queues=null}append(e,t,s){if(this.queues===null||this.tracks===null)return;const i=this.queues[t];i.push(e),i.length===1&&!s&&this.executeNext(t)}appendBlocker(e){return new Promise(t=>{const s={label:"async-blocker",execute:t,onStart:()=>{},onComplete:()=>{},onError:()=>{}};this.append(s,e)})}prependBlocker(e){return new Promise(t=>{if(this.queues){const s={label:"async-blocker-prepend",execute:t,onStart:()=>{},onComplete:()=>{},onError:()=>{}};this.queues[e].unshift(s)}})}removeBlockers(){this.queues!==null&&[this.queues.video,this.queues.audio,this.queues.audiovideo].forEach(e=>{var t;const s=(t=e[0])==null?void 0:t.label;(s==="async-blocker"||s==="async-blocker-prepend")&&(e[0].execute(),e.splice(0,1))})}unblockAudio(e){if(this.queues===null)return;this.queues.audio[0]===e&&this.shiftAndExecuteNext("audio")}executeNext(e){if(this.queues===null||this.tracks===null)return;const t=this.queues[e];if(t.length){const i=t[0];try{i.execute()}catch(r){var s;if(i.onError(r),this.queues===null||this.tracks===null)return;const n=(s=this.tracks[e])==null?void 0:s.buffer;n!=null&&n.updating||this.shiftAndExecuteNext(e)}}}shiftAndExecuteNext(e){this.queues!==null&&(this.queues[e].shift(),this.executeNext(e))}current(e){var t;return((t=this.queues)==null?void 0:t[e][0])||null}toString(){const{queues:e,tracks:t}=this;return e===null||t===null?"<destroyed>":`
109109+ timeOffset: ${p}
110110+ initSegmentChange: ${I}`);const C=new Tu(s,i,t,o,h);this.configureTransmuxer(C)}if(this.frag=r,this.part=a,this.workerContext)this.workerContext.worker.postMessage({instanceNo:f,cmd:"demux",data:e,decryptdata:y,chunkMeta:l,state:_},e instanceof ArrayBuffer?[e]:[]);else if(g){const C=g.push(e,y,l,_);Wt(C)?C.then(k=>{this.handleTransmuxComplete(k)}).catch(k=>{this.transmuxerError(k,l,"transmuxer-interface push error")}):this.handleTransmuxComplete(C)}}flush(e){e.transmuxing.start=self.performance.now();const{instanceNo:t,transmuxer:s}=this;if(this.workerContext)this.workerContext.worker.postMessage({instanceNo:t,cmd:"flush",chunkMeta:e});else if(s){const i=s.flush(e);Wt(i)?i.then(r=>{this.handleFlushResult(r,e)}).catch(r=>{this.transmuxerError(r,e,"transmuxer-interface flush error")}):this.handleFlushResult(i,e)}}transmuxerError(e,t,s){this.hls&&(this.error=e,this.hls.trigger(m.ERROR,{type:H.MEDIA_ERROR,details:R.FRAG_PARSING_ERROR,chunkMeta:t,frag:this.frag||void 0,part:this.part||void 0,fatal:!1,error:e,err:e,reason:s}))}handleFlushResult(e,t){e.forEach(s=>{this.handleTransmuxComplete(s)}),this.onFlush(t)}configureTransmuxer(e){const{instanceNo:t,transmuxer:s}=this;this.workerContext?this.workerContext.worker.postMessage({instanceNo:t,cmd:"configure",config:e}):s&&s.configure(e)}handleTransmuxComplete(e){e.chunkMeta.transmuxing.end=self.performance.now(),this.onTransmuxComplete(e)}}const Dn=100;class vu extends sr{constructor(e,t,s){super(e,t,s,"audio-stream-controller",U.AUDIO),this.mainAnchor=null,this.mainFragLoading=null,this.audioOnly=!1,this.bufferedTrack=null,this.switchingTrack=null,this.trackId=-1,this.waitingData=null,this.mainDetails=null,this.flushing=!1,this.bufferFlushed=!1,this.cachedTrackLoadedData=null,this.registerListeners()}onHandlerDestroying(){this.unregisterListeners(),super.onHandlerDestroying(),this.resetItem()}resetItem(){this.mainDetails=this.mainAnchor=this.mainFragLoading=this.bufferedTrack=this.switchingTrack=this.waitingData=this.cachedTrackLoadedData=null}registerListeners(){super.registerListeners();const{hls:e}=this;e.on(m.LEVEL_LOADED,this.onLevelLoaded,this),e.on(m.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.on(m.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(m.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(m.BUFFER_RESET,this.onBufferReset,this),e.on(m.BUFFER_CREATED,this.onBufferCreated,this),e.on(m.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(m.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(m.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(m.FRAG_LOADING,this.onFragLoading,this),e.on(m.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){const{hls:e}=this;e&&(super.unregisterListeners(),e.off(m.LEVEL_LOADED,this.onLevelLoaded,this),e.off(m.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.off(m.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(m.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(m.BUFFER_RESET,this.onBufferReset,this),e.off(m.BUFFER_CREATED,this.onBufferCreated,this),e.off(m.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(m.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(m.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(m.FRAG_LOADING,this.onFragLoading,this),e.off(m.FRAG_BUFFERED,this.onFragBuffered,this))}onInitPtsFound(e,{frag:t,id:s,initPTS:i,timescale:r,trackId:a}){if(s===U.MAIN){const o=t.cc,c=this.fragCurrent;if(this.initPTS[o]={baseTime:i,timescale:r,trackId:a},this.log(`InitPTS for cc: ${o} found from main: ${i/r} (${i}/${r}) trackId: ${a}`),this.mainAnchor=t,this.state===P.WAITING_INIT_PTS){const l=this.waitingData;(!l&&!this.loadingParts||l&&l.frag.cc!==o)&&this.syncWithAnchor(t,l==null?void 0:l.frag)}else!this.hls.hasEnoughToStart&&c&&c.cc!==o?(c.abortRequests(),this.syncWithAnchor(t,c)):this.state===P.IDLE&&this.tick()}}getLoadPosition(){return!this.startFragRequested&&this.nextLoadPosition>=0?this.nextLoadPosition:super.getLoadPosition()}syncWithAnchor(e,t){var s;const i=((s=this.mainFragLoading)==null?void 0:s.frag)||null;if(t&&(i==null?void 0:i.cc)===t.cc)return;const r=(i||e).cc,a=this.getLevelDetails(),o=this.getLoadPosition(),c=Na(a,r,o);c&&(this.log(`Syncing with main frag at ${c.start} cc ${c.cc}`),this.startFragRequested=!1,this.nextLoadPosition=c.start,this.resetLoadingState(),this.state===P.IDLE&&this.doTickIdle())}startLoad(e,t){if(!this.levels){this.startPosition=e,this.state=P.STOPPED;return}const s=this.lastCurrentTime;this.stopLoad(),this.setInterval(Dn),s>0&&e===-1?(this.log(`Override startPosition with lastCurrentTime @${s.toFixed(3)}`),e=s,this.state=P.IDLE):this.state=P.WAITING_TRACK,this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,this.tick()}doTick(){switch(this.state){case P.IDLE:this.doTickIdle();break;case P.WAITING_TRACK:{const{levels:e,trackId:t}=this,s=e==null?void 0:e[t],i=s==null?void 0:s.details;if(i&&!this.waitForLive(s)){if(this.waitForCdnTuneIn(i))break;this.state=P.WAITING_INIT_PTS}break}case P.FRAG_LOADING_WAITING_RETRY:{this.checkRetryDate();break}case P.WAITING_INIT_PTS:{const e=this.waitingData;if(e){const{frag:t,part:s,cache:i,complete:r}=e,a=this.mainAnchor;if(this.initPTS[t.cc]!==void 0){this.waitingData=null,this.state=P.FRAG_LOADING;const o=i.flush().buffer,c={frag:t,part:s,payload:o,networkDetails:null};this._handleFragmentLoadProgress(c),r&&super._handleFragmentLoadComplete(c)}else a&&a.cc!==e.frag.cc&&this.syncWithAnchor(a,e.frag)}else this.state=P.IDLE}}this.onTickEnd()}resetLoadingState(){const e=this.waitingData;e&&(this.fragmentTracker.removeFragment(e.frag),this.waitingData=null),super.resetLoadingState()}onTickEnd(){const{media:e}=this;e!=null&&e.readyState&&(this.lastCurrentTime=e.currentTime)}doTickIdle(){var e;const{hls:t,levels:s,media:i,trackId:r}=this,a=t.config;if(!this.buffering||!i&&!this.primaryPrefetch&&(this.startFragRequested||!a.startFragPrefetch)||!(s!=null&&s[r]))return;const o=s[r],c=o.details;if(!c||this.waitForLive(o)||this.waitForCdnTuneIn(c)){this.state=P.WAITING_TRACK,this.startFragRequested=!1;return}const l=this.mediaBuffer?this.mediaBuffer:this.media;this.bufferFlushed&&l&&(this.bufferFlushed=!1,this.afterBufferFlushed(l,ne.AUDIO,U.AUDIO));const h=this.getFwdBufferInfo(l,U.AUDIO);if(h===null)return;if(!this.switchingTrack&&this._streamEnded(h,c)){t.trigger(m.BUFFER_EOS,{type:"audio"}),this.state=P.ENDED;return}const u=h.len,d=t.maxBufferLength,f=c.fragments,g=f[0].start,p=this.getLoadPosition(),y=this.flushing?p:h.end;if(this.switchingTrack&&i){const S=p;c.PTSKnown&&S<g&&(h.end>g||h.nextStart)&&(this.log("Alt audio track ahead of main track, seek to start of alt audio track"),i.currentTime=g+.05)}if(u>=d&&!this.switchingTrack&&y<f[f.length-1].start)return;let E=this.getNextFragment(y,c);if(E&&this.isLoopLoading(E,y)&&(E=this.getNextFragmentLoopLoading(E,c,h,U.MAIN,d)),!E){this.bufferFlushed=!0;return}let T=((e=this.mainFragLoading)==null?void 0:e.frag)||null;if(!this.audioOnly&&this.startFragRequested&&T&&de(E)&&!E.endList&&(!c.live||!this.loadingParts&&y<this.hls.liveSyncPosition)&&(this.fragmentTracker.getState(T)===me.OK&&(this.mainFragLoading=T=null),T&&de(T))){if(E.start>T.end){const v=this.fragmentTracker.getFragAtPos(y,U.MAIN);v&&v.end>T.end&&(T=v,this.mainFragLoading={frag:v,targetBufferTime:null})}if(E.start>T.end)return}this.loadFragment(E,o,y)}onMediaDetaching(e,t){this.bufferFlushed=this.flushing=!1,super.onMediaDetaching(e,t)}onAudioTracksUpdated(e,{audioTracks:t}){this.resetTransmuxer(),this.levels=t.map(s=>new Kt(s))}onAudioTrackSwitching(e,t){const s=!!t.url;this.trackId=t.id;const{fragCurrent:i}=this;i&&(i.abortRequests(),this.removeUnbufferedFrags(i.start)),this.resetLoadingState(),s?(this.switchingTrack=t,this.flushAudioIfNeeded(t),this.state!==P.STOPPED&&(this.setInterval(Dn),this.state=P.IDLE,this.tick())):(this.resetTransmuxer(),this.switchingTrack=null,this.bufferedTrack=t,this.clearInterval())}onManifestLoading(){super.onManifestLoading(),this.bufferFlushed=this.flushing=this.audioOnly=!1,this.resetItem(),this.trackId=-1}onLevelLoaded(e,t){this.mainDetails=t.details;const s=this.cachedTrackLoadedData;s&&(this.cachedTrackLoadedData=null,this.onAudioTrackLoaded(m.AUDIO_TRACK_LOADED,s))}onAudioTrackLoaded(e,t){var s;const{levels:i}=this,{details:r,id:a,groupId:o,track:c}=t;if(!i){this.warn(`Audio tracks reset while loading track ${a} "${c.name}" of "${o}"`);return}const l=this.mainDetails;if(!l||r.endCC>l.endCC||l.expired){this.cachedTrackLoadedData=t,this.state!==P.STOPPED&&(this.state=P.WAITING_TRACK);return}this.cachedTrackLoadedData=null,this.log(`Audio track ${a} "${c.name}" of "${o}" loaded [${r.startSN},${r.endSN}]${r.lastPartSn?`[part-${r.lastPartSn}-${r.lastPartIndex}]`:""},duration:${r.totalduration}`);const h=i[a];let u=0;if(r.live||(s=h.details)!=null&&s.live){if(this.checkLiveUpdate(r),r.deltaUpdateFailed)return;if(h.details){var d;u=this.alignPlaylists(r,h.details,(d=this.levelLastLoaded)==null?void 0:d.details)}r.alignedSliding||(to(r,l),r.alignedSliding||Ms(r,l),u=r.fragmentStart)}h.details=r,this.levelLastLoaded=h,this.startFragRequested||this.setStartPosition(l,u),this.hls.trigger(m.AUDIO_TRACK_UPDATED,{details:r,id:a,groupId:t.groupId}),this.state===P.WAITING_TRACK&&!this.waitForCdnTuneIn(r)&&(this.state=P.IDLE),this.tick()}_handleFragmentLoadProgress(e){var t;const s=e.frag,{part:i,payload:r}=e,{config:a,trackId:o,levels:c}=this;if(!c){this.warn(`Audio tracks were reset while fragment load was in progress. Fragment ${s.sn} of level ${s.level} will not be buffered`);return}const l=c[o];if(!l){this.warn("Audio track is undefined on fragment load progress");return}const h=l.details;if(!h){this.warn("Audio track details undefined on fragment load progress"),this.removeUnbufferedFrags(s.start);return}const u=a.defaultAudioCodec||l.audioCodec||"mp4a.40.2";let d=this.transmuxer;d||(d=this.transmuxer=new xo(this.hls,U.AUDIO,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)));const f=this.initPTS[s.cc],g=(t=s.initSegment)==null?void 0:t.data;if(f!==void 0){const y=i?i.index:-1,E=y!==-1,T=new Ji(s.level,s.sn,s.stats.chunkCount,r.byteLength,y,E);d.push(r,g,u,"",s,i,h.totalduration,!1,T,f)}else{this.log(`Unknown video PTS for cc ${s.cc}, waiting for video PTS before demuxing audio frag ${s.sn} of [${h.startSN} ,${h.endSN}],track ${o}`);const{cache:p}=this.waitingData=this.waitingData||{frag:s,part:i,cache:new so,complete:!1};p.push(new Uint8Array(r)),this.state!==P.STOPPED&&(this.state=P.WAITING_INIT_PTS)}}_handleFragmentLoadComplete(e){if(this.waitingData){this.waitingData.complete=!0;return}super._handleFragmentLoadComplete(e)}onBufferReset(){this.mediaBuffer=null}onBufferCreated(e,t){this.bufferFlushed=this.flushing=!1;const s=t.tracks.audio;s&&(this.mediaBuffer=s.buffer||null)}onFragLoading(e,t){!this.audioOnly&&t.frag.type===U.MAIN&&de(t.frag)&&(this.mainFragLoading=t,this.state===P.IDLE&&this.tick())}onFragBuffered(e,t){const{frag:s,part:i}=t;if(s.type!==U.AUDIO){!this.audioOnly&&s.type===U.MAIN&&!s.elementaryStreams.video&&!s.elementaryStreams.audiovideo&&(this.audioOnly=!0,this.mainFragLoading=null);return}if(this.fragContextChanged(s)){this.warn(`Fragment ${s.sn}${i?" p: "+i.index:""} of level ${s.level} finished buffering, but was aborted. state: ${this.state}, audioSwitch: ${this.switchingTrack?this.switchingTrack.name:"false"}`);return}if(de(s)){this.fragPrevious=s;const r=this.switchingTrack;r&&(this.bufferedTrack=r,this.switchingTrack=null,this.hls.trigger(m.AUDIO_TRACK_SWITCHED,se({},r)))}this.fragBufferedComplete(s,i),this.media&&this.tick()}onError(e,t){var s;if(t.fatal){this.state=P.ERROR;return}switch(t.details){case R.FRAG_GAP:case R.FRAG_PARSING_ERROR:case R.FRAG_DECRYPT_ERROR:case R.FRAG_LOAD_ERROR:case R.FRAG_LOAD_TIMEOUT:case R.KEY_LOAD_ERROR:case R.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(U.AUDIO,t);break;case R.AUDIO_TRACK_LOAD_ERROR:case R.AUDIO_TRACK_LOAD_TIMEOUT:case R.LEVEL_PARSING_ERROR:!t.levelRetry&&this.state===P.WAITING_TRACK&&((s=t.context)==null?void 0:s.type)===Q.AUDIO_TRACK&&(this.state=P.IDLE);break;case R.BUFFER_ADD_CODEC_ERROR:case R.BUFFER_APPEND_ERROR:if(t.parent!=="audio")return;this.reduceLengthAndFlushBuffer(t)||this.resetLoadingState();break;case R.BUFFER_FULL_ERROR:if(t.parent!=="audio")return;this.reduceLengthAndFlushBuffer(t)&&(this.bufferedTrack=null,super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"));break;case R.INTERNAL_EXCEPTION:this.recoverWorkerError(t);break}}onBufferFlushing(e,{type:t}){t!==ne.VIDEO&&(this.flushing=!0)}onBufferFlushed(e,{type:t}){if(t!==ne.VIDEO){this.flushing=!1,this.bufferFlushed=!0,this.state===P.ENDED&&(this.state=P.IDLE);const s=this.mediaBuffer||this.media;s&&(this.afterBufferFlushed(s,t,U.AUDIO),this.tick())}}_handleTransmuxComplete(e){var t;const s="audio",{hls:i}=this,{remuxResult:r,chunkMeta:a}=e,o=this.getCurrentContext(a);if(!o){this.resetWhenMissingContext(a);return}const{frag:c,part:l,level:h}=o,{details:u}=h,{audio:d,text:f,id3:g,initSegment:p}=r;if(this.fragContextChanged(c)||!u){this.fragmentTracker.removeFragment(c);return}if(this.state=P.PARSING,this.switchingTrack&&d&&this.completeAudioSwitch(this.switchingTrack),p!=null&&p.tracks){const y=c.initSegment||c;if(this.unhandledEncryptionError(p,c))return;this._bufferInitSegment(h,p.tracks,y,a),i.trigger(m.FRAG_PARSING_INIT_SEGMENT,{frag:y,id:s,tracks:p.tracks})}if(d){const{startPTS:y,endPTS:E,startDTS:T,endDTS:S}=d;l&&(l.elementaryStreams[ne.AUDIO]={startPTS:y,endPTS:E,startDTS:T,endDTS:S}),c.setElementaryStreamInfo(ne.AUDIO,y,E,T,S),this.bufferFragmentData(d,c,l,a)}if(g!=null&&(t=g.samples)!=null&&t.length){const y=re({id:s,frag:c,details:u},g);i.trigger(m.FRAG_PARSING_METADATA,y)}if(f){const y=re({id:s,frag:c,details:u},f);i.trigger(m.FRAG_PARSING_USERDATA,y)}}_bufferInitSegment(e,t,s,i){if(this.state!==P.PARSING||(t.video&&delete t.video,t.audiovideo&&delete t.audiovideo,!t.audio))return;const r=t.audio;r.id=U.AUDIO;const a=e.audioCodec;this.log(`Init audio buffer, container:${r.container}, codecs[level/parsed]=[${a}/${r.codec}]`),a&&a.split(",").length===1&&(r.levelCodec=a),this.hls.trigger(m.BUFFER_CODECS,t);const o=r.initSegment;if(o!=null&&o.byteLength){const c={type:"audio",frag:s,part:null,chunkMeta:i,parent:s.type,data:o};this.hls.trigger(m.BUFFER_APPENDING,c)}this.tickImmediate()}loadFragment(e,t,s){const i=this.fragmentTracker.getState(e);if(this.switchingTrack||i===me.NOT_LOADED||i===me.PARTIAL){var r;if(!de(e))this._loadInitSegment(e,t);else if((r=t.details)!=null&&r.live&&!this.initPTS[e.cc]){this.log(`Waiting for video PTS in continuity counter ${e.cc} of live stream before loading audio fragment ${e.sn} of level ${this.trackId}`),this.state=P.WAITING_INIT_PTS;const a=this.mainDetails;a&&a.fragmentStart!==t.details.fragmentStart&&Ms(t.details,a)}else super.loadFragment(e,t,s)}else this.clearTrackerIfNeeded(e)}flushAudioIfNeeded(e){if(this.media&&this.bufferedTrack){const{name:t,lang:s,assocLang:i,characteristics:r,audioCodec:a,channels:o}=this.bufferedTrack;gt({name:t,lang:s,assocLang:i,characteristics:r,audioCodec:a,channels:o},e,ft)||(Ps(e.url,this.hls)?(this.log("Switching audio track : flushing all audio"),super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"),this.bufferedTrack=null):this.bufferedTrack=e)}}completeAudioSwitch(e){const{hls:t}=this;this.flushAudioIfNeeded(e),this.bufferedTrack=e,this.switchingTrack=null,t.trigger(m.AUDIO_TRACK_SWITCHED,se({},e))}}class hr extends Fe{constructor(e,t){super(t,e.logger),this.hls=void 0,this.canLoad=!1,this.timer=-1,this.hls=e}destroy(){this.clearTimer(),this.hls=this.log=this.warn=null}clearTimer(){this.timer!==-1&&(self.clearTimeout(this.timer),this.timer=-1)}startLoad(){this.canLoad=!0,this.loadPlaylist()}stopLoad(){this.canLoad=!1,this.clearTimer()}switchParams(e,t,s){const i=t==null?void 0:t.renditionReports;if(i){let r=-1;for(let a=0;a<i.length;a++){const o=i[a];let c;try{c=new self.URL(o.URI,t.url).href}catch(l){this.warn(`Could not construct new URL for Rendition Report: ${l}`),c=o.URI||""}if(c===e){r=a;break}else c===e.substring(0,c.length)&&(r=a)}if(r!==-1){const a=i[r],o=parseInt(a["LAST-MSN"])||t.lastPartSn;let c=parseInt(a["LAST-PART"])||t.lastPartIndex;if(this.hls.config.lowLatencyMode){const h=Math.min(t.age-t.partTarget,t.targetduration);c>=0&&h>t.partTarget&&(c+=1)}const l=s&&Vr(s);return new Hr(o,c>=0?c:void 0,l)}}}loadPlaylist(e){this.clearTimer()}loadingPlaylist(e,t){this.clearTimer()}shouldLoadPlaylist(e){return this.canLoad&&!!e&&!!e.url&&(!e.details||e.details.live)}getUrlWithDirectives(e,t){if(t)try{return t.addDirectives(e)}catch(s){this.warn(`Could not construct new URL with HLS Delivery Directives: ${s}`)}return e}playlistLoaded(e,t,s){const{details:i,stats:r}=t,a=self.performance.now(),o=r.loading.first?Math.max(0,a-r.loading.first):0;i.advancedDateTime=Date.now()-o;const c=this.hls.config.timelineOffset;if(c!==i.appliedTimelineOffset){const h=Math.max(c||0,0);i.appliedTimelineOffset=h,i.fragments.forEach(u=>{u.setStart(u.playlistOffset+h)})}if(i.live||s!=null&&s.live){const h="levelInfo"in t?t.levelInfo:t.track;if(i.reloaded(s),s&&i.fragments.length>0){fh(s,i,this);const T=i.playlistParsingError;if(T){this.warn(T);const S=this.hls;if(!S.config.ignorePlaylistParsingErrors){var l;const{networkDetails:v}=t;S.trigger(m.ERROR,{type:H.NETWORK_ERROR,details:R.LEVEL_PARSING_ERROR,fatal:!1,url:i.url,error:T,reason:T.message,level:t.level||void 0,parent:(l=i.fragments[0])==null?void 0:l.type,networkDetails:v,stats:r});return}i.playlistParsingError=null}}i.requestScheduled===-1&&(i.requestScheduled=r.loading.start);const u=this.hls.mainForwardBufferInfo,d=u?u.end-u.len:0,f=(i.edge-d)*1e3,g=za(i,f);if(i.requestScheduled+g<a?i.requestScheduled=a:i.requestScheduled+=g,this.log(`live playlist ${e} ${i.advanced?"REFRESHED "+i.lastPartSn+"-"+i.lastPartIndex:i.updated?"UPDATED":"MISSED"}`),!this.canLoad||!i.live)return;let p,y,E;if(i.canBlockReload&&i.endSN&&i.advanced){const T=this.hls.config.lowLatencyMode,S=i.lastPartSn,v=i.endSN,x=i.lastPartIndex,D=x!==-1,A=S===v;D?A?(y=v+1,E=T?0:x):(y=S,E=T?x+1:i.maxPartIndex):y=v+1;const b=i.age,I=b+i.ageHeader;let _=Math.min(I-i.partTarget,i.targetduration*1.5);if(_>0){if(I>i.targetduration*3)this.log(`Playlist last advanced ${b.toFixed(2)}s ago. Omitting segment and part directives.`),y=void 0,E=void 0;else if(s!=null&&s.tuneInGoal&&I-i.partTarget>s.tuneInGoal)this.warn(`CDN Tune-in goal increased from: ${s.tuneInGoal} to: ${_} with playlist age: ${i.age}`),_=0;else{const C=Math.floor(_/i.targetduration);if(y+=C,E!==void 0){const k=Math.round(_%i.targetduration/i.partTarget);E+=k}this.log(`CDN Tune-in age: ${i.ageHeader}s last advanced ${b.toFixed(2)}s goal: ${_} skip sn ${C} to part ${E}`)}i.tuneInGoal=_}if(p=this.getDeliveryDirectives(i,t.deliveryDirectives,y,E),T||!A){i.requestScheduled=a,this.loadingPlaylist(h,p);return}}else(i.canBlockReload||i.canSkipUntil)&&(p=this.getDeliveryDirectives(i,t.deliveryDirectives,y,E));p&&y!==void 0&&i.canBlockReload&&(i.requestScheduled=r.loading.first+Math.max(g-o*2,g/2)),this.scheduleLoading(h,p,i)}else this.clearTimer()}scheduleLoading(e,t,s){const i=s||e.details;if(!i){this.loadingPlaylist(e,t);return}const r=self.performance.now(),a=i.requestScheduled;if(r>=a){this.loadingPlaylist(e,t);return}const o=a-r;this.log(`reload live playlist ${e.name||e.bitrate+"bps"} in ${Math.round(o)} ms`),this.clearTimer(),this.timer=self.setTimeout(()=>this.loadingPlaylist(e,t),o)}getDeliveryDirectives(e,t,s,i){let r=Vr(e);return t!=null&&t.skip&&e.deltaUpdateFailed&&(s=t.msn,i=t.part,r=ps.No),new Hr(s,i,r)}checkRetry(e){const t=e.details,s=ks(e),i=e.errorAction,{action:r,retryCount:a=0,retryConfig:o}=i||{},c=!!i&&!!o&&(r===Ee.RetryRequest||!i.resolved&&r===Ee.SendAlternateToPenaltyBox);if(c){var l;if(a>=o.maxNumRetry)return!1;if(s&&(l=e.context)!=null&&l.deliveryDirectives)this.warn(`Retrying playlist loading ${a+1}/${o.maxNumRetry} after "${t}" without delivery-directives`),this.loadPlaylist();else{const h=Qi(o,a);this.clearTimer(),this.timer=self.setTimeout(()=>this.loadPlaylist(),h),this.warn(`Retrying playlist loading ${a+1}/${o.maxNumRetry} after "${t}" in ${h}ms`)}e.levelRetry=!0,i.resolved=!0}return c}}function Ao(n,e){if(n.length!==e.length)return!1;for(let t=0;t<n.length;t++)if(!Yt(n[t].attrs,e[t].attrs))return!1;return!0}function Yt(n,e,t){const s=n["STABLE-RENDITION-ID"];return s&&!t?s===e["STABLE-RENDITION-ID"]:!(t||["LANGUAGE","NAME","CHARACTERISTICS","AUTOSELECT","DEFAULT","FORCED","ASSOC-LANGUAGE"]).some(i=>n[i]!==e[i])}function Oi(n,e){return e.label.toLowerCase()===n.name.toLowerCase()&&(!e.language||e.language.toLowerCase()===(n.lang||"").toLowerCase())}class xu extends hr{constructor(e){super(e,"audio-track-controller"),this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0,this.registerListeners()}registerListeners(){const{hls:e}=this;e.on(m.MANIFEST_LOADING,this.onManifestLoading,this),e.on(m.MANIFEST_PARSED,this.onManifestParsed,this),e.on(m.LEVEL_LOADING,this.onLevelLoading,this),e.on(m.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(m.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(m.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(m.MANIFEST_LOADING,this.onManifestLoading,this),e.off(m.MANIFEST_PARSED,this.onManifestParsed,this),e.off(m.LEVEL_LOADING,this.onLevelLoading,this),e.off(m.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(m.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(m.ERROR,this.onError,this)}destroy(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.currentTrack=null,super.destroy()}onManifestLoading(){this.tracks=[],this.tracksInGroup=[],this.groupIds=null,this.currentTrack=null,this.trackId=-1,this.selectDefaultTrack=!0}onManifestParsed(e,t){this.tracks=t.audioTracks||[]}onAudioTrackLoaded(e,t){const{id:s,groupId:i,details:r}=t,a=this.tracksInGroup[s];if(!a||a.groupId!==i){this.warn(`Audio track with id:${s} and group:${i} not found in active group ${a==null?void 0:a.groupId}`);return}const o=a.details;a.details=t.details,this.log(`Audio track ${s} "${a.name}" lang:${a.lang} group:${i} loaded [${r.startSN}-${r.endSN}]`),s===this.trackId&&this.playlistLoaded(s,t,o)}onLevelLoading(e,t){this.switchLevel(t.level)}onLevelSwitching(e,t){this.switchLevel(t.level)}switchLevel(e){const t=this.hls.levels[e];if(!t)return;const s=t.audioGroups||null,i=this.groupIds;let r=this.currentTrack;if(!s||(i==null?void 0:i.length)!==(s==null?void 0:s.length)||s!=null&&s.some(o=>(i==null?void 0:i.indexOf(o))===-1)){this.groupIds=s,this.trackId=-1,this.currentTrack=null;const o=this.tracks.filter(d=>!s||s.indexOf(d.groupId)!==-1);if(o.length)this.selectDefaultTrack&&!o.some(d=>d.default)&&(this.selectDefaultTrack=!1),o.forEach((d,f)=>{d.id=f});else if(!r&&!this.tracksInGroup.length)return;this.tracksInGroup=o;const c=this.hls.config.audioPreference;if(!r&&c){const d=He(c,o,ft);if(d>-1)r=o[d];else{const f=He(c,this.tracks);r=this.tracks[f]}}let l=this.findTrackId(r);l===-1&&r&&(l=this.findTrackId(null));const h={audioTracks:o};this.log(`Updating audio tracks, ${o.length} track(s) found in group(s): ${s==null?void 0:s.join(",")}`),this.hls.trigger(m.AUDIO_TRACKS_UPDATED,h);const u=this.trackId;if(l!==-1&&u===-1)this.setAudioTrack(l);else if(o.length&&u===-1){var a;const d=new Error(`No audio track selected for current audio group-ID(s): ${(a=this.groupIds)==null?void 0:a.join(",")} track count: ${o.length}`);this.warn(d.message),this.hls.trigger(m.ERROR,{type:H.MEDIA_ERROR,details:R.AUDIO_TRACK_LOAD_ERROR,fatal:!0,error:d})}}}onError(e,t){t.fatal||!t.context||t.context.type===Q.AUDIO_TRACK&&t.context.id===this.trackId&&(!this.groupIds||this.groupIds.indexOf(t.context.groupId)!==-1)&&this.checkRetry(t)}get allAudioTracks(){return this.tracks}get audioTracks(){return this.tracksInGroup}get audioTrack(){return this.trackId}set audioTrack(e){this.selectDefaultTrack=!1,this.setAudioTrack(e)}setAudioOption(e){const t=this.hls;if(t.config.audioPreference=e,e){const s=this.allAudioTracks;if(this.selectDefaultTrack=!1,s.length){const i=this.currentTrack;if(i&>(e,i,ft))return i;const r=He(e,this.tracksInGroup,ft);if(r>-1){const a=this.tracksInGroup[r];return this.setAudioTrack(r),a}else if(i){let a=t.loadLevel;a===-1&&(a=t.firstAutoLevel);const o=Oc(e,t.levels,s,a,ft);if(o===-1)return null;t.nextLoadLevel=o}if(e.channels||e.audioCodec){const a=He(e,s);if(a>-1)return s[a]}}}return null}setAudioTrack(e){const t=this.tracksInGroup;if(e<0||e>=t.length){this.warn(`Invalid audio track id: ${e}`);return}this.selectDefaultTrack=!1;const s=this.currentTrack,i=t[e],r=i.details&&!i.details.live;if(e===this.trackId&&i===s&&r||(this.log(`Switching to audio-track ${e} "${i.name}" lang:${i.lang} group:${i.groupId} channels:${i.channels}`),this.trackId=e,this.currentTrack=i,this.hls.trigger(m.AUDIO_TRACK_SWITCHING,se({},i)),r))return;const a=this.switchParams(i.url,s==null?void 0:s.details,i.details);this.loadPlaylist(a)}findTrackId(e){const t=this.tracksInGroup;for(let s=0;s<t.length;s++){const i=t[s];if(!(this.selectDefaultTrack&&!i.default)&&(!e||gt(e,i,ft)))return s}if(e){const{name:s,lang:i,assocLang:r,characteristics:a,audioCodec:o,channels:c}=e;for(let l=0;l<t.length;l++){const h=t[l];if(gt({name:s,lang:i,assocLang:r,characteristics:a,audioCodec:o,channels:c},h,ft))return l}for(let l=0;l<t.length;l++){const h=t[l];if(Yt(e.attrs,h.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return l}for(let l=0;l<t.length;l++){const h=t[l];if(Yt(e.attrs,h.attrs,["LANGUAGE"]))return l}}return-1}loadPlaylist(e){super.loadPlaylist();const t=this.currentTrack;this.shouldLoadPlaylist(t)&&Ps(t.url,this.hls)&&this.scheduleLoading(t,e)}loadingPlaylist(e,t){super.loadingPlaylist(e,t);const s=e.id,i=e.groupId,r=this.getUrlWithDirectives(e.url,t),a=e.details,o=a==null?void 0:a.age;this.log(`Loading audio-track ${s} "${e.name}" lang:${e.lang} group:${i}${(t==null?void 0:t.msn)!==void 0?" at sn "+t.msn+" part "+t.part:""}${o&&a.live?" age "+o.toFixed(1)+(a.type&&" "+a.type||""):""} ${r}`),this.hls.trigger(m.AUDIO_TRACK_LOADING,{url:r,id:s,groupId:i,deliveryDirectives:t||null,track:e})}}class Au{constructor(e){this.tracks=void 0,this.queues={video:[],audio:[],audiovideo:[]},this.tracks=e}destroy(){this.tracks=this.queues=null}append(e,t,s){if(this.queues===null||this.tracks===null)return;const i=this.queues[t];i.push(e),i.length===1&&!s&&this.executeNext(t)}appendBlocker(e){return new Promise(t=>{const s={label:"async-blocker",execute:t,onStart:()=>{},onComplete:()=>{},onError:()=>{}};this.append(s,e)})}prependBlocker(e){return new Promise(t=>{if(this.queues){const s={label:"async-blocker-prepend",execute:t,onStart:()=>{},onComplete:()=>{},onError:()=>{}};this.queues[e].unshift(s)}})}removeBlockers(){this.queues!==null&&[this.queues.video,this.queues.audio,this.queues.audiovideo].forEach(e=>{var t;const s=(t=e[0])==null?void 0:t.label;(s==="async-blocker"||s==="async-blocker-prepend")&&(e[0].execute(),e.splice(0,1))})}unblockAudio(e){if(this.queues===null)return;this.queues.audio[0]===e&&this.shiftAndExecuteNext("audio")}executeNext(e){if(this.queues===null||this.tracks===null)return;const t=this.queues[e];if(t.length){const i=t[0];try{i.execute()}catch(r){var s;if(i.onError(r),this.queues===null||this.tracks===null)return;const a=(s=this.tracks[e])==null?void 0:s.buffer;a!=null&&a.updating||this.shiftAndExecuteNext(e)}}}shiftAndExecuteNext(e){this.queues!==null&&(this.queues[e].shift(),this.executeNext(e))}current(e){var t;return((t=this.queues)==null?void 0:t[e][0])||null}toString(){const{queues:e,tracks:t}=this;return e===null||t===null?"<destroyed>":`
246111${this.list("video")}
247112${this.list("audio")}
248248-${this.list("audiovideo")}}`}list(e){var t,s;return(t=this.queues)!=null&&t[e]||(s=this.tracks)!=null&&s[e]?`${e}: (${this.listSbInfo(e)}) ${this.listOps(e)}`:""}listSbInfo(e){var t;const s=(t=this.tracks)==null?void 0:t[e],i=s==null?void 0:s.buffer;return i?`SourceBuffer${i.updating?" updating":""}${s.ended?" ended":""}${s.ending?" ending":""}`:"none"}listOps(e){var t;return((t=this.queues)==null?void 0:t[e].map(s=>s.label).join(", "))||""}}const jr=/(avc[1234]|hvc1|hev1|dvh[1e]|vp09|av01)(?:\.[^.,]+)+/,Ia="HlsJsTrackRemovedError";class Gc extends Error{constructor(e){super(e),this.name=Ia}}class Kc extends we{constructor(e,t){super("buffer-controller",e.logger),this.hls=void 0,this.fragmentTracker=void 0,this.details=null,this._objectUrl=null,this.operationQueue=null,this.bufferCodecEventsTotal=0,this.media=null,this.mediaSource=null,this.lastMpegAudioChunk=null,this.blockedAudioAppend=null,this.lastVideoAppendEnd=0,this.appendSource=void 0,this.transferData=void 0,this.overrides=void 0,this.appendErrors={audio:0,video:0,audiovideo:0},this.tracks={},this.sourceBuffers=[[null,null],[null,null]],this._onEndStreaming=s=>{var i;this.hls&&((i=this.mediaSource)==null?void 0:i.readyState)==="open"&&this.hls.pauseBuffering()},this._onStartStreaming=s=>{this.hls&&this.hls.resumeBuffering()},this._onMediaSourceOpen=s=>{const{media:i,mediaSource:r}=this;s&&this.log("Media source opened"),!(!i||!r)&&(r.removeEventListener("sourceopen",this._onMediaSourceOpen),i.removeEventListener("emptied",this._onMediaEmptied),this.updateDuration(),this.hls.trigger(m.MEDIA_ATTACHED,{media:i,mediaSource:r}),this.mediaSource!==null&&this.checkPendingTracks())},this._onMediaSourceClose=()=>{this.log("Media source closed")},this._onMediaSourceEnded=()=>{this.log("Media source ended")},this._onMediaEmptied=()=>{const{mediaSrc:s,_objectUrl:i}=this;s!==i&&this.error(`Media element src was set while attaching MediaSource (${i} > ${s})`)},this.hls=e,this.fragmentTracker=t,this.appendSource=co(rt(e.config.preferManagedMediaSource)),this.initTracks(),this.registerListeners()}hasSourceTypes(){return Object.keys(this.tracks).length>0}destroy(){this.unregisterListeners(),this.details=null,this.lastMpegAudioChunk=this.blockedAudioAppend=null,this.transferData=this.overrides=void 0,this.operationQueue&&(this.operationQueue.destroy(),this.operationQueue=null),this.hls=this.fragmentTracker=null,this._onMediaSourceOpen=this._onMediaSourceClose=null,this._onMediaSourceEnded=null,this._onStartStreaming=this._onEndStreaming=null}registerListeners(){const{hls:e}=this;e.on(m.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(m.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(m.MANIFEST_LOADING,this.onManifestLoading,this),e.on(m.MANIFEST_PARSED,this.onManifestParsed,this),e.on(m.BUFFER_RESET,this.onBufferReset,this),e.on(m.BUFFER_APPENDING,this.onBufferAppending,this),e.on(m.BUFFER_CODECS,this.onBufferCodecs,this),e.on(m.BUFFER_EOS,this.onBufferEos,this),e.on(m.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(m.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(m.FRAG_PARSED,this.onFragParsed,this),e.on(m.FRAG_CHANGED,this.onFragChanged,this),e.on(m.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(m.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(m.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(m.MANIFEST_LOADING,this.onManifestLoading,this),e.off(m.MANIFEST_PARSED,this.onManifestParsed,this),e.off(m.BUFFER_RESET,this.onBufferReset,this),e.off(m.BUFFER_APPENDING,this.onBufferAppending,this),e.off(m.BUFFER_CODECS,this.onBufferCodecs,this),e.off(m.BUFFER_EOS,this.onBufferEos,this),e.off(m.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(m.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(m.FRAG_PARSED,this.onFragParsed,this),e.off(m.FRAG_CHANGED,this.onFragChanged,this),e.off(m.ERROR,this.onError,this)}transferMedia(){const{media:e,mediaSource:t}=this;if(!e)return null;const s={};if(this.operationQueue){const r=this.isUpdating();r||this.operationQueue.removeBlockers();const n=this.isQueued();(r||n)&&this.warn(`Transfering MediaSource with${n?" operations in queue":""}${r?" updating SourceBuffer(s)":""} ${this.operationQueue}`),this.operationQueue.destroy()}const i=this.transferData;return!this.sourceBufferCount&&i&&i.mediaSource===t?ie(s,i.tracks):this.sourceBuffers.forEach(r=>{const[n]=r;n&&(s[n]=ie({},this.tracks[n]),this.removeBuffer(n)),r[0]=r[1]=null}),{media:e,mediaSource:t,tracks:s}}initTracks(){const e={};this.sourceBuffers=[[null,null],[null,null]],this.tracks=e,this.resetQueue(),this.resetAppendErrors(),this.lastMpegAudioChunk=this.blockedAudioAppend=null,this.lastVideoAppendEnd=0}onManifestLoading(){this.bufferCodecEventsTotal=0,this.details=null}onManifestParsed(e,t){var s;let i=2;(t.audio&&!t.video||!t.altAudio)&&(i=1),this.bufferCodecEventsTotal=i,this.log(`${i} bufferCodec event(s) expected.`),(s=this.transferData)!=null&&s.mediaSource&&this.sourceBufferCount&&i&&this.bufferCreated()}onMediaAttaching(e,t){const s=this.media=t.media;this.transferData=this.overrides=void 0;const i=rt(this.appendSource);if(i){const r=!!t.mediaSource;(r||t.overrides)&&(this.transferData=t,this.overrides=t.overrides);const n=this.mediaSource=t.mediaSource||new i;if(this.assignMediaSource(n),r)this._objectUrl=s.src,this.attachTransferred();else{const o=this._objectUrl=self.URL.createObjectURL(n);if(this.appendSource)try{s.removeAttribute("src");const c=self.ManagedMediaSource;s.disableRemotePlayback=s.disableRemotePlayback||c&&n instanceof c,Xr(s),Vc(s,o),s.load()}catch{s.src=o}else s.src=o}s.addEventListener("emptied",this._onMediaEmptied)}}assignMediaSource(e){var t,s;this.log(`${((t=this.transferData)==null?void 0:t.mediaSource)===e?"transferred":"created"} media source: ${(s=e.constructor)==null?void 0:s.name}`),e.addEventListener("sourceopen",this._onMediaSourceOpen),e.addEventListener("sourceended",this._onMediaSourceEnded),e.addEventListener("sourceclose",this._onMediaSourceClose),this.appendSource&&(e.addEventListener("startstreaming",this._onStartStreaming),e.addEventListener("endstreaming",this._onEndStreaming))}attachTransferred(){const e=this.media,t=this.transferData;if(!t||!e)return;const s=this.tracks,i=t.tracks,r=i?Object.keys(i):null,n=r?r.length:0,o=()=>{Promise.resolve().then(()=>{this.media&&this.mediaSourceOpenOrEnded&&this._onMediaSourceOpen()})};if(i&&r&&n){if(!this.tracksReady){this.hls.config.startFragPrefetch=!0,this.log("attachTransferred: waiting for SourceBuffer track info");return}if(this.log(`attachTransferred: (bufferCodecEventsTotal ${this.bufferCodecEventsTotal})
249249-required tracks: ${ne(s,(c,l)=>c==="initSegment"?void 0:l)};
250250-transfer tracks: ${ne(i,(c,l)=>c==="initSegment"?void 0:l)}}`),!Sn(i,s)){t.mediaSource=null,t.tracks=void 0;const c=e.currentTime,l=this.details,h=Math.max(c,(l==null?void 0:l.fragments[0].start)||0);if(h-c>1){this.log(`attachTransferred: waiting for playback to reach new tracks start time ${c} -> ${h}`);return}this.warn(`attachTransferred: resetting MediaSource for incompatible tracks ("${Object.keys(i)}"->"${Object.keys(s)}") start time: ${h} currentTime: ${c}`),this.onMediaDetaching(m.MEDIA_DETACHING,{}),this.onMediaAttaching(m.MEDIA_ATTACHING,t),e.currentTime=h;return}this.transferData=void 0,r.forEach(c=>{const l=c,h=i[l];if(h){const d=h.buffer;if(d){const u=this.fragmentTracker,f=h.id;if(u.hasFragments(f)||u.hasParts(f)){const p=q.getBuffered(d);u.detectEvictedFragments(l,p,f,null,!0)}const g=Ws(l),y=[l,d];this.sourceBuffers[g]=y,d.updating&&this.operationQueue&&this.operationQueue.prependBlocker(l),this.trackSourceBuffer(l,h)}}}),o(),this.bufferCreated()}else this.log("attachTransferred: MediaSource w/o SourceBuffers"),o()}get mediaSourceOpenOrEnded(){var e;const t=(e=this.mediaSource)==null?void 0:e.readyState;return t==="open"||t==="ended"}onMediaDetaching(e,t){const s=!!t.transferMedia;this.transferData=this.overrides=void 0;const{media:i,mediaSource:r,_objectUrl:n}=this;if(r){if(this.log(`media source ${s?"transferring":"detaching"}`),s)this.sourceBuffers.forEach(([o])=>{o&&this.removeBuffer(o)}),this.resetQueue();else{if(this.mediaSourceOpenOrEnded){const o=r.readyState==="open";try{const c=r.sourceBuffers;for(let l=c.length;l--;)o&&c[l].abort(),r.removeSourceBuffer(c[l]);o&&r.endOfStream()}catch(c){this.warn(`onMediaDetaching: ${c.message} while calling endOfStream`)}}this.sourceBufferCount&&this.onBufferReset()}r.removeEventListener("sourceopen",this._onMediaSourceOpen),r.removeEventListener("sourceended",this._onMediaSourceEnded),r.removeEventListener("sourceclose",this._onMediaSourceClose),this.appendSource&&(r.removeEventListener("startstreaming",this._onStartStreaming),r.removeEventListener("endstreaming",this._onEndStreaming)),this.mediaSource=null,this._objectUrl=null}i&&(i.removeEventListener("emptied",this._onMediaEmptied),s||(n&&self.URL.revokeObjectURL(n),this.mediaSrc===n?(i.removeAttribute("src"),this.appendSource&&Xr(i),i.load()):this.warn("media|source.src was changed by a third party - skip cleanup")),this.media=null),this.hls.trigger(m.MEDIA_DETACHED,t)}onBufferReset(){this.sourceBuffers.forEach(([e])=>{e&&this.resetBuffer(e)}),this.initTracks()}resetBuffer(e){var t;const s=(t=this.tracks[e])==null?void 0:t.buffer;if(this.removeBuffer(e),s)try{var i;(i=this.mediaSource)!=null&&i.sourceBuffers.length&&this.mediaSource.removeSourceBuffer(s)}catch(r){this.warn(`onBufferReset ${e}`,r)}delete this.tracks[e]}removeBuffer(e){this.removeBufferListeners(e),this.sourceBuffers[Ws(e)]=[null,null];const t=this.tracks[e];t&&(t.buffer=void 0)}resetQueue(){this.operationQueue&&this.operationQueue.destroy(),this.operationQueue=new $c(this.tracks)}onBufferCodecs(e,t){var s;const i=this.tracks,r=Object.keys(t);this.log(`BUFFER_CODECS: "${r}" (current SB count ${this.sourceBufferCount})`);const n="audiovideo"in t&&(i.audio||i.video)||i.audiovideo&&("audio"in t||"video"in t),o=!n&&this.sourceBufferCount&&this.media&&r.some(c=>!i[c]);if(n||o){this.warn(`Unsupported transition between "${Object.keys(i)}" and "${r}" SourceBuffers`);return}r.forEach(c=>{var l,h;const d=t[c],{id:u,codec:f,levelCodec:g,container:y,metadata:p,supplemental:E}=d;let T=i[c];const S=(l=this.transferData)==null||(l=l.tracks)==null?void 0:l[c],v=S!=null&&S.buffer?S:T,A=(v==null?void 0:v.pendingCodec)||(v==null?void 0:v.codec),D=v==null?void 0:v.levelCodec;T||(T=i[c]={buffer:void 0,listeners:[],codec:f,supplemental:E,container:y,levelCodec:g,metadata:p,id:u});const x=cs(A,D),b=x==null?void 0:x.replace(jr,"$1");let _=cs(f,g);const I=(h=_)==null?void 0:h.replace(jr,"$1");_&&x&&b!==I&&(c.slice(0,5)==="audio"&&(_=Ts(_,this.appendSource)),this.log(`switching codec ${A} to ${_}`),_!==(T.pendingCodec||T.codec)&&(T.pendingCodec=_),T.container=y,this.appendChangeType(c,y,_))}),(this.tracksReady||this.sourceBufferCount)&&(t.tracks=this.sourceBufferTracks),!this.sourceBufferCount&&(this.bufferCodecEventsTotal>1&&!this.tracks.video&&!t.video&&((s=t.audio)==null?void 0:s.id)==="main"&&(this.log("Main audio-only"),this.bufferCodecEventsTotal=1),this.mediaSourceOpenOrEnded&&this.checkPendingTracks())}get sourceBufferTracks(){return Object.keys(this.tracks).reduce((e,t)=>{const s=this.tracks[t];return e[t]={id:s.id,container:s.container,codec:s.codec,levelCodec:s.levelCodec},e},{})}appendChangeType(e,t,s){const i=`${t};codecs=${s}`,r={label:`change-type=${i}`,execute:()=>{const n=this.tracks[e];if(n){const o=n.buffer;o!=null&&o.changeType&&(this.log(`changing ${e} sourceBuffer type to ${i}`),o.changeType(i),n.codec=s,n.container=t)}this.shiftAndExecuteNext(e)},onStart:()=>{},onComplete:()=>{},onError:n=>{this.warn(`Failed to change ${e} SourceBuffer type`,n)}};this.append(r,e,this.isPending(this.tracks[e]))}blockAudio(e){var t;const s=e.start,i=s+e.duration*.05;if(((t=this.fragmentTracker.getAppendedFrag(s,B.MAIN))==null?void 0:t.gap)===!0)return;const n={label:"block-audio",execute:()=>{var o;const c=this.tracks.video;(this.lastVideoAppendEnd>i||c!=null&&c.buffer&&q.isBuffered(c.buffer,i)||((o=this.fragmentTracker.getAppendedFrag(i,B.MAIN))==null?void 0:o.gap)===!0)&&(this.blockedAudioAppend=null,this.shiftAndExecuteNext("audio"))},onStart:()=>{},onComplete:()=>{},onError:o=>{this.warn("Error executing block-audio operation",o)}};this.blockedAudioAppend={op:n,frag:e},this.append(n,"audio",!0)}unblockAudio(){const{blockedAudioAppend:e,operationQueue:t}=this;e&&t&&(this.blockedAudioAppend=null,t.unblockAudio(e.op))}onBufferAppending(e,t){const{tracks:s}=this,{data:i,type:r,parent:n,frag:o,part:c,chunkMeta:l,offset:h}=t,d=l.buffering[r],{sn:u,cc:f}=o,g=self.performance.now();d.start=g;const y=o.stats.buffering,p=c?c.stats.buffering:null;y.start===0&&(y.start=g),p&&p.start===0&&(p.start=g);const E=s.audio;let T=!1;r==="audio"&&(E==null?void 0:E.container)==="audio/mpeg"&&(T=!this.lastMpegAudioChunk||l.id===1||this.lastMpegAudioChunk.sn!==l.sn,this.lastMpegAudioChunk=l);const S=s.video,v=S==null?void 0:S.buffer;if(v&&u!=="initSegment"){const x=c||o,b=this.blockedAudioAppend;if(r==="audio"&&n!=="main"&&!this.blockedAudioAppend&&!(S.ending||S.ended)){const I=x.start+x.duration*.05,P=v.buffered,F=this.currentOp("video");!P.length&&!F?this.blockAudio(x):!F&&!q.isBuffered(v,I)&&this.lastVideoAppendEnd<I&&this.blockAudio(x)}else if(r==="video"){const _=x.end;if(b){const I=b.frag.start;(_>I||_<this.lastVideoAppendEnd||q.isBuffered(v,I))&&this.unblockAudio()}this.lastVideoAppendEnd=_}}const A=(c||o).start,D={label:`append-${r}`,execute:()=>{var x;d.executeStart=self.performance.now();const b=(x=this.tracks[r])==null?void 0:x.buffer;b&&(T?this.updateTimestampOffset(b,A,.1,r,u,f):h!==void 0&&M(h)&&this.updateTimestampOffset(b,h,1e-6,r,u,f)),this.appendExecutor(i,r)},onStart:()=>{},onComplete:()=>{const x=self.performance.now();d.executeEnd=d.end=x,y.first===0&&(y.first=x),p&&p.first===0&&(p.first=x);const b={};this.sourceBuffers.forEach(([_,I])=>{_&&(b[_]=q.getBuffered(I))}),this.appendErrors[r]=0,r==="audio"||r==="video"?this.appendErrors.audiovideo=0:(this.appendErrors.audio=0,this.appendErrors.video=0),this.hls.trigger(m.BUFFER_APPENDED,{type:r,frag:o,part:c,chunkMeta:l,parent:o.type,timeRanges:b})},onError:x=>{var b;const _={type:V.MEDIA_ERROR,parent:o.type,details:R.BUFFER_APPEND_ERROR,sourceBufferName:r,frag:o,part:c,chunkMeta:l,error:x,err:x,fatal:!1},I=(b=this.media)==null?void 0:b.error;if(x.code===DOMException.QUOTA_EXCEEDED_ERR||x.name=="QuotaExceededError"||"quota"in x)_.details=R.BUFFER_FULL_ERROR;else if(x.code===DOMException.INVALID_STATE_ERR&&this.mediaSourceOpenOrEnded&&!I)_.errorAction=It(!0);else if(x.name===Ia&&this.sourceBufferCount===0)_.errorAction=It(!0);else{const P=++this.appendErrors[r];this.warn(`Failed ${P}/${this.hls.config.appendErrorMaxRetry} times to append segment in "${r}" sourceBuffer (${I||"no media error"})`),(P>=this.hls.config.appendErrorMaxRetry||I)&&(_.fatal=!0)}this.hls.trigger(m.ERROR,_)}};this.log(`queuing "${r}" append sn: ${u}${c?" p: "+c.index:""} of ${o.type===B.MAIN?"level":"track"} ${o.level} cc: ${f}`),this.append(D,r,this.isPending(this.tracks[r]))}getFlushOp(e,t,s){return this.log(`queuing "${e}" remove ${t}-${s}`),{label:"remove",execute:()=>{this.removeExecutor(e,t,s)},onStart:()=>{},onComplete:()=>{this.hls.trigger(m.BUFFER_FLUSHED,{type:e})},onError:i=>{this.warn(`Failed to remove ${t}-${s} from "${e}" SourceBuffer`,i)}}}onBufferFlushing(e,t){const{type:s,startOffset:i,endOffset:r}=t;s?this.append(this.getFlushOp(s,i,r),s):this.sourceBuffers.forEach(([n])=>{n&&this.append(this.getFlushOp(n,i,r),n)})}onFragParsed(e,t){const{frag:s,part:i}=t,r=[],n=i?i.elementaryStreams:s.elementaryStreams;n[re.AUDIOVIDEO]?r.push("audiovideo"):(n[re.AUDIO]&&r.push("audio"),n[re.VIDEO]&&r.push("video"));const o=()=>{const c=self.performance.now();s.stats.buffering.end=c,i&&(i.stats.buffering.end=c);const l=i?i.stats:s.stats;this.hls.trigger(m.FRAG_BUFFERED,{frag:s,part:i,stats:l,id:s.type})};r.length===0&&this.warn(`Fragments must have at least one ElementaryStreamType set. type: ${s.type} level: ${s.level} sn: ${s.sn}`),this.blockBuffers(o,r).catch(c=>{this.warn(`Fragment buffered callback ${c}`),this.stepOperationQueue(this.sourceBufferTypes)})}onFragChanged(e,t){this.trimBuffers()}get bufferedToEnd(){return this.sourceBufferCount>0&&!this.sourceBuffers.some(([e])=>{if(e){const t=this.tracks[e];if(t)return!t.ended||t.ending}return!1})}onBufferEos(e,t){var s;this.sourceBuffers.forEach(([n])=>{if(n){const o=this.tracks[n];(!t.type||t.type===n)&&(o.ending=!0,o.ended||(o.ended=!0,this.log(`${n} buffer reached EOS`)))}});const i=((s=this.overrides)==null?void 0:s.endOfStream)!==!1;this.sourceBufferCount>0&&!this.sourceBuffers.some(([n])=>{var o;return n&&!((o=this.tracks[n])!=null&&o.ended)})?i?(this.log("Queueing EOS"),this.blockUntilOpen(()=>{this.tracksEnded();const{mediaSource:n}=this;if(!n||n.readyState!=="open"){n&&this.log(`Could not call mediaSource.endOfStream(). mediaSource.readyState: ${n.readyState}`);return}this.log("Calling mediaSource.endOfStream()"),n.endOfStream(),this.hls.trigger(m.BUFFERED_TO_END,void 0)})):(this.tracksEnded(),this.hls.trigger(m.BUFFERED_TO_END,void 0)):t.type==="video"&&this.unblockAudio()}tracksEnded(){this.sourceBuffers.forEach(([e])=>{if(e!==null){const t=this.tracks[e];t&&(t.ending=!1)}})}onLevelUpdated(e,{details:t}){t.fragments.length&&(this.details=t,this.updateDuration())}updateDuration(){this.blockUntilOpen(()=>{const e=this.getDurationAndRange();e&&this.updateMediaSource(e)})}onError(e,t){if(t.details===R.BUFFER_APPEND_ERROR&&t.frag){var s;const i=(s=t.errorAction)==null?void 0:s.nextAutoLevel;M(i)&&i!==t.frag.level&&this.resetAppendErrors()}}resetAppendErrors(){this.appendErrors={audio:0,video:0,audiovideo:0}}trimBuffers(){const{hls:e,details:t,media:s}=this;if(!s||t===null||!this.sourceBufferCount)return;const i=e.config,r=s.currentTime,n=t.levelTargetDuration,o=t.live&&i.liveBackBufferLength!==null?i.liveBackBufferLength:i.backBufferLength;if(M(o)&&o>=0){const l=Math.max(o,n),h=Math.floor(r/n)*n-l;this.flushBackBuffer(r,n,h)}const c=i.frontBufferFlushThreshold;if(M(c)&&c>0){const l=Math.max(i.maxBufferLength,c),h=Math.max(l,n),d=Math.floor(r/n)*n+h;this.flushFrontBuffer(r,n,d)}}flushBackBuffer(e,t,s){this.sourceBuffers.forEach(([i,r])=>{if(r){const o=q.getBuffered(r);if(o.length>0&&s>o.start(0)){var n;this.hls.trigger(m.BACK_BUFFER_REACHED,{bufferEnd:s});const c=this.tracks[i];if((n=this.details)!=null&&n.live)this.hls.trigger(m.LIVE_BACK_BUFFER_REACHED,{bufferEnd:s});else if(c!=null&&c.ended){this.log(`Cannot flush ${i} back buffer while SourceBuffer is in ended state`);return}this.hls.trigger(m.BUFFER_FLUSHING,{startOffset:0,endOffset:s,type:i})}}})}flushFrontBuffer(e,t,s){this.sourceBuffers.forEach(([i,r])=>{if(r){const n=q.getBuffered(r),o=n.length;if(o<2)return;const c=n.start(o-1),l=n.end(o-1);if(s>c||e>=c&&e<=l)return;this.hls.trigger(m.BUFFER_FLUSHING,{startOffset:c,endOffset:1/0,type:i})}})}getDurationAndRange(){var e;const{details:t,mediaSource:s}=this;if(!t||!this.media||(s==null?void 0:s.readyState)!=="open")return null;const i=t.edge;if(t.live&&this.hls.config.liveDurationInfinity){if(t.fragments.length&&s.setLiveSeekableRange){const l=Math.max(0,t.fragmentStart),h=Math.max(l,i);return{duration:1/0,start:l,end:h}}return{duration:1/0}}const r=(e=this.overrides)==null?void 0:e.duration;if(r)return M(r)?{duration:r}:null;const n=this.media.duration,o=M(s.duration)?s.duration:0;return i>o&&i>n||!M(n)?{duration:i}:null}updateMediaSource({duration:e,start:t,end:s}){const i=this.mediaSource;!this.media||!i||i.readyState!=="open"||(i.duration!==e&&(M(e)&&this.log(`Updating MediaSource duration to ${e.toFixed(3)}`),i.duration=e),t!==void 0&&s!==void 0&&(this.log(`MediaSource duration is set to ${i.duration}. Setting seekable range to ${t}-${s}.`),i.setLiveSeekableRange(t,s)))}get tracksReady(){const e=this.pendingTrackCount;return e>0&&(e>=this.bufferCodecEventsTotal||this.isPending(this.tracks.audiovideo))}checkPendingTracks(){const{bufferCodecEventsTotal:e,pendingTrackCount:t,tracks:s}=this;if(this.log(`checkPendingTracks (pending: ${t} codec events expected: ${e}) ${ne(s)}`),this.tracksReady){var i;const r=(i=this.transferData)==null?void 0:i.tracks;r&&Object.keys(r).length?this.attachTransferred():this.createSourceBuffers()}}bufferCreated(){if(this.sourceBufferCount){const e={};this.sourceBuffers.forEach(([t,s])=>{if(t){const i=this.tracks[t];e[t]={buffer:s,container:i.container,codec:i.codec,supplemental:i.supplemental,levelCodec:i.levelCodec,id:i.id,metadata:i.metadata}}}),this.hls.trigger(m.BUFFER_CREATED,{tracks:e}),this.log(`SourceBuffers created. Running queue: ${this.operationQueue}`),this.sourceBuffers.forEach(([t])=>{this.executeNext(t)})}else{const e=new Error("could not create source buffer for media codec(s)");this.hls.trigger(m.ERROR,{type:V.MEDIA_ERROR,details:R.BUFFER_INCOMPATIBLE_CODECS_ERROR,fatal:!0,error:e,reason:e.message})}}createSourceBuffers(){const{tracks:e,sourceBuffers:t,mediaSource:s}=this;if(!s)throw new Error("createSourceBuffers called when mediaSource was null");for(const r in e){const n=r,o=e[n];if(this.isPending(o)){const c=this.getTrackCodec(o,n),l=`${o.container};codecs=${c}`;o.codec=c,this.log(`creating sourceBuffer(${l})${this.currentOp(n)?" Queued":""} ${ne(o)}`);try{const h=s.addSourceBuffer(l),d=Ws(n),u=[n,h];t[d]=u,o.buffer=h}catch(h){var i;this.error(`error while trying to add sourceBuffer: ${h.message}`),this.shiftAndExecuteNext(n),(i=this.operationQueue)==null||i.removeBlockers(),delete this.tracks[n],this.hls.trigger(m.ERROR,{type:V.MEDIA_ERROR,details:R.BUFFER_ADD_CODEC_ERROR,fatal:!1,error:h,sourceBufferName:n,mimeType:l,parent:o.id});return}this.trackSourceBuffer(n,o)}}this.bufferCreated()}getTrackCodec(e,t){const s=e.supplemental;let i=e.codec;s&&(t==="video"||t==="audiovideo")&&Bt(s,"video")&&(i=ko(i,s));const r=cs(i,e.levelCodec);return r?t.slice(0,5)==="audio"?Ts(r,this.appendSource):r:""}trackSourceBuffer(e,t){const s=t.buffer;if(!s)return;const i=this.getTrackCodec(t,e);this.tracks[e]={buffer:s,codec:i,container:t.container,levelCodec:t.levelCodec,supplemental:t.supplemental,metadata:t.metadata,id:t.id,listeners:[]},this.removeBufferListeners(e),this.addBufferListener(e,"updatestart",this.onSBUpdateStart),this.addBufferListener(e,"updateend",this.onSBUpdateEnd),this.addBufferListener(e,"error",this.onSBUpdateError),this.appendSource&&this.addBufferListener(e,"bufferedchange",(r,n)=>{const o=n.removedRanges;o!=null&&o.length&&this.hls.trigger(m.BUFFER_FLUSHED,{type:r})})}get mediaSrc(){var e,t;const s=((e=this.media)==null||(t=e.querySelector)==null?void 0:t.call(e,"source"))||this.media;return s==null?void 0:s.src}onSBUpdateStart(e){const t=this.currentOp(e);t&&t.onStart()}onSBUpdateEnd(e){var t;if(((t=this.mediaSource)==null?void 0:t.readyState)==="closed"){this.resetBuffer(e);return}const s=this.currentOp(e);s&&(s.onComplete(),this.shiftAndExecuteNext(e))}onSBUpdateError(e,t){var s;const i=new Error(`${e} SourceBuffer error. MediaSource readyState: ${(s=this.mediaSource)==null?void 0:s.readyState}`);this.error(`${i}`,t),this.hls.trigger(m.ERROR,{type:V.MEDIA_ERROR,details:R.BUFFER_APPENDING_ERROR,sourceBufferName:e,error:i,fatal:!1});const r=this.currentOp(e);r&&r.onError(i)}updateTimestampOffset(e,t,s,i,r,n){const o=t-e.timestampOffset;Math.abs(o)>=s&&(this.log(`Updating ${i} SourceBuffer timestampOffset to ${t} (sn: ${r} cc: ${n})`),e.timestampOffset=t)}removeExecutor(e,t,s){const{media:i,mediaSource:r}=this,n=this.tracks[e],o=n==null?void 0:n.buffer;if(!i||!r||!o){this.warn(`Attempting to remove from the ${e} SourceBuffer, but it does not exist`),this.shiftAndExecuteNext(e);return}const c=M(i.duration)?i.duration:1/0,l=M(r.duration)?r.duration:1/0,h=Math.max(0,t),d=Math.min(s,c,l);d>h&&(!n.ending||n.ended)?(n.ended=!1,this.log(`Removing [${h},${d}] from the ${e} SourceBuffer`),o.remove(h,d)):this.shiftAndExecuteNext(e)}appendExecutor(e,t){const s=this.tracks[t],i=s==null?void 0:s.buffer;if(!i)throw new Gc(`Attempting to append to the ${t} SourceBuffer, but it does not exist`);s.ending=!1,s.ended=!1,i.appendBuffer(e)}blockUntilOpen(e){if(this.isUpdating()||this.isQueued())this.blockBuffers(e).catch(t=>{this.warn(`SourceBuffer blocked callback ${t}`),this.stepOperationQueue(this.sourceBufferTypes)});else try{e()}catch(t){this.warn(`Callback run without blocking ${this.operationQueue} ${t}`)}}isUpdating(){return this.sourceBuffers.some(([e,t])=>e&&t.updating)}isQueued(){return this.sourceBuffers.some(([e])=>e&&!!this.currentOp(e))}isPending(e){return!!e&&!e.buffer}blockBuffers(e,t=this.sourceBufferTypes){if(!t.length)return this.log("Blocking operation requested, but no SourceBuffers exist"),Promise.resolve().then(e);const{operationQueue:s}=this,i=t.map(n=>this.appendBlocker(n));return t.length>1&&!!this.blockedAudioAppend&&this.unblockAudio(),Promise.all(i).then(n=>{s===this.operationQueue&&(e(),this.stepOperationQueue(this.sourceBufferTypes))})}stepOperationQueue(e){e.forEach(t=>{var s;const i=(s=this.tracks[t])==null?void 0:s.buffer;!i||i.updating||this.shiftAndExecuteNext(t)})}append(e,t,s){this.operationQueue&&this.operationQueue.append(e,t,s)}appendBlocker(e){if(this.operationQueue)return this.operationQueue.appendBlocker(e)}currentOp(e){return this.operationQueue?this.operationQueue.current(e):null}executeNext(e){e&&this.operationQueue&&this.operationQueue.executeNext(e)}shiftAndExecuteNext(e){this.operationQueue&&this.operationQueue.shiftAndExecuteNext(e)}get pendingTrackCount(){return Object.keys(this.tracks).reduce((e,t)=>e+(this.isPending(this.tracks[t])?1:0),0)}get sourceBufferCount(){return this.sourceBuffers.reduce((e,[t])=>e+(t?1:0),0)}get sourceBufferTypes(){return this.sourceBuffers.map(([e])=>e).filter(e=>!!e)}addBufferListener(e,t,s){const i=this.tracks[e];if(!i)return;const r=i.buffer;if(!r)return;const n=s.bind(this,e);i.listeners.push({event:t,listener:n}),r.addEventListener(t,n)}removeBufferListeners(e){const t=this.tracks[e];if(!t)return;const s=t.buffer;s&&(t.listeners.forEach(i=>{s.removeEventListener(i.event,i.listener)}),t.listeners.length=0)}}function Xr(a){const e=a.querySelectorAll("source");[].slice.call(e).forEach(t=>{a.removeChild(t)})}function Vc(a,e){const t=self.document.createElement("source");t.type="video/mp4",t.src=e,a.appendChild(t)}function Ws(a){return a==="audio"?1:0}class Vi{constructor(e){this.hls=void 0,this.autoLevelCapping=void 0,this.firstLevel=void 0,this.media=void 0,this.restrictedLevels=void 0,this.timer=void 0,this.clientRect=void 0,this.streamController=void 0,this.hls=e,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.firstLevel=-1,this.media=null,this.restrictedLevels=[],this.timer=void 0,this.clientRect=null,this.registerListeners()}setStreamController(e){this.streamController=e}destroy(){this.hls&&this.unregisterListener(),this.timer&&this.stopCapping(),this.media=null,this.clientRect=null,this.hls=this.streamController=null}registerListeners(){const{hls:e}=this;e.on(m.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.on(m.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(m.MANIFEST_PARSED,this.onManifestParsed,this),e.on(m.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(m.BUFFER_CODECS,this.onBufferCodecs,this),e.on(m.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListener(){const{hls:e}=this;e.off(m.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.off(m.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(m.MANIFEST_PARSED,this.onManifestParsed,this),e.off(m.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(m.BUFFER_CODECS,this.onBufferCodecs,this),e.off(m.MEDIA_DETACHING,this.onMediaDetaching,this)}onFpsDropLevelCapping(e,t){const s=this.hls.levels[t.droppedLevel];this.isLevelAllowed(s)&&this.restrictedLevels.push({bitrate:s.bitrate,height:s.height,width:s.width})}onMediaAttaching(e,t){this.media=t.media instanceof HTMLVideoElement?t.media:null,this.clientRect=null,this.timer&&this.hls.levels.length&&this.detectPlayerSize()}onManifestParsed(e,t){const s=this.hls;this.restrictedLevels=[],this.firstLevel=t.firstLevel,s.config.capLevelToPlayerSize&&t.video&&this.startCapping()}onLevelsUpdated(e,t){this.timer&&M(this.autoLevelCapping)&&this.detectPlayerSize()}onBufferCodecs(e,t){this.hls.config.capLevelToPlayerSize&&t.video&&this.startCapping()}onMediaDetaching(){this.stopCapping(),this.media=null}detectPlayerSize(){if(this.media){if(this.mediaHeight<=0||this.mediaWidth<=0){this.clientRect=null;return}const e=this.hls.levels;if(e.length){const t=this.hls,s=this.getMaxLevel(e.length-1);s!==this.autoLevelCapping&&t.logger.log(`Setting autoLevelCapping to ${s}: ${e[s].height}p@${e[s].bitrate} for media ${this.mediaWidth}x${this.mediaHeight}`),t.autoLevelCapping=s,t.autoLevelEnabled&&t.autoLevelCapping>this.autoLevelCapping&&this.streamController&&this.streamController.nextLevelSwitch(),this.autoLevelCapping=t.autoLevelCapping}}}getMaxLevel(e){const t=this.hls.levels;if(!t.length)return-1;const s=t.filter((i,r)=>this.isLevelAllowed(i)&&r<=e);return this.clientRect=null,Vi.getMaxLevelByMediaSize(s,this.mediaWidth,this.mediaHeight)}startCapping(){this.timer||(this.autoLevelCapping=Number.POSITIVE_INFINITY,self.clearInterval(this.timer),this.timer=self.setInterval(this.detectPlayerSize.bind(this),1e3),this.detectPlayerSize())}stopCapping(){this.restrictedLevels=[],this.firstLevel=-1,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.timer&&(self.clearInterval(this.timer),this.timer=void 0)}getDimensions(){if(this.clientRect)return this.clientRect;const e=this.media,t={width:0,height:0};if(e){const s=e.getBoundingClientRect();t.width=s.width,t.height=s.height,!t.width&&!t.height&&(t.width=s.right-s.left||e.width||0,t.height=s.bottom-s.top||e.height||0)}return this.clientRect=t,t}get mediaWidth(){return this.getDimensions().width*this.contentScaleFactor}get mediaHeight(){return this.getDimensions().height*this.contentScaleFactor}get contentScaleFactor(){let e=1;if(!this.hls.config.ignoreDevicePixelRatio)try{e=self.devicePixelRatio}catch{}return Math.min(e,this.hls.config.maxDevicePixelRatio)}isLevelAllowed(e){return!this.restrictedLevels.some(s=>e.bitrate===s.bitrate&&e.width===s.width&&e.height===s.height)}static getMaxLevelByMediaSize(e,t,s){if(!(e!=null&&e.length))return-1;const i=(o,c)=>c?o.width!==c.width||o.height!==c.height:!0;let r=e.length-1;const n=Math.max(t,s);for(let o=0;o<e.length;o+=1){const c=e[o];if((c.width>=n||c.height>=n)&&i(c,e[o+1])){r=o;break}}return r}}const Hc={MANIFEST:"m",AUDIO:"a",VIDEO:"v",MUXED:"av",INIT:"i",CAPTION:"c",TIMED_TEXT:"tt",KEY:"k",OTHER:"o"},Se=Hc,Yc={HLS:"h"},Wc=Yc;class Ye{constructor(e,t){Array.isArray(e)&&(e=e.map(s=>s instanceof Ye?s:new Ye(s))),this.value=e,this.params=t}}const qc="Dict";function jc(a){return Array.isArray(a)?JSON.stringify(a):a instanceof Map?"Map{}":a instanceof Set?"Set{}":typeof a=="object"?JSON.stringify(a):String(a)}function Xc(a,e,t,s){return new Error(`failed to ${a} "${jc(e)}" as ${t}`,{cause:s})}function We(a,e,t){return Xc("serialize",a,e,t)}class La{constructor(e){this.description=e}}const zr="Bare Item",zc="Boolean";function Qc(a){if(typeof a!="boolean")throw We(a,zc);return a?"?1":"?0"}function Zc(a){return btoa(String.fromCharCode(...a))}const Jc="Byte Sequence";function eh(a){if(ArrayBuffer.isView(a)===!1)throw We(a,Jc);return`:${Zc(a)}:`}const th="Integer";function sh(a){return a<-999999999999999||999999999999999<a}function Ra(a){if(sh(a))throw We(a,th);return a.toString()}function ih(a){return`@${Ra(a.getTime()/1e3)}`}function ba(a,e){if(a<0)return-ba(-a,e);const t=Math.pow(10,e);if(Math.abs(a*t%1-.5)<Number.EPSILON){const i=Math.floor(a*t);return(i%2===0?i:i+1)/t}else return Math.round(a*t)/t}const rh="Decimal";function nh(a){const e=ba(a,3);if(Math.floor(Math.abs(e)).toString().length>12)throw We(a,rh);const t=e.toString();return t.includes(".")?t:`${t}.0`}const ah="String",oh=/[\x00-\x1f\x7f]+/;function lh(a){if(oh.test(a))throw We(a,ah);return`"${a.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}function ch(a){return a.description||a.toString().slice(7,-1)}const hh="Token";function Qr(a){const e=ch(a);if(/^([a-zA-Z*])([!#$%&'*+\-.^_`|~\w:/]*)$/.test(e)===!1)throw We(e,hh);return e}function pi(a){switch(typeof a){case"number":if(!M(a))throw We(a,zr);return Number.isInteger(a)?Ra(a):nh(a);case"string":return lh(a);case"symbol":return Qr(a);case"boolean":return Qc(a);case"object":if(a instanceof Date)return ih(a);if(a instanceof Uint8Array)return eh(a);if(a instanceof La)return Qr(a);default:throw We(a,zr)}}const dh="Key";function yi(a){if(/^[a-z*][a-z0-9\-_.*]*$/.test(a)===!1)throw We(a,dh);return a}function Hi(a){return a==null?"":Object.entries(a).map(([e,t])=>t===!0?`;${yi(e)}`:`;${yi(e)}=${pi(t)}`).join("")}function _a(a){return a instanceof Ye?`${pi(a.value)}${Hi(a.params)}`:pi(a)}function uh(a){return`(${a.value.map(_a).join(" ")})${Hi(a.params)}`}function fh(a,e={whitespace:!0}){if(typeof a!="object"||a==null)throw We(a,qc);const t=a instanceof Map?a.entries():Object.entries(a),s=e!=null&&e.whitespace?" ":"";return Array.from(t).map(([i,r])=>{r instanceof Ye||(r=new Ye(r));let n=yi(i);return r.value===!0?n+=Hi(r.params):(n+="=",Array.isArray(r.value)?n+=uh(r):n+=_a(r)),n}).join(`,${s}`)}function Da(a,e){return fh(a,e)}const $e="CMCD-Object",le="CMCD-Request",ct="CMCD-Session",Je="CMCD-Status",gh={br:$e,ab:$e,d:$e,ot:$e,tb:$e,tpb:$e,lb:$e,tab:$e,lab:$e,url:$e,pb:le,bl:le,tbl:le,dl:le,ltc:le,mtp:le,nor:le,nrr:le,rc:le,sn:le,sta:le,su:le,ttfb:le,ttfbb:le,ttlb:le,cmsdd:le,cmsds:le,smrt:le,df:le,cs:le,ts:le,cid:ct,pr:ct,sf:ct,sid:ct,st:ct,v:ct,msd:ct,bs:Je,bsd:Je,cdn:Je,rtp:Je,bg:Je,pt:Je,ec:Je,e:Je},mh={REQUEST:le};function ph(a){return Object.keys(a).reduce((e,t)=>{var s;return(s=a[t])===null||s===void 0||s.forEach(i=>e[i]=t),e},{})}function yh(a,e){const t={};if(!a)return t;const s=Object.keys(a),i=e?ph(e):{};return s.reduce((r,n)=>{var o;const c=gh[n]||i[n]||mh.REQUEST,l=(o=r[c])!==null&&o!==void 0?o:r[c]={};return l[n]=a[n],r},t)}function Eh(a){return["ot","sf","st","e","sta"].includes(a)}function Th(a){return typeof a=="number"?M(a):a!=null&&a!==""&&a!==!1}const Ca="event";function Sh(a,e){const t=new URL(a),s=new URL(e);if(t.origin!==s.origin)return a;const i=t.pathname.split("/").slice(1),r=s.pathname.split("/").slice(1,-1);for(;i[0]===r[0];)i.shift(),r.shift();for(;r.length;)r.shift(),i.unshift("..");return i.join("/")+t.search+t.hash}const gs=a=>Math.round(a),Ei=(a,e)=>Array.isArray(a)?a.map(t=>Ei(t,e)):a instanceof Ye&&typeof a.value=="string"?new Ye(Ei(a.value,e),a.params):(e.baseUrl&&(a=Sh(a,e.baseUrl)),e.version===1?encodeURIComponent(a):a),Jt=a=>gs(a/100)*100,vh=(a,e)=>{let t=a;return e.version>=2&&(a instanceof Ye&&typeof a.value=="string"?t=new Ye([a]):typeof a=="string"&&(t=[a])),Ei(t,e)},xh={br:gs,d:gs,bl:Jt,dl:Jt,mtp:Jt,nor:vh,rtp:Jt,tb:gs},Pa="request",ka="response",Yi=["ab","bg","bl","br","bs","bsd","cdn","cid","cs","df","ec","lab","lb","ltc","msd","mtp","pb","pr","pt","sf","sid","sn","st","sta","tab","tb","tbl","tpb","ts","v"],Ah=["e"],Ih=/^[a-zA-Z0-9-.]+-[a-zA-Z0-9-.]+$/;function Ps(a){return Ih.test(a)}function Lh(a){return Yi.includes(a)||Ah.includes(a)||Ps(a)}const wa=["d","dl","nor","ot","rtp","su"];function Rh(a){return Yi.includes(a)||wa.includes(a)||Ps(a)}const bh=["cmsdd","cmsds","rc","smrt","ttfb","ttfbb","ttlb","url"];function _h(a){return Yi.includes(a)||wa.includes(a)||bh.includes(a)||Ps(a)}const Dh=["bl","br","bs","cid","d","dl","mtp","nor","nrr","ot","pr","rtp","sf","sid","st","su","tb","v"];function Ch(a){return Dh.includes(a)||Ps(a)}const Ph={[ka]:_h,[Ca]:Lh,[Pa]:Rh};function Oa(a,e={}){const t={};if(a==null||typeof a!="object")return t;const s=e.version||a.v||1,i=e.reportingMode||Pa,r=s===1?Ch:Ph[i];let n=Object.keys(a).filter(r);const o=e.filter;typeof o=="function"&&(n=n.filter(o));const c=i===ka||i===Ca;c&&!n.includes("ts")&&n.push("ts"),s>1&&!n.includes("v")&&n.push("v");const l=ie({},xh,e.formatters),h={version:s,reportingMode:i,baseUrl:e.baseUrl};return n.sort().forEach(d=>{let u=a[d];const f=l[d];if(typeof f=="function"&&(u=f(u,h)),d==="v"){if(s===1)return;u=s}d=="pr"&&u===1||(c&&d==="ts"&&!M(u)&&(u=Date.now()),Th(u)&&(Eh(d)&&typeof u=="string"&&(u=new La(u)),t[d]=u))}),t}function kh(a,e={}){const t={};if(!a)return t;const s=Oa(a,e),i=yh(s,e==null?void 0:e.customHeaderMap);return Object.entries(i).reduce((r,[n,o])=>{const c=Da(o,{whitespace:!1});return c&&(r[n]=c),r},t)}function wh(a,e,t){return ie(a,kh(e,t))}const Oh="CMCD";function Fh(a,e={}){return a?Da(Oa(a,e),{whitespace:!1}):""}function Mh(a,e={}){if(!a)return"";const t=Fh(a,e);return encodeURIComponent(t)}function Nh(a,e={}){if(!a)return"";const t=Mh(a,e);return`${Oh}=${t}`}const Zr=/CMCD=[^&#]+/;function Bh(a,e,t){const s=Nh(e,t);if(!s)return a;if(Zr.test(a))return a.replace(Zr,s);const i=a.includes("?")?"&":"?";return`${a}${i}${s}`}class Uh{constructor(e){this.hls=void 0,this.config=void 0,this.media=void 0,this.sid=void 0,this.cid=void 0,this.useHeaders=!1,this.includeKeys=void 0,this.initialized=!1,this.starved=!1,this.buffering=!0,this.audioBuffer=void 0,this.videoBuffer=void 0,this.onWaiting=()=>{this.initialized&&(this.starved=!0),this.buffering=!0},this.onPlaying=()=>{this.initialized||(this.initialized=!0),this.buffering=!1},this.applyPlaylistData=i=>{try{this.apply(i,{ot:Se.MANIFEST,su:!this.initialized})}catch(r){this.hls.logger.warn("Could not generate manifest CMCD data.",r)}},this.applyFragmentData=i=>{try{const{frag:r,part:n}=i,o=this.hls.levels[r.level],c=this.getObjectType(r),l={d:(n||r).duration*1e3,ot:c};(c===Se.VIDEO||c===Se.AUDIO||c==Se.MUXED)&&(l.br=o.bitrate/1e3,l.tb=this.getTopBandwidth(c)/1e3,l.bl=this.getBufferLength(c));const h=n?this.getNextPart(n):this.getNextFrag(r);h!=null&&h.url&&h.url!==r.url&&(l.nor=h.url),this.apply(i,l)}catch(r){this.hls.logger.warn("Could not generate segment CMCD data.",r)}},this.hls=e;const t=this.config=e.config,{cmcd:s}=t;s!=null&&(t.pLoader=this.createPlaylistLoader(),t.fLoader=this.createFragmentLoader(),this.sid=s.sessionId||e.sessionId,this.cid=s.contentId,this.useHeaders=s.useHeaders===!0,this.includeKeys=s.includeKeys,this.registerListeners())}registerListeners(){const e=this.hls;e.on(m.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(m.MEDIA_DETACHED,this.onMediaDetached,this),e.on(m.BUFFER_CREATED,this.onBufferCreated,this)}unregisterListeners(){const e=this.hls;e.off(m.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(m.MEDIA_DETACHED,this.onMediaDetached,this),e.off(m.BUFFER_CREATED,this.onBufferCreated,this)}destroy(){this.unregisterListeners(),this.onMediaDetached(),this.hls=this.config=this.audioBuffer=this.videoBuffer=null,this.onWaiting=this.onPlaying=this.media=null}onMediaAttached(e,t){this.media=t.media,this.media.addEventListener("waiting",this.onWaiting),this.media.addEventListener("playing",this.onPlaying)}onMediaDetached(){this.media&&(this.media.removeEventListener("waiting",this.onWaiting),this.media.removeEventListener("playing",this.onPlaying),this.media=null)}onBufferCreated(e,t){var s,i;this.audioBuffer=(s=t.tracks.audio)==null?void 0:s.buffer,this.videoBuffer=(i=t.tracks.video)==null?void 0:i.buffer}createData(){var e;return{v:1,sf:Wc.HLS,sid:this.sid,cid:this.cid,pr:(e=this.media)==null?void 0:e.playbackRate,mtp:this.hls.bandwidthEstimate/1e3}}apply(e,t={}){ie(t,this.createData());const s=t.ot===Se.INIT||t.ot===Se.VIDEO||t.ot===Se.MUXED;this.starved&&s&&(t.bs=!0,t.su=!0,this.starved=!1),t.su==null&&(t.su=this.buffering);const{includeKeys:i}=this;i&&(t=Object.keys(t).reduce((n,o)=>(i.includes(o)&&(n[o]=t[o]),n),{}));const r={baseUrl:e.url};this.useHeaders?(e.headers||(e.headers={}),wh(e.headers,t,r)):e.url=Bh(e.url,t,r)}getNextFrag(e){var t;const s=(t=this.hls.levels[e.level])==null?void 0:t.details;if(s){const i=e.sn-s.startSN;return s.fragments[i+1]}}getNextPart(e){var t;const{index:s,fragment:i}=e,r=(t=this.hls.levels[i.level])==null||(t=t.details)==null?void 0:t.partList;if(r){const{sn:n}=i;for(let o=r.length-1;o>=0;o--){const c=r[o];if(c.index===s&&c.fragment.sn===n)return r[o+1]}}}getObjectType(e){const{type:t}=e;if(t==="subtitle")return Se.TIMED_TEXT;if(e.sn==="initSegment")return Se.INIT;if(t==="audio")return Se.AUDIO;if(t==="main")return this.hls.audioTracks.length?Se.VIDEO:Se.MUXED}getTopBandwidth(e){let t=0,s;const i=this.hls;if(e===Se.AUDIO)s=i.audioTracks;else{const r=i.maxAutoLevel,n=r>-1?r+1:i.levels.length;s=i.levels.slice(0,n)}return s.forEach(r=>{r.bitrate>t&&(t=r.bitrate)}),t>0?t:NaN}getBufferLength(e){const t=this.media,s=e===Se.AUDIO?this.audioBuffer:this.videoBuffer;return!s||!t?NaN:q.bufferInfo(s,t.currentTime,this.config.maxBufferHole).len*1e3}createPlaylistLoader(){const{pLoader:e}=this.config,t=this.applyPlaylistData,s=e||this.config.loader;return class{constructor(r){this.loader=void 0,this.loader=new s(r)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(r,n,o){t(r),this.loader.load(r,n,o)}}}createFragmentLoader(){const{fLoader:e}=this.config,t=this.applyFragmentData,s=e||this.config.loader;return class{constructor(r){this.loader=void 0,this.loader=new s(r)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(r,n,o){t(r),this.loader.load(r,n,o)}}}}const $h=3e5;class Gh extends we{constructor(e){super("content-steering",e.logger),this.hls=void 0,this.loader=null,this.uri=null,this.pathwayId=".",this._pathwayPriority=null,this.timeToLoad=300,this.reloadTimer=-1,this.updated=0,this.started=!1,this.enabled=!0,this.levels=null,this.audioTracks=null,this.subtitleTracks=null,this.penalizedPathways={},this.hls=e,this.registerListeners()}registerListeners(){const e=this.hls;e.on(m.MANIFEST_LOADING,this.onManifestLoading,this),e.on(m.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(m.MANIFEST_PARSED,this.onManifestParsed,this),e.on(m.ERROR,this.onError,this)}unregisterListeners(){const e=this.hls;e&&(e.off(m.MANIFEST_LOADING,this.onManifestLoading,this),e.off(m.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(m.MANIFEST_PARSED,this.onManifestParsed,this),e.off(m.ERROR,this.onError,this))}pathways(){return(this.levels||[]).reduce((e,t)=>(e.indexOf(t.pathwayId)===-1&&e.push(t.pathwayId),e),[])}get pathwayPriority(){return this._pathwayPriority}set pathwayPriority(e){this.updatePathwayPriority(e)}startLoad(){if(this.started=!0,this.clearTimeout(),this.enabled&&this.uri){if(this.updated){const e=this.timeToLoad*1e3-(performance.now()-this.updated);if(e>0){this.scheduleRefresh(this.uri,e);return}}this.loadSteeringManifest(this.uri)}}stopLoad(){this.started=!1,this.loader&&(this.loader.destroy(),this.loader=null),this.clearTimeout()}clearTimeout(){this.reloadTimer!==-1&&(self.clearTimeout(this.reloadTimer),this.reloadTimer=-1)}destroy(){this.unregisterListeners(),this.stopLoad(),this.hls=null,this.levels=this.audioTracks=this.subtitleTracks=null}removeLevel(e){const t=this.levels;t&&(this.levels=t.filter(s=>s!==e))}onManifestLoading(){this.stopLoad(),this.enabled=!0,this.timeToLoad=300,this.updated=0,this.uri=null,this.pathwayId=".",this.levels=this.audioTracks=this.subtitleTracks=null}onManifestLoaded(e,t){const{contentSteering:s}=t;s!==null&&(this.pathwayId=s.pathwayId,this.uri=s.uri,this.started&&this.startLoad())}onManifestParsed(e,t){this.audioTracks=t.audioTracks,this.subtitleTracks=t.subtitleTracks}onError(e,t){const{errorAction:s}=t;if((s==null?void 0:s.action)===ge.SendAlternateToPenaltyBox&&s.flags===Ie.MoveAllAlternatesMatchingHost){const i=this.levels;let r=this._pathwayPriority,n=this.pathwayId;if(t.context){const{groupId:o,pathwayId:c,type:l}=t.context;o&&i?n=this.getPathwayForGroupId(o,l,n):c&&(n=c)}n in this.penalizedPathways||(this.penalizedPathways[n]=performance.now()),!r&&i&&(r=this.pathways()),r&&r.length>1&&(this.updatePathwayPriority(r),s.resolved=this.pathwayId!==n),t.details===R.BUFFER_APPEND_ERROR&&!t.fatal?s.resolved=!0:s.resolved||this.warn(`Could not resolve ${t.details} ("${t.error.message}") with content-steering for Pathway: ${n} levels: ${i&&i.length} priorities: ${ne(r)} penalized: ${ne(this.penalizedPathways)}`)}}filterParsedLevels(e){this.levels=e;let t=this.getLevelsForPathway(this.pathwayId);if(t.length===0){const s=e[0].pathwayId;this.log(`No levels found in Pathway ${this.pathwayId}. Setting initial Pathway to "${s}"`),t=this.getLevelsForPathway(s),this.pathwayId=s}return t.length!==e.length&&this.log(`Found ${t.length}/${e.length} levels in Pathway "${this.pathwayId}"`),t}getLevelsForPathway(e){return this.levels===null?[]:this.levels.filter(t=>e===t.pathwayId)}updatePathwayPriority(e){this._pathwayPriority=e;let t;const s=this.penalizedPathways,i=performance.now();Object.keys(s).forEach(r=>{i-s[r]>$h&&delete s[r]});for(let r=0;r<e.length;r++){const n=e[r];if(n in s)continue;if(n===this.pathwayId)return;const o=this.hls.nextLoadLevel,c=this.hls.levels[o];if(t=this.getLevelsForPathway(n),t.length>0){this.log(`Setting Pathway to "${n}"`),this.pathwayId=n,ea(t),this.hls.trigger(m.LEVELS_UPDATED,{levels:t});const l=this.hls.levels[o];c&&l&&this.levels&&(l.attrs["STABLE-VARIANT-ID"]!==c.attrs["STABLE-VARIANT-ID"]&&l.bitrate!==c.bitrate&&this.log(`Unstable Pathways change from bitrate ${c.bitrate} to ${l.bitrate}`),this.hls.nextLoadLevel=o);break}}}getPathwayForGroupId(e,t,s){const i=this.getLevelsForPathway(s).concat(this.levels||[]);for(let r=0;r<i.length;r++)if(t===Q.AUDIO_TRACK&&i[r].hasAudioGroup(e)||t===Q.SUBTITLE_TRACK&&i[r].hasSubtitleGroup(e))return i[r].pathwayId;return s}clonePathways(e){const t=this.levels;if(!t)return;const s={},i={};e.forEach(r=>{const{ID:n,"BASE-ID":o,"URI-REPLACEMENT":c}=r;if(t.some(h=>h.pathwayId===n))return;const l=this.getLevelsForPathway(o).map(h=>{const d=new ae(h.attrs);d["PATHWAY-ID"]=n;const u=d.AUDIO&&`${d.AUDIO}_clone_${n}`,f=d.SUBTITLES&&`${d.SUBTITLES}_clone_${n}`;u&&(s[d.AUDIO]=u,d.AUDIO=u),f&&(i[d.SUBTITLES]=f,d.SUBTITLES=f);const g=Fa(h.uri,d["STABLE-VARIANT-ID"],"PER-VARIANT-URIS",c),y=new $t({attrs:d,audioCodec:h.audioCodec,bitrate:h.bitrate,height:h.height,name:h.name,url:g,videoCodec:h.videoCodec,width:h.width});if(h.audioGroups)for(let p=1;p<h.audioGroups.length;p++)y.addGroupId("audio",`${h.audioGroups[p]}_clone_${n}`);if(h.subtitleGroups)for(let p=1;p<h.subtitleGroups.length;p++)y.addGroupId("text",`${h.subtitleGroups[p]}_clone_${n}`);return y});t.push(...l),Jr(this.audioTracks,s,c,n),Jr(this.subtitleTracks,i,c,n)})}loadSteeringManifest(e){const t=this.hls.config,s=t.loader;this.loader&&this.loader.destroy(),this.loader=new s(t);let i;try{i=new self.URL(e)}catch{this.enabled=!1,this.log(`Failed to parse Steering Manifest URI: ${e}`);return}if(i.protocol!=="data:"){const h=(this.hls.bandwidthEstimate||t.abrEwmaDefaultEstimate)|0;i.searchParams.set("_HLS_pathway",this.pathwayId),i.searchParams.set("_HLS_throughput",""+h)}const r={responseType:"json",url:i.href},n=t.steeringManifestLoadPolicy.default,o=n.errorRetry||n.timeoutRetry||{},c={loadPolicy:n,timeout:n.maxLoadTimeMs,maxRetry:o.maxNumRetry||0,retryDelay:o.retryDelayMs||0,maxRetryDelay:o.maxRetryDelayMs||0},l={onSuccess:(h,d,u,f)=>{this.log(`Loaded steering manifest: "${i}"`);const g=h.data;if((g==null?void 0:g.VERSION)!==1){this.log(`Steering VERSION ${g.VERSION} not supported!`);return}this.updated=performance.now(),this.timeToLoad=g.TTL;const{"RELOAD-URI":y,"PATHWAY-CLONES":p,"PATHWAY-PRIORITY":E}=g;if(y)try{this.uri=new self.URL(y,i).href}catch{this.enabled=!1,this.log(`Failed to parse Steering Manifest RELOAD-URI: ${y}`);return}this.scheduleRefresh(this.uri||u.url),p&&this.clonePathways(p);const T={steeringManifest:g,url:i.toString()};this.hls.trigger(m.STEERING_MANIFEST_LOADED,T),E&&this.updatePathwayPriority(E)},onError:(h,d,u,f)=>{if(this.log(`Error loading steering manifest: ${h.code} ${h.text} (${d.url})`),this.stopLoad(),h.code===410){this.enabled=!1,this.log(`Steering manifest ${d.url} no longer available`);return}let g=this.timeToLoad*1e3;if(h.code===429){const y=this.loader;if(typeof(y==null?void 0:y.getResponseHeader)=="function"){const p=y.getResponseHeader("Retry-After");p&&(g=parseFloat(p)*1e3)}this.log(`Steering manifest ${d.url} rate limited`);return}this.scheduleRefresh(this.uri||d.url,g)},onTimeout:(h,d,u)=>{this.log(`Timeout loading steering manifest (${d.url})`),this.scheduleRefresh(this.uri||d.url)}};this.log(`Requesting steering manifest: ${i}`),this.loader.load(r,c,l)}scheduleRefresh(e,t=this.timeToLoad*1e3){this.clearTimeout(),this.reloadTimer=self.setTimeout(()=>{var s;const i=(s=this.hls)==null?void 0:s.media;if(i&&!i.ended){this.loadSteeringManifest(e);return}this.scheduleRefresh(e,this.timeToLoad*1e3)},t)}}function Jr(a,e,t,s){a&&Object.keys(e).forEach(i=>{const r=a.filter(n=>n.groupId===i).map(n=>{const o=ie({},n);return o.details=void 0,o.attrs=new ae(o.attrs),o.url=o.attrs.URI=Fa(n.url,n.attrs["STABLE-RENDITION-ID"],"PER-RENDITION-URIS",t),o.groupId=o.attrs["GROUP-ID"]=e[i],o.attrs["PATHWAY-ID"]=s,o});a.push(...r)})}function Fa(a,e,t,s){const{HOST:i,PARAMS:r,[t]:n}=s;let o;e&&(o=n==null?void 0:n[e],o&&(a=o));const c=new self.URL(a);return i&&!o&&(c.host=i),r&&Object.keys(r).sort().forEach(l=>{l&&c.searchParams.set(l,r[l])}),c.href}class Rt extends we{constructor(e){super("eme",e.logger),this.hls=void 0,this.config=void 0,this.media=null,this.mediaResolved=void 0,this.keyFormatPromise=null,this.keySystemAccessPromises={},this._requestLicenseFailureCount=0,this.mediaKeySessions=[],this.keyIdToKeySessionPromise={},this.mediaKeys=null,this.setMediaKeysQueue=Rt.CDMCleanupPromise?[Rt.CDMCleanupPromise]:[],this.bannedKeyIds={},this.onMediaEncrypted=t=>{const{initDataType:s,initData:i}=t,r=`"${t.type}" event: init data type: "${s}"`;if(this.debug(r),i!==null){if(!this.keyFormatPromise){let n=Object.keys(this.keySystemAccessPromises);n.length||(n=wt(this.config));const o=n.map(Bs).filter(c=>!!c);this.keyFormatPromise=this.getKeyFormatPromise(o)}this.keyFormatPromise.then(n=>{const o=ds(n);if(s!=="sinf"||o!==oe.FAIRPLAY){this.log(`Ignoring "${t.type}" event with init data type: "${s}" for selected key-system ${o}`);return}let c;try{const f=he(new Uint8Array(i)),g=wi(JSON.parse(f).sinf),y=Dn(g);if(!y)throw new Error("'schm' box missing or not cbcs/cenc with schi > tenc");c=new Uint8Array(y.subarray(8,24))}catch(f){this.warn(`${r} Failed to parse sinf: ${f}`);return}const l=me(c),{keyIdToKeySessionPromise:h,mediaKeySessions:d}=this;let u=h[l];for(let f=0;f<d.length;f++){const g=d[f],y=g.decryptdata;if(!y.keyId)continue;const p=me(y.keyId);if(Is(c,y.keyId)||y.uri.replace(/-/g,"").indexOf(l)!==-1){if(u=h[p],!u)continue;if(y.pssh)break;delete h[p],y.pssh=new Uint8Array(i),y.keyId=c,u=h[l]=u.then(()=>this.generateRequestWithPreferredKeySession(g,s,i,"encrypted-event-key-match")),u.catch(E=>this.handleError(E));break}}u||this.handleError(new Error(`Key ID ${l} not encountered in playlist. Key-system sessions ${d.length}.`))}).catch(n=>this.handleError(n))}},this.onWaitingForKey=t=>{this.log(`"${t.type}" event`)},this.hls=e,this.config=e.config,this.registerListeners()}destroy(){this.onDestroying(),this.onMediaDetached();const e=this.config;e.requestMediaKeySystemAccessFunc=null,e.licenseXhrSetup=e.licenseResponseCallback=void 0,e.drmSystems=e.drmSystemOptions={},this.hls=this.config=this.keyIdToKeySessionPromise=null,this.onMediaEncrypted=this.onWaitingForKey=null}registerListeners(){this.hls.on(m.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.on(m.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.on(m.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.on(m.MANIFEST_LOADED,this.onManifestLoaded,this),this.hls.on(m.DESTROYING,this.onDestroying,this)}unregisterListeners(){this.hls.off(m.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.off(m.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.off(m.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.off(m.MANIFEST_LOADED,this.onManifestLoaded,this),this.hls.off(m.DESTROYING,this.onDestroying,this)}getLicenseServerUrl(e){const{drmSystems:t,widevineLicenseUrl:s}=this.config,i=t==null?void 0:t[e];if(i)return i.licenseUrl;if(e===oe.WIDEVINE&&s)return s}getLicenseServerUrlOrThrow(e){const t=this.getLicenseServerUrl(e);if(t===void 0)throw new Error(`no license server URL configured for key-system "${e}"`);return t}getServerCertificateUrl(e){const{drmSystems:t}=this.config,s=t==null?void 0:t[e];if(s)return s.serverCertificateUrl;this.log(`No Server Certificate in config.drmSystems["${e}"]`)}attemptKeySystemAccess(e){const t=this.hls.levels,s=(n,o,c)=>!!n&&c.indexOf(n)===o,i=t.map(n=>n.audioCodec).filter(s),r=t.map(n=>n.videoCodec).filter(s);return i.length+r.length===0&&r.push("avc1.42e01e"),new Promise((n,o)=>{const c=l=>{const h=l.shift();this.getMediaKeysPromise(h,i,r).then(d=>n({keySystem:h,mediaKeys:d})).catch(d=>{l.length?c(l):d instanceof Ae?o(d):o(new Ae({type:V.KEY_SYSTEM_ERROR,details:R.KEY_SYSTEM_NO_ACCESS,error:d,fatal:!0},d.message))})};c(e)})}requestMediaKeySystemAccess(e,t){const{requestMediaKeySystemAccessFunc:s}=this.config;if(typeof s!="function"){let i=`Configured requestMediaKeySystemAccess is not a function ${s}`;return Wn===null&&self.location.protocol==="http:"&&(i=`navigator.requestMediaKeySystemAccess is not available over insecure protocol ${location.protocol}`),Promise.reject(new Error(i))}return s(e,t)}getMediaKeysPromise(e,t,s){var i;const r=vl(e,t,s,this.config.drmSystemOptions||{});let n=this.keySystemAccessPromises[e],o=(i=n)==null?void 0:i.keySystemAccess;if(!o){this.log(`Requesting encrypted media "${e}" key-system access with config: ${ne(r)}`),o=this.requestMediaKeySystemAccess(e,r);const c=n=this.keySystemAccessPromises[e]={keySystemAccess:o};return o.catch(l=>{this.log(`Failed to obtain access to key-system "${e}": ${l}`)}),o.then(l=>{this.log(`Access for key-system "${l.keySystem}" obtained`);const h=this.fetchServerCertificate(e);this.log(`Create media-keys for "${e}"`);const d=c.mediaKeys=l.createMediaKeys().then(u=>(this.log(`Media-keys created for "${e}"`),c.hasMediaKeys=!0,h.then(f=>f?this.setMediaKeysServerCertificate(u,e,f):u)));return d.catch(u=>{this.error(`Failed to create media-keys for "${e}"}: ${u}`)}),d})}return o.then(()=>n.mediaKeys)}createMediaKeySessionContext({decryptdata:e,keySystem:t,mediaKeys:s}){this.log(`Creating key-system session "${t}" keyId: ${me(e.keyId||[])} keyUri: ${e.uri}`);const i=s.createSession(),r={decryptdata:e,keySystem:t,mediaKeys:s,mediaKeysSession:i,keyStatus:"status-pending"};return this.mediaKeySessions.push(r),r}renewKeySession(e){const t=e.decryptdata;if(t.pssh){const s=this.createMediaKeySessionContext(e),i=es(t),r="cenc";this.keyIdToKeySessionPromise[i]=this.generateRequestWithPreferredKeySession(s,r,t.pssh.buffer,"expired")}else this.warn("Could not renew expired session. Missing pssh initData.");this.removeSession(e)}updateKeySession(e,t){const s=e.mediaKeysSession;return this.log(`Updating key-session "${s.sessionId}" for keyId ${me(e.decryptdata.keyId||[])}
251251- } (data length: ${t.byteLength})`),s.update(t)}getSelectedKeySystemFormats(){return Object.keys(this.keySystemAccessPromises).map(e=>({keySystem:e,hasMediaKeys:this.keySystemAccessPromises[e].hasMediaKeys})).filter(({hasMediaKeys:e})=>!!e).map(({keySystem:e})=>Bs(e)).filter(e=>!!e)}getKeySystemAccess(e){return this.getKeySystemSelectionPromise(e).then(({keySystem:t,mediaKeys:s})=>this.attemptSetMediaKeys(t,s))}selectKeySystem(e){return new Promise((t,s)=>{this.getKeySystemSelectionPromise(e).then(({keySystem:i})=>{const r=Bs(i);r?t(r):s(new Error(`Unable to find format for key-system "${i}"`))}).catch(s)})}selectKeySystemFormat(e){const t=Object.keys(e.levelkeys||{});return this.keyFormatPromise||(this.log(`Selecting key-system from fragment (sn: ${e.sn} ${e.type}: ${e.level}) key formats ${t.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(t)),this.keyFormatPromise}getKeyFormatPromise(e){const t=wt(this.config),s=e.map(ds).filter(i=>!!i&&t.indexOf(i)!==-1);return this.selectKeySystem(s)}getKeyStatus(e){const{mediaKeySessions:t}=this;for(let s=0;s<t.length;s++){const i=Kh(e,t[s]);if(i)return i}}loadKey(e){const t=e.keyInfo.decryptdata,s=es(t),i=this.bannedKeyIds[s];if(i||this.getKeyStatus(t)==="internal-error"){const o=en(i||"internal-error",t);return this.handleError(o,e.frag),Promise.reject(o)}const r=`(keyId: ${s} format: "${t.keyFormat}" method: ${t.method} uri: ${t.uri})`;this.log(`Starting session for key ${r}`);const n=this.keyIdToKeySessionPromise[s];if(!n){const o=this.getKeySystemForKeyPromise(t).then(({keySystem:c,mediaKeys:l})=>(this.throwIfDestroyed(),this.log(`Handle encrypted media sn: ${e.frag.sn} ${e.frag.type}: ${e.frag.level} using key ${r}`),this.attemptSetMediaKeys(c,l).then(()=>(this.throwIfDestroyed(),this.createMediaKeySessionContext({keySystem:c,mediaKeys:l,decryptdata:t}))))).then(c=>{const l="cenc",h=t.pssh?t.pssh.buffer:null;return this.generateRequestWithPreferredKeySession(c,l,h,"playlist-key")});return o.catch(c=>this.handleError(c,e.frag)),this.keyIdToKeySessionPromise[s]=o,o}return n.catch(o=>{if(o instanceof Ae){const c=te({},o.data);this.getKeyStatus(t)==="internal-error"&&(c.decryptdata=t);const l=new Ae(c,o.message);this.handleError(l,e.frag)}}),n}throwIfDestroyed(e="Invalid state"){if(!this.hls)throw new Error("invalid state")}handleError(e,t){if(this.hls)if(e instanceof Ae){t&&(e.data.frag=t);const s=e.data.decryptdata;this.error(`${e.message}${s?` (${me(s.keyId||[])})`:""}`),this.hls.trigger(m.ERROR,e.data)}else this.error(e.message),this.hls.trigger(m.ERROR,{type:V.KEY_SYSTEM_ERROR,details:R.KEY_SYSTEM_NO_KEYS,error:e,fatal:!0})}getKeySystemForKeyPromise(e){const t=es(e),s=this.keyIdToKeySessionPromise[t];if(!s){const i=ds(e.keyFormat),r=i?[i]:wt(this.config);return this.attemptKeySystemAccess(r)}return s}getKeySystemSelectionPromise(e){if(e.length||(e=wt(this.config)),e.length===0)throw new Ae({type:V.KEY_SYSTEM_ERROR,details:R.KEY_SYSTEM_NO_CONFIGURED_LICENSE,fatal:!0},`Missing key-system license configuration options ${ne({drmSystems:this.config.drmSystems})}`);return this.attemptKeySystemAccess(e)}attemptSetMediaKeys(e,t){if(this.mediaResolved=void 0,this.mediaKeys===t)return Promise.resolve();const s=this.setMediaKeysQueue.slice();this.log(`Setting media-keys for "${e}"`);const i=Promise.all(s).then(()=>this.media?this.media.setMediaKeys(t):new Promise((r,n)=>{this.mediaResolved=()=>{if(this.mediaResolved=void 0,!this.media)return n(new Error("Attempted to set mediaKeys without media element attached"));this.mediaKeys=t,this.media.setMediaKeys(t).then(r).catch(n)}}));return this.mediaKeys=t,this.setMediaKeysQueue.push(i),i.then(()=>{this.log(`Media-keys set for "${e}"`),s.push(i),this.setMediaKeysQueue=this.setMediaKeysQueue.filter(r=>s.indexOf(r)===-1)})}generateRequestWithPreferredKeySession(e,t,s,i){var r;const n=(r=this.config.drmSystems)==null||(r=r[e.keySystem])==null?void 0:r.generateRequest;if(n)try{const g=n.call(this.hls,t,s,e);if(!g)throw new Error("Invalid response from configured generateRequest filter");t=g.initDataType,s=g.initData?g.initData:null,e.decryptdata.pssh=s?new Uint8Array(s):null}catch(g){if(this.warn(g.message),this.hls&&this.hls.config.debug)throw g}if(s===null)return this.log(`Skipping key-session request for "${i}" (no initData)`),Promise.resolve(e);const o=es(e.decryptdata),c=e.decryptdata.uri;this.log(`Generating key-session request for "${i}" keyId: ${o} URI: ${c} (init data type: ${t} length: ${s.byteLength})`);const l=new Fi,h=e._onmessage=g=>{const y=e.mediaKeysSession;if(!y){l.emit("error",new Error("invalid state"));return}const{messageType:p,message:E}=g;this.log(`"${p}" message event for session "${y.sessionId}" message size: ${E.byteLength}`),p==="license-request"||p==="license-renewal"?this.renewLicense(e,E).catch(T=>{l.eventNames().length?l.emit("error",T):this.handleError(T)}):p==="license-release"?e.keySystem===oe.FAIRPLAY&&this.updateKeySession(e,hi("acknowledged")).then(()=>this.removeSession(e)).catch(T=>this.handleError(T)):this.warn(`unhandled media key message type "${p}"`)},d=(g,y)=>{y.keyStatus=g;let p;g.startsWith("usable")?l.emit("resolved"):g==="internal-error"||g==="output-restricted"||g==="output-downscaled"?p=en(g,y.decryptdata):g==="expired"?p=new Error(`key expired (keyId: ${o})`):g==="released"?p=new Error("key released"):g==="status-pending"||this.warn(`unhandled key status change "${g}" (keyId: ${o})`),p&&(l.eventNames().length?l.emit("error",p):this.handleError(p))},u=e._onkeystatuseschange=g=>{if(!e.mediaKeysSession){l.emit("error",new Error("invalid state"));return}const p=this.getKeyStatuses(e);if(!Object.keys(p).some(v=>p[v]!=="status-pending"))return;if(p[o]==="expired"){this.log(`Expired key ${ne(p)} in key-session "${e.mediaKeysSession.sessionId}"`),this.renewKeySession(e);return}let T=p[o];if(T)d(T,e);else{var S;e.keyStatusTimeouts||(e.keyStatusTimeouts={}),(S=e.keyStatusTimeouts)[o]||(S[o]=self.setTimeout(()=>{if(!e.mediaKeysSession||!this.mediaKeys)return;const A=this.getKeyStatus(e.decryptdata);if(A&&A!=="status-pending")return this.log(`No status for keyId ${o} in key-session "${e.mediaKeysSession.sessionId}". Using session key-status ${A} from other session.`),d(A,e);this.log(`key status for ${o} in key-session "${e.mediaKeysSession.sessionId}" timed out after 1000ms`),T="internal-error",d(T,e)},1e3)),this.log(`No status for keyId ${o} (${ne(p)}).`)}};Te(e.mediaKeysSession,"message",h),Te(e.mediaKeysSession,"keystatuseschange",u);const f=new Promise((g,y)=>{l.on("error",y),l.on("resolved",g)});return e.mediaKeysSession.generateRequest(t,s).then(()=>{this.log(`Request generated for key-session "${e.mediaKeysSession.sessionId}" keyId: ${o} URI: ${c}`)}).catch(g=>{throw new Ae({type:V.KEY_SYSTEM_ERROR,details:R.KEY_SYSTEM_NO_SESSION,error:g,decryptdata:e.decryptdata,fatal:!1},`Error generating key-session request: ${g}`)}).then(()=>f).catch(g=>(l.removeAllListeners(),this.removeSession(e).then(()=>{throw g}))).then(()=>(l.removeAllListeners(),e))}getKeyStatuses(e){const t={};return e.mediaKeysSession.keyStatuses.forEach((s,i)=>{if(typeof i=="string"&&typeof s=="object"){const o=i;i=s,s=o}const r="buffer"in i?new Uint8Array(i.buffer,i.byteOffset,i.byteLength):new Uint8Array(i);if(e.keySystem===oe.PLAYREADY&&r.length===16){const o=me(r);t[o]=s,Hn(r)}const n=me(r);s==="internal-error"&&(this.bannedKeyIds[n]=s),this.log(`key status change "${s}" for keyStatuses keyId: ${n} key-session "${e.mediaKeysSession.sessionId}"`),t[n]=s}),t}fetchServerCertificate(e){const t=this.config,s=t.loader,i=new s(t),r=this.getServerCertificateUrl(e);return r?(this.log(`Fetching server certificate for "${e}"`),new Promise((n,o)=>{const c={responseType:"arraybuffer",url:r},l=t.certLoadPolicy.default,h={loadPolicy:l,timeout:l.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},d={onSuccess:(u,f,g,y)=>{n(u.data)},onError:(u,f,g,y)=>{o(new Ae({type:V.KEY_SYSTEM_ERROR,details:R.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:g,response:te({url:c.url,data:void 0},u)},`"${e}" certificate request failed (${r}). Status: ${u.code} (${u.text})`))},onTimeout:(u,f,g)=>{o(new Ae({type:V.KEY_SYSTEM_ERROR,details:R.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:g,response:{url:c.url,data:void 0}},`"${e}" certificate request timed out (${r})`))},onAbort:(u,f,g)=>{o(new Error("aborted"))}};i.load(c,h,d)})):Promise.resolve()}setMediaKeysServerCertificate(e,t,s){return new Promise((i,r)=>{e.setServerCertificate(s).then(n=>{this.log(`setServerCertificate ${n?"success":"not supported by CDM"} (${s.byteLength}) on "${t}"`),i(e)}).catch(n=>{r(new Ae({type:V.KEY_SYSTEM_ERROR,details:R.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED,error:n,fatal:!0},n.message))})})}renewLicense(e,t){return this.requestLicense(e,new Uint8Array(t)).then(s=>this.updateKeySession(e,new Uint8Array(s)).catch(i=>{throw new Ae({type:V.KEY_SYSTEM_ERROR,details:R.KEY_SYSTEM_SESSION_UPDATE_FAILED,decryptdata:e.decryptdata,error:i,fatal:!1},i.message)}))}unpackPlayReadyKeyMessage(e,t){const s=String.fromCharCode.apply(null,new Uint16Array(t.buffer));if(!s.includes("PlayReadyKeyMessage"))return e.setRequestHeader("Content-Type","text/xml; charset=utf-8"),t;const i=new DOMParser().parseFromString(s,"application/xml"),r=i.querySelectorAll("HttpHeader");if(r.length>0){let h;for(let d=0,u=r.length;d<u;d++){var n,o;h=r[d];const f=(n=h.querySelector("name"))==null?void 0:n.textContent,g=(o=h.querySelector("value"))==null?void 0:o.textContent;f&&g&&e.setRequestHeader(f,g)}}const c=i.querySelector("Challenge"),l=c==null?void 0:c.textContent;if(!l)throw new Error("Cannot find <Challenge> in key message");return hi(atob(l))}setupLicenseXHR(e,t,s,i){const r=this.config.licenseXhrSetup;return r?Promise.resolve().then(()=>{if(!s.decryptdata)throw new Error("Key removed");return r.call(this.hls,e,t,s,i)}).catch(n=>{if(!s.decryptdata)throw n;return e.open("POST",t,!0),r.call(this.hls,e,t,s,i)}).then(n=>(e.readyState||e.open("POST",t,!0),{xhr:e,licenseChallenge:n||i})):(e.open("POST",t,!0),Promise.resolve({xhr:e,licenseChallenge:i}))}requestLicense(e,t){const s=this.config.keyLoadPolicy.default;return new Promise((i,r)=>{const n=this.getLicenseServerUrlOrThrow(e.keySystem);this.log(`Sending license request to URL: ${n}`);const o=new XMLHttpRequest;o.responseType="arraybuffer",o.onreadystatechange=()=>{if(!this.hls||!e.mediaKeysSession)return r(new Error("invalid state"));if(o.readyState===4)if(o.status===200){this._requestLicenseFailureCount=0;let c=o.response;this.log(`License received ${c instanceof ArrayBuffer?c.byteLength:c}`);const l=this.config.licenseResponseCallback;if(l)try{c=l.call(this.hls,o,n,e)}catch(h){this.error(h)}i(c)}else{const c=s.errorRetry,l=c?c.maxNumRetry:0;if(this._requestLicenseFailureCount++,this._requestLicenseFailureCount>l||o.status>=400&&o.status<500)r(new Ae({type:V.KEY_SYSTEM_ERROR,details:R.KEY_SYSTEM_LICENSE_REQUEST_FAILED,decryptdata:e.decryptdata,fatal:!0,networkDetails:o,response:{url:n,data:void 0,code:o.status,text:o.statusText}},`License Request XHR failed (${n}). Status: ${o.status} (${o.statusText})`));else{const h=l-this._requestLicenseFailureCount+1;this.warn(`Retrying license request, ${h} attempts left`),this.requestLicense(e,t).then(i,r)}}},e.licenseXhr&&e.licenseXhr.readyState!==XMLHttpRequest.DONE&&e.licenseXhr.abort(),e.licenseXhr=o,this.setupLicenseXHR(o,n,e,t).then(({xhr:c,licenseChallenge:l})=>{e.keySystem==oe.PLAYREADY&&(l=this.unpackPlayReadyKeyMessage(c,l)),c.send(l)}).catch(r)})}onDestroying(){this.unregisterListeners(),this._clear()}onMediaAttached(e,t){if(!this.config.emeEnabled)return;const s=t.media;this.media=s,Te(s,"encrypted",this.onMediaEncrypted),Te(s,"waitingforkey",this.onWaitingForKey);const i=this.mediaResolved;i?i():this.mediaKeys=s.mediaKeys}onMediaDetached(){const e=this.media;e&&(ve(e,"encrypted",this.onMediaEncrypted),ve(e,"waitingforkey",this.onWaitingForKey),this.media=null,this.mediaKeys=null)}_clear(){var e;this._requestLicenseFailureCount=0,this.keyIdToKeySessionPromise={},this.bannedKeyIds={};const t=this.mediaResolved;if(t&&t(),!this.mediaKeys&&!this.mediaKeySessions.length)return;const s=this.media,i=this.mediaKeySessions.slice();this.mediaKeySessions=[],this.mediaKeys=null,it.clearKeyUriToKeyIdMap();const r=i.length;Rt.CDMCleanupPromise=Promise.all(i.map(n=>this.removeSession(n)).concat((s==null||(e=s.setMediaKeys(null))==null?void 0:e.catch(n=>{this.log(`Could not clear media keys: ${n}`),this.hls&&this.hls.trigger(m.ERROR,{type:V.OTHER_ERROR,details:R.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR,fatal:!1,error:new Error(`Could not clear media keys: ${n}`)})}))||Promise.resolve())).catch(n=>{this.log(`Could not close sessions and clear media keys: ${n}`),this.hls&&this.hls.trigger(m.ERROR,{type:V.OTHER_ERROR,details:R.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error(`Could not close sessions and clear media keys: ${n}`)})}).then(()=>{r&&this.log("finished closing key sessions and clearing media keys")})}onManifestLoading(){this._clear()}onManifestLoaded(e,{sessionKeys:t}){if(!(!t||!this.config.emeEnabled)&&!this.keyFormatPromise){const s=t.reduce((i,r)=>(i.indexOf(r.keyFormat)===-1&&i.push(r.keyFormat),i),[]);this.log(`Selecting key-system from session-keys ${s.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(s)}}removeSession(e){const{mediaKeysSession:t,licenseXhr:s,decryptdata:i}=e;if(t){this.log(`Remove licenses and keys and close session "${t.sessionId}" keyId: ${me((i==null?void 0:i.keyId)||[])}`),e._onmessage&&(t.removeEventListener("message",e._onmessage),e._onmessage=void 0),e._onkeystatuseschange&&(t.removeEventListener("keystatuseschange",e._onkeystatuseschange),e._onkeystatuseschange=void 0),s&&s.readyState!==XMLHttpRequest.DONE&&s.abort(),e.mediaKeysSession=e.decryptdata=e.licenseXhr=void 0;const r=this.mediaKeySessions.indexOf(e);r>-1&&this.mediaKeySessions.splice(r,1);const{keyStatusTimeouts:n}=e;n&&Object.keys(n).forEach(l=>self.clearTimeout(n[l]));const{drmSystemOptions:o}=this.config;return(Al(o)?new Promise((l,h)=>{self.setTimeout(()=>h(new Error("MediaKeySession.remove() timeout")),8e3),t.remove().then(l).catch(h)}):Promise.resolve()).catch(l=>{this.log(`Could not remove session: ${l}`),this.hls&&this.hls.trigger(m.ERROR,{type:V.OTHER_ERROR,details:R.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR,fatal:!1,error:new Error(`Could not remove session: ${l}`)})}).then(()=>t.close()).catch(l=>{this.log(`Could not close session: ${l}`),this.hls&&this.hls.trigger(m.ERROR,{type:V.OTHER_ERROR,details:R.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error(`Could not close session: ${l}`)})})}return Promise.resolve()}}Rt.CDMCleanupPromise=void 0;function es(a){if(!a)throw new Error("Could not read keyId of undefined decryptdata");if(a.keyId===null)throw new Error("keyId is null");return me(a.keyId)}function Kh(a,e){if(a.keyId&&e.mediaKeysSession.keyStatuses.has(a.keyId))return e.mediaKeysSession.keyStatuses.get(a.keyId);if(a.matches(e.decryptdata))return e.keyStatus}class Ae extends Error{constructor(e,t){super(t),this.data=void 0,e.error||(e.error=new Error(t)),this.data=e,e.err=e.error}}function en(a,e){const t=a==="output-restricted",s=t?R.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:R.KEY_SYSTEM_STATUS_INTERNAL_ERROR;return new Ae({type:V.KEY_SYSTEM_ERROR,details:s,fatal:!1,decryptdata:e},t?"HDCP level output restricted":`key status changed to "${a}"`)}class Vh{constructor(e){this.hls=void 0,this.isVideoPlaybackQualityAvailable=!1,this.timer=void 0,this.media=null,this.lastTime=void 0,this.lastDroppedFrames=0,this.lastDecodedFrames=0,this.streamController=void 0,this.hls=e,this.registerListeners()}setStreamController(e){this.streamController=e}registerListeners(){this.hls.on(m.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.on(m.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListeners(){this.hls.off(m.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.off(m.MEDIA_DETACHING,this.onMediaDetaching,this)}destroy(){this.timer&&clearInterval(this.timer),this.unregisterListeners(),this.isVideoPlaybackQualityAvailable=!1,this.media=null}onMediaAttaching(e,t){const s=this.hls.config;if(s.capLevelOnFPSDrop){const i=t.media instanceof self.HTMLVideoElement?t.media:null;this.media=i,i&&typeof i.getVideoPlaybackQuality=="function"&&(this.isVideoPlaybackQualityAvailable=!0),self.clearInterval(this.timer),this.timer=self.setInterval(this.checkFPSInterval.bind(this),s.fpsDroppedMonitoringPeriod)}}onMediaDetaching(){this.media=null}checkFPS(e,t,s){const i=performance.now();if(t){if(this.lastTime){const r=i-this.lastTime,n=s-this.lastDroppedFrames,o=t-this.lastDecodedFrames,c=1e3*n/r,l=this.hls;if(l.trigger(m.FPS_DROP,{currentDropped:n,currentDecoded:o,totalDroppedFrames:s}),c>0&&n>l.config.fpsDroppedMonitoringThreshold*o){let h=l.currentLevel;l.logger.warn("drop FPS ratio greater than max allowed value for currentLevel: "+h),h>0&&(l.autoLevelCapping===-1||l.autoLevelCapping>=h)&&(h=h-1,l.trigger(m.FPS_DROP_LEVEL_CAPPING,{level:h,droppedLevel:l.currentLevel}),l.autoLevelCapping=h,this.streamController.nextLevelSwitch())}}this.lastTime=i,this.lastDroppedFrames=s,this.lastDecodedFrames=t}}checkFPSInterval(){const e=this.media;if(e)if(this.isVideoPlaybackQualityAvailable){const t=e.getVideoPlaybackQuality();this.checkFPS(e,t.totalVideoFrames,t.droppedVideoFrames)}else this.checkFPS(e,e.webkitDecodedFrameCount,e.webkitDroppedFrameCount)}}function Ma(a,e){let t;try{t=new Event("addtrack")}catch{t=document.createEvent("Event"),t.initEvent("addtrack",!1,!1)}t.track=a,e.dispatchEvent(t)}function Na(a,e){const t=a.mode;if(t==="disabled"&&(a.mode="hidden"),a.cues&&!a.cues.getCueById(e.id))try{if(a.addCue(e),!a.cues.getCueById(e.id))throw new Error(`addCue is failed for: ${e}`)}catch(s){se.debug(`[texttrack-utils]: ${s}`);try{const i=new self.TextTrackCue(e.startTime,e.endTime,e.text);i.id=e.id,a.addCue(i)}catch(i){se.debug(`[texttrack-utils]: Legacy TextTrackCue fallback failed: ${i}`)}}t==="disabled"&&(a.mode=t)}function At(a,e){const t=a.mode;if(t==="disabled"&&(a.mode="hidden"),a.cues)for(let s=a.cues.length;s--;)e&&a.cues[s].removeEventListener("enter",e),a.removeCue(a.cues[s]);t==="disabled"&&(a.mode=t)}function Ti(a,e,t,s){const i=a.mode;if(i==="disabled"&&(a.mode="hidden"),a.cues&&a.cues.length>0){const r=Yh(a.cues,e,t);for(let n=0;n<r.length;n++)(!s||s(r[n]))&&a.removeCue(r[n])}i==="disabled"&&(a.mode=i)}function Hh(a,e){if(e<=a[0].startTime)return 0;const t=a.length-1;if(e>a[t].endTime)return-1;let s=0,i=t,r;for(;s<=i;)if(r=Math.floor((i+s)/2),e<a[r].startTime)i=r-1;else if(e>a[r].startTime&&s<t)s=r+1;else return r;return a[s].startTime-e<e-a[i].startTime?s:i}function Yh(a,e,t){const s=[],i=Hh(a,e);if(i>-1)for(let r=i,n=a.length;r<n;r++){const o=a[r];if(o.startTime>=e&&o.endTime<=t)s.push(o);else if(o.startTime>t)return s}return s}function ms(a){const e=[];for(let t=0;t<a.length;t++){const s=a[t];(s.kind==="subtitles"||s.kind==="captions")&&s.label&&e.push(a[t])}return e}class Wh extends Ki{constructor(e){super(e,"subtitle-track-controller"),this.media=null,this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0,this.queuedDefaultTrack=-1,this.useTextTrackPolling=!1,this.subtitlePollingInterval=-1,this._subtitleDisplay=!0,this.asyncPollTrackChange=()=>this.pollTrackChange(0),this.onTextTracksChanged=()=>{if(this.useTextTrackPolling||self.clearInterval(this.subtitlePollingInterval),!this.media||!this.hls.config.renderTextTracksNatively)return;let t=null;const s=ms(this.media.textTracks);for(let r=0;r<s.length;r++)if(s[r].mode==="hidden")t=s[r];else if(s[r].mode==="showing"){t=s[r];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(e){this._subtitleDisplay=e,this.trackId>-1&&this.toggleTrackModes()}registerListeners(){const{hls:e}=this;e.on(m.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(m.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(m.MANIFEST_LOADING,this.onManifestLoading,this),e.on(m.MANIFEST_PARSED,this.onManifestParsed,this),e.on(m.LEVEL_LOADING,this.onLevelLoading,this),e.on(m.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(m.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(m.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(m.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(m.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(m.MANIFEST_LOADING,this.onManifestLoading,this),e.off(m.MANIFEST_PARSED,this.onManifestParsed,this),e.off(m.LEVEL_LOADING,this.onLevelLoading,this),e.off(m.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(m.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(m.ERROR,this.onError,this)}onMediaAttached(e,t){this.media=t.media,this.media&&(this.queuedDefaultTrack>-1&&(this.subtitleTrack=this.queuedDefaultTrack,this.queuedDefaultTrack=-1),this.useTextTrackPolling=!(this.media.textTracks&&"onchange"in this.media.textTracks),this.useTextTrackPolling?this.pollTrackChange(500):this.media.textTracks.addEventListener("change",this.asyncPollTrackChange))}pollTrackChange(e){self.clearInterval(this.subtitlePollingInterval),this.subtitlePollingInterval=self.setInterval(this.onTextTracksChanged,e)}onMediaDetaching(e,t){const s=this.media;if(!s)return;const i=!!t.transferMedia;if(self.clearInterval(this.subtitlePollingInterval),this.useTextTrackPolling||s.textTracks.removeEventListener("change",this.asyncPollTrackChange),this.trackId>-1&&(this.queuedDefaultTrack=this.trackId),this.subtitleTrack=-1,this.media=null,i)return;ms(s.textTracks).forEach(n=>{At(n)})}onManifestLoading(){this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0}onManifestParsed(e,t){this.tracks=t.subtitleTracks}onSubtitleTrackLoaded(e,t){const{id:s,groupId:i,details:r}=t,n=this.tracksInGroup[s];if(!n||n.groupId!==i){this.warn(`Subtitle track with id:${s} and group:${i} not found in active group ${n==null?void 0:n.groupId}`);return}const o=n.details;n.details=t.details,this.log(`Subtitle track ${s} "${n.name}" lang:${n.lang} group:${i} loaded [${r.startSN}-${r.endSN}]`),s===this.trackId&&this.playlistLoaded(s,t,o)}onLevelLoading(e,t){this.switchLevel(t.level)}onLevelSwitching(e,t){this.switchLevel(t.level)}switchLevel(e){const t=this.hls.levels[e];if(!t)return;const s=t.subtitleGroups||null,i=this.groupIds;let r=this.currentTrack;if(!s||(i==null?void 0:i.length)!==(s==null?void 0:s.length)||s!=null&&s.some(n=>(i==null?void 0:i.indexOf(n))===-1)){this.groupIds=s,this.trackId=-1,this.currentTrack=null;const n=this.tracks.filter(h=>!s||s.indexOf(h.groupId)!==-1);if(n.length)this.selectDefaultTrack&&!n.some(h=>h.default)&&(this.selectDefaultTrack=!1),n.forEach((h,d)=>{h.id=d});else if(!r&&!this.tracksInGroup.length)return;this.tracksInGroup=n;const o=this.hls.config.subtitlePreference;if(!r&&o){this.selectDefaultTrack=!1;const h=Ve(o,n);if(h>-1)r=n[h];else{const d=Ve(o,this.tracks);r=this.tracks[d]}}let c=this.findTrackId(r);c===-1&&r&&(c=this.findTrackId(null));const l={subtitleTracks:n};this.log(`Updating subtitle tracks, ${n.length} track(s) found in "${s==null?void 0:s.join(",")}" group-id`),this.hls.trigger(m.SUBTITLE_TRACKS_UPDATED,l),c!==-1&&this.trackId===-1&&this.setSubtitleTrack(c)}}findTrackId(e){const t=this.tracksInGroup,s=this.selectDefaultTrack;for(let i=0;i<t.length;i++){const r=t[i];if(!(s&&!r.default||!s&&!e)&&(!e||ft(r,e)))return i}if(e){for(let i=0;i<t.length;i++){const r=t[i];if(Ht(e.attrs,r.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return i}for(let i=0;i<t.length;i++){const r=t[i];if(Ht(e.attrs,r.attrs,["LANGUAGE"]))return i}}return-1}findTrackForTextTrack(e){if(e){const t=this.tracksInGroup;for(let s=0;s<t.length;s++){const i=t[s];if(mi(i,e))return s}}return-1}onError(e,t){t.fatal||!t.context||t.context.type===Q.SUBTITLE_TRACK&&t.context.id===this.trackId&&(!this.groupIds||this.groupIds.indexOf(t.context.groupId)!==-1)&&this.checkRetry(t)}get allSubtitleTracks(){return this.tracks}get subtitleTracks(){return this.tracksInGroup}get subtitleTrack(){return this.trackId}set subtitleTrack(e){this.selectDefaultTrack=!1,this.setSubtitleTrack(e)}setSubtitleOption(e){if(this.hls.config.subtitlePreference=e,e){if(e.id===-1)return this.setSubtitleTrack(-1),null;const t=this.allSubtitleTracks;if(this.selectDefaultTrack=!1,t.length){const s=this.currentTrack;if(s&&ft(e,s))return s;const i=Ve(e,this.tracksInGroup);if(i>-1){const r=this.tracksInGroup[i];return this.setSubtitleTrack(i),r}else{if(s)return null;{const r=Ve(e,t);if(r>-1)return t[r]}}}}return null}loadPlaylist(e){super.loadPlaylist(),this.shouldLoadPlaylist(this.currentTrack)&&this.scheduleLoading(this.currentTrack,e)}loadingPlaylist(e,t){super.loadingPlaylist(e,t);const s=e.id,i=e.groupId,r=this.getUrlWithDirectives(e.url,t),n=e.details,o=n==null?void 0:n.age;this.log(`Loading subtitle ${s} "${e.name}" lang:${e.lang} group:${i}${(t==null?void 0:t.msn)!==void 0?" at sn "+t.msn+" part "+t.part:""}${o&&n.live?" age "+o.toFixed(1)+(n.type&&" "+n.type||""):""} ${r}`),this.hls.trigger(m.SUBTITLE_TRACK_LOADING,{url:r,id:s,groupId:i,deliveryDirectives:t||null,track:e})}toggleTrackModes(){const{media:e}=this;if(!e)return;const t=ms(e.textTracks),s=this.currentTrack;let i;if(s&&(i=t.filter(r=>mi(s,r))[0],i||this.warn(`Unable to find subtitle TextTrack with name "${s.name}" and language "${s.lang}"`)),[].slice.call(t).forEach(r=>{r.mode!=="disabled"&&r!==i&&(r.mode="disabled")}),i){const r=this.subtitleDisplay?"showing":"hidden";i.mode!==r&&(i.mode=r)}}setSubtitleTrack(e){const t=this.tracksInGroup;if(!this.media){this.queuedDefaultTrack=e;return}if(e<-1||e>=t.length||!M(e)){this.warn(`Invalid subtitle track id: ${e}`);return}this.selectDefaultTrack=!1;const s=this.currentTrack,i=t[e]||null;if(this.trackId=e,this.currentTrack=i,this.toggleTrackModes(),!i){this.hls.trigger(m.SUBTITLE_TRACK_SWITCH,{id:e});return}const r=!!i.details&&!i.details.live;if(e===this.trackId&&i===s&&r)return;this.log(`Switching to subtitle-track ${e}`+(i?` "${i.name}" lang:${i.lang} group:${i.groupId}`:""));const{id:n,groupId:o="",name:c,type:l,url:h}=i;this.hls.trigger(m.SUBTITLE_TRACK_SWITCH,{id:n,groupId:o,name:c,type:l,url:h});const d=this.switchParams(i.url,s==null?void 0:s.details,i.details);this.loadPlaylist(d)}}function qh(){try{return crypto.randomUUID()}catch{try{const e=URL.createObjectURL(new Blob),t=e.toString();return URL.revokeObjectURL(e),t.slice(t.lastIndexOf("/")+1)}catch{let t=new Date().getTime();return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,i=>{const r=(t+Math.random()*16)%16|0;return t=Math.floor(t/16),(i=="x"?r:r&3|8).toString(16)})}}}function Mt(a){let e=5381,t=a.length;for(;t;)e=e*33^a.charCodeAt(--t);return(e>>>0).toString()}const bt=.025;let _s=function(a){return a[a.Point=0]="Point",a[a.Range=1]="Range",a}({});function jh(a,e,t){return`${a.identifier}-${t+1}-${Mt(e)}`}class Xh{constructor(e,t){this.base=void 0,this._duration=null,this._timelineStart=null,this.appendInPlaceDisabled=void 0,this.appendInPlaceStarted=void 0,this.dateRange=void 0,this.hasPlayed=!1,this.cumulativeDuration=0,this.resumeOffset=NaN,this.playoutLimit=NaN,this.restrictions={skip:!1,jump:!1},this.snapOptions={out:!1,in:!1},this.assetList=[],this.assetListLoader=void 0,this.assetListResponse=null,this.resumeAnchor=void 0,this.error=void 0,this.resetOnResume=void 0,this.base=t,this.dateRange=e,this.setDateRange(e)}setDateRange(e){this.dateRange=e,this.resumeOffset=e.attr.optionalFloat("X-RESUME-OFFSET",this.resumeOffset),this.playoutLimit=e.attr.optionalFloat("X-PLAYOUT-LIMIT",this.playoutLimit),this.restrictions=e.attr.enumeratedStringList("X-RESTRICT",this.restrictions),this.snapOptions=e.attr.enumeratedStringList("X-SNAP",this.snapOptions)}reset(){var e;this.appendInPlaceStarted=!1,(e=this.assetListLoader)==null||e.destroy(),this.assetListLoader=void 0,this.supplementsPrimary||(this.assetListResponse=null,this.assetList=[],this._duration=null)}isAssetPastPlayoutLimit(e){var t;if(e>0&&e>=this.assetList.length)return!0;const s=this.playoutLimit;return e<=0||isNaN(s)?!1:s===0?!0:(((t=this.assetList[e])==null?void 0:t.startOffset)||0)>s}findAssetIndex(e){return this.assetList.indexOf(e)}get identifier(){return this.dateRange.id}get startDate(){return this.dateRange.startDate}get startTime(){const e=this.dateRange.startTime;if(this.snapOptions.out){const t=this.dateRange.tagAnchor;if(t)return qs(e,t)}return e}get startOffset(){return this.cue.pre?0:this.startTime}get startIsAligned(){if(this.startTime===0||this.snapOptions.out)return!0;const e=this.dateRange.tagAnchor;if(e){const t=this.dateRange.startTime,s=qs(t,e);return t-s<.1}return!1}get resumptionOffset(){const e=this.resumeOffset,t=M(e)?e:this.duration;return this.cumulativeDuration+t}get resumeTime(){const e=this.startOffset+this.resumptionOffset;if(this.snapOptions.in){const t=this.resumeAnchor;if(t)return qs(e,t)}return e}get appendInPlace(){return this.appendInPlaceStarted?!0:this.appendInPlaceDisabled?!1:!!(!this.cue.once&&!this.cue.pre&&this.startIsAligned&&(isNaN(this.playoutLimit)&&isNaN(this.resumeOffset)||this.resumeOffset&&this.duration&&Math.abs(this.resumeOffset-this.duration)<bt))}set appendInPlace(e){if(this.appendInPlaceStarted){this.resetOnResume=!e;return}this.appendInPlaceDisabled=!e}get timelineStart(){return this._timelineStart!==null?this._timelineStart:this.startTime}set timelineStart(e){this._timelineStart=e}get duration(){const e=this.playoutLimit;let t;return this._duration!==null?t=this._duration:this.dateRange.duration?t=this.dateRange.duration:t=this.dateRange.plannedDuration||0,!isNaN(e)&&e<t&&(t=e),t}set duration(e){this._duration=e}get cue(){return this.dateRange.cue}get timelineOccupancy(){return this.dateRange.attr["X-TIMELINE-OCCUPIES"]==="RANGE"?_s.Range:_s.Point}get supplementsPrimary(){return this.dateRange.attr["X-TIMELINE-STYLE"]==="PRIMARY"}get contentMayVary(){return this.dateRange.attr["X-CONTENT-MAY-VARY"]!=="NO"}get assetUrl(){return this.dateRange.attr["X-ASSET-URI"]}get assetListUrl(){return this.dateRange.attr["X-ASSET-LIST"]}get baseUrl(){return this.base.url}get assetListLoaded(){return this.assetList.length>0||this.assetListResponse!==null}toString(){return zh(this)}}function qs(a,e){return a-e.start<e.duration/2&&!(Math.abs(a-(e.start+e.duration))<bt)?e.start:e.start+e.duration}function Ba(a,e,t){const s=new self.URL(a,t);return s.protocol!=="data:"&&s.searchParams.set("_HLS_primary_id",e),s}function js(a,e){for(;(t=a.assetList[++e])!=null&&t.error;)var t;return e}function zh(a){return`["${a.identifier}" ${a.cue.pre?"<pre>":a.cue.post?"<post>":""}${a.timelineStart.toFixed(2)}-${a.resumeTime.toFixed(2)}]`}function xt(a){const e=a.timelineStart,t=a.duration||0;return`["${a.identifier}" ${e.toFixed(2)}-${(e+t).toFixed(2)}]`}class Qh{constructor(e,t,s,i){this.hls=void 0,this.interstitial=void 0,this.assetItem=void 0,this.tracks=null,this.hasDetails=!1,this.mediaAttached=null,this._currentTime=void 0,this._bufferedEosTime=void 0,this.checkPlayout=()=>{this.reachedPlayout(this.currentTime)&&this.hls&&this.hls.trigger(m.PLAYOUT_LIMIT_REACHED,{})};const r=this.hls=new e(t);this.interstitial=s,this.assetItem=i;const n=()=>{this.hasDetails=!0};r.once(m.LEVEL_LOADED,n),r.once(m.AUDIO_TRACK_LOADED,n),r.once(m.SUBTITLE_TRACK_LOADED,n),r.on(m.MEDIA_ATTACHING,(o,{media:c})=>{this.removeMediaListeners(),this.mediaAttached=c,this.interstitial.playoutLimit&&(c.addEventListener("timeupdate",this.checkPlayout),this.appendInPlace&&r.on(m.BUFFER_APPENDED,()=>{const h=this.bufferedEnd;this.reachedPlayout(h)&&(this._bufferedEosTime=h,r.trigger(m.BUFFERED_TO_END,void 0))}))})}get appendInPlace(){return this.interstitial.appendInPlace}loadSource(){const e=this.hls;if(e)if(e.url)e.levels.length&&!e.started&&e.startLoad(-1,!0);else{let t=this.assetItem.uri;try{t=Ba(t,e.config.primarySessionId||"").href}catch{}e.loadSource(t)}}bufferedInPlaceToEnd(e){var t;if(!this.appendInPlace)return!1;if((t=this.hls)!=null&&t.bufferedToEnd)return!0;if(!e)return!1;const s=Math.min(this._bufferedEosTime||1/0,this.duration),i=this.timelineOffset,r=q.bufferInfo(e,i,0);return this.getAssetTime(r.end)>=s-.02}reachedPlayout(e){const s=this.interstitial.playoutLimit;return this.startOffset+e>=s}get destroyed(){var e;return!((e=this.hls)!=null&&e.userConfig)}get assetId(){return this.assetItem.identifier}get interstitialId(){return this.assetItem.parentIdentifier}get media(){var e;return((e=this.hls)==null?void 0:e.media)||null}get bufferedEnd(){const e=this.media||this.mediaAttached;if(!e)return this._bufferedEosTime?this._bufferedEosTime:this.currentTime;const t=q.bufferInfo(e,e.currentTime,.001);return this.getAssetTime(t.end)}get currentTime(){const e=this.media||this.mediaAttached;return e?this.getAssetTime(e.currentTime):this._currentTime||0}get duration(){const e=this.assetItem.duration;if(!e)return 0;const t=this.interstitial.playoutLimit;if(t){const s=t-this.startOffset;if(s>0&&s<e)return s}return e}get remaining(){const e=this.duration;return e?Math.max(0,e-this.currentTime):0}get startOffset(){return this.assetItem.startOffset}get timelineOffset(){var e;return((e=this.hls)==null?void 0:e.config.timelineOffset)||0}set timelineOffset(e){const t=this.timelineOffset;if(e!==t){const s=e-t;if(Math.abs(s)>1/9e4&&this.hls){if(this.hasDetails)throw new Error("Cannot set timelineOffset after playlists are loaded");this.hls.config.timelineOffset=e}}}getAssetTime(e){const t=this.timelineOffset,s=this.duration;return Math.min(Math.max(0,e-t),s)}removeMediaListeners(){const e=this.mediaAttached;e&&(this._currentTime=e.currentTime,this.bufferSnapShot(),e.removeEventListener("timeupdate",this.checkPlayout))}bufferSnapShot(){if(this.mediaAttached){var e;(e=this.hls)!=null&&e.bufferedToEnd&&(this._bufferedEosTime=this.bufferedEnd)}}destroy(){this.removeMediaListeners(),this.hls&&this.hls.destroy(),this.hls=null,this.tracks=this.mediaAttached=this.checkPlayout=null}attachMedia(e){var t;this.loadSource(),(t=this.hls)==null||t.attachMedia(e)}detachMedia(){var e;this.removeMediaListeners(),this.mediaAttached=null,(e=this.hls)==null||e.detachMedia()}resumeBuffering(){var e;(e=this.hls)==null||e.resumeBuffering()}pauseBuffering(){var e;(e=this.hls)==null||e.pauseBuffering()}transferMedia(){var e;return this.bufferSnapShot(),((e=this.hls)==null?void 0:e.transferMedia())||null}resetDetails(){const e=this.hls;if(e&&this.hasDetails){e.stopLoad();const t=s=>delete s.details;e.levels.forEach(t),e.allAudioTracks.forEach(t),e.allSubtitleTracks.forEach(t),this.hasDetails=!1}}on(e,t,s){var i;(i=this.hls)==null||i.on(e,t)}once(e,t,s){var i;(i=this.hls)==null||i.once(e,t)}off(e,t,s){var i;(i=this.hls)==null||i.off(e,t)}toString(){var e;return`HlsAssetPlayer: ${xt(this.assetItem)} ${(e=this.hls)==null?void 0:e.sessionId} ${this.appendInPlace?"append-in-place":""}`}}const tn=.033;class Zh extends we{constructor(e,t){super("interstitials-sched",t),this.onScheduleUpdate=void 0,this.eventMap={},this.events=null,this.items=null,this.durations={primary:0,playout:0,integrated:0},this.onScheduleUpdate=e}destroy(){this.reset(),this.onScheduleUpdate=null}reset(){this.eventMap={},this.setDurations(0,0,0),this.events&&this.events.forEach(e=>e.reset()),this.events=this.items=null}resetErrorsInRange(e,t){return this.events?this.events.reduce((s,i)=>e<=i.startOffset&&t>i.startOffset?(delete i.error,s+1):s,0):0}get duration(){const e=this.items;return e?e[e.length-1].end:0}get length(){return this.items?this.items.length:0}getEvent(e){return e&&this.eventMap[e]||null}hasEvent(e){return e in this.eventMap}findItemIndex(e,t){if(e.event)return this.findEventIndex(e.event.identifier);let s=-1;e.nextEvent?s=this.findEventIndex(e.nextEvent.identifier)-1:e.previousEvent&&(s=this.findEventIndex(e.previousEvent.identifier)+1);const i=this.items;if(i)for(i[s]||(t===void 0&&(t=e.start),s=this.findItemIndexAtTime(t));s>=0&&(r=i[s])!=null&&r.event;){var r;s--}return s}findItemIndexAtTime(e,t){const s=this.items;if(s)for(let i=0;i<s.length;i++){let r=s[i];if(t&&t!=="primary"&&(r=r[t]),e===r.start||e>r.start&&e<r.end)return i}return-1}findJumpRestrictedIndex(e,t){const s=this.items;if(s)for(let i=e;i<=t&&s[i];i++){const r=s[i].event;if(r!=null&&r.restrictions.jump&&!r.appendInPlace)return i}return-1}findEventIndex(e){const t=this.items;if(t)for(let i=t.length;i--;){var s;if(((s=t[i].event)==null?void 0:s.identifier)===e)return i}return-1}findAssetIndex(e,t){const s=e.assetList,i=s.length;if(i>1)for(let r=0;r<i;r++){const n=s[r];if(!n.error){const o=n.timelineStart;if(t===o||t>o&&(t<o+(n.duration||0)||r===i-1))return r}}return 0}get assetIdAtEnd(){var e;const t=(e=this.items)==null||(e=e[this.length-1])==null?void 0:e.event;if(t){const s=t.assetList,i=s[s.length-1];if(i)return i.identifier}return null}parseInterstitialDateRanges(e,t){const s=e.main.details,{dateRanges:i}=s,r=this.events,n=this.parseDateRanges(i,{url:s.url},t),o=Object.keys(i),c=r?r.filter(l=>!o.includes(l.identifier)):[];n.length&&n.sort((l,h)=>{const d=l.cue.pre,u=l.cue.post,f=h.cue.pre,g=h.cue.post;if(d&&!f)return-1;if(f&&!d||u&&!g)return 1;if(g&&!u)return-1;if(!d&&!f&&!u&&!g){const y=l.startTime,p=h.startTime;if(y!==p)return y-p}return l.dateRange.tagOrder-h.dateRange.tagOrder}),this.events=n,c.forEach(l=>{this.removeEvent(l)}),this.updateSchedule(e,c)}updateSchedule(e,t=[],s=!1){const i=this.events||[];if(i.length||t.length||this.length<2){const r=this.items,n=this.parseSchedule(i,e);(s||t.length||(r==null?void 0:r.length)!==n.length||n.some((c,l)=>Math.abs(c.playout.start-r[l].playout.start)>.005||Math.abs(c.playout.end-r[l].playout.end)>.005))&&(this.items=n,this.onScheduleUpdate(t,r))}}parseDateRanges(e,t,s){const i=[],r=Object.keys(e);for(let n=0;n<r.length;n++){const o=r[n],c=e[o];if(c.isInterstitial){let l=this.eventMap[o];l?l.setDateRange(c):(l=new Xh(c,t),this.eventMap[o]=l,s===!1&&(l.appendInPlace=s)),i.push(l)}}return i}parseSchedule(e,t){const s=[],i=t.main.details,r=i.live?1/0:i.edge;let n=0;if(e=e.filter(c=>!c.error&&!(c.cue.once&&c.hasPlayed)),e.length){this.resolveOffsets(e,t);let c=0,l=0;if(e.forEach((h,d)=>{const u=h.cue.pre,f=h.cue.post,g=e[d-1]||null,y=h.appendInPlace,p=f?r:h.startOffset,E=h.duration,T=h.timelineOccupancy===_s.Range?E:0,S=h.resumptionOffset,v=(g==null?void 0:g.startTime)===p,A=p+h.cumulativeDuration;let D=y?A+E:p+S;if(u||!f&&p<=0){const b=l;l+=T,h.timelineStart=A;const _=n;n+=E,s.push({event:h,start:A,end:D,playout:{start:_,end:n},integrated:{start:b,end:l}})}else if(p<=r){if(!v){const I=p-c;if(I>tn){const P=c,F=l;l+=I;const U=n;n+=I;const H={previousEvent:e[d-1]||null,nextEvent:h,start:P,end:P+I,playout:{start:U,end:n},integrated:{start:F,end:l}};s.push(H)}else I>0&&g&&(g.cumulativeDuration+=I,s[s.length-1].end=p)}f&&(D=A),h.timelineStart=A;const b=l;l+=T;const _=n;n+=E,s.push({event:h,start:A,end:D,playout:{start:_,end:n},integrated:{start:b,end:l}})}else return;const x=h.resumeTime;f||x>r?c=r:c=x}),c<r){var o;const h=c,d=l,u=r-c;l+=u;const f=n;n+=u,s.push({previousEvent:((o=s[s.length-1])==null?void 0:o.event)||null,nextEvent:null,start:c,end:h+u,playout:{start:f,end:n},integrated:{start:d,end:l}})}this.setDurations(r,n,l)}else s.push({previousEvent:null,nextEvent:null,start:0,end:r,playout:{start:0,end:r},integrated:{start:0,end:r}}),this.setDurations(r,r,r);return s}setDurations(e,t,s){this.durations={primary:e,playout:t,integrated:s}}resolveOffsets(e,t){const s=t.main.details,i=s.live?1/0:s.edge;let r=0,n=-1;e.forEach((o,c)=>{const l=o.cue.pre,h=o.cue.post,d=l?0:h?i:o.startTime;this.updateAssetDurations(o),n===d?o.cumulativeDuration=r:(r=0,n=d),!h&&o.snapOptions.in&&(o.resumeAnchor=gt(null,s.fragments,o.startOffset+o.resumptionOffset,0,0)||void 0),o.appendInPlace&&!o.appendInPlaceStarted&&(this.primaryCanResumeInPlaceAt(o,t)||(o.appendInPlace=!1)),!o.appendInPlace&&c+1<e.length&&e[c+1].startTime-e[c].resumeTime<tn&&(e[c+1].appendInPlace=!1,e[c+1].appendInPlace&&this.warn(`Could not change append strategy for abutting event ${o}`));const f=M(o.resumeOffset)?o.resumeOffset:o.duration;r+=f})}primaryCanResumeInPlaceAt(e,t){const s=e.resumeTime,i=e.startTime+e.resumptionOffset;return Math.abs(s-i)>bt?(this.log(`"${e.identifier}" resumption ${s} not aligned with estimated timeline end ${i}`),!1):!Object.keys(t).some(n=>{const o=t[n].details,c=o.edge;if(s>=c)return this.log(`"${e.identifier}" resumption ${s} past ${n} playlist end ${c}`),!1;const l=gt(null,o.fragments,s);if(!l)return this.log(`"${e.identifier}" resumption ${s} does not align with any fragments in ${n} playlist (${o.fragStart}-${o.fragmentEnd})`),!0;const h=n==="audio"?.175:0;return Math.abs(l.start-s)<bt+h||Math.abs(l.end-s)<bt+h?!1:(this.log(`"${e.identifier}" resumption ${s} not aligned with ${n} fragment bounds (${l.start}-${l.end} sn: ${l.sn} cc: ${l.cc})`),!0)})}updateAssetDurations(e){if(!e.assetListLoaded)return;const t=e.timelineStart;let s=0,i=!1,r=!1;for(let n=0;n<e.assetList.length;n++){const o=e.assetList[n],c=t+s;o.startOffset=s,o.timelineStart=c,i||(i=o.duration===null),r||(r=!!o.error);const l=o.error?0:o.duration||0;s+=l}i&&!r?e.duration=Math.max(s,e.duration):e.duration=s}removeEvent(e){e.reset(),delete this.eventMap[e.identifier]}}function Fe(a){return`[${a.event?'"'+a.event.identifier+'"':"primary"}: ${a.start.toFixed(2)}-${a.end.toFixed(2)}]`}class Jh{constructor(e){this.hls=void 0,this.hls=e}destroy(){this.hls=null}loadAssetList(e,t){const s=e.assetListUrl;let i;try{i=Ba(s,this.hls.sessionId,e.baseUrl)}catch(u){const f=this.assignAssetListError(e,R.ASSET_LIST_LOAD_ERROR,u,s);this.hls.trigger(m.ERROR,f);return}t&&i.protocol!=="data:"&&i.searchParams.set("_HLS_start_offset",""+t);const r=this.hls.config,n=r.loader,o=new n(r),c={responseType:"json",url:i.href},l=r.interstitialAssetListLoadPolicy.default,h={loadPolicy:l,timeout:l.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},d={onSuccess:(u,f,g,y)=>{const p=u.data,E=p==null?void 0:p.ASSETS;if(!Array.isArray(E)){const T=this.assignAssetListError(e,R.ASSET_LIST_PARSING_ERROR,new Error("Invalid interstitial asset list"),g.url,f,y);this.hls.trigger(m.ERROR,T);return}e.assetListResponse=p,this.hls.trigger(m.ASSET_LIST_LOADED,{event:e,assetListResponse:p,networkDetails:y})},onError:(u,f,g,y)=>{const p=this.assignAssetListError(e,R.ASSET_LIST_LOAD_ERROR,new Error(`Error loading X-ASSET-LIST: HTTP status ${u.code} ${u.text} (${f.url})`),f.url,y,g);this.hls.trigger(m.ERROR,p)},onTimeout:(u,f,g)=>{const y=this.assignAssetListError(e,R.ASSET_LIST_LOAD_TIMEOUT,new Error(`Timeout loading X-ASSET-LIST (${f.url})`),f.url,u,g);this.hls.trigger(m.ERROR,y)}};return o.load(c,h,d),this.hls.trigger(m.ASSET_LIST_LOADING,{event:e}),o}assignAssetListError(e,t,s,i,r,n){return e.error=s,{type:V.NETWORK_ERROR,details:t,fatal:!1,interstitial:e,url:i,error:s,networkDetails:n,stats:r}}}function sn(a){var e;a==null||(e=a.play())==null||e.catch(()=>{})}function ts(a,e){return`[${a}] Advancing timeline position to ${e}`}class ed extends we{constructor(e,t){super("interstitials",e.logger),this.HlsPlayerClass=void 0,this.hls=void 0,this.assetListLoader=void 0,this.mediaSelection=null,this.altSelection=null,this.media=null,this.detachedData=null,this.requiredTracks=null,this.manager=null,this.playerQueue=[],this.bufferedPos=-1,this.timelinePos=-1,this.schedule=void 0,this.playingItem=null,this.bufferingItem=null,this.waitingItem=null,this.endedItem=null,this.playingAsset=null,this.endedAsset=null,this.bufferingAsset=null,this.shouldPlay=!1,this.onPlay=()=>{this.shouldPlay=!0},this.onPause=()=>{this.shouldPlay=!1},this.onSeeking=()=>{const s=this.currentTime;if(s===void 0||this.playbackDisabled||!this.schedule)return;const i=s-this.timelinePos;if(Math.abs(i)<1/7056e5)return;const n=i<=-.01;this.timelinePos=s,this.bufferedPos=s;const o=this.playingItem;if(!o){this.checkBuffer();return}if(n&&this.schedule.resetErrorsInRange(s,s-i)&&this.updateSchedule(!0),this.checkBuffer(),n&&s<o.start||s>=o.end){var c;const f=this.findItemIndex(o);let g=this.schedule.findItemIndexAtTime(s);if(g===-1&&(g=f+(n?-1:1),this.log(`seeked ${n?"back ":""}to position not covered by schedule ${s} (resolving from ${f} to ${g})`)),!this.isInterstitial(o)&&(c=this.media)!=null&&c.paused&&(this.shouldPlay=!1),!n&&g>f){const y=this.schedule.findJumpRestrictedIndex(f+1,g);if(y>f){this.setSchedulePosition(y);return}}this.setSchedulePosition(g);return}const l=this.playingAsset;if(!l){if(this.playingLastItem&&this.isInterstitial(o)){const f=o.event.assetList[0];f&&(this.endedItem=this.playingItem,this.playingItem=null,this.setScheduleToAssetAtTime(s,f))}return}const h=l.timelineStart,d=l.duration||0;if(n&&s<h||s>=h+d){var u;(u=o.event)!=null&&u.appendInPlace&&(this.clearAssetPlayers(o.event,o),this.flushFrontBuffer(s)),this.setScheduleToAssetAtTime(s,l)}},this.onTimeupdate=()=>{const s=this.currentTime;if(s===void 0||this.playbackDisabled)return;if(s>this.timelinePos)this.timelinePos=s,s>this.bufferedPos&&this.checkBuffer();else return;const i=this.playingItem;if(!i||this.playingLastItem)return;if(s>=i.end){this.timelinePos=i.end;const o=this.findItemIndex(i);this.setSchedulePosition(o+1)}const r=this.playingAsset;if(!r)return;const n=r.timelineStart+(r.duration||0);s>=n&&this.setScheduleToAssetAtTime(s,r)},this.onScheduleUpdate=(s,i)=>{const r=this.schedule;if(!r)return;const n=this.playingItem,o=r.events||[],c=r.items||[],l=r.durations,h=s.map(y=>y.identifier),d=!!(o.length||h.length);(d||i)&&this.log(`INTERSTITIALS_UPDATED (${o.length}): ${o}
252252-Schedule: ${c.map(y=>Fe(y))} pos: ${this.timelinePos}`),h.length&&this.log(`Removed events ${h}`);let u=null,f=null;n&&(u=this.updateItem(n,this.timelinePos),this.itemsMatch(n,u)?this.playingItem=u:this.waitingItem=this.endedItem=null),this.waitingItem=this.updateItem(this.waitingItem),this.endedItem=this.updateItem(this.endedItem);const g=this.bufferingItem;if(g&&(f=this.updateItem(g,this.bufferedPos),this.itemsMatch(g,f)?this.bufferingItem=f:g.event&&(this.bufferingItem=this.playingItem,this.clearInterstitial(g.event,null))),s.forEach(y=>{y.assetList.forEach(p=>{this.clearAssetPlayer(p.identifier,null)})}),this.playerQueue.forEach(y=>{if(y.interstitial.appendInPlace){const p=y.assetItem.timelineStart,E=y.timelineOffset-p;if(E)try{y.timelineOffset=p}catch(T){Math.abs(E)>bt&&this.warn(`${T} ("${y.assetId}" ${y.timelineOffset}->${p})`)}}}),d||i){if(this.hls.trigger(m.INTERSTITIALS_UPDATED,{events:o.slice(0),schedule:c.slice(0),durations:l,removedIds:h}),this.isInterstitial(n)&&h.includes(n.event.identifier)){this.warn(`Interstitial "${n.event.identifier}" removed while playing`),this.primaryFallback(n.event);return}n&&this.trimInPlace(u,n),g&&f!==u&&this.trimInPlace(f,g),this.checkBuffer()}},this.hls=e,this.HlsPlayerClass=t,this.assetListLoader=new Jh(e),this.schedule=new Zh(this.onScheduleUpdate,e.logger),this.registerListeners()}registerListeners(){const e=this.hls;e&&(e.on(m.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(m.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(m.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(m.MANIFEST_LOADING,this.onManifestLoading,this),e.on(m.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(m.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(m.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),e.on(m.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.on(m.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),e.on(m.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),e.on(m.ASSET_LIST_LOADED,this.onAssetListLoaded,this),e.on(m.BUFFER_APPENDED,this.onBufferAppended,this),e.on(m.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(m.BUFFERED_TO_END,this.onBufferedToEnd,this),e.on(m.MEDIA_ENDED,this.onMediaEnded,this),e.on(m.ERROR,this.onError,this),e.on(m.DESTROYING,this.onDestroying,this))}unregisterListeners(){const e=this.hls;e&&(e.off(m.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(m.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(m.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(m.MANIFEST_LOADING,this.onManifestLoading,this),e.off(m.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(m.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(m.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),e.off(m.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.off(m.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),e.off(m.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),e.off(m.ASSET_LIST_LOADED,this.onAssetListLoaded,this),e.off(m.BUFFER_CODECS,this.onBufferCodecs,this),e.off(m.BUFFER_APPENDED,this.onBufferAppended,this),e.off(m.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(m.BUFFERED_TO_END,this.onBufferedToEnd,this),e.off(m.MEDIA_ENDED,this.onMediaEnded,this),e.off(m.ERROR,this.onError,this),e.off(m.DESTROYING,this.onDestroying,this))}startLoad(){this.resumeBuffering()}stopLoad(){this.pauseBuffering()}resumeBuffering(){var e;(e=this.getBufferingPlayer())==null||e.resumeBuffering()}pauseBuffering(){var e;(e=this.getBufferingPlayer())==null||e.pauseBuffering()}destroy(){this.unregisterListeners(),this.stopLoad(),this.assetListLoader&&this.assetListLoader.destroy(),this.emptyPlayerQueue(),this.clearScheduleState(),this.schedule&&this.schedule.destroy(),this.media=this.detachedData=this.mediaSelection=this.requiredTracks=this.altSelection=this.schedule=this.manager=null,this.hls=this.HlsPlayerClass=this.log=null,this.assetListLoader=null,this.onPlay=this.onPause=this.onSeeking=this.onTimeupdate=null,this.onScheduleUpdate=null}onDestroying(){const e=this.primaryMedia||this.media;e&&this.removeMediaListeners(e)}removeMediaListeners(e){ve(e,"play",this.onPlay),ve(e,"pause",this.onPause),ve(e,"seeking",this.onSeeking),ve(e,"timeupdate",this.onTimeupdate)}onMediaAttaching(e,t){const s=this.media=t.media;Te(s,"seeking",this.onSeeking),Te(s,"timeupdate",this.onTimeupdate),Te(s,"play",this.onPlay),Te(s,"pause",this.onPause)}onMediaAttached(e,t){const s=this.effectivePlayingItem,i=this.detachedData;if(this.detachedData=null,s===null)this.checkStart();else if(!i){this.clearScheduleState();const r=this.findItemIndex(s);this.setSchedulePosition(r)}}clearScheduleState(){this.log("clear schedule state"),this.playingItem=this.bufferingItem=this.waitingItem=this.endedItem=this.playingAsset=this.endedAsset=this.bufferingAsset=null}onMediaDetaching(e,t){const s=!!t.transferMedia,i=this.media;if(this.media=null,!s&&(i&&this.removeMediaListeners(i),this.detachedData)){const r=this.getBufferingPlayer();r&&(this.log(`Removing schedule state for detachedData and ${r}`),this.playingAsset=this.endedAsset=this.bufferingAsset=this.bufferingItem=this.waitingItem=this.detachedData=null,r.detachMedia()),this.shouldPlay=!1}}get interstitialsManager(){if(!this.hls)return null;if(this.manager)return this.manager;const e=this,t=()=>e.bufferingItem||e.waitingItem,s=d=>d&&e.getAssetPlayer(d.identifier),i=(d,u,f,g,y)=>{if(d){let p=d[u].start;const E=d.event;if(E){if(u==="playout"||E.timelineOccupancy!==_s.Point){const T=s(f);(T==null?void 0:T.interstitial)===E&&(p+=T.assetItem.startOffset+T[y])}}else{const T=g==="bufferedPos"?n():e[g];p+=T-d.start}return p}return 0},r=(d,u)=>{var f;if(d!==0&&u!=="primary"&&(f=e.schedule)!=null&&f.length){var g;const y=e.schedule.findItemIndexAtTime(d),p=(g=e.schedule.items)==null?void 0:g[y];if(p){const E=p[u].start-p.start;return d+E}}return d},n=()=>{const d=e.bufferedPos;return d===Number.MAX_VALUE?o("primary"):Math.max(d,0)},o=d=>{var u,f;return(u=e.primaryDetails)!=null&&u.live?e.primaryDetails.edge:((f=e.schedule)==null?void 0:f.durations[d])||0},c=(d,u)=>{var f,g;const y=e.effectivePlayingItem;if(y!=null&&(f=y.event)!=null&&f.restrictions.skip||!e.schedule)return;e.log(`seek to ${d} "${u}"`);const p=e.effectivePlayingItem,E=e.schedule.findItemIndexAtTime(d,u),T=(g=e.schedule.items)==null?void 0:g[E],S=e.getBufferingPlayer(),v=S==null?void 0:S.interstitial,A=v==null?void 0:v.appendInPlace,D=p&&e.itemsMatch(p,T);if(p&&(A||D)){const x=s(e.playingAsset),b=(x==null?void 0:x.media)||e.primaryMedia;if(b){const _=u==="primary"?b.currentTime:i(p,u,e.playingAsset,"timelinePos","currentTime"),I=d-_,P=(A?_:b.currentTime)+I;if(P>=0&&(!x||A||P<=x.duration)){b.currentTime=P;return}}}if(T){let x=d;if(u!=="primary"){const _=T[u].start,I=d-_;x=T.start+I}const b=!e.isInterstitial(T);if((!e.isInterstitial(p)||p.event.appendInPlace)&&(b||T.event.appendInPlace)){const _=e.media||(A?S==null?void 0:S.media:null);_&&(_.currentTime=x)}else if(p){const _=e.findItemIndex(p);if(E>_){const P=e.schedule.findJumpRestrictedIndex(_+1,E);if(P>_){e.setSchedulePosition(P);return}}let I=0;if(b)e.timelinePos=x,e.checkBuffer();else{const P=T.event.assetList,F=d-(T[u]||T).start;for(let U=P.length;U--;){const H=P[U];if(H.duration&&F>=H.startOffset&&F<H.startOffset+H.duration){I=U;break}}}e.setSchedulePosition(E,I)}}},l=()=>{const d=e.effectivePlayingItem;if(e.isInterstitial(d))return d;const u=t();return e.isInterstitial(u)?u:null},h={get bufferedEnd(){const d=t(),u=e.bufferingItem;if(u&&u===d){var f;return i(u,"playout",e.bufferingAsset,"bufferedPos","bufferedEnd")-u.playout.start||((f=e.bufferingAsset)==null?void 0:f.startOffset)||0}return 0},get currentTime(){const d=l(),u=e.effectivePlayingItem;return u&&u===d?i(u,"playout",e.effectivePlayingAsset,"timelinePos","currentTime")-u.playout.start:0},set currentTime(d){const u=l(),f=e.effectivePlayingItem;f&&f===u&&c(d+f.playout.start,"playout")},get duration(){const d=l();return d?d.playout.end-d.playout.start:0},get assetPlayers(){var d;const u=(d=l())==null?void 0:d.event.assetList;return u?u.map(f=>e.getAssetPlayer(f.identifier)):[]},get playingIndex(){var d;const u=(d=l())==null?void 0:d.event;return u&&e.effectivePlayingAsset?u.findAssetIndex(e.effectivePlayingAsset):-1},get scheduleItem(){return l()}};return this.manager={get events(){var d;return((d=e.schedule)==null||(d=d.events)==null?void 0:d.slice(0))||[]},get schedule(){var d;return((d=e.schedule)==null||(d=d.items)==null?void 0:d.slice(0))||[]},get interstitialPlayer(){return l()?h:null},get playerQueue(){return e.playerQueue.slice(0)},get bufferingAsset(){return e.bufferingAsset},get bufferingItem(){return t()},get bufferingIndex(){const d=t();return e.findItemIndex(d)},get playingAsset(){return e.effectivePlayingAsset},get playingItem(){return e.effectivePlayingItem},get playingIndex(){const d=e.effectivePlayingItem;return e.findItemIndex(d)},primary:{get bufferedEnd(){return n()},get currentTime(){const d=e.timelinePos;return d>0?d:0},set currentTime(d){c(d,"primary")},get duration(){return o("primary")},get seekableStart(){var d;return((d=e.primaryDetails)==null?void 0:d.fragmentStart)||0}},integrated:{get bufferedEnd(){return i(t(),"integrated",e.bufferingAsset,"bufferedPos","bufferedEnd")},get currentTime(){return i(e.effectivePlayingItem,"integrated",e.effectivePlayingAsset,"timelinePos","currentTime")},set currentTime(d){c(d,"integrated")},get duration(){return o("integrated")},get seekableStart(){var d;return r(((d=e.primaryDetails)==null?void 0:d.fragmentStart)||0,"integrated")}},skip:()=>{const d=e.effectivePlayingItem,u=d==null?void 0:d.event;if(u&&!u.restrictions.skip){const f=e.findItemIndex(d);if(u.appendInPlace){const g=d.playout.start+d.event.duration;c(g+.001,"playout")}else e.advanceAfterAssetEnded(u,f,1/0)}}}}get effectivePlayingItem(){return this.waitingItem||this.playingItem||this.endedItem}get effectivePlayingAsset(){return this.playingAsset||this.endedAsset}get playingLastItem(){var e;const t=this.playingItem,s=(e=this.schedule)==null?void 0:e.items;return!this.playbackStarted||!t||!s?!1:this.findItemIndex(t)===s.length-1}get playbackStarted(){return this.effectivePlayingItem!==null}get currentTime(){var e,t;if(this.mediaSelection===null)return;const s=this.waitingItem||this.playingItem;if(this.isInterstitial(s)&&!s.event.appendInPlace)return;let i=this.media;!i&&(e=this.bufferingItem)!=null&&(e=e.event)!=null&&e.appendInPlace&&(i=this.primaryMedia);const r=(t=i)==null?void 0:t.currentTime;if(!(r===void 0||!M(r)))return r}get primaryMedia(){var e;return this.media||((e=this.detachedData)==null?void 0:e.media)||null}isInterstitial(e){return!!(e!=null&&e.event)}retreiveMediaSource(e,t){const s=this.getAssetPlayer(e);s&&this.transferMediaFromPlayer(s,t)}transferMediaFromPlayer(e,t){const s=e.interstitial.appendInPlace,i=e.media;if(s&&i===this.primaryMedia){if(this.bufferingAsset=null,(!t||this.isInterstitial(t)&&!t.event.appendInPlace)&&t&&i){this.detachedData={media:i};return}const r=e.transferMedia();this.log(`transfer MediaSource from ${e} ${ne(r)}`),this.detachedData=r}else t&&i&&(this.shouldPlay||(this.shouldPlay=!i.paused))}transferMediaTo(e,t){var s,i;if(e.media===t)return;let r=null;const n=this.hls,o=e!==n,c=o&&e.interstitial.appendInPlace,l=(s=this.detachedData)==null?void 0:s.mediaSource;let h;if(n.media)c&&(r=n.transferMedia(),this.detachedData=r),h="Primary";else if(l){const g=this.getBufferingPlayer();g?(r=g.transferMedia(),h=`${g}`):h="detached MediaSource"}else h="detached media";if(!r){if(l)r=this.detachedData,this.log(`using detachedData: MediaSource ${ne(r)}`);else if(!this.detachedData||n.media===t){const g=this.playerQueue;g.length>1&&g.forEach(y=>{if(o&&y.interstitial.appendInPlace!==c){const p=y.interstitial;this.clearInterstitial(y.interstitial,null),p.appendInPlace=!1,p.appendInPlace&&this.warn(`Could not change append strategy for queued assets ${p}`)}}),this.hls.detachMedia(),this.detachedData={media:t}}}const d=r&&"mediaSource"in r&&((i=r.mediaSource)==null?void 0:i.readyState)!=="closed",u=d&&r?r:t;this.log(`${d?"transfering MediaSource":"attaching media"} to ${o?e:"Primary"} from ${h} (media.currentTime: ${t.currentTime})`);const f=this.schedule;if(u===r&&f){const g=o&&e.assetId===f.assetIdAtEnd;u.overrides={duration:f.duration,endOfStream:!o||g,cueRemoval:!o}}e.attachMedia(u)}onInterstitialCueEnter(){this.onTimeupdate()}checkStart(){const e=this.schedule,t=e==null?void 0:e.events;if(!t||this.playbackDisabled||!this.media)return;this.bufferedPos===-1&&(this.bufferedPos=0);const s=this.timelinePos,i=this.effectivePlayingItem;if(s===-1){const r=this.hls.startPosition;if(this.log(ts("checkStart",r)),this.timelinePos=r,t.length&&t[0].cue.pre){const n=e.findEventIndex(t[0].identifier);this.setSchedulePosition(n)}else if(r>=0||!this.primaryLive){const n=this.timelinePos=r>0?r:0,o=e.findItemIndexAtTime(n);this.setSchedulePosition(o)}}else if(i&&!this.playingItem){const r=e.findItemIndex(i);this.setSchedulePosition(r)}}advanceAssetBuffering(e,t){const s=e.event,i=s.findAssetIndex(t),r=js(s,i);if(!s.isAssetPastPlayoutLimit(r))this.bufferedToEvent(e,r);else if(this.schedule){var n;const o=(n=this.schedule.items)==null?void 0:n[this.findItemIndex(e)+1];o&&this.bufferedToItem(o)}}advanceAfterAssetEnded(e,t,s){const i=js(e,s);if(e.isAssetPastPlayoutLimit(i)){if(this.schedule){const r=this.schedule.items;if(r){const n=t+1,o=r.length;if(n>=o){this.setSchedulePosition(-1);return}const c=e.resumeTime;this.timelinePos<c&&(this.log(ts("advanceAfterAssetEnded",c)),this.timelinePos=c,e.appendInPlace&&this.advanceInPlace(c),this.checkBuffer(this.bufferedPos<c)),this.setSchedulePosition(n)}}}else{if(e.appendInPlace){const r=e.assetList[i];r&&this.advanceInPlace(r.timelineStart)}this.setSchedulePosition(t,i)}}setScheduleToAssetAtTime(e,t){const s=this.schedule;if(!s)return;const i=t.parentIdentifier,r=s.getEvent(i);if(r){const n=s.findEventIndex(i),o=s.findAssetIndex(r,e);this.advanceAfterAssetEnded(r,n,o-1)}}setSchedulePosition(e,t){var s;const i=(s=this.schedule)==null?void 0:s.items;if(!i||this.playbackDisabled)return;const r=e>=0?i[e]:null;this.log(`setSchedulePosition ${e}, ${t} (${r&&Fe(r)}) pos: ${this.timelinePos}`);const n=this.waitingItem||this.playingItem,o=this.playingLastItem;if(this.isInterstitial(n)){const h=n.event,d=this.playingAsset,u=d==null?void 0:d.identifier,f=u?this.getAssetPlayer(u):null;if(f&&u&&(!this.eventItemsMatch(n,r)||t!==void 0&&u!==h.assetList[t].identifier)){var c;const g=h.findAssetIndex(d);if(this.log(`INTERSTITIAL_ASSET_ENDED ${g+1}/${h.assetList.length} ${xt(d)}`),this.endedAsset=d,this.playingAsset=null,this.hls.trigger(m.INTERSTITIAL_ASSET_ENDED,{asset:d,assetListIndex:g,event:h,schedule:i.slice(0),scheduleIndex:e,player:f}),n!==this.playingItem){this.itemsMatch(n,this.playingItem)&&!this.playingAsset&&this.advanceAfterAssetEnded(h,this.findItemIndex(this.playingItem),g);return}this.retreiveMediaSource(u,r),f.media&&!((c=this.detachedData)!=null&&c.mediaSource)&&f.detachMedia()}if(!this.eventItemsMatch(n,r)&&(this.endedItem=n,this.playingItem=null,this.log(`INTERSTITIAL_ENDED ${h} ${Fe(n)}`),h.hasPlayed=!0,this.hls.trigger(m.INTERSTITIAL_ENDED,{event:h,schedule:i.slice(0),scheduleIndex:e}),h.cue.once)){var l;this.updateSchedule();const g=(l=this.schedule)==null?void 0:l.items;if(r&&g){const y=this.findItemIndex(r);this.advanceSchedule(y,g,t,n,o)}return}}this.advanceSchedule(e,i,t,n,o)}advanceSchedule(e,t,s,i,r){const n=this.schedule;if(!n)return;const o=t[e]||null,c=this.primaryMedia,l=this.playerQueue;if(l.length&&l.forEach(h=>{const d=h.interstitial,u=n.findEventIndex(d.identifier);(u<e||u>e+1)&&this.clearInterstitial(d,o)}),this.isInterstitial(o)){this.timelinePos=Math.min(Math.max(this.timelinePos,o.start),o.end);const h=o.event;if(s===void 0){s=n.findAssetIndex(h,this.timelinePos);const g=js(h,s-1);if(h.isAssetPastPlayoutLimit(g)||h.appendInPlace&&this.timelinePos===o.end){this.advanceAfterAssetEnded(h,e,s);return}s=g}const d=this.waitingItem;this.assetsBuffered(o,c)||this.setBufferingItem(o);let u=this.preloadAssets(h,s);if(this.eventItemsMatch(o,d||i)||(this.waitingItem=o,this.log(`INTERSTITIAL_STARTED ${Fe(o)} ${h.appendInPlace?"append in place":""}`),this.hls.trigger(m.INTERSTITIAL_STARTED,{event:h,schedule:t.slice(0),scheduleIndex:e})),!h.assetListLoaded){this.log(`Waiting for ASSET-LIST to complete loading ${h}`);return}if(h.assetListLoader&&(h.assetListLoader.destroy(),h.assetListLoader=void 0),!c){this.log(`Waiting for attachMedia to start Interstitial ${h}`);return}this.waitingItem=this.endedItem=null,this.playingItem=o;const f=h.assetList[s];if(!f){this.advanceAfterAssetEnded(h,e,s||0);return}if(u||(u=this.getAssetPlayer(f.identifier)),u===null||u.destroyed){const g=h.assetList.length;this.warn(`asset ${s+1}/${g} player destroyed ${h}`),u=this.createAssetPlayer(h,f,s),u.loadSource()}if(!this.eventItemsMatch(o,this.bufferingItem)&&h.appendInPlace&&this.isAssetBuffered(f))return;this.startAssetPlayer(u,s,t,e,c),this.shouldPlay&&sn(u.media)}else o?(this.resumePrimary(o,e,i),this.shouldPlay&&sn(this.hls.media)):r&&this.isInterstitial(i)&&(this.endedItem=null,this.playingItem=i,i.event.appendInPlace||this.attachPrimary(n.durations.primary,null))}get playbackDisabled(){return this.hls.config.enableInterstitialPlayback===!1}get primaryDetails(){var e;return(e=this.mediaSelection)==null?void 0:e.main.details}get primaryLive(){var e;return!!((e=this.primaryDetails)!=null&&e.live)}resumePrimary(e,t,s){var i,r;if(this.playingItem=e,this.playingAsset=this.endedAsset=null,this.waitingItem=this.endedItem=null,this.bufferedToItem(e),this.log(`resuming ${Fe(e)}`),!((i=this.detachedData)!=null&&i.mediaSource)){let o=this.timelinePos;(o<e.start||o>=e.end)&&(o=this.getPrimaryResumption(e,t),this.log(ts("resumePrimary",o)),this.timelinePos=o),this.attachPrimary(o,e)}if(!s)return;const n=(r=this.schedule)==null?void 0:r.items;n&&(this.log(`INTERSTITIALS_PRIMARY_RESUMED ${Fe(e)}`),this.hls.trigger(m.INTERSTITIALS_PRIMARY_RESUMED,{schedule:n.slice(0),scheduleIndex:t}),this.checkBuffer())}getPrimaryResumption(e,t){const s=e.start;if(this.primaryLive){const i=this.primaryDetails;if(t===0)return this.hls.startPosition;if(i&&(s<i.fragmentStart||s>i.edge))return this.hls.liveSyncPosition||-1}return s}isAssetBuffered(e){const t=this.getAssetPlayer(e.identifier);return t!=null&&t.hls?t.hls.bufferedToEnd:q.bufferInfo(this.primaryMedia,this.timelinePos,0).end+1>=e.timelineStart+(e.duration||0)}attachPrimary(e,t,s){t?this.setBufferingItem(t):this.bufferingItem=this.playingItem,this.bufferingAsset=null;const i=this.primaryMedia;if(!i)return;const r=this.hls;r.media?this.checkBuffer():(this.transferMediaTo(r,i),s&&this.startLoadingPrimaryAt(e,s)),s||(this.log(ts("attachPrimary",e)),this.timelinePos=e,this.startLoadingPrimaryAt(e,s))}startLoadingPrimaryAt(e,t){var s;const i=this.hls;!i.loadingEnabled||!i.media||Math.abs((((s=i.mainForwardBufferInfo)==null?void 0:s.start)||i.media.currentTime)-e)>.5?i.startLoad(e,t):i.bufferingEnabled||i.resumeBuffering()}onManifestLoading(){var e;this.stopLoad(),(e=this.schedule)==null||e.reset(),this.emptyPlayerQueue(),this.clearScheduleState(),this.shouldPlay=!1,this.bufferedPos=this.timelinePos=-1,this.mediaSelection=this.altSelection=this.manager=this.requiredTracks=null,this.hls.off(m.BUFFER_CODECS,this.onBufferCodecs,this),this.hls.on(m.BUFFER_CODECS,this.onBufferCodecs,this)}onLevelUpdated(e,t){if(t.level===-1||!this.schedule)return;const s=this.hls.levels[t.level];if(!s.details)return;const i=te(te({},this.mediaSelection||this.altSelection),{},{main:s});this.mediaSelection=i,this.schedule.parseInterstitialDateRanges(i,this.hls.config.interstitialAppendInPlace),!this.effectivePlayingItem&&this.schedule.items&&this.checkStart()}onAudioTrackUpdated(e,t){const s=this.hls.audioTracks[t.id],i=this.mediaSelection;if(!i){this.altSelection=te(te({},this.altSelection),{},{audio:s});return}const r=te(te({},i),{},{audio:s});this.mediaSelection=r}onSubtitleTrackUpdated(e,t){const s=this.hls.subtitleTracks[t.id],i=this.mediaSelection;if(!i){this.altSelection=te(te({},this.altSelection),{},{subtitles:s});return}const r=te(te({},i),{},{subtitles:s});this.mediaSelection=r}onAudioTrackSwitching(e,t){const s=dr(t);this.playerQueue.forEach(({hls:i})=>i&&(i.setAudioOption(t)||i.setAudioOption(s)))}onSubtitleTrackSwitch(e,t){const s=dr(t);this.playerQueue.forEach(({hls:i})=>i&&(i.setSubtitleOption(t)||t.id!==-1&&i.setSubtitleOption(s)))}onBufferCodecs(e,t){const s=t.tracks;s&&(this.requiredTracks=s)}onBufferAppended(e,t){this.checkBuffer()}onBufferFlushed(e,t){const s=this.playingItem;if(s&&!this.itemsMatch(s,this.bufferingItem)&&!this.isInterstitial(s)){const i=this.timelinePos;this.bufferedPos=i,this.checkBuffer()}}onBufferedToEnd(e){if(!this.schedule)return;const t=this.schedule.events;if(this.bufferedPos<Number.MAX_VALUE&&t){for(let i=0;i<t.length;i++){const r=t[i];if(r.cue.post){var s;const n=this.schedule.findEventIndex(r.identifier),o=(s=this.schedule.items)==null?void 0:s[n];this.isInterstitial(o)&&this.eventItemsMatch(o,this.bufferingItem)&&this.bufferedToItem(o,0);break}}this.bufferedPos=Number.MAX_VALUE}}onMediaEnded(e){const t=this.playingItem;if(!this.playingLastItem&&t){const s=this.findItemIndex(t);this.setSchedulePosition(s+1)}else this.shouldPlay=!1}updateItem(e,t){var s;const i=(s=this.schedule)==null?void 0:s.items;if(e&&i){const r=this.findItemIndex(e,t);return i[r]||null}return null}trimInPlace(e,t){if(this.isInterstitial(e)&&e.event.appendInPlace&&t.end-e.end>.25){e.event.assetList.forEach((r,n)=>{e.event.isAssetPastPlayoutLimit(n)&&this.clearAssetPlayer(r.identifier,null)});const s=e.end+.25,i=q.bufferInfo(this.primaryMedia,s,0);(i.end>s||(i.nextStart||0)>s)&&(this.log(`trim buffered interstitial ${Fe(e)} (was ${Fe(t)})`),this.attachPrimary(s,null,!0),this.flushFrontBuffer(s))}}itemsMatch(e,t){return!!t&&(e===t||e.event&&t.event&&this.eventItemsMatch(e,t)||!e.event&&!t.event&&this.findItemIndex(e)===this.findItemIndex(t))}eventItemsMatch(e,t){var s;return!!t&&(e===t||e.event.identifier===((s=t.event)==null?void 0:s.identifier))}findItemIndex(e,t){return e&&this.schedule?this.schedule.findItemIndex(e,t):-1}updateSchedule(e=!1){var t;const s=this.mediaSelection;s&&((t=this.schedule)==null||t.updateSchedule(s,[],e))}checkBuffer(e){var t;const s=(t=this.schedule)==null?void 0:t.items;if(!s)return;const i=q.bufferInfo(this.primaryMedia,this.timelinePos,0);e&&(this.bufferedPos=this.timelinePos),e||(e=i.len<1),this.updateBufferedPos(i.end,s,e)}updateBufferedPos(e,t,s){const i=this.schedule,r=this.bufferingItem;if(this.bufferedPos>e||!i)return;if(t.length===1&&this.itemsMatch(t[0],r)){this.bufferedPos=e;return}const n=this.playingItem,o=this.findItemIndex(n);let c=i.findItemIndexAtTime(e);if(this.bufferedPos<e){var l;const h=this.findItemIndex(r),d=Math.min(h+1,t.length-1),u=t[d];if((c===-1&&r&&e>=r.end||(l=u.event)!=null&&l.appendInPlace&&e+.01>=u.start)&&(c=d),this.isInterstitial(r)){const f=r.event;if(d-o>1&&f.appendInPlace===!1||f.assetList.length===0&&f.assetListLoader)return}if(this.bufferedPos=e,c>h&&c>o)this.bufferedToItem(u);else{const f=this.primaryDetails;this.primaryLive&&f&&e>f.edge-f.targetduration&&u.start<f.edge+this.hls.config.interstitialLiveLookAhead&&this.isInterstitial(u)&&this.preloadAssets(u.event,0)}}else s&&n&&!this.itemsMatch(n,r)&&(c===o?this.bufferedToItem(n):c===o+1&&this.bufferedToItem(t[c]))}assetsBuffered(e,t){return e.event.assetList.length===0?!1:!e.event.assetList.some(i=>{const r=this.getAssetPlayer(i.identifier);return!(r!=null&&r.bufferedInPlaceToEnd(t))})}setBufferingItem(e){const t=this.bufferingItem,s=this.schedule;if(!this.itemsMatch(e,t)&&s){const{items:i,events:r}=s;if(!i||!r)return t;const n=this.isInterstitial(e),o=this.getBufferingPlayer();this.bufferingItem=e,this.bufferedPos=Math.max(e.start,Math.min(e.end,this.timelinePos));const c=o?o.remaining:t?t.end-this.timelinePos:0;if(this.log(`INTERSTITIALS_BUFFERED_TO_BOUNDARY ${Fe(e)}`+(t?` (${c.toFixed(2)} remaining)`:"")),!this.playbackDisabled)if(n){const l=s.findAssetIndex(e.event,this.bufferedPos);e.event.assetList.forEach((h,d)=>{const u=this.getAssetPlayer(h.identifier);u&&(d===l&&u.loadSource(),u.resumeBuffering())})}else this.hls.resumeBuffering(),this.playerQueue.forEach(l=>l.pauseBuffering());this.hls.trigger(m.INTERSTITIALS_BUFFERED_TO_BOUNDARY,{events:r.slice(0),schedule:i.slice(0),bufferingIndex:this.findItemIndex(e),playingIndex:this.findItemIndex(this.playingItem)})}else this.bufferingItem!==e&&(this.bufferingItem=e);return t}bufferedToItem(e,t=0){const s=this.setBufferingItem(e);if(!this.playbackDisabled){if(this.isInterstitial(e))this.bufferedToEvent(e,t);else if(s!==null){this.bufferingAsset=null;const i=this.detachedData;i?i.mediaSource?this.attachPrimary(e.start,e,!0):this.preloadPrimary(e):this.preloadPrimary(e)}}}preloadPrimary(e){const t=this.findItemIndex(e),s=this.getPrimaryResumption(e,t);this.startLoadingPrimaryAt(s)}bufferedToEvent(e,t){const s=e.event,i=s.assetList.length===0&&!s.assetListLoader,r=s.cue.once;if(i||!r){const n=this.preloadAssets(s,t);if(n!=null&&n.interstitial.appendInPlace){const o=this.primaryMedia;o&&this.bufferAssetPlayer(n,o)}}}preloadAssets(e,t){const s=e.assetUrl,i=e.assetList.length,r=i===0&&!e.assetListLoader,n=e.cue.once;if(r){const c=e.timelineStart;if(e.appendInPlace){var o;const u=this.playingItem;!this.isInterstitial(u)&&(u==null||(o=u.nextEvent)==null?void 0:o.identifier)===e.identifier&&this.flushFrontBuffer(c+.25)}let l,h=0;if(!this.playingItem&&this.primaryLive&&(h=this.hls.startPosition,h===-1&&(h=this.hls.liveSyncPosition||0)),h&&!(e.cue.pre||e.cue.post)){const u=h-c;u>0&&(l=Math.round(u*1e3)/1e3)}if(this.log(`Load interstitial asset ${t+1}/${s?1:i} ${e}${l?` live-start: ${h} start-offset: ${l}`:""}`),s)return this.createAsset(e,0,0,c,e.duration,s);const d=this.assetListLoader.loadAssetList(e,l);d&&(e.assetListLoader=d)}else if(!n&&i){for(let l=t;l<i;l++){const h=e.assetList[l],d=this.getAssetPlayerQueueIndex(h.identifier);(d===-1||this.playerQueue[d].destroyed)&&!h.error&&this.createAssetPlayer(e,h,l)}const c=e.assetList[t];if(c){const l=this.getAssetPlayer(c.identifier);return l&&l.loadSource(),l}}return null}flushFrontBuffer(e){const t=this.requiredTracks;if(!t)return;this.log(`Removing front buffer starting at ${e}`),Object.keys(t).forEach(i=>{this.hls.trigger(m.BUFFER_FLUSHING,{startOffset:e,endOffset:1/0,type:i})})}getAssetPlayerQueueIndex(e){const t=this.playerQueue;for(let s=0;s<t.length;s++)if(e===t[s].assetId)return s;return-1}getAssetPlayer(e){const t=this.getAssetPlayerQueueIndex(e);return this.playerQueue[t]||null}getBufferingPlayer(){const{playerQueue:e,primaryMedia:t}=this;if(t){for(let s=0;s<e.length;s++)if(e[s].media===t)return e[s]}return null}createAsset(e,t,s,i,r,n){const o={parentIdentifier:e.identifier,identifier:jh(e,n,t),duration:r,startOffset:s,timelineStart:i,uri:n};return this.createAssetPlayer(e,o,t)}createAssetPlayer(e,t,s){const i=this.hls,r=i.userConfig;let n=r.videoPreference;const o=i.loadLevelObj||i.levels[i.currentLevel];(n||o)&&(n=ie({},n),o.videoCodec&&(n.videoCodec=o.videoCodec),o.videoRange&&(n.allowedVideoRanges=[o.videoRange]));const c=i.audioTracks[i.audioTrack],l=i.subtitleTracks[i.subtitleTrack];let h=0;if(this.primaryLive||e.appendInPlace){const v=this.timelinePos-t.timelineStart;if(v>1){const A=t.duration;A&&v<A&&(h=v)}}const d=t.identifier,u=te(te({},r),{},{maxMaxBufferLength:Math.min(180,i.config.maxMaxBufferLength),autoStartLoad:!0,startFragPrefetch:!0,primarySessionId:i.sessionId,assetPlayerId:d,abrEwmaDefaultEstimate:i.bandwidthEstimate,interstitialsController:void 0,startPosition:h,liveDurationInfinity:!1,testBandwidth:!1,videoPreference:n,audioPreference:c||r.audioPreference,subtitlePreference:l||r.subtitlePreference});e.appendInPlace&&(e.appendInPlaceStarted=!0,t.timelineStart&&(u.timelineOffset=t.timelineStart));const f=u.cmcd;f!=null&&f.sessionId&&f.contentId&&(u.cmcd=ie({},f,{contentId:Mt(t.uri)})),this.getAssetPlayer(d)&&this.warn(`Duplicate date range identifier ${e} and asset ${d}`);const g=new Qh(this.HlsPlayerClass,u,e,t);this.playerQueue.push(g),e.assetList[s]=t;let y=!0;const p=v=>{if(v.live){var A;const b=new Error(`Interstitials MUST be VOD assets ${e}`),_={fatal:!0,type:V.OTHER_ERROR,details:R.INTERSTITIAL_ASSET_ITEM_ERROR,error:b},I=((A=this.schedule)==null?void 0:A.findEventIndex(e.identifier))||-1;this.handleAssetItemError(_,e,I,s,b.message);return}const D=v.edge-v.fragmentStart,x=t.duration;(y||x===null||D>x)&&(y=!1,this.log(`Interstitial asset "${d}" duration change ${x} > ${D}`),t.duration=D,this.updateSchedule())};g.on(m.LEVEL_UPDATED,(v,{details:A})=>p(A)),g.on(m.LEVEL_PTS_UPDATED,(v,{details:A})=>p(A)),g.on(m.EVENT_CUE_ENTER,()=>this.onInterstitialCueEnter());const E=(v,A)=>{const D=this.getAssetPlayer(d);if(D&&A.tracks){D.off(m.BUFFER_CODECS,E),D.tracks=A.tracks;const x=this.primaryMedia;this.bufferingAsset===D.assetItem&&x&&!D.media&&this.bufferAssetPlayer(D,x)}};g.on(m.BUFFER_CODECS,E);const T=()=>{var v;const A=this.getAssetPlayer(d);if(this.log(`buffered to end of asset ${A}`),!A||!this.schedule)return;const D=this.schedule.findEventIndex(e.identifier),x=(v=this.schedule.items)==null?void 0:v[D];this.isInterstitial(x)&&this.advanceAssetBuffering(x,t)};g.on(m.BUFFERED_TO_END,T);const S=v=>()=>{if(!this.getAssetPlayer(d)||!this.schedule)return;this.shouldPlay=!0;const D=this.schedule.findEventIndex(e.identifier);this.advanceAfterAssetEnded(e,D,v)};return g.once(m.MEDIA_ENDED,S(s)),g.once(m.PLAYOUT_LIMIT_REACHED,S(1/0)),g.on(m.ERROR,(v,A)=>{if(!this.schedule)return;const D=this.getAssetPlayer(d);if(A.details===R.BUFFER_STALLED_ERROR){if(D!=null&&D.appendInPlace){this.handleInPlaceStall(e);return}this.onTimeupdate(),this.checkBuffer(!0);return}this.handleAssetItemError(A,e,this.schedule.findEventIndex(e.identifier),s,`Asset player error ${A.error} ${e}`)}),g.on(m.DESTROYING,()=>{if(!this.getAssetPlayer(d)||!this.schedule)return;const A=new Error(`Asset player destroyed unexpectedly ${d}`),D={fatal:!0,type:V.OTHER_ERROR,details:R.INTERSTITIAL_ASSET_ITEM_ERROR,error:A};this.handleAssetItemError(D,e,this.schedule.findEventIndex(e.identifier),s,A.message)}),this.log(`INTERSTITIAL_ASSET_PLAYER_CREATED ${xt(t)}`),this.hls.trigger(m.INTERSTITIAL_ASSET_PLAYER_CREATED,{asset:t,assetListIndex:s,event:e,player:g}),g}clearInterstitial(e,t){this.clearAssetPlayers(e,t),e.reset()}clearAssetPlayers(e,t){e.assetList.forEach(s=>{this.clearAssetPlayer(s.identifier,t)})}resetAssetPlayer(e){const t=this.getAssetPlayerQueueIndex(e);if(t!==-1){this.log(`reset asset player "${e}" after error`);const s=this.playerQueue[t];this.transferMediaFromPlayer(s,null),s.resetDetails()}}clearAssetPlayer(e,t){const s=this.getAssetPlayerQueueIndex(e);if(s!==-1){const i=this.playerQueue[s];this.log(`clear ${i} toSegment: ${t&&Fe(t)}`),this.transferMediaFromPlayer(i,t),this.playerQueue.splice(s,1),i.destroy()}}emptyPlayerQueue(){let e;for(;e=this.playerQueue.pop();)e.destroy();this.playerQueue=[]}startAssetPlayer(e,t,s,i,r){const{interstitial:n,assetItem:o,assetId:c}=e,l=n.assetList.length,h=this.playingAsset;this.endedAsset=null,this.playingAsset=o,(!h||h.identifier!==c)&&(h&&(this.clearAssetPlayer(h.identifier,s[i]),delete h.error),this.log(`INTERSTITIAL_ASSET_STARTED ${t+1}/${l} ${xt(o)}`),this.hls.trigger(m.INTERSTITIAL_ASSET_STARTED,{asset:o,assetListIndex:t,event:n,schedule:s.slice(0),scheduleIndex:i,player:e})),this.bufferAssetPlayer(e,r)}bufferAssetPlayer(e,t){var s,i;if(!this.schedule)return;const{interstitial:r,assetItem:n}=e,o=this.schedule.findEventIndex(r.identifier),c=(s=this.schedule.items)==null?void 0:s[o];if(!c)return;e.loadSource(),this.setBufferingItem(c),this.bufferingAsset=n;const l=this.getBufferingPlayer();if(l===e)return;const h=r.appendInPlace;if(h&&(l==null?void 0:l.interstitial.appendInPlace)===!1)return;const d=(l==null?void 0:l.tracks)||((i=this.detachedData)==null?void 0:i.tracks)||this.requiredTracks;if(h&&n!==this.playingAsset){if(!e.tracks){this.log(`Waiting for track info before buffering ${e}`);return}if(d&&!Sn(d,e.tracks)){const u=new Error(`Asset ${xt(n)} SourceBuffer tracks ('${Object.keys(e.tracks)}') are not compatible with primary content tracks ('${Object.keys(d)}')`),f={fatal:!0,type:V.OTHER_ERROR,details:R.INTERSTITIAL_ASSET_ITEM_ERROR,error:u},g=r.findAssetIndex(n);this.handleAssetItemError(f,r,o,g,u.message);return}}this.transferMediaTo(e,t)}handleInPlaceStall(e){const t=this.schedule,s=this.primaryMedia;if(!t||!s)return;const i=s.currentTime,r=t.findAssetIndex(e,i),n=e.assetList[r];if(n){const o=this.getAssetPlayer(n.identifier);if(o){const c=o.currentTime||i-n.timelineStart,l=o.duration-c;if(this.warn(`Stalled at ${c} of ${c+l} in ${o} ${e} (media.currentTime: ${i})`),c&&(l/s.playbackRate<.5||o.bufferedInPlaceToEnd(s))&&o.hls){const h=t.findEventIndex(e.identifier);this.advanceAfterAssetEnded(e,h,r)}}}}advanceInPlace(e){const t=this.primaryMedia;t&&t.currentTime<e&&(t.currentTime=e)}handleAssetItemError(e,t,s,i,r){if(e.details===R.BUFFER_STALLED_ERROR)return;const n=t.assetList[i]||null;if(this.warn(`INTERSTITIAL_ASSET_ERROR ${n&&xt(n)} ${e.error}`),!this.schedule)return;const o=(n==null?void 0:n.identifier)||"",c=this.getAssetPlayerQueueIndex(o),l=this.playerQueue[c]||null,h=this.schedule.items,d=ie({},e,{fatal:!1,errorAction:It(!0),asset:n,assetListIndex:i,event:t,schedule:h,scheduleIndex:s,player:l});if(this.hls.trigger(m.INTERSTITIAL_ASSET_ERROR,d),!e.fatal)return;const u=this.playingAsset,f=this.bufferingAsset,g=new Error(r);if(n&&(this.clearAssetPlayer(o,null),n.error=g),!t.assetList.some(y=>!y.error))t.error=g;else for(let y=i;y<t.assetList.length;y++)this.resetAssetPlayer(t.assetList[y].identifier);this.updateSchedule(!0),t.error?this.primaryFallback(t):u&&u.identifier===o?this.advanceAfterAssetEnded(t,s,i):f&&f.identifier===o&&this.isInterstitial(this.bufferingItem)&&this.advanceAssetBuffering(this.bufferingItem,f)}primaryFallback(e){const t=e.timelineStart,s=this.effectivePlayingItem;let i=this.timelinePos;if(s){this.log(`Fallback to primary from event "${e.identifier}" start: ${t} pos: ${i} playing: ${Fe(s)} error: ${e.error}`),i===-1&&(i=this.hls.startPosition);const n=this.updateItem(s,i);this.itemsMatch(s,n)&&this.clearInterstitial(e,null),e.appendInPlace&&(this.attachPrimary(t,null),this.flushFrontBuffer(t))}else if(i===-1){this.checkStart();return}if(!this.schedule)return;const r=this.schedule.findItemIndexAtTime(i);this.setSchedulePosition(r)}onAssetListLoaded(e,t){var s,i;const r=t.event,n=r.identifier,o=t.assetListResponse.ASSETS;if(!((s=this.schedule)!=null&&s.hasEvent(n)))return;const c=r.timelineStart,l=r.duration;let h=0;o.forEach((y,p)=>{const E=parseFloat(y.DURATION);this.createAsset(r,p,h,c+h,E,y.URI),h+=E}),r.duration=h,this.log(`Loaded asset-list with duration: ${h} (was: ${l}) ${r}`);const d=this.waitingItem,u=(d==null?void 0:d.event.identifier)===n;this.updateSchedule();const f=(i=this.bufferingItem)==null?void 0:i.event;if(u){var g;const y=this.schedule.findEventIndex(n),p=(g=this.schedule.items)==null?void 0:g[y];if(p){if(!this.playingItem&&this.timelinePos>p.end&&this.schedule.findItemIndexAtTime(this.timelinePos)!==y){r.error=new Error(`Interstitial ${o.length?"no longer within playback range":"asset-list is empty"} ${this.timelinePos} ${r}`),this.log(r.error.message),this.updateSchedule(!0),this.primaryFallback(r);return}this.setBufferingItem(p)}this.setSchedulePosition(y)}else if((f==null?void 0:f.identifier)===n){const y=r.assetList[0];if(y){const p=this.getAssetPlayer(y.identifier);if(f.appendInPlace){const E=this.primaryMedia;p&&E&&this.bufferAssetPlayer(p,E)}else p&&p.loadSource()}}}onError(e,t){if(this.schedule)switch(t.details){case R.ASSET_LIST_PARSING_ERROR:case R.ASSET_LIST_LOAD_ERROR:case R.ASSET_LIST_LOAD_TIMEOUT:{const s=t.interstitial;s&&(this.updateSchedule(!0),this.primaryFallback(s));break}case R.BUFFER_STALLED_ERROR:{const s=this.endedItem||this.waitingItem||this.playingItem;if(this.isInterstitial(s)&&s.event.appendInPlace){this.handleInPlaceStall(s.event);return}this.log(`Primary player stall @${this.timelinePos} bufferedPos: ${this.bufferedPos}`),this.onTimeupdate(),this.checkBuffer(!0);break}}}}const rn=500;class td extends Oi{constructor(e,t,s){super(e,t,s,"subtitle-stream-controller",B.SUBTITLE),this.currentTrackId=-1,this.tracksBuffered=[],this.mainDetails=null,this.registerListeners()}onHandlerDestroying(){this.unregisterListeners(),super.onHandlerDestroying(),this.mainDetails=null}registerListeners(){super.registerListeners();const{hls:e}=this;e.on(m.LEVEL_LOADED,this.onLevelLoaded,this),e.on(m.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(m.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.on(m.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(m.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.on(m.BUFFER_FLUSHING,this.onBufferFlushing,this)}unregisterListeners(){super.unregisterListeners();const{hls:e}=this;e.off(m.LEVEL_LOADED,this.onLevelLoaded,this),e.off(m.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(m.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.off(m.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(m.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.off(m.BUFFER_FLUSHING,this.onBufferFlushing,this)}startLoad(e,t){this.stopLoad(),this.state=C.IDLE,this.setInterval(rn),this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,this.tick()}onManifestLoading(){super.onManifestLoading(),this.mainDetails=null}onMediaDetaching(e,t){this.tracksBuffered=[],super.onMediaDetaching(e,t)}onLevelLoaded(e,t){this.mainDetails=t.details}onSubtitleFragProcessed(e,t){const{frag:s,success:i}=t;if(this.fragContextChanged(s)||(ce(s)&&(this.fragPrevious=s),this.state=C.IDLE),!i)return;const r=this.tracksBuffered[this.currentTrackId];if(!r)return;let n;const o=s.start;for(let l=0;l<r.length;l++)if(o>=r[l].start&&o<=r[l].end){n=r[l];break}const c=s.start+s.duration;n?n.end=c:(n={start:o,end:c},r.push(n)),this.fragmentTracker.fragBuffered(s),this.fragBufferedComplete(s,null),this.media&&this.tick()}onBufferFlushing(e,t){const{startOffset:s,endOffset:i}=t;if(s===0&&i!==Number.POSITIVE_INFINITY){const r=i-1;if(r<=0)return;t.endOffsetSubtitles=Math.max(0,r),this.tracksBuffered.forEach(n=>{for(let o=0;o<n.length;){if(n[o].end<=r){n.shift();continue}else if(n[o].start<r)n[o].start=r;else break;o++}}),this.fragmentTracker.removeFragmentsInRange(s,r,B.SUBTITLE)}}onError(e,t){const s=t.frag;(s==null?void 0:s.type)===B.SUBTITLE&&(t.details===R.FRAG_GAP&&this.fragmentTracker.fragBuffered(s,!0),this.fragCurrent&&this.fragCurrent.abortRequests(),this.state!==C.STOPPED&&(this.state=C.IDLE))}onSubtitleTracksUpdated(e,{subtitleTracks:t}){if(this.levels&&Aa(this.levels,t)){this.levels=t.map(s=>new $t(s));return}this.tracksBuffered=[],this.levels=t.map(s=>{const i=new $t(s);return this.tracksBuffered[i.id]=[],i}),this.fragmentTracker.removeFragmentsInRange(0,Number.POSITIVE_INFINITY,B.SUBTITLE),this.fragPrevious=null,this.mediaBuffer=null}onSubtitleTrackSwitch(e,t){var s;if(this.currentTrackId=t.id,!((s=this.levels)!=null&&s.length)||this.currentTrackId===-1){this.clearInterval();return}const i=this.levels[this.currentTrackId];i!=null&&i.details?this.mediaBuffer=this.mediaBufferTimeRanges:this.mediaBuffer=null,i&&this.state!==C.STOPPED&&this.setInterval(rn)}onSubtitleTrackLoaded(e,t){var s;const{currentTrackId:i,levels:r}=this,{details:n,id:o}=t;if(!r){this.warn(`Subtitle tracks were reset while loading level ${o}`);return}const c=r[o];if(o>=r.length||!c)return;this.log(`Subtitle track ${o} 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||(s=c.details)!=null&&s.live){if(n.deltaUpdateFailed)return;const d=this.mainDetails;if(!d){this.startFragRequested=!1;return}const u=d.fragments[0];if(!c.details)n.hasProgramDateTime&&d.hasProgramDateTime?(Rs(n,d),l=n.fragmentStart):u&&(l=u.start,ui(n,l));else{var h;l=this.alignPlaylists(n,c.details,(h=this.levelLastLoaded)==null?void 0:h.details),l===0&&u&&(l=u.start,ui(n,l))}d&&!this.startFragRequested&&this.setStartPosition(d,l)}c.details=n,this.levelLastLoaded=c,o===i&&(this.hls.trigger(m.SUBTITLE_TRACK_UPDATED,{details:n,id:o,groupId:t.groupId}),this.tick(),n.live&&!this.fragCurrent&&this.media&&this.state===C.IDLE&&(gt(null,n.fragments,this.media.currentTime,0)||(this.warn("Subtitle playlist not aligned with playback"),c.details=void 0)))}_handleFragmentLoadComplete(e){const{frag:t,payload:s}=e,i=t.decryptdata,r=this.hls;if(!this.fragContextChanged(t)&&s&&s.byteLength>0&&i!=null&&i.key&&i.iv&&Lt(i.method)){const n=performance.now();this.decrypter.decrypt(new Uint8Array(s),i.key.buffer,i.iv.buffer,ki(i.method)).catch(o=>{throw r.trigger(m.ERROR,{type:V.MEDIA_ERROR,details:R.FRAG_DECRYPT_ERROR,fatal:!1,error:o,reason:o.message,frag:t}),o}).then(o=>{const c=performance.now();r.trigger(m.FRAG_DECRYPTED,{frag:t,payload:o,stats:{tstart:n,tdecrypt:c}})}).catch(o=>{this.warn(`${o.name}: ${o.message}`),this.state=C.IDLE})}}doTick(){if(!this.media){this.state=C.IDLE;return}if(this.state===C.IDLE){const{currentTrackId:e,levels:t}=this,s=t==null?void 0:t[e];if(!s||!t.length||!s.details||this.waitForLive(s))return;const{config:i}=this,r=this.getLoadPosition(),n=q.bufferedInfo(this.tracksBuffered[this.currentTrackId]||[],r,i.maxBufferHole),{end:o,len:c}=n,l=s.details,h=this.hls.maxBufferLength+l.levelTargetDuration;if(c>h)return;const d=l.fragments,u=d.length,f=l.edge;let g=null;const y=this.fragPrevious;if(o<f){const T=i.maxFragLookUpTolerance,S=o>f-T?0:T;g=gt(y,d,Math.max(d[0].start,o),S),!g&&y&&y.start<d[0].start&&(g=d[0])}else g=d[u-1];if(g=this.filterReplacedPrimary(g,s.details),!g)return;const p=g.sn-l.startSN,E=d[p-1];if(E&&E.cc===g.cc&&this.fragmentTracker.getState(E)===de.NOT_LOADED&&(g=E),this.fragmentTracker.getState(g)===de.NOT_LOADED){const T=this.mapToInitFragWhenRequired(g);T&&this.loadFragment(T,s,o)}}}loadFragment(e,t,s){ce(e)?super.loadFragment(e,t,s):this._loadInitSegment(e,t)}get mediaBufferTimeRanges(){return new sd(this.tracksBuffered[this.currentTrackId]||[])}}class sd{constructor(e){this.buffered=void 0;const t=(s,i,r)=>{if(i=i>>>0,i>r-1)throw new DOMException(`Failed to execute '${s}' on 'TimeRanges': The index provided (${i}) is greater than the maximum bound (${r})`);return e[i][s]};this.buffered={get length(){return e.length},end(s){return t("end",s,e.length)},start(s){return t("start",s,e.length)}}}}const id={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},Ua=a=>String.fromCharCode(id[a]||a),Ne=15,je=100,rd={17:1,18:3,21:5,22:7,23:9,16:11,19:12,20:14},nd={17:2,18:4,21:6,22:8,23:10,19:13,20:15},ad={25:1,26:3,29:5,30:7,31:9,24:11,27:12,28:14},od={25:2,26:4,29:6,30:8,31:10,27:13,28:15},ld=["white","green","blue","cyan","red","yellow","magenta","black","transparent"];class cd{constructor(){this.time=null,this.verboseLevel=0}log(e,t){if(this.verboseLevel>=e){const s=typeof t=="function"?t():t;se.log(`${this.time} [${e}] ${s}`)}}}const ht=function(e){const t=[];for(let s=0;s<e.length;s++)t.push(e[s].toString(16));return t};class $a{constructor(){this.foreground="white",this.underline=!1,this.italics=!1,this.background="black",this.flash=!1}reset(){this.foreground="white",this.underline=!1,this.italics=!1,this.background="black",this.flash=!1}setStyles(e){const t=["foreground","underline","italics","background","flash"];for(let s=0;s<t.length;s++){const i=t[s];e.hasOwnProperty(i)&&(this[i]=e[i])}}isDefault(){return this.foreground==="white"&&!this.underline&&!this.italics&&this.background==="black"&&!this.flash}equals(e){return this.foreground===e.foreground&&this.underline===e.underline&&this.italics===e.italics&&this.background===e.background&&this.flash===e.flash}copy(e){this.foreground=e.foreground,this.underline=e.underline,this.italics=e.italics,this.background=e.background,this.flash=e.flash}toString(){return"color="+this.foreground+", underline="+this.underline+", italics="+this.italics+", background="+this.background+", flash="+this.flash}}class hd{constructor(){this.uchar=" ",this.penState=new $a}reset(){this.uchar=" ",this.penState.reset()}setChar(e,t){this.uchar=e,this.penState.copy(t)}setPenState(e){this.penState.copy(e)}equals(e){return this.uchar===e.uchar&&this.penState.equals(e.penState)}copy(e){this.uchar=e.uchar,this.penState.copy(e.penState)}isEmpty(){return this.uchar===" "&&this.penState.isDefault()}}class dd{constructor(e){this.chars=[],this.pos=0,this.currPenState=new $a,this.cueStartTime=null,this.logger=void 0;for(let t=0;t<je;t++)this.chars.push(new hd);this.logger=e}equals(e){for(let t=0;t<je;t++)if(!this.chars[t].equals(e.chars[t]))return!1;return!0}copy(e){for(let t=0;t<je;t++)this.chars[t].copy(e.chars[t])}isEmpty(){let e=!0;for(let t=0;t<je;t++)if(!this.chars[t].isEmpty()){e=!1;break}return e}setCursor(e){this.pos!==e&&(this.pos=e),this.pos<0?(this.logger.log(3,"Negative cursor position "+this.pos),this.pos=0):this.pos>je&&(this.logger.log(3,"Too large cursor position "+this.pos),this.pos=je)}moveCursor(e){const t=this.pos+e;if(e>1)for(let s=this.pos+1;s<t+1;s++)this.chars[s].setPenState(this.currPenState);this.setCursor(t)}backSpace(){this.moveCursor(-1),this.chars[this.pos].setChar(" ",this.currPenState)}insertChar(e){e>=144&&this.backSpace();const t=Ua(e);if(this.pos>=je){this.logger.log(0,()=>"Cannot insert "+e.toString(16)+" ("+t+") at position "+this.pos+". Skipping it!");return}this.chars[this.pos].setChar(t,this.currPenState),this.moveCursor(1)}clearFromPos(e){let t;for(t=e;t<je;t++)this.chars[t].reset()}clear(){this.clearFromPos(0),this.pos=0,this.currPenState.reset()}clearToEndOfRow(){this.clearFromPos(this.pos)}getTextString(){const e=[];let t=!0;for(let s=0;s<je;s++){const i=this.chars[s].uchar;i!==" "&&(t=!1),e.push(i)}return t?"":e.join("")}setPenStyles(e){this.currPenState.setStyles(e),this.chars[this.pos].setPenState(this.currPenState)}}class Xs{constructor(e){this.rows=[],this.currRow=Ne-1,this.nrRollUpRows=null,this.lastOutputScreen=null,this.logger=void 0;for(let t=0;t<Ne;t++)this.rows.push(new dd(e));this.logger=e}reset(){for(let e=0;e<Ne;e++)this.rows[e].clear();this.currRow=Ne-1}equals(e){let t=!0;for(let s=0;s<Ne;s++)if(!this.rows[s].equals(e.rows[s])){t=!1;break}return t}copy(e){for(let t=0;t<Ne;t++)this.rows[t].copy(e.rows[t])}isEmpty(){let e=!0;for(let t=0;t<Ne;t++)if(!this.rows[t].isEmpty()){e=!1;break}return e}backSpace(){this.rows[this.currRow].backSpace()}clearToEndOfRow(){this.rows[this.currRow].clearToEndOfRow()}insertChar(e){this.rows[this.currRow].insertChar(e)}setPen(e){this.rows[this.currRow].setPenStyles(e)}moveCursor(e){this.rows[this.currRow].moveCursor(e)}setCursor(e){this.logger.log(2,"setCursor: "+e),this.rows[this.currRow].setCursor(e)}setPAC(e){this.logger.log(2,()=>"pacData = "+ne(e));let t=e.row-1;if(this.nrRollUpRows&&t<this.nrRollUpRows-1&&(t=this.nrRollUpRows-1),this.nrRollUpRows&&this.currRow!==t){for(let o=0;o<Ne;o++)this.rows[o].clear();const r=this.currRow+1-this.nrRollUpRows,n=this.lastOutputScreen;if(n){const o=n.rows[r].cueStartTime,c=this.logger.time;if(o!==null&&c!==null&&o<c)for(let l=0;l<this.nrRollUpRows;l++)this.rows[t-this.nrRollUpRows+l+1].copy(n.rows[r+l])}}this.currRow=t;const s=this.rows[this.currRow];if(e.indent!==null){const r=e.indent,n=Math.max(r-1,0);s.setCursor(e.indent),e.color=s.chars[n].penState.foreground}const i={foreground:e.color,underline:e.underline,italics:e.italics,background:"black",flash:!1};this.setPen(i)}setBkgData(e){this.logger.log(2,()=>"bkgData = "+ne(e)),this.backSpace(),this.setPen(e),this.insertChar(32)}setRollUpRows(e){this.nrRollUpRows=e}rollUp(){if(this.nrRollUpRows===null){this.logger.log(3,"roll_up but nrRollUpRows not set yet");return}this.logger.log(1,()=>this.getDisplayText());const e=this.currRow+1-this.nrRollUpRows,t=this.rows.splice(e,1)[0];t.clear(),this.rows.splice(this.currRow,0,t),this.logger.log(2,"Rolling up")}getDisplayText(e){e=e||!1;const t=[];let s="",i=-1;for(let r=0;r<Ne;r++){const n=this.rows[r].getTextString();n&&(i=r+1,e?t.push("Row "+i+": '"+n+"'"):t.push(n.trim()))}return t.length>0&&(e?s="["+t.join(" | ")+"]":s=t.join(`
253253-`)),s}getTextAndFormat(){return this.rows}}class nn{constructor(e,t,s){this.chNr=void 0,this.outputFilter=void 0,this.mode=void 0,this.verbose=void 0,this.displayedMemory=void 0,this.nonDisplayedMemory=void 0,this.lastOutputScreen=void 0,this.currRollUpRow=void 0,this.writeScreen=void 0,this.cueStartTime=void 0,this.logger=void 0,this.chNr=e,this.outputFilter=t,this.mode=null,this.verbose=0,this.displayedMemory=new Xs(s),this.nonDisplayedMemory=new Xs(s),this.lastOutputScreen=new Xs(s),this.currRollUpRow=this.displayedMemory.rows[Ne-1],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null,this.logger=s}reset(){this.mode=null,this.displayedMemory.reset(),this.nonDisplayedMemory.reset(),this.lastOutputScreen.reset(),this.outputFilter.reset(),this.currRollUpRow=this.displayedMemory.rows[Ne-1],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null}getHandler(){return this.outputFilter}setHandler(e){this.outputFilter=e}setPAC(e){this.writeScreen.setPAC(e)}setBkgData(e){this.writeScreen.setBkgData(e)}setMode(e){e!==this.mode&&(this.mode=e,this.logger.log(2,()=>"MODE="+e),this.mode==="MODE_POP-ON"?this.writeScreen=this.nonDisplayedMemory:(this.writeScreen=this.displayedMemory,this.writeScreen.reset()),this.mode!=="MODE_ROLL-UP"&&(this.displayedMemory.nrRollUpRows=null,this.nonDisplayedMemory.nrRollUpRows=null),this.mode=e)}insertChars(e){for(let s=0;s<e.length;s++)this.writeScreen.insertChar(e[s]);const t=this.writeScreen===this.displayedMemory?"DISP":"NON_DISP";this.logger.log(2,()=>t+": "+this.writeScreen.getDisplayText(!0)),(this.mode==="MODE_PAINT-ON"||this.mode==="MODE_ROLL-UP")&&(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"),this.mode!=="MODE_TEXT"&&(this.writeScreen.backSpace(),this.writeScreen===this.displayedMemory&&this.outputDataUpdate())}ccAOF(){}ccAON(){}ccDER(){this.logger.log(2,"DER- Delete to End of Row"),this.writeScreen.clearToEndOfRow(),this.outputDataUpdate()}ccRU(e){this.logger.log(2,"RU("+e+") - Roll Up"),this.writeScreen=this.displayedMemory,this.setMode("MODE_ROLL-UP"),this.writeScreen.setRollUpRows(e)}ccFON(){this.logger.log(2,"FON - Flash On"),this.writeScreen.setPen({flash:!0})}ccRDC(){this.logger.log(2,"RDC - Resume Direct Captioning"),this.setMode("MODE_PAINT-ON")}ccTR(){this.logger.log(2,"TR"),this.setMode("MODE_TEXT")}ccRTD(){this.logger.log(2,"RTD"),this.setMode("MODE_TEXT")}ccEDM(){this.logger.log(2,"EDM - Erase Displayed Memory"),this.displayedMemory.reset(),this.outputDataUpdate(!0)}ccCR(){this.logger.log(2,"CR - Carriage Return"),this.writeScreen.rollUp(),this.outputDataUpdate(!0)}ccENM(){this.logger.log(2,"ENM - Erase Non-displayed Memory"),this.nonDisplayedMemory.reset()}ccEOC(){if(this.logger.log(2,"EOC - End Of Caption"),this.mode==="MODE_POP-ON"){const e=this.displayedMemory;this.displayedMemory=this.nonDisplayedMemory,this.nonDisplayedMemory=e,this.writeScreen=this.nonDisplayedMemory,this.logger.log(1,()=>"DISP: "+this.displayedMemory.getDisplayText())}this.outputDataUpdate(!0)}ccTO(e){this.logger.log(2,"TO("+e+") - Tab Offset"),this.writeScreen.moveCursor(e)}ccMIDROW(e){const t={flash:!1};if(t.underline=e%2===1,t.italics=e>=46,t.italics)t.foreground="white";else{const s=Math.floor(e/2)-16,i=["white","green","blue","cyan","red","yellow","magenta"];t.foreground=i[s]}this.logger.log(2,"MIDROW: "+ne(t)),this.writeScreen.setPen(t)}outputDataUpdate(e=!1){const t=this.logger.time;t!==null&&this.outputFilter&&(this.cueStartTime===null&&!this.displayedMemory.isEmpty()?this.cueStartTime=t:this.displayedMemory.equals(this.lastOutputScreen)||(this.outputFilter.newCue(this.cueStartTime,t,this.lastOutputScreen),e&&this.outputFilter.dispatchCue&&this.outputFilter.dispatchCue(),this.cueStartTime=this.displayedMemory.isEmpty()?null:t),this.lastOutputScreen.copy(this.displayedMemory))}cueSplitAtTime(e){this.outputFilter&&(this.displayedMemory.isEmpty()||(this.outputFilter.newCue&&this.outputFilter.newCue(this.cueStartTime,e,this.displayedMemory),this.cueStartTime=e))}}class an{constructor(e,t,s){this.channels=void 0,this.currentChannel=0,this.cmdHistory=fd(),this.logger=void 0;const i=this.logger=new cd;this.channels=[null,new nn(e,t,i),new nn(e+1,s,i)]}getHandler(e){return this.channels[e].getHandler()}setHandler(e,t){this.channels[e].setHandler(t)}addData(e,t){this.logger.time=e;for(let s=0;s<t.length;s+=2){const i=t[s]&127,r=t[s+1]&127;let n=!1,o=null;if(i===0&&r===0)continue;this.logger.log(3,()=>"["+ht([t[s],t[s+1]])+"] -> ("+ht([i,r])+")");const c=this.cmdHistory;if(i>=16&&i<=31){if(ud(i,r,c)){ss(null,null,c),this.logger.log(3,()=>"Repeated command ("+ht([i,r])+") is dropped");continue}ss(i,r,this.cmdHistory),n=this.parseCmd(i,r),n||(n=this.parseMidrow(i,r)),n||(n=this.parsePAC(i,r)),n||(n=this.parseBackgroundAttributes(i,r))}else ss(null,null,c);if(!n&&(o=this.parseChars(i,r),o)){const h=this.currentChannel;h&&h>0?this.channels[h].insertChars(o):this.logger.log(2,"No channel found yet. TEXT-MODE?")}!n&&!o&&this.logger.log(2,()=>"Couldn't parse cleaned data "+ht([i,r])+" orig: "+ht([t[s],t[s+1]]))}}parseCmd(e,t){const s=(e===20||e===28||e===21||e===29)&&t>=32&&t<=47,i=(e===23||e===31)&&t>=33&&t<=35;if(!(s||i))return!1;const r=e===20||e===21||e===23?1:2,n=this.channels[r];return e===20||e===21||e===28||e===29?t===32?n.ccRCL():t===33?n.ccBS():t===34?n.ccAOF():t===35?n.ccAON():t===36?n.ccDER():t===37?n.ccRU(2):t===38?n.ccRU(3):t===39?n.ccRU(4):t===40?n.ccFON():t===41?n.ccRDC():t===42?n.ccTR():t===43?n.ccRTD():t===44?n.ccEDM():t===45?n.ccCR():t===46?n.ccENM():t===47&&n.ccEOC():n.ccTO(t-32),this.currentChannel=r,!0}parseMidrow(e,t){let s=0;if((e===17||e===25)&&t>=32&&t<=47){if(e===17?s=1:s=2,s!==this.currentChannel)return this.logger.log(0,"Mismatch channel in midrow parsing"),!1;const i=this.channels[s];return i?(i.ccMIDROW(t),this.logger.log(3,()=>"MIDROW ("+ht([e,t])+")"),!0):!1}return!1}parsePAC(e,t){let s;const i=(e>=17&&e<=23||e>=25&&e<=31)&&t>=64&&t<=127,r=(e===16||e===24)&&t>=64&&t<=95;if(!(i||r))return!1;const n=e<=23?1:2;t>=64&&t<=95?s=n===1?rd[e]:ad[e]:s=n===1?nd[e]:od[e];const o=this.channels[n];return o?(o.setPAC(this.interpretPAC(s,t)),this.currentChannel=n,!0):!1}interpretPAC(e,t){let s;const i={color:null,italics:!1,indent:null,underline:!1,row:e};return t>95?s=t-96:s=t-64,i.underline=(s&1)===1,s<=13?i.color=["white","green","blue","cyan","red","yellow","magenta","white"][Math.floor(s/2)]:s<=15?(i.italics=!0,i.color="white"):i.indent=Math.floor((s-16)/2)*4,i}parseChars(e,t){let s,i=null,r=null;if(e>=25?(s=2,r=e-8):(s=1,r=e),r>=17&&r<=19){let n;r===17?n=t+80:r===18?n=t+112:n=t+144,this.logger.log(2,()=>"Special char '"+Ua(n)+"' in channel "+s),i=[n]}else e>=32&&e<=127&&(i=t===0?[e]:[e,t]);return i&&this.logger.log(3,()=>"Char codes = "+ht(i).join(",")),i}parseBackgroundAttributes(e,t){const s=(e===16||e===24)&&t>=32&&t<=47,i=(e===23||e===31)&&t>=45&&t<=47;if(!(s||i))return!1;let r;const n={};e===16||e===24?(r=Math.floor((t-32)/2),n.background=ld[r],t%2===1&&(n.background=n.background+"_semi")):t===45?n.background="transparent":(n.foreground="black",t===47&&(n.underline=!0));const o=e<=23?1:2;return this.channels[o].setBkgData(n),!0}reset(){for(let e=0;e<Object.keys(this.channels).length;e++){const t=this.channels[e];t&&t.reset()}ss(null,null,this.cmdHistory)}cueSplitAtTime(e){for(let t=0;t<this.channels.length;t++){const s=this.channels[t];s&&s.cueSplitAtTime(e)}}}function ss(a,e,t){t.a=a,t.b=e}function ud(a,e,t){return t.a===a&&t.b===e}function fd(){return{a:null,b:null}}var Wi=function(){if(Ls!=null&&Ls.VTTCue)return self.VTTCue;const a=["","lr","rl"],e=["start","middle","end","left","right"];function t(o,c){if(typeof c!="string"||!Array.isArray(o))return!1;const l=c.toLowerCase();return~o.indexOf(l)?l:!1}function s(o){return t(a,o)}function i(o){return t(e,o)}function r(o,...c){let l=1;for(;l<arguments.length;l++){const h=arguments[l];for(const d in h)o[d]=h[d]}return o}function n(o,c,l){const h=this,d={enumerable:!0};h.hasBeenReset=!1;let u="",f=!1,g=o,y=c,p=l,E=null,T="",S=!0,v="auto",A="start",D=50,x="middle",b=50,_="middle";Object.defineProperty(h,"id",r({},d,{get:function(){return u},set:function(I){u=""+I}})),Object.defineProperty(h,"pauseOnExit",r({},d,{get:function(){return f},set:function(I){f=!!I}})),Object.defineProperty(h,"startTime",r({},d,{get:function(){return g},set:function(I){if(typeof I!="number")throw new TypeError("Start time must be set to a number.");g=I,this.hasBeenReset=!0}})),Object.defineProperty(h,"endTime",r({},d,{get:function(){return y},set:function(I){if(typeof I!="number")throw new TypeError("End time must be set to a number.");y=I,this.hasBeenReset=!0}})),Object.defineProperty(h,"text",r({},d,{get:function(){return p},set:function(I){p=""+I,this.hasBeenReset=!0}})),Object.defineProperty(h,"region",r({},d,{get:function(){return E},set:function(I){E=I,this.hasBeenReset=!0}})),Object.defineProperty(h,"vertical",r({},d,{get:function(){return T},set:function(I){const P=s(I);if(P===!1)throw new SyntaxError("An invalid or illegal string was specified.");T=P,this.hasBeenReset=!0}})),Object.defineProperty(h,"snapToLines",r({},d,{get:function(){return S},set:function(I){S=!!I,this.hasBeenReset=!0}})),Object.defineProperty(h,"line",r({},d,{get:function(){return v},set:function(I){if(typeof I!="number"&&I!=="auto")throw new SyntaxError("An invalid number or illegal string was specified.");v=I,this.hasBeenReset=!0}})),Object.defineProperty(h,"lineAlign",r({},d,{get:function(){return A},set:function(I){const P=i(I);if(!P)throw new SyntaxError("An invalid or illegal string was specified.");A=P,this.hasBeenReset=!0}})),Object.defineProperty(h,"position",r({},d,{get:function(){return D},set:function(I){if(I<0||I>100)throw new Error("Position must be between 0 and 100.");D=I,this.hasBeenReset=!0}})),Object.defineProperty(h,"positionAlign",r({},d,{get:function(){return x},set:function(I){const P=i(I);if(!P)throw new SyntaxError("An invalid or illegal string was specified.");x=P,this.hasBeenReset=!0}})),Object.defineProperty(h,"size",r({},d,{get:function(){return b},set:function(I){if(I<0||I>100)throw new Error("Size must be between 0 and 100.");b=I,this.hasBeenReset=!0}})),Object.defineProperty(h,"align",r({},d,{get:function(){return _},set:function(I){const P=i(I);if(!P)throw new SyntaxError("An invalid or illegal string was specified.");_=P,this.hasBeenReset=!0}})),h.displayState=void 0}return n.prototype.getCueAsHTML=function(){return self.WebVTT.convertCueToDOMTree(self,this.text)},n}();class gd{decode(e,t){if(!e)return"";if(typeof e!="string")throw new Error("Error - expected string data.");return decodeURIComponent(encodeURIComponent(e))}}function Ga(a){function e(s,i,r,n){return(s|0)*3600+(i|0)*60+(r|0)+parseFloat(n||0)}const t=a.match(/^(?:(\d+):)?(\d{2}):(\d{2})(\.\d+)?/);return t?parseFloat(t[2])>59?e(t[2],t[3],0,t[4]):e(t[1],t[2],t[3],t[4]):null}class md{constructor(){this.values=Object.create(null)}set(e,t){!this.get(e)&&t!==""&&(this.values[e]=t)}get(e,t,s){return s?this.has(e)?this.values[e]:t[s]:this.has(e)?this.values[e]:t}has(e){return e in this.values}alt(e,t,s){for(let i=0;i<s.length;++i)if(t===s[i]){this.set(e,t);break}}integer(e,t){/^-?\d+$/.test(t)&&this.set(e,parseInt(t,10))}percent(e,t){if(/^([\d]{1,3})(\.[\d]*)?%$/.test(t)){const s=parseFloat(t);if(s>=0&&s<=100)return this.set(e,s),!0}return!1}}function Ka(a,e,t,s){const i=s?a.split(s):[a];for(const r in i){if(typeof i[r]!="string")continue;const n=i[r].split(t);if(n.length!==2)continue;const o=n[0],c=n[1];e(o,c)}}const Si=new Wi(0,0,""),is=Si.align==="middle"?"middle":"center";function pd(a,e,t){const s=a;function i(){const o=Ga(a);if(o===null)throw new Error("Malformed timestamp: "+s);return a=a.replace(/^[^\sa-zA-Z-]+/,""),o}function r(o,c){const l=new md;Ka(o,function(u,f){let g;switch(u){case"region":for(let y=t.length-1;y>=0;y--)if(t[y].id===f){l.set(u,t[y].region);break}break;case"vertical":l.alt(u,f,["rl","lr"]);break;case"line":g=f.split(","),l.integer(u,g[0]),l.percent(u,g[0])&&l.set("snapToLines",!1),l.alt(u,g[0],["auto"]),g.length===2&&l.alt("lineAlign",g[1],["start",is,"end"]);break;case"position":g=f.split(","),l.percent(u,g[0]),g.length===2&&l.alt("positionAlign",g[1],["start",is,"end","line-left","line-right","auto"]);break;case"size":l.percent(u,f);break;case"align":l.alt(u,f,["start",is,"end","left","right"]);break}},/:/,/\s/),c.region=l.get("region",null),c.vertical=l.get("vertical","");let h=l.get("line","auto");h==="auto"&&Si.line===-1&&(h=-1),c.line=h,c.lineAlign=l.get("lineAlign","start"),c.snapToLines=l.get("snapToLines",!0),c.size=l.get("size",100),c.align=l.get("align",is);let d=l.get("position","auto");d==="auto"&&Si.position===50&&(d=c.align==="start"||c.align==="left"?0:c.align==="end"||c.align==="right"?100:50),c.position=d}function n(){a=a.replace(/^\s+/,"")}if(n(),e.startTime=i(),n(),a.slice(0,3)!=="-->")throw new Error("Malformed time stamp (time stamps must be separated by '-->'): "+s);a=a.slice(3),n(),e.endTime=i(),n(),r(a,e)}function Va(a){return a.replace(/<br(?: \/)?>/gi,`
254254-`)}class yd{constructor(){this.state="INITIAL",this.buffer="",this.decoder=new gd,this.regionList=[],this.cue=null,this.oncue=void 0,this.onparsingerror=void 0,this.onflush=void 0}parse(e){const t=this;e&&(t.buffer+=t.decoder.decode(e,{stream:!0}));function s(){let r=t.buffer,n=0;for(r=Va(r);n<r.length&&r[n]!=="\r"&&r[n]!==`
255255-`;)++n;const o=r.slice(0,n);return r[n]==="\r"&&++n,r[n]===`
256256-`&&++n,t.buffer=r.slice(n),o}function i(r){Ka(r,function(n,o){},/:/)}try{let r="";if(t.state==="INITIAL"){if(!/\r\n|\n/.test(t.buffer))return this;r=s();const o=r.match(/^()?WEBVTT([ \t].*)?$/);if(!(o!=null&&o[0]))throw new Error("Malformed WebVTT signature.");t.state="HEADER"}let n=!1;for(;t.buffer;){if(!/\r\n|\n/.test(t.buffer))return this;switch(n?n=!1:r=s(),t.state){case"HEADER":/:/.test(r)?i(r):r||(t.state="ID");continue;case"NOTE":r||(t.state="ID");continue;case"ID":if(/^NOTE($|[ \t])/.test(r)){t.state="NOTE";break}if(!r)continue;if(t.cue=new Wi(0,0,""),t.state="CUE",r.indexOf("-->")===-1){t.cue.id=r;continue}case"CUE":if(!t.cue){t.state="BADCUE";continue}try{pd(r,t.cue,t.regionList)}catch{t.cue=null,t.state="BADCUE";continue}t.state="CUETEXT";continue;case"CUETEXT":{const o=r.indexOf("-->")!==-1;if(!r||o&&(n=!0)){t.oncue&&t.cue&&t.oncue(t.cue),t.cue=null,t.state="ID";continue}if(t.cue===null)continue;t.cue.text&&(t.cue.text+=`
113113+${this.list("audiovideo")}}`}list(e){var t,s;return(t=this.queues)!=null&&t[e]||(s=this.tracks)!=null&&s[e]?`${e}: (${this.listSbInfo(e)}) ${this.listOps(e)}`:""}listSbInfo(e){var t;const s=(t=this.tracks)==null?void 0:t[e],i=s==null?void 0:s.buffer;return i?`SourceBuffer${i.updating?" updating":""}${s.ended?" ended":""}${s.ending?" ending":""}`:"none"}listOps(e){var t;return((t=this.queues)==null?void 0:t[e].map(s=>s.label).join(", "))||""}}const Cn=/(avc[1234]|hvc1|hev1|dvh[1e]|vp09|av01)(?:\.[^.,]+)+/,_o="HlsJsTrackRemovedError";class _u extends Error{constructor(e){super(e),this.name=_o}}class Iu extends Fe{constructor(e,t){super("buffer-controller",e.logger),this.hls=void 0,this.fragmentTracker=void 0,this.details=null,this._objectUrl=null,this.operationQueue=null,this.bufferCodecEventsTotal=0,this.media=null,this.mediaSource=null,this.lastMpegAudioChunk=null,this.blockedAudioAppend=null,this.lastVideoAppendEnd=0,this.appendSource=void 0,this.transferData=void 0,this.overrides=void 0,this.appendErrors={audio:0,video:0,audiovideo:0},this.tracks={},this.sourceBuffers=[[null,null],[null,null]],this._onEndStreaming=s=>{var i;this.hls&&((i=this.mediaSource)==null?void 0:i.readyState)==="open"&&this.hls.pauseBuffering()},this._onStartStreaming=s=>{this.hls&&this.hls.resumeBuffering()},this._onMediaSourceOpen=s=>{const{media:i,mediaSource:r}=this;s&&this.log("Media source opened"),!(!i||!r)&&(r.removeEventListener("sourceopen",this._onMediaSourceOpen),i.removeEventListener("emptied",this._onMediaEmptied),this.updateDuration(),this.hls.trigger(m.MEDIA_ATTACHED,{media:i,mediaSource:r}),this.mediaSource!==null&&this.checkPendingTracks())},this._onMediaSourceClose=()=>{this.log("Media source closed")},this._onMediaSourceEnded=()=>{this.log("Media source ended")},this._onMediaEmptied=()=>{const{mediaSrc:s,_objectUrl:i}=this;s!==i&&this.error(`Media element src was set while attaching MediaSource (${i} > ${s})`)},this.hls=e,this.fragmentTracker=t,this.appendSource=ql(at(e.config.preferManagedMediaSource)),this.initTracks(),this.registerListeners()}hasSourceTypes(){return Object.keys(this.tracks).length>0}destroy(){this.unregisterListeners(),this.details=null,this.lastMpegAudioChunk=this.blockedAudioAppend=null,this.transferData=this.overrides=void 0,this.operationQueue&&(this.operationQueue.destroy(),this.operationQueue=null),this.hls=this.fragmentTracker=null,this._onMediaSourceOpen=this._onMediaSourceClose=null,this._onMediaSourceEnded=null,this._onStartStreaming=this._onEndStreaming=null}registerListeners(){const{hls:e}=this;e.on(m.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(m.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(m.MANIFEST_LOADING,this.onManifestLoading,this),e.on(m.MANIFEST_PARSED,this.onManifestParsed,this),e.on(m.BUFFER_RESET,this.onBufferReset,this),e.on(m.BUFFER_APPENDING,this.onBufferAppending,this),e.on(m.BUFFER_CODECS,this.onBufferCodecs,this),e.on(m.BUFFER_EOS,this.onBufferEos,this),e.on(m.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(m.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(m.FRAG_PARSED,this.onFragParsed,this),e.on(m.FRAG_CHANGED,this.onFragChanged,this),e.on(m.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(m.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(m.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(m.MANIFEST_LOADING,this.onManifestLoading,this),e.off(m.MANIFEST_PARSED,this.onManifestParsed,this),e.off(m.BUFFER_RESET,this.onBufferReset,this),e.off(m.BUFFER_APPENDING,this.onBufferAppending,this),e.off(m.BUFFER_CODECS,this.onBufferCodecs,this),e.off(m.BUFFER_EOS,this.onBufferEos,this),e.off(m.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(m.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(m.FRAG_PARSED,this.onFragParsed,this),e.off(m.FRAG_CHANGED,this.onFragChanged,this),e.off(m.ERROR,this.onError,this)}transferMedia(){const{media:e,mediaSource:t}=this;if(!e)return null;const s={};if(this.operationQueue){const r=this.isUpdating();r||this.operationQueue.removeBlockers();const a=this.isQueued();(r||a)&&this.warn(`Transfering MediaSource with${a?" operations in queue":""}${r?" updating SourceBuffer(s)":""} ${this.operationQueue}`),this.operationQueue.destroy()}const i=this.transferData;return!this.sourceBufferCount&&i&&i.mediaSource===t?re(s,i.tracks):this.sourceBuffers.forEach(r=>{const[a]=r;a&&(s[a]=re({},this.tracks[a]),this.removeBuffer(a)),r[0]=r[1]=null}),{media:e,mediaSource:t,tracks:s}}initTracks(){const e={};this.sourceBuffers=[[null,null],[null,null]],this.tracks=e,this.resetQueue(),this.resetAppendErrors(),this.lastMpegAudioChunk=this.blockedAudioAppend=null,this.lastVideoAppendEnd=0}onManifestLoading(){this.bufferCodecEventsTotal=0,this.details=null}onManifestParsed(e,t){var s;let i=2;(t.audio&&!t.video||!t.altAudio)&&(i=1),this.bufferCodecEventsTotal=i,this.log(`${i} bufferCodec event(s) expected.`),(s=this.transferData)!=null&&s.mediaSource&&this.sourceBufferCount&&i&&this.bufferCreated()}onMediaAttaching(e,t){const s=this.media=t.media;this.transferData=this.overrides=void 0;const i=at(this.appendSource);if(i){const r=!!t.mediaSource;(r||t.overrides)&&(this.transferData=t,this.overrides=t.overrides);const a=this.mediaSource=t.mediaSource||new i;if(this.assignMediaSource(a),r)this._objectUrl=s.src,this.attachTransferred();else{const o=this._objectUrl=self.URL.createObjectURL(a);if(this.appendSource)try{s.removeAttribute("src");const c=self.ManagedMediaSource;s.disableRemotePlayback=s.disableRemotePlayback||c&&a instanceof c,Pn(s),Lu(s,o),s.load()}catch{s.src=o}else s.src=o}s.addEventListener("emptied",this._onMediaEmptied)}}assignMediaSource(e){var t,s;this.log(`${((t=this.transferData)==null?void 0:t.mediaSource)===e?"transferred":"created"} media source: ${(s=e.constructor)==null?void 0:s.name}`),e.addEventListener("sourceopen",this._onMediaSourceOpen),e.addEventListener("sourceended",this._onMediaSourceEnded),e.addEventListener("sourceclose",this._onMediaSourceClose),this.appendSource&&(e.addEventListener("startstreaming",this._onStartStreaming),e.addEventListener("endstreaming",this._onEndStreaming))}attachTransferred(){const e=this.media,t=this.transferData;if(!t||!e)return;const s=this.tracks,i=t.tracks,r=i?Object.keys(i):null,a=r?r.length:0,o=()=>{Promise.resolve().then(()=>{this.media&&this.mediaSourceOpenOrEnded&&this._onMediaSourceOpen()})};if(i&&r&&a){if(!this.tracksReady){this.hls.config.startFragPrefetch=!0,this.log("attachTransferred: waiting for SourceBuffer track info");return}if(this.log(`attachTransferred: (bufferCodecEventsTotal ${this.bufferCodecEventsTotal})
114114+required tracks: ${oe(s,(c,l)=>c==="initSegment"?void 0:l)};
115115+transfer tracks: ${oe(i,(c,l)=>c==="initSegment"?void 0:l)}}`),!Ta(i,s)){t.mediaSource=null,t.tracks=void 0;const c=e.currentTime,l=this.details,h=Math.max(c,(l==null?void 0:l.fragments[0].start)||0);if(h-c>1){this.log(`attachTransferred: waiting for playback to reach new tracks start time ${c} -> ${h}`);return}this.warn(`attachTransferred: resetting MediaSource for incompatible tracks ("${Object.keys(i)}"->"${Object.keys(s)}") start time: ${h} currentTime: ${c}`),this.onMediaDetaching(m.MEDIA_DETACHING,{}),this.onMediaAttaching(m.MEDIA_ATTACHING,t),e.currentTime=h;return}this.transferData=void 0,r.forEach(c=>{const l=c,h=i[l];if(h){const u=h.buffer;if(u){const d=this.fragmentTracker,f=h.id;if(d.hasFragments(f)||d.hasParts(f)){const y=q.getBuffered(u);d.detectEvictedFragments(l,y,f,null,!0)}const g=ni(l),p=[l,u];this.sourceBuffers[g]=p,u.updating&&this.operationQueue&&this.operationQueue.prependBlocker(l),this.trackSourceBuffer(l,h)}}}),o(),this.bufferCreated()}else this.log("attachTransferred: MediaSource w/o SourceBuffers"),o()}get mediaSourceOpenOrEnded(){var e;const t=(e=this.mediaSource)==null?void 0:e.readyState;return t==="open"||t==="ended"}onMediaDetaching(e,t){const s=!!t.transferMedia;this.transferData=this.overrides=void 0;const{media:i,mediaSource:r,_objectUrl:a}=this;if(r){if(this.log(`media source ${s?"transferring":"detaching"}`),s)this.sourceBuffers.forEach(([o])=>{o&&this.removeBuffer(o)}),this.resetQueue();else{if(this.mediaSourceOpenOrEnded){const o=r.readyState==="open";try{const c=r.sourceBuffers;for(let l=c.length;l--;)o&&c[l].abort(),r.removeSourceBuffer(c[l]);o&&r.endOfStream()}catch(c){this.warn(`onMediaDetaching: ${c.message} while calling endOfStream`)}}this.sourceBufferCount&&this.onBufferReset()}r.removeEventListener("sourceopen",this._onMediaSourceOpen),r.removeEventListener("sourceended",this._onMediaSourceEnded),r.removeEventListener("sourceclose",this._onMediaSourceClose),this.appendSource&&(r.removeEventListener("startstreaming",this._onStartStreaming),r.removeEventListener("endstreaming",this._onEndStreaming)),this.mediaSource=null,this._objectUrl=null}i&&(i.removeEventListener("emptied",this._onMediaEmptied),s||(a&&self.URL.revokeObjectURL(a),this.mediaSrc===a?(i.removeAttribute("src"),this.appendSource&&Pn(i),i.load()):this.warn("media|source.src was changed by a third party - skip cleanup")),this.media=null),this.hls.trigger(m.MEDIA_DETACHED,t)}onBufferReset(){this.sourceBuffers.forEach(([e])=>{e&&this.resetBuffer(e)}),this.initTracks()}resetBuffer(e){var t;const s=(t=this.tracks[e])==null?void 0:t.buffer;if(this.removeBuffer(e),s)try{var i;(i=this.mediaSource)!=null&&i.sourceBuffers.length&&this.mediaSource.removeSourceBuffer(s)}catch(r){this.warn(`onBufferReset ${e}`,r)}delete this.tracks[e]}removeBuffer(e){this.removeBufferListeners(e),this.sourceBuffers[ni(e)]=[null,null];const t=this.tracks[e];t&&(t.buffer=void 0)}resetQueue(){this.operationQueue&&this.operationQueue.destroy(),this.operationQueue=new Au(this.tracks)}onBufferCodecs(e,t){var s;const i=this.tracks,r=Object.keys(t);this.log(`BUFFER_CODECS: "${r}" (current SB count ${this.sourceBufferCount})`);const a="audiovideo"in t&&(i.audio||i.video)||i.audiovideo&&("audio"in t||"video"in t),o=!a&&this.sourceBufferCount&&this.media&&r.some(c=>!i[c]);if(a||o){this.warn(`Unsupported transition between "${Object.keys(i)}" and "${r}" SourceBuffers`);return}r.forEach(c=>{var l,h;const u=t[c],{id:d,codec:f,levelCodec:g,container:p,metadata:y,supplemental:E}=u;let T=i[c];const S=(l=this.transferData)==null||(l=l.tracks)==null?void 0:l[c],v=S!=null&&S.buffer?S:T,x=(v==null?void 0:v.pendingCodec)||(v==null?void 0:v.codec),D=v==null?void 0:v.levelCodec;T||(T=i[c]={buffer:void 0,listeners:[],codec:f,supplemental:E,container:p,levelCodec:g,metadata:y,id:d});const A=ms(x,D),b=A==null?void 0:A.replace(Cn,"$1");let I=ms(f,g);const _=(h=I)==null?void 0:h.replace(Cn,"$1");I&&A&&b!==_&&(c.slice(0,5)==="audio"&&(I=Ds(I,this.appendSource)),this.log(`switching codec ${x} to ${I}`),I!==(T.pendingCodec||T.codec)&&(T.pendingCodec=I),T.container=p,this.appendChangeType(c,p,I))}),(this.tracksReady||this.sourceBufferCount)&&(t.tracks=this.sourceBufferTracks),!this.sourceBufferCount&&(this.bufferCodecEventsTotal>1&&!this.tracks.video&&!t.video&&((s=t.audio)==null?void 0:s.id)==="main"&&(this.log("Main audio-only"),this.bufferCodecEventsTotal=1),this.mediaSourceOpenOrEnded&&this.checkPendingTracks())}get sourceBufferTracks(){return Object.keys(this.tracks).reduce((e,t)=>{const s=this.tracks[t];return e[t]={id:s.id,container:s.container,codec:s.codec,levelCodec:s.levelCodec},e},{})}appendChangeType(e,t,s){const i=`${t};codecs=${s}`,r={label:`change-type=${i}`,execute:()=>{const a=this.tracks[e];if(a){const o=a.buffer;o!=null&&o.changeType&&(this.log(`changing ${e} sourceBuffer type to ${i}`),o.changeType(i),a.codec=s,a.container=t)}this.shiftAndExecuteNext(e)},onStart:()=>{},onComplete:()=>{},onError:a=>{this.warn(`Failed to change ${e} SourceBuffer type`,a)}};this.append(r,e,this.isPending(this.tracks[e]))}blockAudio(e){var t;const s=e.start,i=s+e.duration*.05;if(((t=this.fragmentTracker.getAppendedFrag(s,U.MAIN))==null?void 0:t.gap)===!0)return;const a={label:"block-audio",execute:()=>{var o;const c=this.tracks.video;(this.lastVideoAppendEnd>i||c!=null&&c.buffer&&q.isBuffered(c.buffer,i)||((o=this.fragmentTracker.getAppendedFrag(i,U.MAIN))==null?void 0:o.gap)===!0)&&(this.blockedAudioAppend=null,this.shiftAndExecuteNext("audio"))},onStart:()=>{},onComplete:()=>{},onError:o=>{this.warn("Error executing block-audio operation",o)}};this.blockedAudioAppend={op:a,frag:e},this.append(a,"audio",!0)}unblockAudio(){const{blockedAudioAppend:e,operationQueue:t}=this;e&&t&&(this.blockedAudioAppend=null,t.unblockAudio(e.op))}onBufferAppending(e,t){const{tracks:s}=this,{data:i,type:r,parent:a,frag:o,part:c,chunkMeta:l,offset:h}=t,u=l.buffering[r],{sn:d,cc:f}=o,g=self.performance.now();u.start=g;const p=o.stats.buffering,y=c?c.stats.buffering:null;p.start===0&&(p.start=g),y&&y.start===0&&(y.start=g);const E=s.audio;let T=!1;r==="audio"&&(E==null?void 0:E.container)==="audio/mpeg"&&(T=!this.lastMpegAudioChunk||l.id===1||this.lastMpegAudioChunk.sn!==l.sn,this.lastMpegAudioChunk=l);const S=s.video,v=S==null?void 0:S.buffer;if(v&&d!=="initSegment"){const A=c||o,b=this.blockedAudioAppend;if(r==="audio"&&a!=="main"&&!this.blockedAudioAppend&&!(S.ending||S.ended)){const _=A.start+A.duration*.05,C=v.buffered,k=this.currentOp("video");!C.length&&!k?this.blockAudio(A):!k&&!q.isBuffered(v,_)&&this.lastVideoAppendEnd<_&&this.blockAudio(A)}else if(r==="video"){const I=A.end;if(b){const _=b.frag.start;(I>_||I<this.lastVideoAppendEnd||q.isBuffered(v,_))&&this.unblockAudio()}this.lastVideoAppendEnd=I}}const x=(c||o).start,D={label:`append-${r}`,execute:()=>{var A;u.executeStart=self.performance.now();const b=(A=this.tracks[r])==null?void 0:A.buffer;b&&(T?this.updateTimestampOffset(b,x,.1,r,d,f):h!==void 0&&M(h)&&this.updateTimestampOffset(b,h,1e-6,r,d,f)),this.appendExecutor(i,r)},onStart:()=>{},onComplete:()=>{const A=self.performance.now();u.executeEnd=u.end=A,p.first===0&&(p.first=A),y&&y.first===0&&(y.first=A);const b={};this.sourceBuffers.forEach(([I,_])=>{I&&(b[I]=q.getBuffered(_))}),this.appendErrors[r]=0,r==="audio"||r==="video"?this.appendErrors.audiovideo=0:(this.appendErrors.audio=0,this.appendErrors.video=0),this.hls.trigger(m.BUFFER_APPENDED,{type:r,frag:o,part:c,chunkMeta:l,parent:o.type,timeRanges:b})},onError:A=>{var b;const I={type:H.MEDIA_ERROR,parent:o.type,details:R.BUFFER_APPEND_ERROR,sourceBufferName:r,frag:o,part:c,chunkMeta:l,error:A,err:A,fatal:!1},_=(b=this.media)==null?void 0:b.error;if(A.code===DOMException.QUOTA_EXCEEDED_ERR||A.name=="QuotaExceededError"||"quota"in A)I.details=R.BUFFER_FULL_ERROR;else if(A.code===DOMException.INVALID_STATE_ERR&&this.mediaSourceOpenOrEnded&&!_)I.errorAction=_t(!0);else if(A.name===_o&&this.sourceBufferCount===0)I.errorAction=_t(!0);else{const C=++this.appendErrors[r];this.warn(`Failed ${C}/${this.hls.config.appendErrorMaxRetry} times to append segment in "${r}" sourceBuffer (${_||"no media error"})`),(C>=this.hls.config.appendErrorMaxRetry||_)&&(I.fatal=!0)}this.hls.trigger(m.ERROR,I)}};this.log(`queuing "${r}" append sn: ${d}${c?" p: "+c.index:""} of ${o.type===U.MAIN?"level":"track"} ${o.level} cc: ${f}`),this.append(D,r,this.isPending(this.tracks[r]))}getFlushOp(e,t,s){return this.log(`queuing "${e}" remove ${t}-${s}`),{label:"remove",execute:()=>{this.removeExecutor(e,t,s)},onStart:()=>{},onComplete:()=>{this.hls.trigger(m.BUFFER_FLUSHED,{type:e})},onError:i=>{this.warn(`Failed to remove ${t}-${s} from "${e}" SourceBuffer`,i)}}}onBufferFlushing(e,t){const{type:s,startOffset:i,endOffset:r}=t;s?this.append(this.getFlushOp(s,i,r),s):this.sourceBuffers.forEach(([a])=>{a&&this.append(this.getFlushOp(a,i,r),a)})}onFragParsed(e,t){const{frag:s,part:i}=t,r=[],a=i?i.elementaryStreams:s.elementaryStreams;a[ne.AUDIOVIDEO]?r.push("audiovideo"):(a[ne.AUDIO]&&r.push("audio"),a[ne.VIDEO]&&r.push("video"));const o=()=>{const c=self.performance.now();s.stats.buffering.end=c,i&&(i.stats.buffering.end=c);const l=i?i.stats:s.stats;this.hls.trigger(m.FRAG_BUFFERED,{frag:s,part:i,stats:l,id:s.type})};r.length===0&&this.warn(`Fragments must have at least one ElementaryStreamType set. type: ${s.type} level: ${s.level} sn: ${s.sn}`),this.blockBuffers(o,r).catch(c=>{this.warn(`Fragment buffered callback ${c}`),this.stepOperationQueue(this.sourceBufferTypes)})}onFragChanged(e,t){this.trimBuffers()}get bufferedToEnd(){return this.sourceBufferCount>0&&!this.sourceBuffers.some(([e])=>{if(e){const t=this.tracks[e];if(t)return!t.ended||t.ending}return!1})}onBufferEos(e,t){var s;this.sourceBuffers.forEach(([a])=>{if(a){const o=this.tracks[a];(!t.type||t.type===a)&&(o.ending=!0,o.ended||(o.ended=!0,this.log(`${a} buffer reached EOS`)))}});const i=((s=this.overrides)==null?void 0:s.endOfStream)!==!1;this.sourceBufferCount>0&&!this.sourceBuffers.some(([a])=>{var o;return a&&!((o=this.tracks[a])!=null&&o.ended)})?i?(this.log("Queueing EOS"),this.blockUntilOpen(()=>{this.tracksEnded();const{mediaSource:a}=this;if(!a||a.readyState!=="open"){a&&this.log(`Could not call mediaSource.endOfStream(). mediaSource.readyState: ${a.readyState}`);return}this.log("Calling mediaSource.endOfStream()"),a.endOfStream(),this.hls.trigger(m.BUFFERED_TO_END,void 0)})):(this.tracksEnded(),this.hls.trigger(m.BUFFERED_TO_END,void 0)):t.type==="video"&&this.unblockAudio()}tracksEnded(){this.sourceBuffers.forEach(([e])=>{if(e!==null){const t=this.tracks[e];t&&(t.ending=!1)}})}onLevelUpdated(e,{details:t}){t.fragments.length&&(this.details=t,this.updateDuration())}updateDuration(){this.blockUntilOpen(()=>{const e=this.getDurationAndRange();e&&this.updateMediaSource(e)})}onError(e,t){if(t.details===R.BUFFER_APPEND_ERROR&&t.frag){var s;const i=(s=t.errorAction)==null?void 0:s.nextAutoLevel;M(i)&&i!==t.frag.level&&this.resetAppendErrors()}}resetAppendErrors(){this.appendErrors={audio:0,video:0,audiovideo:0}}trimBuffers(){const{hls:e,details:t,media:s}=this;if(!s||t===null||!this.sourceBufferCount)return;const i=e.config,r=s.currentTime,a=t.levelTargetDuration,o=t.live&&i.liveBackBufferLength!==null?i.liveBackBufferLength:i.backBufferLength;if(M(o)&&o>=0){const l=Math.max(o,a),h=Math.floor(r/a)*a-l;this.flushBackBuffer(r,a,h)}const c=i.frontBufferFlushThreshold;if(M(c)&&c>0){const l=Math.max(i.maxBufferLength,c),h=Math.max(l,a),u=Math.floor(r/a)*a+h;this.flushFrontBuffer(r,a,u)}}flushBackBuffer(e,t,s){this.sourceBuffers.forEach(([i,r])=>{if(r){const o=q.getBuffered(r);if(o.length>0&&s>o.start(0)){var a;this.hls.trigger(m.BACK_BUFFER_REACHED,{bufferEnd:s});const c=this.tracks[i];if((a=this.details)!=null&&a.live)this.hls.trigger(m.LIVE_BACK_BUFFER_REACHED,{bufferEnd:s});else if(c!=null&&c.ended){this.log(`Cannot flush ${i} back buffer while SourceBuffer is in ended state`);return}this.hls.trigger(m.BUFFER_FLUSHING,{startOffset:0,endOffset:s,type:i})}}})}flushFrontBuffer(e,t,s){this.sourceBuffers.forEach(([i,r])=>{if(r){const a=q.getBuffered(r),o=a.length;if(o<2)return;const c=a.start(o-1),l=a.end(o-1);if(s>c||e>=c&&e<=l)return;this.hls.trigger(m.BUFFER_FLUSHING,{startOffset:c,endOffset:1/0,type:i})}})}getDurationAndRange(){var e;const{details:t,mediaSource:s}=this;if(!t||!this.media||(s==null?void 0:s.readyState)!=="open")return null;const i=t.edge;if(t.live&&this.hls.config.liveDurationInfinity){if(t.fragments.length&&s.setLiveSeekableRange){const l=Math.max(0,t.fragmentStart),h=Math.max(l,i);return{duration:1/0,start:l,end:h}}return{duration:1/0}}const r=(e=this.overrides)==null?void 0:e.duration;if(r)return M(r)?{duration:r}:null;const a=this.media.duration,o=M(s.duration)?s.duration:0;return i>o&&i>a||!M(a)?{duration:i}:null}updateMediaSource({duration:e,start:t,end:s}){const i=this.mediaSource;!this.media||!i||i.readyState!=="open"||(i.duration!==e&&(M(e)&&this.log(`Updating MediaSource duration to ${e.toFixed(3)}`),i.duration=e),t!==void 0&&s!==void 0&&(this.log(`MediaSource duration is set to ${i.duration}. Setting seekable range to ${t}-${s}.`),i.setLiveSeekableRange(t,s)))}get tracksReady(){const e=this.pendingTrackCount;return e>0&&(e>=this.bufferCodecEventsTotal||this.isPending(this.tracks.audiovideo))}checkPendingTracks(){const{bufferCodecEventsTotal:e,pendingTrackCount:t,tracks:s}=this;if(this.log(`checkPendingTracks (pending: ${t} codec events expected: ${e}) ${oe(s)}`),this.tracksReady){var i;const r=(i=this.transferData)==null?void 0:i.tracks;r&&Object.keys(r).length?this.attachTransferred():this.createSourceBuffers()}}bufferCreated(){if(this.sourceBufferCount){const e={};this.sourceBuffers.forEach(([t,s])=>{if(t){const i=this.tracks[t];e[t]={buffer:s,container:i.container,codec:i.codec,supplemental:i.supplemental,levelCodec:i.levelCodec,id:i.id,metadata:i.metadata}}}),this.hls.trigger(m.BUFFER_CREATED,{tracks:e}),this.log(`SourceBuffers created. Running queue: ${this.operationQueue}`),this.sourceBuffers.forEach(([t])=>{this.executeNext(t)})}else{const e=new Error("could not create source buffer for media codec(s)");this.hls.trigger(m.ERROR,{type:H.MEDIA_ERROR,details:R.BUFFER_INCOMPATIBLE_CODECS_ERROR,fatal:!0,error:e,reason:e.message})}}createSourceBuffers(){const{tracks:e,sourceBuffers:t,mediaSource:s}=this;if(!s)throw new Error("createSourceBuffers called when mediaSource was null");for(const r in e){const a=r,o=e[a];if(this.isPending(o)){const c=this.getTrackCodec(o,a),l=`${o.container};codecs=${c}`;o.codec=c,this.log(`creating sourceBuffer(${l})${this.currentOp(a)?" Queued":""} ${oe(o)}`);try{const h=s.addSourceBuffer(l),u=ni(a),d=[a,h];t[u]=d,o.buffer=h}catch(h){var i;this.error(`error while trying to add sourceBuffer: ${h.message}`),this.shiftAndExecuteNext(a),(i=this.operationQueue)==null||i.removeBlockers(),delete this.tracks[a],this.hls.trigger(m.ERROR,{type:H.MEDIA_ERROR,details:R.BUFFER_ADD_CODEC_ERROR,fatal:!1,error:h,sourceBufferName:a,mimeType:l,parent:o.id});return}this.trackSourceBuffer(a,o)}}this.bufferCreated()}getTrackCodec(e,t){const s=e.supplemental;let i=e.codec;s&&(t==="video"||t==="audiovideo")&&$t(s,"video")&&(i=mc(i,s));const r=ms(i,e.levelCodec);return r?t.slice(0,5)==="audio"?Ds(r,this.appendSource):r:""}trackSourceBuffer(e,t){const s=t.buffer;if(!s)return;const i=this.getTrackCodec(t,e);this.tracks[e]={buffer:s,codec:i,container:t.container,levelCodec:t.levelCodec,supplemental:t.supplemental,metadata:t.metadata,id:t.id,listeners:[]},this.removeBufferListeners(e),this.addBufferListener(e,"updatestart",this.onSBUpdateStart),this.addBufferListener(e,"updateend",this.onSBUpdateEnd),this.addBufferListener(e,"error",this.onSBUpdateError),this.appendSource&&this.addBufferListener(e,"bufferedchange",(r,a)=>{const o=a.removedRanges;o!=null&&o.length&&this.hls.trigger(m.BUFFER_FLUSHED,{type:r})})}get mediaSrc(){var e,t;const s=((e=this.media)==null||(t=e.querySelector)==null?void 0:t.call(e,"source"))||this.media;return s==null?void 0:s.src}onSBUpdateStart(e){const t=this.currentOp(e);t&&t.onStart()}onSBUpdateEnd(e){var t;if(((t=this.mediaSource)==null?void 0:t.readyState)==="closed"){this.resetBuffer(e);return}const s=this.currentOp(e);s&&(s.onComplete(),this.shiftAndExecuteNext(e))}onSBUpdateError(e,t){var s;const i=new Error(`${e} SourceBuffer error. MediaSource readyState: ${(s=this.mediaSource)==null?void 0:s.readyState}`);this.error(`${i}`,t),this.hls.trigger(m.ERROR,{type:H.MEDIA_ERROR,details:R.BUFFER_APPENDING_ERROR,sourceBufferName:e,error:i,fatal:!1});const r=this.currentOp(e);r&&r.onError(i)}updateTimestampOffset(e,t,s,i,r,a){const o=t-e.timestampOffset;Math.abs(o)>=s&&(this.log(`Updating ${i} SourceBuffer timestampOffset to ${t} (sn: ${r} cc: ${a})`),e.timestampOffset=t)}removeExecutor(e,t,s){const{media:i,mediaSource:r}=this,a=this.tracks[e],o=a==null?void 0:a.buffer;if(!i||!r||!o){this.warn(`Attempting to remove from the ${e} SourceBuffer, but it does not exist`),this.shiftAndExecuteNext(e);return}const c=M(i.duration)?i.duration:1/0,l=M(r.duration)?r.duration:1/0,h=Math.max(0,t),u=Math.min(s,c,l);u>h&&(!a.ending||a.ended)?(a.ended=!1,this.log(`Removing [${h},${u}] from the ${e} SourceBuffer`),o.remove(h,u)):this.shiftAndExecuteNext(e)}appendExecutor(e,t){const s=this.tracks[t],i=s==null?void 0:s.buffer;if(!i)throw new _u(`Attempting to append to the ${t} SourceBuffer, but it does not exist`);s.ending=!1,s.ended=!1,i.appendBuffer(e)}blockUntilOpen(e){if(this.isUpdating()||this.isQueued())this.blockBuffers(e).catch(t=>{this.warn(`SourceBuffer blocked callback ${t}`),this.stepOperationQueue(this.sourceBufferTypes)});else try{e()}catch(t){this.warn(`Callback run without blocking ${this.operationQueue} ${t}`)}}isUpdating(){return this.sourceBuffers.some(([e,t])=>e&&t.updating)}isQueued(){return this.sourceBuffers.some(([e])=>e&&!!this.currentOp(e))}isPending(e){return!!e&&!e.buffer}blockBuffers(e,t=this.sourceBufferTypes){if(!t.length)return this.log("Blocking operation requested, but no SourceBuffers exist"),Promise.resolve().then(e);const{operationQueue:s}=this,i=t.map(a=>this.appendBlocker(a));return t.length>1&&!!this.blockedAudioAppend&&this.unblockAudio(),Promise.all(i).then(a=>{s===this.operationQueue&&(e(),this.stepOperationQueue(this.sourceBufferTypes))})}stepOperationQueue(e){e.forEach(t=>{var s;const i=(s=this.tracks[t])==null?void 0:s.buffer;!i||i.updating||this.shiftAndExecuteNext(t)})}append(e,t,s){this.operationQueue&&this.operationQueue.append(e,t,s)}appendBlocker(e){if(this.operationQueue)return this.operationQueue.appendBlocker(e)}currentOp(e){return this.operationQueue?this.operationQueue.current(e):null}executeNext(e){e&&this.operationQueue&&this.operationQueue.executeNext(e)}shiftAndExecuteNext(e){this.operationQueue&&this.operationQueue.shiftAndExecuteNext(e)}get pendingTrackCount(){return Object.keys(this.tracks).reduce((e,t)=>e+(this.isPending(this.tracks[t])?1:0),0)}get sourceBufferCount(){return this.sourceBuffers.reduce((e,[t])=>e+(t?1:0),0)}get sourceBufferTypes(){return this.sourceBuffers.map(([e])=>e).filter(e=>!!e)}addBufferListener(e,t,s){const i=this.tracks[e];if(!i)return;const r=i.buffer;if(!r)return;const a=s.bind(this,e);i.listeners.push({event:t,listener:a}),r.addEventListener(t,a)}removeBufferListeners(e){const t=this.tracks[e];if(!t)return;const s=t.buffer;s&&(t.listeners.forEach(i=>{s.removeEventListener(i.event,i.listener)}),t.listeners.length=0)}}function Pn(n){const e=n.querySelectorAll("source");[].slice.call(e).forEach(t=>{n.removeChild(t)})}function Lu(n,e){const t=self.document.createElement("source");t.type="video/mp4",t.src=e,n.appendChild(t)}function ni(n){return n==="audio"?1:0}class ur{constructor(e){this.hls=void 0,this.autoLevelCapping=void 0,this.firstLevel=void 0,this.media=void 0,this.restrictedLevels=void 0,this.timer=void 0,this.clientRect=void 0,this.streamController=void 0,this.hls=e,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.firstLevel=-1,this.media=null,this.restrictedLevels=[],this.timer=void 0,this.clientRect=null,this.registerListeners()}setStreamController(e){this.streamController=e}destroy(){this.hls&&this.unregisterListener(),this.timer&&this.stopCapping(),this.media=null,this.clientRect=null,this.hls=this.streamController=null}registerListeners(){const{hls:e}=this;e.on(m.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.on(m.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(m.MANIFEST_PARSED,this.onManifestParsed,this),e.on(m.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(m.BUFFER_CODECS,this.onBufferCodecs,this),e.on(m.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListener(){const{hls:e}=this;e.off(m.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.off(m.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(m.MANIFEST_PARSED,this.onManifestParsed,this),e.off(m.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(m.BUFFER_CODECS,this.onBufferCodecs,this),e.off(m.MEDIA_DETACHING,this.onMediaDetaching,this)}onFpsDropLevelCapping(e,t){const s=this.hls.levels[t.droppedLevel];this.isLevelAllowed(s)&&this.restrictedLevels.push({bitrate:s.bitrate,height:s.height,width:s.width})}onMediaAttaching(e,t){this.media=t.media instanceof HTMLVideoElement?t.media:null,this.clientRect=null,this.timer&&this.hls.levels.length&&this.detectPlayerSize()}onManifestParsed(e,t){const s=this.hls;this.restrictedLevels=[],this.firstLevel=t.firstLevel,s.config.capLevelToPlayerSize&&t.video&&this.startCapping()}onLevelsUpdated(e,t){this.timer&&M(this.autoLevelCapping)&&this.detectPlayerSize()}onBufferCodecs(e,t){this.hls.config.capLevelToPlayerSize&&t.video&&this.startCapping()}onMediaDetaching(){this.stopCapping(),this.media=null}detectPlayerSize(){if(this.media){if(this.mediaHeight<=0||this.mediaWidth<=0){this.clientRect=null;return}const e=this.hls.levels;if(e.length){const t=this.hls,s=this.getMaxLevel(e.length-1);s!==this.autoLevelCapping&&t.logger.log(`Setting autoLevelCapping to ${s}: ${e[s].height}p@${e[s].bitrate} for media ${this.mediaWidth}x${this.mediaHeight}`),t.autoLevelCapping=s,t.autoLevelEnabled&&t.autoLevelCapping>this.autoLevelCapping&&this.streamController&&this.streamController.nextLevelSwitch(),this.autoLevelCapping=t.autoLevelCapping}}}getMaxLevel(e){const t=this.hls.levels;if(!t.length)return-1;const s=t.filter((i,r)=>this.isLevelAllowed(i)&&r<=e);return this.clientRect=null,ur.getMaxLevelByMediaSize(s,this.mediaWidth,this.mediaHeight)}startCapping(){this.timer||(this.autoLevelCapping=Number.POSITIVE_INFINITY,self.clearInterval(this.timer),this.timer=self.setInterval(this.detectPlayerSize.bind(this),1e3),this.detectPlayerSize())}stopCapping(){this.restrictedLevels=[],this.firstLevel=-1,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.timer&&(self.clearInterval(this.timer),this.timer=void 0)}getDimensions(){if(this.clientRect)return this.clientRect;const e=this.media,t={width:0,height:0};if(e){const s=e.getBoundingClientRect();t.width=s.width,t.height=s.height,!t.width&&!t.height&&(t.width=s.right-s.left||e.width||0,t.height=s.bottom-s.top||e.height||0)}return this.clientRect=t,t}get mediaWidth(){return this.getDimensions().width*this.contentScaleFactor}get mediaHeight(){return this.getDimensions().height*this.contentScaleFactor}get contentScaleFactor(){let e=1;if(!this.hls.config.ignoreDevicePixelRatio)try{e=self.devicePixelRatio}catch{}return Math.min(e,this.hls.config.maxDevicePixelRatio)}isLevelAllowed(e){return!this.restrictedLevels.some(s=>e.bitrate===s.bitrate&&e.width===s.width&&e.height===s.height)}static getMaxLevelByMediaSize(e,t,s){if(!(e!=null&&e.length))return-1;const i=(o,c)=>c?o.width!==c.width||o.height!==c.height:!0;let r=e.length-1;const a=Math.max(t,s);for(let o=0;o<e.length;o+=1){const c=e[o];if((c.width>=a||c.height>=a)&&i(c,e[o+1])){r=o;break}}return r}}const Ru={MANIFEST:"m",AUDIO:"a",VIDEO:"v",MUXED:"av",INIT:"i",CAPTION:"c",TIMED_TEXT:"tt",KEY:"k",OTHER:"o"},_e=Ru,bu={HLS:"h"},Du=bu;class Ye{constructor(e,t){Array.isArray(e)&&(e=e.map(s=>s instanceof Ye?s:new Ye(s))),this.value=e,this.params=t}}const Cu="Dict";function Pu(n){return Array.isArray(n)?JSON.stringify(n):n instanceof Map?"Map{}":n instanceof Set?"Set{}":typeof n=="object"?JSON.stringify(n):String(n)}function ku(n,e,t,s){return new Error(`failed to ${n} "${Pu(e)}" as ${t}`,{cause:s})}function qe(n,e,t){return ku("serialize",n,e,t)}class Io{constructor(e){this.description=e}}const kn="Bare Item",wu="Boolean";function Ou(n){if(typeof n!="boolean")throw qe(n,wu);return n?"?1":"?0"}function Fu(n){return btoa(String.fromCharCode(...n))}const Mu="Byte Sequence";function Nu(n){if(ArrayBuffer.isView(n)===!1)throw qe(n,Mu);return`:${Fu(n)}:`}const Bu="Integer";function Uu(n){return n<-999999999999999||999999999999999<n}function Lo(n){if(Uu(n))throw qe(n,Bu);return n.toString()}function $u(n){return`@${Lo(n.getTime()/1e3)}`}function Ro(n,e){if(n<0)return-Ro(-n,e);const t=Math.pow(10,e);if(Math.abs(n*t%1-.5)<Number.EPSILON){const i=Math.floor(n*t);return(i%2===0?i:i+1)/t}else return Math.round(n*t)/t}const Gu="Decimal";function Ku(n){const e=Ro(n,3);if(Math.floor(Math.abs(e)).toString().length>12)throw qe(n,Gu);const t=e.toString();return t.includes(".")?t:`${t}.0`}const Vu="String",Hu=/[\x00-\x1f\x7f]+/;function Wu(n){if(Hu.test(n))throw qe(n,Vu);return`"${n.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}function Yu(n){return n.description||n.toString().slice(7,-1)}const qu="Token";function wn(n){const e=Yu(n);if(/^([a-zA-Z*])([!#$%&'*+\-.^_`|~\w:/]*)$/.test(e)===!1)throw qe(e,qu);return e}function Fi(n){switch(typeof n){case"number":if(!M(n))throw qe(n,kn);return Number.isInteger(n)?Lo(n):Ku(n);case"string":return Wu(n);case"symbol":return wn(n);case"boolean":return Ou(n);case"object":if(n instanceof Date)return $u(n);if(n instanceof Uint8Array)return Nu(n);if(n instanceof Io)return wn(n);default:throw qe(n,kn)}}const ju="Key";function Mi(n){if(/^[a-z*][a-z0-9\-_.*]*$/.test(n)===!1)throw qe(n,ju);return n}function dr(n){return n==null?"":Object.entries(n).map(([e,t])=>t===!0?`;${Mi(e)}`:`;${Mi(e)}=${Fi(t)}`).join("")}function bo(n){return n instanceof Ye?`${Fi(n.value)}${dr(n.params)}`:Fi(n)}function Xu(n){return`(${n.value.map(bo).join(" ")})${dr(n.params)}`}function zu(n,e={whitespace:!0}){if(typeof n!="object"||n==null)throw qe(n,Cu);const t=n instanceof Map?n.entries():Object.entries(n),s=e!=null&&e.whitespace?" ":"";return Array.from(t).map(([i,r])=>{r instanceof Ye||(r=new Ye(r));let a=Mi(i);return r.value===!0?a+=dr(r.params):(a+="=",Array.isArray(r.value)?a+=Xu(r):a+=bo(r)),a}).join(`,${s}`)}function Do(n,e){return zu(n,e)}const Ge="CMCD-Object",ue="CMCD-Request",ut="CMCD-Session",et="CMCD-Status",Qu={br:Ge,ab:Ge,d:Ge,ot:Ge,tb:Ge,tpb:Ge,lb:Ge,tab:Ge,lab:Ge,url:Ge,pb:ue,bl:ue,tbl:ue,dl:ue,ltc:ue,mtp:ue,nor:ue,nrr:ue,rc:ue,sn:ue,sta:ue,su:ue,ttfb:ue,ttfbb:ue,ttlb:ue,cmsdd:ue,cmsds:ue,smrt:ue,df:ue,cs:ue,ts:ue,cid:ut,pr:ut,sf:ut,sid:ut,st:ut,v:ut,msd:ut,bs:et,bsd:et,cdn:et,rtp:et,bg:et,pt:et,ec:et,e:et},Zu={REQUEST:ue};function Ju(n){return Object.keys(n).reduce((e,t)=>{var s;return(s=n[t])===null||s===void 0||s.forEach(i=>e[i]=t),e},{})}function ed(n,e){const t={};if(!n)return t;const s=Object.keys(n),i=e?Ju(e):{};return s.reduce((r,a)=>{var o;const c=Qu[a]||i[a]||Zu.REQUEST,l=(o=r[c])!==null&&o!==void 0?o:r[c]={};return l[a]=n[a],r},t)}function td(n){return["ot","sf","st","e","sta"].includes(n)}function sd(n){return typeof n=="number"?M(n):n!=null&&n!==""&&n!==!1}const Co="event";function id(n,e){const t=new URL(n),s=new URL(e);if(t.origin!==s.origin)return n;const i=t.pathname.split("/").slice(1),r=s.pathname.split("/").slice(1,-1);for(;i[0]===r[0];)i.shift(),r.shift();for(;r.length;)r.shift(),i.unshift("..");return i.join("/")+t.search+t.hash}const Ss=n=>Math.round(n),Ni=(n,e)=>Array.isArray(n)?n.map(t=>Ni(t,e)):n instanceof Ye&&typeof n.value=="string"?new Ye(Ni(n.value,e),n.params):(e.baseUrl&&(n=id(n,e.baseUrl)),e.version===1?encodeURIComponent(n):n),rs=n=>Ss(n/100)*100,rd=(n,e)=>{let t=n;return e.version>=2&&(n instanceof Ye&&typeof n.value=="string"?t=new Ye([n]):typeof n=="string"&&(t=[n])),Ni(t,e)},nd={br:Ss,d:Ss,bl:rs,dl:rs,mtp:rs,nor:rd,rtp:rs,tb:Ss},Po="request",ko="response",fr=["ab","bg","bl","br","bs","bsd","cdn","cid","cs","df","ec","lab","lb","ltc","msd","mtp","pb","pr","pt","sf","sid","sn","st","sta","tab","tb","tbl","tpb","ts","v"],ad=["e"],od=/^[a-zA-Z0-9-.]+-[a-zA-Z0-9-.]+$/;function Vs(n){return od.test(n)}function ld(n){return fr.includes(n)||ad.includes(n)||Vs(n)}const wo=["d","dl","nor","ot","rtp","su"];function cd(n){return fr.includes(n)||wo.includes(n)||Vs(n)}const hd=["cmsdd","cmsds","rc","smrt","ttfb","ttfbb","ttlb","url"];function ud(n){return fr.includes(n)||wo.includes(n)||hd.includes(n)||Vs(n)}const dd=["bl","br","bs","cid","d","dl","mtp","nor","nrr","ot","pr","rtp","sf","sid","st","su","tb","v"];function fd(n){return dd.includes(n)||Vs(n)}const gd={[ko]:ud,[Co]:ld,[Po]:cd};function Oo(n,e={}){const t={};if(n==null||typeof n!="object")return t;const s=e.version||n.v||1,i=e.reportingMode||Po,r=s===1?fd:gd[i];let a=Object.keys(n).filter(r);const o=e.filter;typeof o=="function"&&(a=a.filter(o));const c=i===ko||i===Co;c&&!a.includes("ts")&&a.push("ts"),s>1&&!a.includes("v")&&a.push("v");const l=re({},nd,e.formatters),h={version:s,reportingMode:i,baseUrl:e.baseUrl};return a.sort().forEach(u=>{let d=n[u];const f=l[u];if(typeof f=="function"&&(d=f(d,h)),u==="v"){if(s===1)return;d=s}u=="pr"&&d===1||(c&&u==="ts"&&!M(d)&&(d=Date.now()),sd(d)&&(td(u)&&typeof d=="string"&&(d=new Io(d)),t[u]=d))}),t}function md(n,e={}){const t={};if(!n)return t;const s=Oo(n,e),i=ed(s,e==null?void 0:e.customHeaderMap);return Object.entries(i).reduce((r,[a,o])=>{const c=Do(o,{whitespace:!1});return c&&(r[a]=c),r},t)}function pd(n,e,t){return re(n,md(e,t))}const yd="CMCD";function Ed(n,e={}){return n?Do(Oo(n,e),{whitespace:!1}):""}function Td(n,e={}){if(!n)return"";const t=Ed(n,e);return encodeURIComponent(t)}function Sd(n,e={}){if(!n)return"";const t=Td(n,e);return`${yd}=${t}`}const On=/CMCD=[^&#]+/;function vd(n,e,t){const s=Sd(e,t);if(!s)return n;if(On.test(n))return n.replace(On,s);const i=n.includes("?")?"&":"?";return`${n}${i}${s}`}class xd{constructor(e){this.hls=void 0,this.config=void 0,this.media=void 0,this.sid=void 0,this.cid=void 0,this.useHeaders=!1,this.includeKeys=void 0,this.initialized=!1,this.starved=!1,this.buffering=!0,this.audioBuffer=void 0,this.videoBuffer=void 0,this.onWaiting=()=>{this.initialized&&(this.starved=!0),this.buffering=!0},this.onPlaying=()=>{this.initialized||(this.initialized=!0),this.buffering=!1},this.applyPlaylistData=i=>{try{this.apply(i,{ot:_e.MANIFEST,su:!this.initialized})}catch(r){this.hls.logger.warn("Could not generate manifest CMCD data.",r)}},this.applyFragmentData=i=>{try{const{frag:r,part:a}=i,o=this.hls.levels[r.level],c=this.getObjectType(r),l={d:(a||r).duration*1e3,ot:c};(c===_e.VIDEO||c===_e.AUDIO||c==_e.MUXED)&&(l.br=o.bitrate/1e3,l.tb=this.getTopBandwidth(c)/1e3,l.bl=this.getBufferLength(c));const h=a?this.getNextPart(a):this.getNextFrag(r);h!=null&&h.url&&h.url!==r.url&&(l.nor=h.url),this.apply(i,l)}catch(r){this.hls.logger.warn("Could not generate segment CMCD data.",r)}},this.hls=e;const t=this.config=e.config,{cmcd:s}=t;s!=null&&(t.pLoader=this.createPlaylistLoader(),t.fLoader=this.createFragmentLoader(),this.sid=s.sessionId||e.sessionId,this.cid=s.contentId,this.useHeaders=s.useHeaders===!0,this.includeKeys=s.includeKeys,this.registerListeners())}registerListeners(){const e=this.hls;e.on(m.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(m.MEDIA_DETACHED,this.onMediaDetached,this),e.on(m.BUFFER_CREATED,this.onBufferCreated,this)}unregisterListeners(){const e=this.hls;e.off(m.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(m.MEDIA_DETACHED,this.onMediaDetached,this),e.off(m.BUFFER_CREATED,this.onBufferCreated,this)}destroy(){this.unregisterListeners(),this.onMediaDetached(),this.hls=this.config=this.audioBuffer=this.videoBuffer=null,this.onWaiting=this.onPlaying=this.media=null}onMediaAttached(e,t){this.media=t.media,this.media.addEventListener("waiting",this.onWaiting),this.media.addEventListener("playing",this.onPlaying)}onMediaDetached(){this.media&&(this.media.removeEventListener("waiting",this.onWaiting),this.media.removeEventListener("playing",this.onPlaying),this.media=null)}onBufferCreated(e,t){var s,i;this.audioBuffer=(s=t.tracks.audio)==null?void 0:s.buffer,this.videoBuffer=(i=t.tracks.video)==null?void 0:i.buffer}createData(){var e;return{v:1,sf:Du.HLS,sid:this.sid,cid:this.cid,pr:(e=this.media)==null?void 0:e.playbackRate,mtp:this.hls.bandwidthEstimate/1e3}}apply(e,t={}){re(t,this.createData());const s=t.ot===_e.INIT||t.ot===_e.VIDEO||t.ot===_e.MUXED;this.starved&&s&&(t.bs=!0,t.su=!0,this.starved=!1),t.su==null&&(t.su=this.buffering);const{includeKeys:i}=this;i&&(t=Object.keys(t).reduce((a,o)=>(i.includes(o)&&(a[o]=t[o]),a),{}));const r={baseUrl:e.url};this.useHeaders?(e.headers||(e.headers={}),pd(e.headers,t,r)):e.url=vd(e.url,t,r)}getNextFrag(e){var t;const s=(t=this.hls.levels[e.level])==null?void 0:t.details;if(s){const i=e.sn-s.startSN;return s.fragments[i+1]}}getNextPart(e){var t;const{index:s,fragment:i}=e,r=(t=this.hls.levels[i.level])==null||(t=t.details)==null?void 0:t.partList;if(r){const{sn:a}=i;for(let o=r.length-1;o>=0;o--){const c=r[o];if(c.index===s&&c.fragment.sn===a)return r[o+1]}}}getObjectType(e){const{type:t}=e;if(t==="subtitle")return _e.TIMED_TEXT;if(e.sn==="initSegment")return _e.INIT;if(t==="audio")return _e.AUDIO;if(t==="main")return this.hls.audioTracks.length?_e.VIDEO:_e.MUXED}getTopBandwidth(e){let t=0,s;const i=this.hls;if(e===_e.AUDIO)s=i.audioTracks;else{const r=i.maxAutoLevel,a=r>-1?r+1:i.levels.length;s=i.levels.slice(0,a)}return s.forEach(r=>{r.bitrate>t&&(t=r.bitrate)}),t>0?t:NaN}getBufferLength(e){const t=this.media,s=e===_e.AUDIO?this.audioBuffer:this.videoBuffer;return!s||!t?NaN:q.bufferInfo(s,t.currentTime,this.config.maxBufferHole).len*1e3}createPlaylistLoader(){const{pLoader:e}=this.config,t=this.applyPlaylistData,s=e||this.config.loader;return class{constructor(r){this.loader=void 0,this.loader=new s(r)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(r,a,o){t(r),this.loader.load(r,a,o)}}}createFragmentLoader(){const{fLoader:e}=this.config,t=this.applyFragmentData,s=e||this.config.loader;return class{constructor(r){this.loader=void 0,this.loader=new s(r)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(r,a,o){t(r),this.loader.load(r,a,o)}}}}const Ad=3e5;class _d extends Fe{constructor(e){super("content-steering",e.logger),this.hls=void 0,this.loader=null,this.uri=null,this.pathwayId=".",this._pathwayPriority=null,this.timeToLoad=300,this.reloadTimer=-1,this.updated=0,this.started=!1,this.enabled=!0,this.levels=null,this.audioTracks=null,this.subtitleTracks=null,this.penalizedPathways={},this.hls=e,this.registerListeners()}registerListeners(){const e=this.hls;e.on(m.MANIFEST_LOADING,this.onManifestLoading,this),e.on(m.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(m.MANIFEST_PARSED,this.onManifestParsed,this),e.on(m.ERROR,this.onError,this)}unregisterListeners(){const e=this.hls;e&&(e.off(m.MANIFEST_LOADING,this.onManifestLoading,this),e.off(m.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(m.MANIFEST_PARSED,this.onManifestParsed,this),e.off(m.ERROR,this.onError,this))}pathways(){return(this.levels||[]).reduce((e,t)=>(e.indexOf(t.pathwayId)===-1&&e.push(t.pathwayId),e),[])}get pathwayPriority(){return this._pathwayPriority}set pathwayPriority(e){this.updatePathwayPriority(e)}startLoad(){if(this.started=!0,this.clearTimeout(),this.enabled&&this.uri){if(this.updated){const e=this.timeToLoad*1e3-(performance.now()-this.updated);if(e>0){this.scheduleRefresh(this.uri,e);return}}this.loadSteeringManifest(this.uri)}}stopLoad(){this.started=!1,this.loader&&(this.loader.destroy(),this.loader=null),this.clearTimeout()}clearTimeout(){this.reloadTimer!==-1&&(self.clearTimeout(this.reloadTimer),this.reloadTimer=-1)}destroy(){this.unregisterListeners(),this.stopLoad(),this.hls=null,this.levels=this.audioTracks=this.subtitleTracks=null}removeLevel(e){const t=this.levels;t&&(this.levels=t.filter(s=>s!==e))}onManifestLoading(){this.stopLoad(),this.enabled=!0,this.timeToLoad=300,this.updated=0,this.uri=null,this.pathwayId=".",this.levels=this.audioTracks=this.subtitleTracks=null}onManifestLoaded(e,t){const{contentSteering:s}=t;s!==null&&(this.pathwayId=s.pathwayId,this.uri=s.uri,this.started&&this.startLoad())}onManifestParsed(e,t){this.audioTracks=t.audioTracks,this.subtitleTracks=t.subtitleTracks}onError(e,t){const{errorAction:s}=t;if((s==null?void 0:s.action)===Ee.SendAlternateToPenaltyBox&&s.flags===Re.MoveAllAlternatesMatchingHost){const i=this.levels;let r=this._pathwayPriority,a=this.pathwayId;if(t.context){const{groupId:o,pathwayId:c,type:l}=t.context;o&&i?a=this.getPathwayForGroupId(o,l,a):c&&(a=c)}a in this.penalizedPathways||(this.penalizedPathways[a]=performance.now()),!r&&i&&(r=this.pathways()),r&&r.length>1&&(this.updatePathwayPriority(r),s.resolved=this.pathwayId!==a),t.details===R.BUFFER_APPEND_ERROR&&!t.fatal?s.resolved=!0:s.resolved||this.warn(`Could not resolve ${t.details} ("${t.error.message}") with content-steering for Pathway: ${a} levels: ${i&&i.length} priorities: ${oe(r)} penalized: ${oe(this.penalizedPathways)}`)}}filterParsedLevels(e){this.levels=e;let t=this.getLevelsForPathway(this.pathwayId);if(t.length===0){const s=e[0].pathwayId;this.log(`No levels found in Pathway ${this.pathwayId}. Setting initial Pathway to "${s}"`),t=this.getLevelsForPathway(s),this.pathwayId=s}return t.length!==e.length&&this.log(`Found ${t.length}/${e.length} levels in Pathway "${this.pathwayId}"`),t}getLevelsForPathway(e){return this.levels===null?[]:this.levels.filter(t=>e===t.pathwayId)}updatePathwayPriority(e){this._pathwayPriority=e;let t;const s=this.penalizedPathways,i=performance.now();Object.keys(s).forEach(r=>{i-s[r]>Ad&&delete s[r]});for(let r=0;r<e.length;r++){const a=e[r];if(a in s)continue;if(a===this.pathwayId)return;const o=this.hls.nextLoadLevel,c=this.hls.levels[o];if(t=this.getLevelsForPathway(a),t.length>0){this.log(`Setting Pathway to "${a}"`),this.pathwayId=a,Ja(t),this.hls.trigger(m.LEVELS_UPDATED,{levels:t});const l=this.hls.levels[o];c&&l&&this.levels&&(l.attrs["STABLE-VARIANT-ID"]!==c.attrs["STABLE-VARIANT-ID"]&&l.bitrate!==c.bitrate&&this.log(`Unstable Pathways change from bitrate ${c.bitrate} to ${l.bitrate}`),this.hls.nextLoadLevel=o);break}}}getPathwayForGroupId(e,t,s){const i=this.getLevelsForPathway(s).concat(this.levels||[]);for(let r=0;r<i.length;r++)if(t===Q.AUDIO_TRACK&&i[r].hasAudioGroup(e)||t===Q.SUBTITLE_TRACK&&i[r].hasSubtitleGroup(e))return i[r].pathwayId;return s}clonePathways(e){const t=this.levels;if(!t)return;const s={},i={};e.forEach(r=>{const{ID:a,"BASE-ID":o,"URI-REPLACEMENT":c}=r;if(t.some(h=>h.pathwayId===a))return;const l=this.getLevelsForPathway(o).map(h=>{const u=new le(h.attrs);u["PATHWAY-ID"]=a;const d=u.AUDIO&&`${u.AUDIO}_clone_${a}`,f=u.SUBTITLES&&`${u.SUBTITLES}_clone_${a}`;d&&(s[u.AUDIO]=d,u.AUDIO=d),f&&(i[u.SUBTITLES]=f,u.SUBTITLES=f);const g=Fo(h.uri,u["STABLE-VARIANT-ID"],"PER-VARIANT-URIS",c),p=new Kt({attrs:u,audioCodec:h.audioCodec,bitrate:h.bitrate,height:h.height,name:h.name,url:g,videoCodec:h.videoCodec,width:h.width});if(h.audioGroups)for(let y=1;y<h.audioGroups.length;y++)p.addGroupId("audio",`${h.audioGroups[y]}_clone_${a}`);if(h.subtitleGroups)for(let y=1;y<h.subtitleGroups.length;y++)p.addGroupId("text",`${h.subtitleGroups[y]}_clone_${a}`);return p});t.push(...l),Fn(this.audioTracks,s,c,a),Fn(this.subtitleTracks,i,c,a)})}loadSteeringManifest(e){const t=this.hls.config,s=t.loader;this.loader&&this.loader.destroy(),this.loader=new s(t);let i;try{i=new self.URL(e)}catch{this.enabled=!1,this.log(`Failed to parse Steering Manifest URI: ${e}`);return}if(i.protocol!=="data:"){const h=(this.hls.bandwidthEstimate||t.abrEwmaDefaultEstimate)|0;i.searchParams.set("_HLS_pathway",this.pathwayId),i.searchParams.set("_HLS_throughput",""+h)}const r={responseType:"json",url:i.href},a=t.steeringManifestLoadPolicy.default,o=a.errorRetry||a.timeoutRetry||{},c={loadPolicy:a,timeout:a.maxLoadTimeMs,maxRetry:o.maxNumRetry||0,retryDelay:o.retryDelayMs||0,maxRetryDelay:o.maxRetryDelayMs||0},l={onSuccess:(h,u,d,f)=>{this.log(`Loaded steering manifest: "${i}"`);const g=h.data;if((g==null?void 0:g.VERSION)!==1){this.log(`Steering VERSION ${g.VERSION} not supported!`);return}this.updated=performance.now(),this.timeToLoad=g.TTL;const{"RELOAD-URI":p,"PATHWAY-CLONES":y,"PATHWAY-PRIORITY":E}=g;if(p)try{this.uri=new self.URL(p,i).href}catch{this.enabled=!1,this.log(`Failed to parse Steering Manifest RELOAD-URI: ${p}`);return}this.scheduleRefresh(this.uri||d.url),y&&this.clonePathways(y);const T={steeringManifest:g,url:i.toString()};this.hls.trigger(m.STEERING_MANIFEST_LOADED,T),E&&this.updatePathwayPriority(E)},onError:(h,u,d,f)=>{if(this.log(`Error loading steering manifest: ${h.code} ${h.text} (${u.url})`),this.stopLoad(),h.code===410){this.enabled=!1,this.log(`Steering manifest ${u.url} no longer available`);return}let g=this.timeToLoad*1e3;if(h.code===429){const p=this.loader;if(typeof(p==null?void 0:p.getResponseHeader)=="function"){const y=p.getResponseHeader("Retry-After");y&&(g=parseFloat(y)*1e3)}this.log(`Steering manifest ${u.url} rate limited`);return}this.scheduleRefresh(this.uri||u.url,g)},onTimeout:(h,u,d)=>{this.log(`Timeout loading steering manifest (${u.url})`),this.scheduleRefresh(this.uri||u.url)}};this.log(`Requesting steering manifest: ${i}`),this.loader.load(r,c,l)}scheduleRefresh(e,t=this.timeToLoad*1e3){this.clearTimeout(),this.reloadTimer=self.setTimeout(()=>{var s;const i=(s=this.hls)==null?void 0:s.media;if(i&&!i.ended){this.loadSteeringManifest(e);return}this.scheduleRefresh(e,this.timeToLoad*1e3)},t)}}function Fn(n,e,t,s){n&&Object.keys(e).forEach(i=>{const r=n.filter(a=>a.groupId===i).map(a=>{const o=re({},a);return o.details=void 0,o.attrs=new le(o.attrs),o.url=o.attrs.URI=Fo(a.url,a.attrs["STABLE-RENDITION-ID"],"PER-RENDITION-URIS",t),o.groupId=o.attrs["GROUP-ID"]=e[i],o.attrs["PATHWAY-ID"]=s,o});n.push(...r)})}function Fo(n,e,t,s){const{HOST:i,PARAMS:r,[t]:a}=s;let o;e&&(o=a==null?void 0:a[e],o&&(n=o));const c=new self.URL(n);return i&&!o&&(c.host=i),r&&Object.keys(r).sort().forEach(l=>{l&&c.searchParams.set(l,r[l])}),c.href}class Lt extends Fe{constructor(e){super("eme",e.logger),this.hls=void 0,this.config=void 0,this.media=null,this.mediaResolved=void 0,this.keyFormatPromise=null,this.keySystemAccessPromises={},this._requestLicenseFailureCount=0,this.mediaKeySessions=[],this.keyIdToKeySessionPromise={},this.mediaKeys=null,this.setMediaKeysQueue=Lt.CDMCleanupPromise?[Lt.CDMCleanupPromise]:[],this.bannedKeyIds={},this.onMediaEncrypted=t=>{const{initDataType:s,initData:i}=t,r=`"${t.type}" event: init data type: "${s}"`;if(this.debug(r),i!==null){if(!this.keyFormatPromise){let a=Object.keys(this.keySystemAccessPromises);a.length||(a=Ft(this.config));const o=a.map(Qs).filter(c=>!!c);this.keyFormatPromise=this.getKeyFormatPromise(o)}this.keyFormatPromise.then(a=>{const o=ys(a);if(s!=="sinf"||o!==he.FAIRPLAY){this.log(`Ignoring "${t.type}" event with init data type: "${s}" for selected key-system ${o}`);return}let c;try{const f=ge(new Uint8Array(i)),g=tr(JSON.parse(f).sinf),p=ba(g);if(!p)throw new Error("'schm' box missing or not cbcs/cenc with schi > tenc");c=new Uint8Array(p.subarray(8,24))}catch(f){this.warn(`${r} Failed to parse sinf: ${f}`);return}const l=Te(c),{keyIdToKeySessionPromise:h,mediaKeySessions:u}=this;let d=h[l];for(let f=0;f<u.length;f++){const g=u[f],p=g.decryptdata;if(!p.keyId)continue;const y=Te(p.keyId);if(Os(c,p.keyId)||p.uri.replace(/-/g,"").indexOf(l)!==-1){if(d=h[y],!d)continue;if(p.pssh)break;delete h[y],p.pssh=new Uint8Array(i),p.keyId=c,d=h[l]=d.then(()=>this.generateRequestWithPreferredKeySession(g,s,i,"encrypted-event-key-match")),d.catch(E=>this.handleError(E));break}}d||this.handleError(new Error(`Key ID ${l} not encountered in playlist. Key-system sessions ${u.length}.`))}).catch(a=>this.handleError(a))}},this.onWaitingForKey=t=>{this.log(`"${t.type}" event`)},this.hls=e,this.config=e.config,this.registerListeners()}destroy(){this.onDestroying(),this.onMediaDetached();const e=this.config;e.requestMediaKeySystemAccessFunc=null,e.licenseXhrSetup=e.licenseResponseCallback=void 0,e.drmSystems=e.drmSystemOptions={},this.hls=this.config=this.keyIdToKeySessionPromise=null,this.onMediaEncrypted=this.onWaitingForKey=null}registerListeners(){this.hls.on(m.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.on(m.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.on(m.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.on(m.MANIFEST_LOADED,this.onManifestLoaded,this),this.hls.on(m.DESTROYING,this.onDestroying,this)}unregisterListeners(){this.hls.off(m.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.off(m.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.off(m.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.off(m.MANIFEST_LOADED,this.onManifestLoaded,this),this.hls.off(m.DESTROYING,this.onDestroying,this)}getLicenseServerUrl(e){const{drmSystems:t,widevineLicenseUrl:s}=this.config,i=t==null?void 0:t[e];if(i)return i.licenseUrl;if(e===he.WIDEVINE&&s)return s}getLicenseServerUrlOrThrow(e){const t=this.getLicenseServerUrl(e);if(t===void 0)throw new Error(`no license server URL configured for key-system "${e}"`);return t}getServerCertificateUrl(e){const{drmSystems:t}=this.config,s=t==null?void 0:t[e];if(s)return s.serverCertificateUrl;this.log(`No Server Certificate in config.drmSystems["${e}"]`)}attemptKeySystemAccess(e){const t=this.hls.levels,s=(a,o,c)=>!!a&&c.indexOf(a)===o,i=t.map(a=>a.audioCodec).filter(s),r=t.map(a=>a.videoCodec).filter(s);return i.length+r.length===0&&r.push("avc1.42e01e"),new Promise((a,o)=>{const c=l=>{const h=l.shift();this.getMediaKeysPromise(h,i,r).then(u=>a({keySystem:h,mediaKeys:u})).catch(u=>{l.length?c(l):u instanceof Le?o(u):o(new Le({type:H.KEY_SYSTEM_ERROR,details:R.KEY_SYSTEM_NO_ACCESS,error:u,fatal:!0},u.message))})};c(e)})}requestMediaKeySystemAccess(e,t){const{requestMediaKeySystemAccessFunc:s}=this.config;if(typeof s!="function"){let i=`Configured requestMediaKeySystemAccess is not a function ${s}`;return Wa===null&&self.location.protocol==="http:"&&(i=`navigator.requestMediaKeySystemAccess is not available over insecure protocol ${location.protocol}`),Promise.reject(new Error(i))}return s(e,t)}getMediaKeysPromise(e,t,s){var i;const r=rh(e,t,s,this.config.drmSystemOptions||{});let a=this.keySystemAccessPromises[e],o=(i=a)==null?void 0:i.keySystemAccess;if(!o){this.log(`Requesting encrypted media "${e}" key-system access with config: ${oe(r)}`),o=this.requestMediaKeySystemAccess(e,r);const c=a=this.keySystemAccessPromises[e]={keySystemAccess:o};return o.catch(l=>{this.log(`Failed to obtain access to key-system "${e}": ${l}`)}),o.then(l=>{this.log(`Access for key-system "${l.keySystem}" obtained`);const h=this.fetchServerCertificate(e);this.log(`Create media-keys for "${e}"`);const u=c.mediaKeys=l.createMediaKeys().then(d=>(this.log(`Media-keys created for "${e}"`),c.hasMediaKeys=!0,h.then(f=>f?this.setMediaKeysServerCertificate(d,e,f):d)));return u.catch(d=>{this.error(`Failed to create media-keys for "${e}"}: ${d}`)}),u})}return o.then(()=>a.mediaKeys)}createMediaKeySessionContext({decryptdata:e,keySystem:t,mediaKeys:s}){this.log(`Creating key-system session "${t}" keyId: ${Te(e.keyId||[])} keyUri: ${e.uri}`);const i=s.createSession(),r={decryptdata:e,keySystem:t,mediaKeys:s,mediaKeysSession:i,keyStatus:"status-pending"};return this.mediaKeySessions.push(r),r}renewKeySession(e){const t=e.decryptdata;if(t.pssh){const s=this.createMediaKeySessionContext(e),i=ns(t),r="cenc";this.keyIdToKeySessionPromise[i]=this.generateRequestWithPreferredKeySession(s,r,t.pssh.buffer,"expired")}else this.warn("Could not renew expired session. Missing pssh initData.");this.removeSession(e)}updateKeySession(e,t){const s=e.mediaKeysSession;return this.log(`Updating key-session "${s.sessionId}" for keyId ${Te(e.decryptdata.keyId||[])}
116116+ } (data length: ${t.byteLength})`),s.update(t)}getSelectedKeySystemFormats(){return Object.keys(this.keySystemAccessPromises).map(e=>({keySystem:e,hasMediaKeys:this.keySystemAccessPromises[e].hasMediaKeys})).filter(({hasMediaKeys:e})=>!!e).map(({keySystem:e})=>Qs(e)).filter(e=>!!e)}getKeySystemAccess(e){return this.getKeySystemSelectionPromise(e).then(({keySystem:t,mediaKeys:s})=>this.attemptSetMediaKeys(t,s))}selectKeySystem(e){return new Promise((t,s)=>{this.getKeySystemSelectionPromise(e).then(({keySystem:i})=>{const r=Qs(i);r?t(r):s(new Error(`Unable to find format for key-system "${i}"`))}).catch(s)})}selectKeySystemFormat(e){const t=Object.keys(e.levelkeys||{});return this.keyFormatPromise||(this.log(`Selecting key-system from fragment (sn: ${e.sn} ${e.type}: ${e.level}) key formats ${t.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(t)),this.keyFormatPromise}getKeyFormatPromise(e){const t=Ft(this.config),s=e.map(ys).filter(i=>!!i&&t.indexOf(i)!==-1);return this.selectKeySystem(s)}getKeyStatus(e){const{mediaKeySessions:t}=this;for(let s=0;s<t.length;s++){const i=Id(e,t[s]);if(i)return i}}loadKey(e){const t=e.keyInfo.decryptdata,s=ns(t),i=this.bannedKeyIds[s];if(i||this.getKeyStatus(t)==="internal-error"){const o=Mn(i||"internal-error",t);return this.handleError(o,e.frag),Promise.reject(o)}const r=`(keyId: ${s} format: "${t.keyFormat}" method: ${t.method} uri: ${t.uri})`;this.log(`Starting session for key ${r}`);const a=this.keyIdToKeySessionPromise[s];if(!a){const o=this.getKeySystemForKeyPromise(t).then(({keySystem:c,mediaKeys:l})=>(this.throwIfDestroyed(),this.log(`Handle encrypted media sn: ${e.frag.sn} ${e.frag.type}: ${e.frag.level} using key ${r}`),this.attemptSetMediaKeys(c,l).then(()=>(this.throwIfDestroyed(),this.createMediaKeySessionContext({keySystem:c,mediaKeys:l,decryptdata:t}))))).then(c=>{const l="cenc",h=t.pssh?t.pssh.buffer:null;return this.generateRequestWithPreferredKeySession(c,l,h,"playlist-key")});return o.catch(c=>this.handleError(c,e.frag)),this.keyIdToKeySessionPromise[s]=o,o}return a.catch(o=>{if(o instanceof Le){const c=se({},o.data);this.getKeyStatus(t)==="internal-error"&&(c.decryptdata=t);const l=new Le(c,o.message);this.handleError(l,e.frag)}}),a}throwIfDestroyed(e="Invalid state"){if(!this.hls)throw new Error("invalid state")}handleError(e,t){if(this.hls)if(e instanceof Le){t&&(e.data.frag=t);const s=e.data.decryptdata;this.error(`${e.message}${s?` (${Te(s.keyId||[])})`:""}`),this.hls.trigger(m.ERROR,e.data)}else this.error(e.message),this.hls.trigger(m.ERROR,{type:H.KEY_SYSTEM_ERROR,details:R.KEY_SYSTEM_NO_KEYS,error:e,fatal:!0})}getKeySystemForKeyPromise(e){const t=ns(e),s=this.keyIdToKeySessionPromise[t];if(!s){const i=ys(e.keyFormat),r=i?[i]:Ft(this.config);return this.attemptKeySystemAccess(r)}return s}getKeySystemSelectionPromise(e){if(e.length||(e=Ft(this.config)),e.length===0)throw new Le({type:H.KEY_SYSTEM_ERROR,details:R.KEY_SYSTEM_NO_CONFIGURED_LICENSE,fatal:!0},`Missing key-system license configuration options ${oe({drmSystems:this.config.drmSystems})}`);return this.attemptKeySystemAccess(e)}attemptSetMediaKeys(e,t){if(this.mediaResolved=void 0,this.mediaKeys===t)return Promise.resolve();const s=this.setMediaKeysQueue.slice();this.log(`Setting media-keys for "${e}"`);const i=Promise.all(s).then(()=>this.media?this.media.setMediaKeys(t):new Promise((r,a)=>{this.mediaResolved=()=>{if(this.mediaResolved=void 0,!this.media)return a(new Error("Attempted to set mediaKeys without media element attached"));this.mediaKeys=t,this.media.setMediaKeys(t).then(r).catch(a)}}));return this.mediaKeys=t,this.setMediaKeysQueue.push(i),i.then(()=>{this.log(`Media-keys set for "${e}"`),s.push(i),this.setMediaKeysQueue=this.setMediaKeysQueue.filter(r=>s.indexOf(r)===-1)})}generateRequestWithPreferredKeySession(e,t,s,i){var r;const a=(r=this.config.drmSystems)==null||(r=r[e.keySystem])==null?void 0:r.generateRequest;if(a)try{const g=a.call(this.hls,t,s,e);if(!g)throw new Error("Invalid response from configured generateRequest filter");t=g.initDataType,s=g.initData?g.initData:null,e.decryptdata.pssh=s?new Uint8Array(s):null}catch(g){if(this.warn(g.message),this.hls&&this.hls.config.debug)throw g}if(s===null)return this.log(`Skipping key-session request for "${i}" (no initData)`),Promise.resolve(e);const o=ns(e.decryptdata),c=e.decryptdata.uri;this.log(`Generating key-session request for "${i}" keyId: ${o} URI: ${c} (init data type: ${t} length: ${s.byteLength})`);const l=new ir,h=e._onmessage=g=>{const p=e.mediaKeysSession;if(!p){l.emit("error",new Error("invalid state"));return}const{messageType:y,message:E}=g;this.log(`"${y}" message event for session "${p.sessionId}" message size: ${E.byteLength}`),y==="license-request"||y==="license-renewal"?this.renewLicense(e,E).catch(T=>{l.eventNames().length?l.emit("error",T):this.handleError(T)}):y==="license-release"?e.keySystem===he.FAIRPLAY&&this.updateKeySession(e,Di("acknowledged")).then(()=>this.removeSession(e)).catch(T=>this.handleError(T)):this.warn(`unhandled media key message type "${y}"`)},u=(g,p)=>{p.keyStatus=g;let y;g.startsWith("usable")?l.emit("resolved"):g==="internal-error"||g==="output-restricted"||g==="output-downscaled"?y=Mn(g,p.decryptdata):g==="expired"?y=new Error(`key expired (keyId: ${o})`):g==="released"?y=new Error("key released"):g==="status-pending"||this.warn(`unhandled key status change "${g}" (keyId: ${o})`),y&&(l.eventNames().length?l.emit("error",y):this.handleError(y))},d=e._onkeystatuseschange=g=>{if(!e.mediaKeysSession){l.emit("error",new Error("invalid state"));return}const y=this.getKeyStatuses(e);if(!Object.keys(y).some(v=>y[v]!=="status-pending"))return;if(y[o]==="expired"){this.log(`Expired key ${oe(y)} in key-session "${e.mediaKeysSession.sessionId}"`),this.renewKeySession(e);return}let T=y[o];if(T)u(T,e);else{var S;e.keyStatusTimeouts||(e.keyStatusTimeouts={}),(S=e.keyStatusTimeouts)[o]||(S[o]=self.setTimeout(()=>{if(!e.mediaKeysSession||!this.mediaKeys)return;const x=this.getKeyStatus(e.decryptdata);if(x&&x!=="status-pending")return this.log(`No status for keyId ${o} in key-session "${e.mediaKeysSession.sessionId}". Using session key-status ${x} from other session.`),u(x,e);this.log(`key status for ${o} in key-session "${e.mediaKeysSession.sessionId}" timed out after 1000ms`),T="internal-error",u(T,e)},1e3)),this.log(`No status for keyId ${o} (${oe(y)}).`)}};Ae(e.mediaKeysSession,"message",h),Ae(e.mediaKeysSession,"keystatuseschange",d);const f=new Promise((g,p)=>{l.on("error",p),l.on("resolved",g)});return e.mediaKeysSession.generateRequest(t,s).then(()=>{this.log(`Request generated for key-session "${e.mediaKeysSession.sessionId}" keyId: ${o} URI: ${c}`)}).catch(g=>{throw new Le({type:H.KEY_SYSTEM_ERROR,details:R.KEY_SYSTEM_NO_SESSION,error:g,decryptdata:e.decryptdata,fatal:!1},`Error generating key-session request: ${g}`)}).then(()=>f).catch(g=>(l.removeAllListeners(),this.removeSession(e).then(()=>{throw g}))).then(()=>(l.removeAllListeners(),e))}getKeyStatuses(e){const t={};return e.mediaKeysSession.keyStatuses.forEach((s,i)=>{if(typeof i=="string"&&typeof s=="object"){const o=i;i=s,s=o}const r="buffer"in i?new Uint8Array(i.buffer,i.byteOffset,i.byteLength):new Uint8Array(i);if(e.keySystem===he.PLAYREADY&&r.length===16){const o=Te(r);t[o]=s,Va(r)}const a=Te(r);s==="internal-error"&&(this.bannedKeyIds[a]=s),this.log(`key status change "${s}" for keyStatuses keyId: ${a} key-session "${e.mediaKeysSession.sessionId}"`),t[a]=s}),t}fetchServerCertificate(e){const t=this.config,s=t.loader,i=new s(t),r=this.getServerCertificateUrl(e);return r?(this.log(`Fetching server certificate for "${e}"`),new Promise((a,o)=>{const c={responseType:"arraybuffer",url:r},l=t.certLoadPolicy.default,h={loadPolicy:l,timeout:l.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},u={onSuccess:(d,f,g,p)=>{a(d.data)},onError:(d,f,g,p)=>{o(new Le({type:H.KEY_SYSTEM_ERROR,details:R.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:g,response:se({url:c.url,data:void 0},d)},`"${e}" certificate request failed (${r}). Status: ${d.code} (${d.text})`))},onTimeout:(d,f,g)=>{o(new Le({type:H.KEY_SYSTEM_ERROR,details:R.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:g,response:{url:c.url,data:void 0}},`"${e}" certificate request timed out (${r})`))},onAbort:(d,f,g)=>{o(new Error("aborted"))}};i.load(c,h,u)})):Promise.resolve()}setMediaKeysServerCertificate(e,t,s){return new Promise((i,r)=>{e.setServerCertificate(s).then(a=>{this.log(`setServerCertificate ${a?"success":"not supported by CDM"} (${s.byteLength}) on "${t}"`),i(e)}).catch(a=>{r(new Le({type:H.KEY_SYSTEM_ERROR,details:R.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED,error:a,fatal:!0},a.message))})})}renewLicense(e,t){return this.requestLicense(e,new Uint8Array(t)).then(s=>this.updateKeySession(e,new Uint8Array(s)).catch(i=>{throw new Le({type:H.KEY_SYSTEM_ERROR,details:R.KEY_SYSTEM_SESSION_UPDATE_FAILED,decryptdata:e.decryptdata,error:i,fatal:!1},i.message)}))}unpackPlayReadyKeyMessage(e,t){const s=String.fromCharCode.apply(null,new Uint16Array(t.buffer));if(!s.includes("PlayReadyKeyMessage"))return e.setRequestHeader("Content-Type","text/xml; charset=utf-8"),t;const i=new DOMParser().parseFromString(s,"application/xml"),r=i.querySelectorAll("HttpHeader");if(r.length>0){let h;for(let u=0,d=r.length;u<d;u++){var a,o;h=r[u];const f=(a=h.querySelector("name"))==null?void 0:a.textContent,g=(o=h.querySelector("value"))==null?void 0:o.textContent;f&&g&&e.setRequestHeader(f,g)}}const c=i.querySelector("Challenge"),l=c==null?void 0:c.textContent;if(!l)throw new Error("Cannot find <Challenge> in key message");return Di(atob(l))}setupLicenseXHR(e,t,s,i){const r=this.config.licenseXhrSetup;return r?Promise.resolve().then(()=>{if(!s.decryptdata)throw new Error("Key removed");return r.call(this.hls,e,t,s,i)}).catch(a=>{if(!s.decryptdata)throw a;return e.open("POST",t,!0),r.call(this.hls,e,t,s,i)}).then(a=>(e.readyState||e.open("POST",t,!0),{xhr:e,licenseChallenge:a||i})):(e.open("POST",t,!0),Promise.resolve({xhr:e,licenseChallenge:i}))}requestLicense(e,t){const s=this.config.keyLoadPolicy.default;return new Promise((i,r)=>{const a=this.getLicenseServerUrlOrThrow(e.keySystem);this.log(`Sending license request to URL: ${a}`);const o=new XMLHttpRequest;o.responseType="arraybuffer",o.onreadystatechange=()=>{if(!this.hls||!e.mediaKeysSession)return r(new Error("invalid state"));if(o.readyState===4)if(o.status===200){this._requestLicenseFailureCount=0;let c=o.response;this.log(`License received ${c instanceof ArrayBuffer?c.byteLength:c}`);const l=this.config.licenseResponseCallback;if(l)try{c=l.call(this.hls,o,a,e)}catch(h){this.error(h)}i(c)}else{const c=s.errorRetry,l=c?c.maxNumRetry:0;if(this._requestLicenseFailureCount++,this._requestLicenseFailureCount>l||o.status>=400&&o.status<500)r(new Le({type:H.KEY_SYSTEM_ERROR,details:R.KEY_SYSTEM_LICENSE_REQUEST_FAILED,decryptdata:e.decryptdata,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{const h=l-this._requestLicenseFailureCount+1;this.warn(`Retrying license request, ${h} attempts left`),this.requestLicense(e,t).then(i,r)}}},e.licenseXhr&&e.licenseXhr.readyState!==XMLHttpRequest.DONE&&e.licenseXhr.abort(),e.licenseXhr=o,this.setupLicenseXHR(o,a,e,t).then(({xhr:c,licenseChallenge:l})=>{e.keySystem==he.PLAYREADY&&(l=this.unpackPlayReadyKeyMessage(c,l)),c.send(l)}).catch(r)})}onDestroying(){this.unregisterListeners(),this._clear()}onMediaAttached(e,t){if(!this.config.emeEnabled)return;const s=t.media;this.media=s,Ae(s,"encrypted",this.onMediaEncrypted),Ae(s,"waitingforkey",this.onWaitingForKey);const i=this.mediaResolved;i?i():this.mediaKeys=s.mediaKeys}onMediaDetached(){const e=this.media;e&&(Ie(e,"encrypted",this.onMediaEncrypted),Ie(e,"waitingforkey",this.onWaitingForKey),this.media=null,this.mediaKeys=null)}_clear(){var e;this._requestLicenseFailureCount=0,this.keyIdToKeySessionPromise={},this.bannedKeyIds={};const t=this.mediaResolved;if(t&&t(),!this.mediaKeys&&!this.mediaKeySessions.length)return;const s=this.media,i=this.mediaKeySessions.slice();this.mediaKeySessions=[],this.mediaKeys=null,nt.clearKeyUriToKeyIdMap();const r=i.length;Lt.CDMCleanupPromise=Promise.all(i.map(a=>this.removeSession(a)).concat((s==null||(e=s.setMediaKeys(null))==null?void 0:e.catch(a=>{this.log(`Could not clear media keys: ${a}`),this.hls&&this.hls.trigger(m.ERROR,{type:H.OTHER_ERROR,details:R.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR,fatal:!1,error:new Error(`Could not clear media keys: ${a}`)})}))||Promise.resolve())).catch(a=>{this.log(`Could not close sessions and clear media keys: ${a}`),this.hls&&this.hls.trigger(m.ERROR,{type:H.OTHER_ERROR,details:R.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error(`Could not close sessions and clear media keys: ${a}`)})}).then(()=>{r&&this.log("finished closing key sessions and clearing media keys")})}onManifestLoading(){this._clear()}onManifestLoaded(e,{sessionKeys:t}){if(!(!t||!this.config.emeEnabled)&&!this.keyFormatPromise){const s=t.reduce((i,r)=>(i.indexOf(r.keyFormat)===-1&&i.push(r.keyFormat),i),[]);this.log(`Selecting key-system from session-keys ${s.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(s)}}removeSession(e){const{mediaKeysSession:t,licenseXhr:s,decryptdata:i}=e;if(t){this.log(`Remove licenses and keys and close session "${t.sessionId}" keyId: ${Te((i==null?void 0:i.keyId)||[])}`),e._onmessage&&(t.removeEventListener("message",e._onmessage),e._onmessage=void 0),e._onkeystatuseschange&&(t.removeEventListener("keystatuseschange",e._onkeystatuseschange),e._onkeystatuseschange=void 0),s&&s.readyState!==XMLHttpRequest.DONE&&s.abort(),e.mediaKeysSession=e.decryptdata=e.licenseXhr=void 0;const r=this.mediaKeySessions.indexOf(e);r>-1&&this.mediaKeySessions.splice(r,1);const{keyStatusTimeouts:a}=e;a&&Object.keys(a).forEach(l=>self.clearTimeout(a[l]));const{drmSystemOptions:o}=this.config;return(ah(o)?new Promise((l,h)=>{self.setTimeout(()=>h(new Error("MediaKeySession.remove() timeout")),8e3),t.remove().then(l).catch(h)}):Promise.resolve()).catch(l=>{this.log(`Could not remove session: ${l}`),this.hls&&this.hls.trigger(m.ERROR,{type:H.OTHER_ERROR,details:R.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR,fatal:!1,error:new Error(`Could not remove session: ${l}`)})}).then(()=>t.close()).catch(l=>{this.log(`Could not close session: ${l}`),this.hls&&this.hls.trigger(m.ERROR,{type:H.OTHER_ERROR,details:R.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error(`Could not close session: ${l}`)})})}return Promise.resolve()}}Lt.CDMCleanupPromise=void 0;function ns(n){if(!n)throw new Error("Could not read keyId of undefined decryptdata");if(n.keyId===null)throw new Error("keyId is null");return Te(n.keyId)}function Id(n,e){if(n.keyId&&e.mediaKeysSession.keyStatuses.has(n.keyId))return e.mediaKeysSession.keyStatuses.get(n.keyId);if(n.matches(e.decryptdata))return e.keyStatus}class Le extends Error{constructor(e,t){super(t),this.data=void 0,e.error||(e.error=new Error(t)),this.data=e,e.err=e.error}}function Mn(n,e){const t=n==="output-restricted",s=t?R.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:R.KEY_SYSTEM_STATUS_INTERNAL_ERROR;return new Le({type:H.KEY_SYSTEM_ERROR,details:s,fatal:!1,decryptdata:e},t?"HDCP level output restricted":`key status changed to "${n}"`)}class Ld{constructor(e){this.hls=void 0,this.isVideoPlaybackQualityAvailable=!1,this.timer=void 0,this.media=null,this.lastTime=void 0,this.lastDroppedFrames=0,this.lastDecodedFrames=0,this.streamController=void 0,this.hls=e,this.registerListeners()}setStreamController(e){this.streamController=e}registerListeners(){this.hls.on(m.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.on(m.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListeners(){this.hls.off(m.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.off(m.MEDIA_DETACHING,this.onMediaDetaching,this)}destroy(){this.timer&&clearInterval(this.timer),this.unregisterListeners(),this.isVideoPlaybackQualityAvailable=!1,this.media=null}onMediaAttaching(e,t){const s=this.hls.config;if(s.capLevelOnFPSDrop){const i=t.media instanceof self.HTMLVideoElement?t.media:null;this.media=i,i&&typeof i.getVideoPlaybackQuality=="function"&&(this.isVideoPlaybackQualityAvailable=!0),self.clearInterval(this.timer),this.timer=self.setInterval(this.checkFPSInterval.bind(this),s.fpsDroppedMonitoringPeriod)}}onMediaDetaching(){this.media=null}checkFPS(e,t,s){const i=performance.now();if(t){if(this.lastTime){const r=i-this.lastTime,a=s-this.lastDroppedFrames,o=t-this.lastDecodedFrames,c=1e3*a/r,l=this.hls;if(l.trigger(m.FPS_DROP,{currentDropped:a,currentDecoded:o,totalDroppedFrames:s}),c>0&&a>l.config.fpsDroppedMonitoringThreshold*o){let h=l.currentLevel;l.logger.warn("drop FPS ratio greater than max allowed value for currentLevel: "+h),h>0&&(l.autoLevelCapping===-1||l.autoLevelCapping>=h)&&(h=h-1,l.trigger(m.FPS_DROP_LEVEL_CAPPING,{level:h,droppedLevel:l.currentLevel}),l.autoLevelCapping=h,this.streamController.nextLevelSwitch())}}this.lastTime=i,this.lastDroppedFrames=s,this.lastDecodedFrames=t}}checkFPSInterval(){const e=this.media;if(e)if(this.isVideoPlaybackQualityAvailable){const t=e.getVideoPlaybackQuality();this.checkFPS(e,t.totalVideoFrames,t.droppedVideoFrames)}else this.checkFPS(e,e.webkitDecodedFrameCount,e.webkitDroppedFrameCount)}}function Mo(n,e){let t;try{t=new Event("addtrack")}catch{t=document.createEvent("Event"),t.initEvent("addtrack",!1,!1)}t.track=n,e.dispatchEvent(t)}function No(n,e){const t=n.mode;if(t==="disabled"&&(n.mode="hidden"),n.cues&&!n.cues.getCueById(e.id))try{if(n.addCue(e),!n.cues.getCueById(e.id))throw new Error(`addCue is failed for: ${e}`)}catch(s){ie.debug(`[texttrack-utils]: ${s}`);try{const i=new self.TextTrackCue(e.startTime,e.endTime,e.text);i.id=e.id,n.addCue(i)}catch(i){ie.debug(`[texttrack-utils]: Legacy TextTrackCue fallback failed: ${i}`)}}t==="disabled"&&(n.mode=t)}function At(n,e){const t=n.mode;if(t==="disabled"&&(n.mode="hidden"),n.cues)for(let s=n.cues.length;s--;)e&&n.cues[s].removeEventListener("enter",e),n.removeCue(n.cues[s]);t==="disabled"&&(n.mode=t)}function Bi(n,e,t,s){const i=n.mode;if(i==="disabled"&&(n.mode="hidden"),n.cues&&n.cues.length>0){const r=bd(n.cues,e,t);for(let a=0;a<r.length;a++)(!s||s(r[a]))&&n.removeCue(r[a])}i==="disabled"&&(n.mode=i)}function Rd(n,e){if(e<=n[0].startTime)return 0;const t=n.length-1;if(e>n[t].endTime)return-1;let s=0,i=t,r;for(;s<=i;)if(r=Math.floor((i+s)/2),e<n[r].startTime)i=r-1;else if(e>n[r].startTime&&s<t)s=r+1;else return r;return n[s].startTime-e<e-n[i].startTime?s:i}function bd(n,e,t){const s=[],i=Rd(n,e);if(i>-1)for(let r=i,a=n.length;r<a;r++){const o=n[r];if(o.startTime>=e&&o.endTime<=t)s.push(o);else if(o.startTime>t)return s}return s}function vs(n){const e=[];for(let t=0;t<n.length;t++){const s=n[t];(s.kind==="subtitles"||s.kind==="captions")&&s.label&&e.push(n[t])}return e}class Dd extends hr{constructor(e){super(e,"subtitle-track-controller"),this.media=null,this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0,this.queuedDefaultTrack=-1,this.useTextTrackPolling=!1,this.subtitlePollingInterval=-1,this._subtitleDisplay=!0,this.asyncPollTrackChange=()=>this.pollTrackChange(0),this.onTextTracksChanged=()=>{if(this.useTextTrackPolling||self.clearInterval(this.subtitlePollingInterval),!this.media||!this.hls.config.renderTextTracksNatively)return;let t=null;const s=vs(this.media.textTracks);for(let r=0;r<s.length;r++)if(s[r].mode==="hidden")t=s[r];else if(s[r].mode==="showing"){t=s[r];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(e){this._subtitleDisplay=e,this.trackId>-1&&this.toggleTrackModes()}registerListeners(){const{hls:e}=this;e.on(m.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(m.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(m.MANIFEST_LOADING,this.onManifestLoading,this),e.on(m.MANIFEST_PARSED,this.onManifestParsed,this),e.on(m.LEVEL_LOADING,this.onLevelLoading,this),e.on(m.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(m.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(m.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(m.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(m.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(m.MANIFEST_LOADING,this.onManifestLoading,this),e.off(m.MANIFEST_PARSED,this.onManifestParsed,this),e.off(m.LEVEL_LOADING,this.onLevelLoading,this),e.off(m.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(m.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(m.ERROR,this.onError,this)}onMediaAttached(e,t){this.media=t.media,this.media&&(this.queuedDefaultTrack>-1&&(this.subtitleTrack=this.queuedDefaultTrack,this.queuedDefaultTrack=-1),this.useTextTrackPolling=!(this.media.textTracks&&"onchange"in this.media.textTracks),this.useTextTrackPolling?this.pollTrackChange(500):this.media.textTracks.addEventListener("change",this.asyncPollTrackChange))}pollTrackChange(e){self.clearInterval(this.subtitlePollingInterval),this.subtitlePollingInterval=self.setInterval(this.onTextTracksChanged,e)}onMediaDetaching(e,t){const s=this.media;if(!s)return;const i=!!t.transferMedia;if(self.clearInterval(this.subtitlePollingInterval),this.useTextTrackPolling||s.textTracks.removeEventListener("change",this.asyncPollTrackChange),this.trackId>-1&&(this.queuedDefaultTrack=this.trackId),this.subtitleTrack=-1,this.media=null,i)return;vs(s.textTracks).forEach(a=>{At(a)})}onManifestLoading(){this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0}onManifestParsed(e,t){this.tracks=t.subtitleTracks}onSubtitleTrackLoaded(e,t){const{id:s,groupId:i,details:r}=t,a=this.tracksInGroup[s];if(!a||a.groupId!==i){this.warn(`Subtitle track with id:${s} and group:${i} not found in active group ${a==null?void 0:a.groupId}`);return}const o=a.details;a.details=t.details,this.log(`Subtitle track ${s} "${a.name}" lang:${a.lang} group:${i} loaded [${r.startSN}-${r.endSN}]`),s===this.trackId&&this.playlistLoaded(s,t,o)}onLevelLoading(e,t){this.switchLevel(t.level)}onLevelSwitching(e,t){this.switchLevel(t.level)}switchLevel(e){const t=this.hls.levels[e];if(!t)return;const s=t.subtitleGroups||null,i=this.groupIds;let r=this.currentTrack;if(!s||(i==null?void 0:i.length)!==(s==null?void 0:s.length)||s!=null&&s.some(a=>(i==null?void 0:i.indexOf(a))===-1)){this.groupIds=s,this.trackId=-1,this.currentTrack=null;const a=this.tracks.filter(h=>!s||s.indexOf(h.groupId)!==-1);if(a.length)this.selectDefaultTrack&&!a.some(h=>h.default)&&(this.selectDefaultTrack=!1),a.forEach((h,u)=>{h.id=u});else if(!r&&!this.tracksInGroup.length)return;this.tracksInGroup=a;const o=this.hls.config.subtitlePreference;if(!r&&o){this.selectDefaultTrack=!1;const h=He(o,a);if(h>-1)r=a[h];else{const u=He(o,this.tracks);r=this.tracks[u]}}let c=this.findTrackId(r);c===-1&&r&&(c=this.findTrackId(null));const l={subtitleTracks:a};this.log(`Updating subtitle tracks, ${a.length} track(s) found in "${s==null?void 0:s.join(",")}" group-id`),this.hls.trigger(m.SUBTITLE_TRACKS_UPDATED,l),c!==-1&&this.trackId===-1&&this.setSubtitleTrack(c)}}findTrackId(e){const t=this.tracksInGroup,s=this.selectDefaultTrack;for(let i=0;i<t.length;i++){const r=t[i];if(!(s&&!r.default||!s&&!e)&&(!e||gt(r,e)))return i}if(e){for(let i=0;i<t.length;i++){const r=t[i];if(Yt(e.attrs,r.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return i}for(let i=0;i<t.length;i++){const r=t[i];if(Yt(e.attrs,r.attrs,["LANGUAGE"]))return i}}return-1}findTrackForTextTrack(e){if(e){const t=this.tracksInGroup;for(let s=0;s<t.length;s++){const i=t[s];if(Oi(i,e))return s}}return-1}onError(e,t){t.fatal||!t.context||t.context.type===Q.SUBTITLE_TRACK&&t.context.id===this.trackId&&(!this.groupIds||this.groupIds.indexOf(t.context.groupId)!==-1)&&this.checkRetry(t)}get allSubtitleTracks(){return this.tracks}get subtitleTracks(){return this.tracksInGroup}get subtitleTrack(){return this.trackId}set subtitleTrack(e){this.selectDefaultTrack=!1,this.setSubtitleTrack(e)}setSubtitleOption(e){if(this.hls.config.subtitlePreference=e,e){if(e.id===-1)return this.setSubtitleTrack(-1),null;const t=this.allSubtitleTracks;if(this.selectDefaultTrack=!1,t.length){const s=this.currentTrack;if(s&>(e,s))return s;const i=He(e,this.tracksInGroup);if(i>-1){const r=this.tracksInGroup[i];return this.setSubtitleTrack(i),r}else{if(s)return null;{const r=He(e,t);if(r>-1)return t[r]}}}}return null}loadPlaylist(e){super.loadPlaylist(),this.shouldLoadPlaylist(this.currentTrack)&&this.scheduleLoading(this.currentTrack,e)}loadingPlaylist(e,t){super.loadingPlaylist(e,t);const s=e.id,i=e.groupId,r=this.getUrlWithDirectives(e.url,t),a=e.details,o=a==null?void 0:a.age;this.log(`Loading subtitle ${s} "${e.name}" lang:${e.lang} group:${i}${(t==null?void 0:t.msn)!==void 0?" at sn "+t.msn+" part "+t.part:""}${o&&a.live?" age "+o.toFixed(1)+(a.type&&" "+a.type||""):""} ${r}`),this.hls.trigger(m.SUBTITLE_TRACK_LOADING,{url:r,id:s,groupId:i,deliveryDirectives:t||null,track:e})}toggleTrackModes(){const{media:e}=this;if(!e)return;const t=vs(e.textTracks),s=this.currentTrack;let i;if(s&&(i=t.filter(r=>Oi(s,r))[0],i||this.warn(`Unable to find subtitle TextTrack with name "${s.name}" and language "${s.lang}"`)),[].slice.call(t).forEach(r=>{r.mode!=="disabled"&&r!==i&&(r.mode="disabled")}),i){const r=this.subtitleDisplay?"showing":"hidden";i.mode!==r&&(i.mode=r)}}setSubtitleTrack(e){const t=this.tracksInGroup;if(!this.media){this.queuedDefaultTrack=e;return}if(e<-1||e>=t.length||!M(e)){this.warn(`Invalid subtitle track id: ${e}`);return}this.selectDefaultTrack=!1;const s=this.currentTrack,i=t[e]||null;if(this.trackId=e,this.currentTrack=i,this.toggleTrackModes(),!i){this.hls.trigger(m.SUBTITLE_TRACK_SWITCH,{id:e});return}const r=!!i.details&&!i.details.live;if(e===this.trackId&&i===s&&r)return;this.log(`Switching to subtitle-track ${e}`+(i?` "${i.name}" lang:${i.lang} group:${i.groupId}`:""));const{id:a,groupId:o="",name:c,type:l,url:h}=i;this.hls.trigger(m.SUBTITLE_TRACK_SWITCH,{id:a,groupId:o,name:c,type:l,url:h});const u=this.switchParams(i.url,s==null?void 0:s.details,i.details);this.loadPlaylist(u)}}function Cd(){try{return crypto.randomUUID()}catch{try{const e=URL.createObjectURL(new Blob),t=e.toString();return URL.revokeObjectURL(e),t.slice(t.lastIndexOf("/")+1)}catch{let t=new Date().getTime();return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,i=>{const r=(t+Math.random()*16)%16|0;return t=Math.floor(t/16),(i=="x"?r:r&3|8).toString(16)})}}}function Ut(n){let e=5381,t=n.length;for(;t;)e=e*33^n.charCodeAt(--t);return(e>>>0).toString()}const Rt=.025;let Bs=function(n){return n[n.Point=0]="Point",n[n.Range=1]="Range",n}({});function Pd(n,e,t){return`${n.identifier}-${t+1}-${Ut(e)}`}class kd{constructor(e,t){this.base=void 0,this._duration=null,this._timelineStart=null,this.appendInPlaceDisabled=void 0,this.appendInPlaceStarted=void 0,this.dateRange=void 0,this.hasPlayed=!1,this.cumulativeDuration=0,this.resumeOffset=NaN,this.playoutLimit=NaN,this.restrictions={skip:!1,jump:!1},this.snapOptions={out:!1,in:!1},this.assetList=[],this.assetListLoader=void 0,this.assetListResponse=null,this.resumeAnchor=void 0,this.error=void 0,this.resetOnResume=void 0,this.base=t,this.dateRange=e,this.setDateRange(e)}setDateRange(e){this.dateRange=e,this.resumeOffset=e.attr.optionalFloat("X-RESUME-OFFSET",this.resumeOffset),this.playoutLimit=e.attr.optionalFloat("X-PLAYOUT-LIMIT",this.playoutLimit),this.restrictions=e.attr.enumeratedStringList("X-RESTRICT",this.restrictions),this.snapOptions=e.attr.enumeratedStringList("X-SNAP",this.snapOptions)}reset(){var e;this.appendInPlaceStarted=!1,(e=this.assetListLoader)==null||e.destroy(),this.assetListLoader=void 0,this.supplementsPrimary||(this.assetListResponse=null,this.assetList=[],this._duration=null)}isAssetPastPlayoutLimit(e){var t;if(e>0&&e>=this.assetList.length)return!0;const s=this.playoutLimit;return e<=0||isNaN(s)?!1:s===0?!0:(((t=this.assetList[e])==null?void 0:t.startOffset)||0)>s}findAssetIndex(e){return this.assetList.indexOf(e)}get identifier(){return this.dateRange.id}get startDate(){return this.dateRange.startDate}get startTime(){const e=this.dateRange.startTime;if(this.snapOptions.out){const t=this.dateRange.tagAnchor;if(t)return ai(e,t)}return e}get startOffset(){return this.cue.pre?0:this.startTime}get startIsAligned(){if(this.startTime===0||this.snapOptions.out)return!0;const e=this.dateRange.tagAnchor;if(e){const t=this.dateRange.startTime,s=ai(t,e);return t-s<.1}return!1}get resumptionOffset(){const e=this.resumeOffset,t=M(e)?e:this.duration;return this.cumulativeDuration+t}get resumeTime(){const e=this.startOffset+this.resumptionOffset;if(this.snapOptions.in){const t=this.resumeAnchor;if(t)return ai(e,t)}return e}get appendInPlace(){return this.appendInPlaceStarted?!0:this.appendInPlaceDisabled?!1:!!(!this.cue.once&&!this.cue.pre&&this.startIsAligned&&(isNaN(this.playoutLimit)&&isNaN(this.resumeOffset)||this.resumeOffset&&this.duration&&Math.abs(this.resumeOffset-this.duration)<Rt))}set appendInPlace(e){if(this.appendInPlaceStarted){this.resetOnResume=!e;return}this.appendInPlaceDisabled=!e}get timelineStart(){return this._timelineStart!==null?this._timelineStart:this.startTime}set timelineStart(e){this._timelineStart=e}get duration(){const e=this.playoutLimit;let t;return this._duration!==null?t=this._duration:this.dateRange.duration?t=this.dateRange.duration:t=this.dateRange.plannedDuration||0,!isNaN(e)&&e<t&&(t=e),t}set duration(e){this._duration=e}get cue(){return this.dateRange.cue}get timelineOccupancy(){return this.dateRange.attr["X-TIMELINE-OCCUPIES"]==="RANGE"?Bs.Range:Bs.Point}get supplementsPrimary(){return this.dateRange.attr["X-TIMELINE-STYLE"]==="PRIMARY"}get contentMayVary(){return this.dateRange.attr["X-CONTENT-MAY-VARY"]!=="NO"}get assetUrl(){return this.dateRange.attr["X-ASSET-URI"]}get assetListUrl(){return this.dateRange.attr["X-ASSET-LIST"]}get baseUrl(){return this.base.url}get assetListLoaded(){return this.assetList.length>0||this.assetListResponse!==null}toString(){return wd(this)}}function ai(n,e){return n-e.start<e.duration/2&&!(Math.abs(n-(e.start+e.duration))<Rt)?e.start:e.start+e.duration}function Bo(n,e,t){const s=new self.URL(n,t);return s.protocol!=="data:"&&s.searchParams.set("_HLS_primary_id",e),s}function oi(n,e){for(;(t=n.assetList[++e])!=null&&t.error;)var t;return e}function wd(n){return`["${n.identifier}" ${n.cue.pre?"<pre>":n.cue.post?"<post>":""}${n.timelineStart.toFixed(2)}-${n.resumeTime.toFixed(2)}]`}function xt(n){const e=n.timelineStart,t=n.duration||0;return`["${n.identifier}" ${e.toFixed(2)}-${(e+t).toFixed(2)}]`}class Od{constructor(e,t,s,i){this.hls=void 0,this.interstitial=void 0,this.assetItem=void 0,this.tracks=null,this.hasDetails=!1,this.mediaAttached=null,this._currentTime=void 0,this._bufferedEosTime=void 0,this.checkPlayout=()=>{this.reachedPlayout(this.currentTime)&&this.hls&&this.hls.trigger(m.PLAYOUT_LIMIT_REACHED,{})};const r=this.hls=new e(t);this.interstitial=s,this.assetItem=i;const a=()=>{this.hasDetails=!0};r.once(m.LEVEL_LOADED,a),r.once(m.AUDIO_TRACK_LOADED,a),r.once(m.SUBTITLE_TRACK_LOADED,a),r.on(m.MEDIA_ATTACHING,(o,{media:c})=>{this.removeMediaListeners(),this.mediaAttached=c,this.interstitial.playoutLimit&&(c.addEventListener("timeupdate",this.checkPlayout),this.appendInPlace&&r.on(m.BUFFER_APPENDED,()=>{const h=this.bufferedEnd;this.reachedPlayout(h)&&(this._bufferedEosTime=h,r.trigger(m.BUFFERED_TO_END,void 0))}))})}get appendInPlace(){return this.interstitial.appendInPlace}loadSource(){const e=this.hls;if(e)if(e.url)e.levels.length&&!e.started&&e.startLoad(-1,!0);else{let t=this.assetItem.uri;try{t=Bo(t,e.config.primarySessionId||"").href}catch{}e.loadSource(t)}}bufferedInPlaceToEnd(e){var t;if(!this.appendInPlace)return!1;if((t=this.hls)!=null&&t.bufferedToEnd)return!0;if(!e)return!1;const s=Math.min(this._bufferedEosTime||1/0,this.duration),i=this.timelineOffset,r=q.bufferInfo(e,i,0);return this.getAssetTime(r.end)>=s-.02}reachedPlayout(e){const s=this.interstitial.playoutLimit;return this.startOffset+e>=s}get destroyed(){var e;return!((e=this.hls)!=null&&e.userConfig)}get assetId(){return this.assetItem.identifier}get interstitialId(){return this.assetItem.parentIdentifier}get media(){var e;return((e=this.hls)==null?void 0:e.media)||null}get bufferedEnd(){const e=this.media||this.mediaAttached;if(!e)return this._bufferedEosTime?this._bufferedEosTime:this.currentTime;const t=q.bufferInfo(e,e.currentTime,.001);return this.getAssetTime(t.end)}get currentTime(){const e=this.media||this.mediaAttached;return e?this.getAssetTime(e.currentTime):this._currentTime||0}get duration(){const e=this.assetItem.duration;if(!e)return 0;const t=this.interstitial.playoutLimit;if(t){const s=t-this.startOffset;if(s>0&&s<e)return s}return e}get remaining(){const e=this.duration;return e?Math.max(0,e-this.currentTime):0}get startOffset(){return this.assetItem.startOffset}get timelineOffset(){var e;return((e=this.hls)==null?void 0:e.config.timelineOffset)||0}set timelineOffset(e){const t=this.timelineOffset;if(e!==t){const s=e-t;if(Math.abs(s)>1/9e4&&this.hls){if(this.hasDetails)throw new Error("Cannot set timelineOffset after playlists are loaded");this.hls.config.timelineOffset=e}}}getAssetTime(e){const t=this.timelineOffset,s=this.duration;return Math.min(Math.max(0,e-t),s)}removeMediaListeners(){const e=this.mediaAttached;e&&(this._currentTime=e.currentTime,this.bufferSnapShot(),e.removeEventListener("timeupdate",this.checkPlayout))}bufferSnapShot(){if(this.mediaAttached){var e;(e=this.hls)!=null&&e.bufferedToEnd&&(this._bufferedEosTime=this.bufferedEnd)}}destroy(){this.removeMediaListeners(),this.hls&&this.hls.destroy(),this.hls=null,this.tracks=this.mediaAttached=this.checkPlayout=null}attachMedia(e){var t;this.loadSource(),(t=this.hls)==null||t.attachMedia(e)}detachMedia(){var e;this.removeMediaListeners(),this.mediaAttached=null,(e=this.hls)==null||e.detachMedia()}resumeBuffering(){var e;(e=this.hls)==null||e.resumeBuffering()}pauseBuffering(){var e;(e=this.hls)==null||e.pauseBuffering()}transferMedia(){var e;return this.bufferSnapShot(),((e=this.hls)==null?void 0:e.transferMedia())||null}resetDetails(){const e=this.hls;if(e&&this.hasDetails){e.stopLoad();const t=s=>delete s.details;e.levels.forEach(t),e.allAudioTracks.forEach(t),e.allSubtitleTracks.forEach(t),this.hasDetails=!1}}on(e,t,s){var i;(i=this.hls)==null||i.on(e,t)}once(e,t,s){var i;(i=this.hls)==null||i.once(e,t)}off(e,t,s){var i;(i=this.hls)==null||i.off(e,t)}toString(){var e;return`HlsAssetPlayer: ${xt(this.assetItem)} ${(e=this.hls)==null?void 0:e.sessionId} ${this.appendInPlace?"append-in-place":""}`}}const Nn=.033;class Fd extends Fe{constructor(e,t){super("interstitials-sched",t),this.onScheduleUpdate=void 0,this.eventMap={},this.events=null,this.items=null,this.durations={primary:0,playout:0,integrated:0},this.onScheduleUpdate=e}destroy(){this.reset(),this.onScheduleUpdate=null}reset(){this.eventMap={},this.setDurations(0,0,0),this.events&&this.events.forEach(e=>e.reset()),this.events=this.items=null}resetErrorsInRange(e,t){return this.events?this.events.reduce((s,i)=>e<=i.startOffset&&t>i.startOffset?(delete i.error,s+1):s,0):0}get duration(){const e=this.items;return e?e[e.length-1].end:0}get length(){return this.items?this.items.length:0}getEvent(e){return e&&this.eventMap[e]||null}hasEvent(e){return e in this.eventMap}findItemIndex(e,t){if(e.event)return this.findEventIndex(e.event.identifier);let s=-1;e.nextEvent?s=this.findEventIndex(e.nextEvent.identifier)-1:e.previousEvent&&(s=this.findEventIndex(e.previousEvent.identifier)+1);const i=this.items;if(i)for(i[s]||(t===void 0&&(t=e.start),s=this.findItemIndexAtTime(t));s>=0&&(r=i[s])!=null&&r.event;){var r;s--}return s}findItemIndexAtTime(e,t){const s=this.items;if(s)for(let i=0;i<s.length;i++){let r=s[i];if(t&&t!=="primary"&&(r=r[t]),e===r.start||e>r.start&&e<r.end)return i}return-1}findJumpRestrictedIndex(e,t){const s=this.items;if(s)for(let i=e;i<=t&&s[i];i++){const r=s[i].event;if(r!=null&&r.restrictions.jump&&!r.appendInPlace)return i}return-1}findEventIndex(e){const t=this.items;if(t)for(let i=t.length;i--;){var s;if(((s=t[i].event)==null?void 0:s.identifier)===e)return i}return-1}findAssetIndex(e,t){const s=e.assetList,i=s.length;if(i>1)for(let r=0;r<i;r++){const a=s[r];if(!a.error){const o=a.timelineStart;if(t===o||t>o&&(t<o+(a.duration||0)||r===i-1))return r}}return 0}get assetIdAtEnd(){var e;const t=(e=this.items)==null||(e=e[this.length-1])==null?void 0:e.event;if(t){const s=t.assetList,i=s[s.length-1];if(i)return i.identifier}return null}parseInterstitialDateRanges(e,t){const s=e.main.details,{dateRanges:i}=s,r=this.events,a=this.parseDateRanges(i,{url:s.url},t),o=Object.keys(i),c=r?r.filter(l=>!o.includes(l.identifier)):[];a.length&&a.sort((l,h)=>{const u=l.cue.pre,d=l.cue.post,f=h.cue.pre,g=h.cue.post;if(u&&!f)return-1;if(f&&!u||d&&!g)return 1;if(g&&!d)return-1;if(!u&&!f&&!d&&!g){const p=l.startTime,y=h.startTime;if(p!==y)return p-y}return l.dateRange.tagOrder-h.dateRange.tagOrder}),this.events=a,c.forEach(l=>{this.removeEvent(l)}),this.updateSchedule(e,c)}updateSchedule(e,t=[],s=!1){const i=this.events||[];if(i.length||t.length||this.length<2){const r=this.items,a=this.parseSchedule(i,e);(s||t.length||(r==null?void 0:r.length)!==a.length||a.some((c,l)=>Math.abs(c.playout.start-r[l].playout.start)>.005||Math.abs(c.playout.end-r[l].playout.end)>.005))&&(this.items=a,this.onScheduleUpdate(t,r))}}parseDateRanges(e,t,s){const i=[],r=Object.keys(e);for(let a=0;a<r.length;a++){const o=r[a],c=e[o];if(c.isInterstitial){let l=this.eventMap[o];l?l.setDateRange(c):(l=new kd(c,t),this.eventMap[o]=l,s===!1&&(l.appendInPlace=s)),i.push(l)}}return i}parseSchedule(e,t){const s=[],i=t.main.details,r=i.live?1/0:i.edge;let a=0;if(e=e.filter(c=>!c.error&&!(c.cue.once&&c.hasPlayed)),e.length){this.resolveOffsets(e,t);let c=0,l=0;if(e.forEach((h,u)=>{const d=h.cue.pre,f=h.cue.post,g=e[u-1]||null,p=h.appendInPlace,y=f?r:h.startOffset,E=h.duration,T=h.timelineOccupancy===Bs.Range?E:0,S=h.resumptionOffset,v=(g==null?void 0:g.startTime)===y,x=y+h.cumulativeDuration;let D=p?x+E:y+S;if(d||!f&&y<=0){const b=l;l+=T,h.timelineStart=x;const I=a;a+=E,s.push({event:h,start:x,end:D,playout:{start:I,end:a},integrated:{start:b,end:l}})}else if(y<=r){if(!v){const _=y-c;if(_>Nn){const C=c,k=l;l+=_;const B=a;a+=_;const K={previousEvent:e[u-1]||null,nextEvent:h,start:C,end:C+_,playout:{start:B,end:a},integrated:{start:k,end:l}};s.push(K)}else _>0&&g&&(g.cumulativeDuration+=_,s[s.length-1].end=y)}f&&(D=x),h.timelineStart=x;const b=l;l+=T;const I=a;a+=E,s.push({event:h,start:x,end:D,playout:{start:I,end:a},integrated:{start:b,end:l}})}else return;const A=h.resumeTime;f||A>r?c=r:c=A}),c<r){var o;const h=c,u=l,d=r-c;l+=d;const f=a;a+=d,s.push({previousEvent:((o=s[s.length-1])==null?void 0:o.event)||null,nextEvent:null,start:c,end:h+d,playout:{start:f,end:a},integrated:{start:u,end:l}})}this.setDurations(r,a,l)}else s.push({previousEvent:null,nextEvent:null,start:0,end:r,playout:{start:0,end:r},integrated:{start:0,end:r}}),this.setDurations(r,r,r);return s}setDurations(e,t,s){this.durations={primary:e,playout:t,integrated:s}}resolveOffsets(e,t){const s=t.main.details,i=s.live?1/0:s.edge;let r=0,a=-1;e.forEach((o,c)=>{const l=o.cue.pre,h=o.cue.post,u=l?0:h?i:o.startTime;this.updateAssetDurations(o),a===u?o.cumulativeDuration=r:(r=0,a=u),!h&&o.snapOptions.in&&(o.resumeAnchor=mt(null,s.fragments,o.startOffset+o.resumptionOffset,0,0)||void 0),o.appendInPlace&&!o.appendInPlaceStarted&&(this.primaryCanResumeInPlaceAt(o,t)||(o.appendInPlace=!1)),!o.appendInPlace&&c+1<e.length&&e[c+1].startTime-e[c].resumeTime<Nn&&(e[c+1].appendInPlace=!1,e[c+1].appendInPlace&&this.warn(`Could not change append strategy for abutting event ${o}`));const f=M(o.resumeOffset)?o.resumeOffset:o.duration;r+=f})}primaryCanResumeInPlaceAt(e,t){const s=e.resumeTime,i=e.startTime+e.resumptionOffset;return Math.abs(s-i)>Rt?(this.log(`"${e.identifier}" resumption ${s} not aligned with estimated timeline end ${i}`),!1):!Object.keys(t).some(a=>{const o=t[a].details,c=o.edge;if(s>=c)return this.log(`"${e.identifier}" resumption ${s} past ${a} playlist end ${c}`),!1;const l=mt(null,o.fragments,s);if(!l)return this.log(`"${e.identifier}" resumption ${s} does not align with any fragments in ${a} playlist (${o.fragStart}-${o.fragmentEnd})`),!0;const h=a==="audio"?.175:0;return Math.abs(l.start-s)<Rt+h||Math.abs(l.end-s)<Rt+h?!1:(this.log(`"${e.identifier}" resumption ${s} not aligned with ${a} fragment bounds (${l.start}-${l.end} sn: ${l.sn} cc: ${l.cc})`),!0)})}updateAssetDurations(e){if(!e.assetListLoaded)return;const t=e.timelineStart;let s=0,i=!1,r=!1;for(let a=0;a<e.assetList.length;a++){const o=e.assetList[a],c=t+s;o.startOffset=s,o.timelineStart=c,i||(i=o.duration===null),r||(r=!!o.error);const l=o.error?0:o.duration||0;s+=l}i&&!r?e.duration=Math.max(s,e.duration):e.duration=s}removeEvent(e){e.reset(),delete this.eventMap[e.identifier]}}function Ne(n){return`[${n.event?'"'+n.event.identifier+'"':"primary"}: ${n.start.toFixed(2)}-${n.end.toFixed(2)}]`}class Md{constructor(e){this.hls=void 0,this.hls=e}destroy(){this.hls=null}loadAssetList(e,t){const s=e.assetListUrl;let i;try{i=Bo(s,this.hls.sessionId,e.baseUrl)}catch(d){const f=this.assignAssetListError(e,R.ASSET_LIST_LOAD_ERROR,d,s);this.hls.trigger(m.ERROR,f);return}t&&i.protocol!=="data:"&&i.searchParams.set("_HLS_start_offset",""+t);const r=this.hls.config,a=r.loader,o=new a(r),c={responseType:"json",url:i.href},l=r.interstitialAssetListLoadPolicy.default,h={loadPolicy:l,timeout:l.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},u={onSuccess:(d,f,g,p)=>{const y=d.data,E=y==null?void 0:y.ASSETS;if(!Array.isArray(E)){const T=this.assignAssetListError(e,R.ASSET_LIST_PARSING_ERROR,new Error("Invalid interstitial asset list"),g.url,f,p);this.hls.trigger(m.ERROR,T);return}e.assetListResponse=y,this.hls.trigger(m.ASSET_LIST_LOADED,{event:e,assetListResponse:y,networkDetails:p})},onError:(d,f,g,p)=>{const y=this.assignAssetListError(e,R.ASSET_LIST_LOAD_ERROR,new Error(`Error loading X-ASSET-LIST: HTTP status ${d.code} ${d.text} (${f.url})`),f.url,p,g);this.hls.trigger(m.ERROR,y)},onTimeout:(d,f,g)=>{const p=this.assignAssetListError(e,R.ASSET_LIST_LOAD_TIMEOUT,new Error(`Timeout loading X-ASSET-LIST (${f.url})`),f.url,d,g);this.hls.trigger(m.ERROR,p)}};return o.load(c,h,u),this.hls.trigger(m.ASSET_LIST_LOADING,{event:e}),o}assignAssetListError(e,t,s,i,r,a){return e.error=s,{type:H.NETWORK_ERROR,details:t,fatal:!1,interstitial:e,url:i,error:s,networkDetails:a,stats:r}}}function Bn(n){var e;n==null||(e=n.play())==null||e.catch(()=>{})}function as(n,e){return`[${n}] Advancing timeline position to ${e}`}class Nd extends Fe{constructor(e,t){super("interstitials",e.logger),this.HlsPlayerClass=void 0,this.hls=void 0,this.assetListLoader=void 0,this.mediaSelection=null,this.altSelection=null,this.media=null,this.detachedData=null,this.requiredTracks=null,this.manager=null,this.playerQueue=[],this.bufferedPos=-1,this.timelinePos=-1,this.schedule=void 0,this.playingItem=null,this.bufferingItem=null,this.waitingItem=null,this.endedItem=null,this.playingAsset=null,this.endedAsset=null,this.bufferingAsset=null,this.shouldPlay=!1,this.onPlay=()=>{this.shouldPlay=!0},this.onPause=()=>{this.shouldPlay=!1},this.onSeeking=()=>{const s=this.currentTime;if(s===void 0||this.playbackDisabled||!this.schedule)return;const i=s-this.timelinePos;if(Math.abs(i)<1/7056e5)return;const a=i<=-.01;this.timelinePos=s,this.bufferedPos=s;const o=this.playingItem;if(!o){this.checkBuffer();return}if(a&&this.schedule.resetErrorsInRange(s,s-i)&&this.updateSchedule(!0),this.checkBuffer(),a&&s<o.start||s>=o.end){var c;const f=this.findItemIndex(o);let g=this.schedule.findItemIndexAtTime(s);if(g===-1&&(g=f+(a?-1:1),this.log(`seeked ${a?"back ":""}to position not covered by schedule ${s} (resolving from ${f} to ${g})`)),!this.isInterstitial(o)&&(c=this.media)!=null&&c.paused&&(this.shouldPlay=!1),!a&&g>f){const p=this.schedule.findJumpRestrictedIndex(f+1,g);if(p>f){this.setSchedulePosition(p);return}}this.setSchedulePosition(g);return}const l=this.playingAsset;if(!l){if(this.playingLastItem&&this.isInterstitial(o)){const f=o.event.assetList[0];f&&(this.endedItem=this.playingItem,this.playingItem=null,this.setScheduleToAssetAtTime(s,f))}return}const h=l.timelineStart,u=l.duration||0;if(a&&s<h||s>=h+u){var d;(d=o.event)!=null&&d.appendInPlace&&(this.clearAssetPlayers(o.event,o),this.flushFrontBuffer(s)),this.setScheduleToAssetAtTime(s,l)}},this.onTimeupdate=()=>{const s=this.currentTime;if(s===void 0||this.playbackDisabled)return;if(s>this.timelinePos)this.timelinePos=s,s>this.bufferedPos&&this.checkBuffer();else return;const i=this.playingItem;if(!i||this.playingLastItem)return;if(s>=i.end){this.timelinePos=i.end;const o=this.findItemIndex(i);this.setSchedulePosition(o+1)}const r=this.playingAsset;if(!r)return;const a=r.timelineStart+(r.duration||0);s>=a&&this.setScheduleToAssetAtTime(s,r)},this.onScheduleUpdate=(s,i)=>{const r=this.schedule;if(!r)return;const a=this.playingItem,o=r.events||[],c=r.items||[],l=r.durations,h=s.map(p=>p.identifier),u=!!(o.length||h.length);(u||i)&&this.log(`INTERSTITIALS_UPDATED (${o.length}): ${o}
117117+Schedule: ${c.map(p=>Ne(p))} pos: ${this.timelinePos}`),h.length&&this.log(`Removed events ${h}`);let d=null,f=null;a&&(d=this.updateItem(a,this.timelinePos),this.itemsMatch(a,d)?this.playingItem=d:this.waitingItem=this.endedItem=null),this.waitingItem=this.updateItem(this.waitingItem),this.endedItem=this.updateItem(this.endedItem);const g=this.bufferingItem;if(g&&(f=this.updateItem(g,this.bufferedPos),this.itemsMatch(g,f)?this.bufferingItem=f:g.event&&(this.bufferingItem=this.playingItem,this.clearInterstitial(g.event,null))),s.forEach(p=>{p.assetList.forEach(y=>{this.clearAssetPlayer(y.identifier,null)})}),this.playerQueue.forEach(p=>{if(p.interstitial.appendInPlace){const y=p.assetItem.timelineStart,E=p.timelineOffset-y;if(E)try{p.timelineOffset=y}catch(T){Math.abs(E)>Rt&&this.warn(`${T} ("${p.assetId}" ${p.timelineOffset}->${y})`)}}}),u||i){if(this.hls.trigger(m.INTERSTITIALS_UPDATED,{events:o.slice(0),schedule:c.slice(0),durations:l,removedIds:h}),this.isInterstitial(a)&&h.includes(a.event.identifier)){this.warn(`Interstitial "${a.event.identifier}" removed while playing`),this.primaryFallback(a.event);return}a&&this.trimInPlace(d,a),g&&f!==d&&this.trimInPlace(f,g),this.checkBuffer()}},this.hls=e,this.HlsPlayerClass=t,this.assetListLoader=new Md(e),this.schedule=new Fd(this.onScheduleUpdate,e.logger),this.registerListeners()}registerListeners(){const e=this.hls;e&&(e.on(m.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(m.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(m.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(m.MANIFEST_LOADING,this.onManifestLoading,this),e.on(m.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(m.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(m.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),e.on(m.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.on(m.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),e.on(m.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),e.on(m.ASSET_LIST_LOADED,this.onAssetListLoaded,this),e.on(m.BUFFER_APPENDED,this.onBufferAppended,this),e.on(m.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(m.BUFFERED_TO_END,this.onBufferedToEnd,this),e.on(m.MEDIA_ENDED,this.onMediaEnded,this),e.on(m.ERROR,this.onError,this),e.on(m.DESTROYING,this.onDestroying,this))}unregisterListeners(){const e=this.hls;e&&(e.off(m.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(m.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(m.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(m.MANIFEST_LOADING,this.onManifestLoading,this),e.off(m.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(m.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(m.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),e.off(m.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.off(m.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),e.off(m.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),e.off(m.ASSET_LIST_LOADED,this.onAssetListLoaded,this),e.off(m.BUFFER_CODECS,this.onBufferCodecs,this),e.off(m.BUFFER_APPENDED,this.onBufferAppended,this),e.off(m.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(m.BUFFERED_TO_END,this.onBufferedToEnd,this),e.off(m.MEDIA_ENDED,this.onMediaEnded,this),e.off(m.ERROR,this.onError,this),e.off(m.DESTROYING,this.onDestroying,this))}startLoad(){this.resumeBuffering()}stopLoad(){this.pauseBuffering()}resumeBuffering(){var e;(e=this.getBufferingPlayer())==null||e.resumeBuffering()}pauseBuffering(){var e;(e=this.getBufferingPlayer())==null||e.pauseBuffering()}destroy(){this.unregisterListeners(),this.stopLoad(),this.assetListLoader&&this.assetListLoader.destroy(),this.emptyPlayerQueue(),this.clearScheduleState(),this.schedule&&this.schedule.destroy(),this.media=this.detachedData=this.mediaSelection=this.requiredTracks=this.altSelection=this.schedule=this.manager=null,this.hls=this.HlsPlayerClass=this.log=null,this.assetListLoader=null,this.onPlay=this.onPause=this.onSeeking=this.onTimeupdate=null,this.onScheduleUpdate=null}onDestroying(){const e=this.primaryMedia||this.media;e&&this.removeMediaListeners(e)}removeMediaListeners(e){Ie(e,"play",this.onPlay),Ie(e,"pause",this.onPause),Ie(e,"seeking",this.onSeeking),Ie(e,"timeupdate",this.onTimeupdate)}onMediaAttaching(e,t){const s=this.media=t.media;Ae(s,"seeking",this.onSeeking),Ae(s,"timeupdate",this.onTimeupdate),Ae(s,"play",this.onPlay),Ae(s,"pause",this.onPause)}onMediaAttached(e,t){const s=this.effectivePlayingItem,i=this.detachedData;if(this.detachedData=null,s===null)this.checkStart();else if(!i){this.clearScheduleState();const r=this.findItemIndex(s);this.setSchedulePosition(r)}}clearScheduleState(){this.log("clear schedule state"),this.playingItem=this.bufferingItem=this.waitingItem=this.endedItem=this.playingAsset=this.endedAsset=this.bufferingAsset=null}onMediaDetaching(e,t){const s=!!t.transferMedia,i=this.media;if(this.media=null,!s&&(i&&this.removeMediaListeners(i),this.detachedData)){const r=this.getBufferingPlayer();r&&(this.log(`Removing schedule state for detachedData and ${r}`),this.playingAsset=this.endedAsset=this.bufferingAsset=this.bufferingItem=this.waitingItem=this.detachedData=null,r.detachMedia()),this.shouldPlay=!1}}get interstitialsManager(){if(!this.hls)return null;if(this.manager)return this.manager;const e=this,t=()=>e.bufferingItem||e.waitingItem,s=u=>u&&e.getAssetPlayer(u.identifier),i=(u,d,f,g,p)=>{if(u){let y=u[d].start;const E=u.event;if(E){if(d==="playout"||E.timelineOccupancy!==Bs.Point){const T=s(f);(T==null?void 0:T.interstitial)===E&&(y+=T.assetItem.startOffset+T[p])}}else{const T=g==="bufferedPos"?a():e[g];y+=T-u.start}return y}return 0},r=(u,d)=>{var f;if(u!==0&&d!=="primary"&&(f=e.schedule)!=null&&f.length){var g;const p=e.schedule.findItemIndexAtTime(u),y=(g=e.schedule.items)==null?void 0:g[p];if(y){const E=y[d].start-y.start;return u+E}}return u},a=()=>{const u=e.bufferedPos;return u===Number.MAX_VALUE?o("primary"):Math.max(u,0)},o=u=>{var d,f;return(d=e.primaryDetails)!=null&&d.live?e.primaryDetails.edge:((f=e.schedule)==null?void 0:f.durations[u])||0},c=(u,d)=>{var f,g;const p=e.effectivePlayingItem;if(p!=null&&(f=p.event)!=null&&f.restrictions.skip||!e.schedule)return;e.log(`seek to ${u} "${d}"`);const y=e.effectivePlayingItem,E=e.schedule.findItemIndexAtTime(u,d),T=(g=e.schedule.items)==null?void 0:g[E],S=e.getBufferingPlayer(),v=S==null?void 0:S.interstitial,x=v==null?void 0:v.appendInPlace,D=y&&e.itemsMatch(y,T);if(y&&(x||D)){const A=s(e.playingAsset),b=(A==null?void 0:A.media)||e.primaryMedia;if(b){const I=d==="primary"?b.currentTime:i(y,d,e.playingAsset,"timelinePos","currentTime"),_=u-I,C=(x?I:b.currentTime)+_;if(C>=0&&(!A||x||C<=A.duration)){b.currentTime=C;return}}}if(T){let A=u;if(d!=="primary"){const I=T[d].start,_=u-I;A=T.start+_}const b=!e.isInterstitial(T);if((!e.isInterstitial(y)||y.event.appendInPlace)&&(b||T.event.appendInPlace)){const I=e.media||(x?S==null?void 0:S.media:null);I&&(I.currentTime=A)}else if(y){const I=e.findItemIndex(y);if(E>I){const C=e.schedule.findJumpRestrictedIndex(I+1,E);if(C>I){e.setSchedulePosition(C);return}}let _=0;if(b)e.timelinePos=A,e.checkBuffer();else{const C=T.event.assetList,k=u-(T[d]||T).start;for(let B=C.length;B--;){const K=C[B];if(K.duration&&k>=K.startOffset&&k<K.startOffset+K.duration){_=B;break}}}e.setSchedulePosition(E,_)}}},l=()=>{const u=e.effectivePlayingItem;if(e.isInterstitial(u))return u;const d=t();return e.isInterstitial(d)?d:null},h={get bufferedEnd(){const u=t(),d=e.bufferingItem;if(d&&d===u){var f;return i(d,"playout",e.bufferingAsset,"bufferedPos","bufferedEnd")-d.playout.start||((f=e.bufferingAsset)==null?void 0:f.startOffset)||0}return 0},get currentTime(){const u=l(),d=e.effectivePlayingItem;return d&&d===u?i(d,"playout",e.effectivePlayingAsset,"timelinePos","currentTime")-d.playout.start:0},set currentTime(u){const d=l(),f=e.effectivePlayingItem;f&&f===d&&c(u+f.playout.start,"playout")},get duration(){const u=l();return u?u.playout.end-u.playout.start:0},get assetPlayers(){var u;const d=(u=l())==null?void 0:u.event.assetList;return d?d.map(f=>e.getAssetPlayer(f.identifier)):[]},get playingIndex(){var u;const d=(u=l())==null?void 0:u.event;return d&&e.effectivePlayingAsset?d.findAssetIndex(e.effectivePlayingAsset):-1},get scheduleItem(){return l()}};return this.manager={get events(){var u;return((u=e.schedule)==null||(u=u.events)==null?void 0:u.slice(0))||[]},get schedule(){var u;return((u=e.schedule)==null||(u=u.items)==null?void 0:u.slice(0))||[]},get interstitialPlayer(){return l()?h:null},get playerQueue(){return e.playerQueue.slice(0)},get bufferingAsset(){return e.bufferingAsset},get bufferingItem(){return t()},get bufferingIndex(){const u=t();return e.findItemIndex(u)},get playingAsset(){return e.effectivePlayingAsset},get playingItem(){return e.effectivePlayingItem},get playingIndex(){const u=e.effectivePlayingItem;return e.findItemIndex(u)},primary:{get bufferedEnd(){return a()},get currentTime(){const u=e.timelinePos;return u>0?u:0},set currentTime(u){c(u,"primary")},get duration(){return o("primary")},get seekableStart(){var u;return((u=e.primaryDetails)==null?void 0:u.fragmentStart)||0}},integrated:{get bufferedEnd(){return i(t(),"integrated",e.bufferingAsset,"bufferedPos","bufferedEnd")},get currentTime(){return i(e.effectivePlayingItem,"integrated",e.effectivePlayingAsset,"timelinePos","currentTime")},set currentTime(u){c(u,"integrated")},get duration(){return o("integrated")},get seekableStart(){var u;return r(((u=e.primaryDetails)==null?void 0:u.fragmentStart)||0,"integrated")}},skip:()=>{const u=e.effectivePlayingItem,d=u==null?void 0:u.event;if(d&&!d.restrictions.skip){const f=e.findItemIndex(u);if(d.appendInPlace){const g=u.playout.start+u.event.duration;c(g+.001,"playout")}else e.advanceAfterAssetEnded(d,f,1/0)}}}}get effectivePlayingItem(){return this.waitingItem||this.playingItem||this.endedItem}get effectivePlayingAsset(){return this.playingAsset||this.endedAsset}get playingLastItem(){var e;const t=this.playingItem,s=(e=this.schedule)==null?void 0:e.items;return!this.playbackStarted||!t||!s?!1:this.findItemIndex(t)===s.length-1}get playbackStarted(){return this.effectivePlayingItem!==null}get currentTime(){var e,t;if(this.mediaSelection===null)return;const s=this.waitingItem||this.playingItem;if(this.isInterstitial(s)&&!s.event.appendInPlace)return;let i=this.media;!i&&(e=this.bufferingItem)!=null&&(e=e.event)!=null&&e.appendInPlace&&(i=this.primaryMedia);const r=(t=i)==null?void 0:t.currentTime;if(!(r===void 0||!M(r)))return r}get primaryMedia(){var e;return this.media||((e=this.detachedData)==null?void 0:e.media)||null}isInterstitial(e){return!!(e!=null&&e.event)}retreiveMediaSource(e,t){const s=this.getAssetPlayer(e);s&&this.transferMediaFromPlayer(s,t)}transferMediaFromPlayer(e,t){const s=e.interstitial.appendInPlace,i=e.media;if(s&&i===this.primaryMedia){if(this.bufferingAsset=null,(!t||this.isInterstitial(t)&&!t.event.appendInPlace)&&t&&i){this.detachedData={media:i};return}const r=e.transferMedia();this.log(`transfer MediaSource from ${e} ${oe(r)}`),this.detachedData=r}else t&&i&&(this.shouldPlay||(this.shouldPlay=!i.paused))}transferMediaTo(e,t){var s,i;if(e.media===t)return;let r=null;const a=this.hls,o=e!==a,c=o&&e.interstitial.appendInPlace,l=(s=this.detachedData)==null?void 0:s.mediaSource;let h;if(a.media)c&&(r=a.transferMedia(),this.detachedData=r),h="Primary";else if(l){const g=this.getBufferingPlayer();g?(r=g.transferMedia(),h=`${g}`):h="detached MediaSource"}else h="detached media";if(!r){if(l)r=this.detachedData,this.log(`using detachedData: MediaSource ${oe(r)}`);else if(!this.detachedData||a.media===t){const g=this.playerQueue;g.length>1&&g.forEach(p=>{if(o&&p.interstitial.appendInPlace!==c){const y=p.interstitial;this.clearInterstitial(p.interstitial,null),y.appendInPlace=!1,y.appendInPlace&&this.warn(`Could not change append strategy for queued assets ${y}`)}}),this.hls.detachMedia(),this.detachedData={media:t}}}const u=r&&"mediaSource"in r&&((i=r.mediaSource)==null?void 0:i.readyState)!=="closed",d=u&&r?r:t;this.log(`${u?"transfering MediaSource":"attaching media"} to ${o?e:"Primary"} from ${h} (media.currentTime: ${t.currentTime})`);const f=this.schedule;if(d===r&&f){const g=o&&e.assetId===f.assetIdAtEnd;d.overrides={duration:f.duration,endOfStream:!o||g,cueRemoval:!o}}e.attachMedia(d)}onInterstitialCueEnter(){this.onTimeupdate()}checkStart(){const e=this.schedule,t=e==null?void 0:e.events;if(!t||this.playbackDisabled||!this.media)return;this.bufferedPos===-1&&(this.bufferedPos=0);const s=this.timelinePos,i=this.effectivePlayingItem;if(s===-1){const r=this.hls.startPosition;if(this.log(as("checkStart",r)),this.timelinePos=r,t.length&&t[0].cue.pre){const a=e.findEventIndex(t[0].identifier);this.setSchedulePosition(a)}else if(r>=0||!this.primaryLive){const a=this.timelinePos=r>0?r:0,o=e.findItemIndexAtTime(a);this.setSchedulePosition(o)}}else if(i&&!this.playingItem){const r=e.findItemIndex(i);this.setSchedulePosition(r)}}advanceAssetBuffering(e,t){const s=e.event,i=s.findAssetIndex(t),r=oi(s,i);if(!s.isAssetPastPlayoutLimit(r))this.bufferedToEvent(e,r);else if(this.schedule){var a;const o=(a=this.schedule.items)==null?void 0:a[this.findItemIndex(e)+1];o&&this.bufferedToItem(o)}}advanceAfterAssetEnded(e,t,s){const i=oi(e,s);if(e.isAssetPastPlayoutLimit(i)){if(this.schedule){const r=this.schedule.items;if(r){const a=t+1,o=r.length;if(a>=o){this.setSchedulePosition(-1);return}const c=e.resumeTime;this.timelinePos<c&&(this.log(as("advanceAfterAssetEnded",c)),this.timelinePos=c,e.appendInPlace&&this.advanceInPlace(c),this.checkBuffer(this.bufferedPos<c)),this.setSchedulePosition(a)}}}else{if(e.appendInPlace){const r=e.assetList[i];r&&this.advanceInPlace(r.timelineStart)}this.setSchedulePosition(t,i)}}setScheduleToAssetAtTime(e,t){const s=this.schedule;if(!s)return;const i=t.parentIdentifier,r=s.getEvent(i);if(r){const a=s.findEventIndex(i),o=s.findAssetIndex(r,e);this.advanceAfterAssetEnded(r,a,o-1)}}setSchedulePosition(e,t){var s;const i=(s=this.schedule)==null?void 0:s.items;if(!i||this.playbackDisabled)return;const r=e>=0?i[e]:null;this.log(`setSchedulePosition ${e}, ${t} (${r&&Ne(r)}) pos: ${this.timelinePos}`);const a=this.waitingItem||this.playingItem,o=this.playingLastItem;if(this.isInterstitial(a)){const h=a.event,u=this.playingAsset,d=u==null?void 0:u.identifier,f=d?this.getAssetPlayer(d):null;if(f&&d&&(!this.eventItemsMatch(a,r)||t!==void 0&&d!==h.assetList[t].identifier)){var c;const g=h.findAssetIndex(u);if(this.log(`INTERSTITIAL_ASSET_ENDED ${g+1}/${h.assetList.length} ${xt(u)}`),this.endedAsset=u,this.playingAsset=null,this.hls.trigger(m.INTERSTITIAL_ASSET_ENDED,{asset:u,assetListIndex:g,event:h,schedule:i.slice(0),scheduleIndex:e,player:f}),a!==this.playingItem){this.itemsMatch(a,this.playingItem)&&!this.playingAsset&&this.advanceAfterAssetEnded(h,this.findItemIndex(this.playingItem),g);return}this.retreiveMediaSource(d,r),f.media&&!((c=this.detachedData)!=null&&c.mediaSource)&&f.detachMedia()}if(!this.eventItemsMatch(a,r)&&(this.endedItem=a,this.playingItem=null,this.log(`INTERSTITIAL_ENDED ${h} ${Ne(a)}`),h.hasPlayed=!0,this.hls.trigger(m.INTERSTITIAL_ENDED,{event:h,schedule:i.slice(0),scheduleIndex:e}),h.cue.once)){var l;this.updateSchedule();const g=(l=this.schedule)==null?void 0:l.items;if(r&&g){const p=this.findItemIndex(r);this.advanceSchedule(p,g,t,a,o)}return}}this.advanceSchedule(e,i,t,a,o)}advanceSchedule(e,t,s,i,r){const a=this.schedule;if(!a)return;const o=t[e]||null,c=this.primaryMedia,l=this.playerQueue;if(l.length&&l.forEach(h=>{const u=h.interstitial,d=a.findEventIndex(u.identifier);(d<e||d>e+1)&&this.clearInterstitial(u,o)}),this.isInterstitial(o)){this.timelinePos=Math.min(Math.max(this.timelinePos,o.start),o.end);const h=o.event;if(s===void 0){s=a.findAssetIndex(h,this.timelinePos);const g=oi(h,s-1);if(h.isAssetPastPlayoutLimit(g)||h.appendInPlace&&this.timelinePos===o.end){this.advanceAfterAssetEnded(h,e,s);return}s=g}const u=this.waitingItem;this.assetsBuffered(o,c)||this.setBufferingItem(o);let d=this.preloadAssets(h,s);if(this.eventItemsMatch(o,u||i)||(this.waitingItem=o,this.log(`INTERSTITIAL_STARTED ${Ne(o)} ${h.appendInPlace?"append in place":""}`),this.hls.trigger(m.INTERSTITIAL_STARTED,{event:h,schedule:t.slice(0),scheduleIndex:e})),!h.assetListLoaded){this.log(`Waiting for ASSET-LIST to complete loading ${h}`);return}if(h.assetListLoader&&(h.assetListLoader.destroy(),h.assetListLoader=void 0),!c){this.log(`Waiting for attachMedia to start Interstitial ${h}`);return}this.waitingItem=this.endedItem=null,this.playingItem=o;const f=h.assetList[s];if(!f){this.advanceAfterAssetEnded(h,e,s||0);return}if(d||(d=this.getAssetPlayer(f.identifier)),d===null||d.destroyed){const g=h.assetList.length;this.warn(`asset ${s+1}/${g} player destroyed ${h}`),d=this.createAssetPlayer(h,f,s),d.loadSource()}if(!this.eventItemsMatch(o,this.bufferingItem)&&h.appendInPlace&&this.isAssetBuffered(f))return;this.startAssetPlayer(d,s,t,e,c),this.shouldPlay&&Bn(d.media)}else o?(this.resumePrimary(o,e,i),this.shouldPlay&&Bn(this.hls.media)):r&&this.isInterstitial(i)&&(this.endedItem=null,this.playingItem=i,i.event.appendInPlace||this.attachPrimary(a.durations.primary,null))}get playbackDisabled(){return this.hls.config.enableInterstitialPlayback===!1}get primaryDetails(){var e;return(e=this.mediaSelection)==null?void 0:e.main.details}get primaryLive(){var e;return!!((e=this.primaryDetails)!=null&&e.live)}resumePrimary(e,t,s){var i,r;if(this.playingItem=e,this.playingAsset=this.endedAsset=null,this.waitingItem=this.endedItem=null,this.bufferedToItem(e),this.log(`resuming ${Ne(e)}`),!((i=this.detachedData)!=null&&i.mediaSource)){let o=this.timelinePos;(o<e.start||o>=e.end)&&(o=this.getPrimaryResumption(e,t),this.log(as("resumePrimary",o)),this.timelinePos=o),this.attachPrimary(o,e)}if(!s)return;const a=(r=this.schedule)==null?void 0:r.items;a&&(this.log(`INTERSTITIALS_PRIMARY_RESUMED ${Ne(e)}`),this.hls.trigger(m.INTERSTITIALS_PRIMARY_RESUMED,{schedule:a.slice(0),scheduleIndex:t}),this.checkBuffer())}getPrimaryResumption(e,t){const s=e.start;if(this.primaryLive){const i=this.primaryDetails;if(t===0)return this.hls.startPosition;if(i&&(s<i.fragmentStart||s>i.edge))return this.hls.liveSyncPosition||-1}return s}isAssetBuffered(e){const t=this.getAssetPlayer(e.identifier);return t!=null&&t.hls?t.hls.bufferedToEnd:q.bufferInfo(this.primaryMedia,this.timelinePos,0).end+1>=e.timelineStart+(e.duration||0)}attachPrimary(e,t,s){t?this.setBufferingItem(t):this.bufferingItem=this.playingItem,this.bufferingAsset=null;const i=this.primaryMedia;if(!i)return;const r=this.hls;r.media?this.checkBuffer():(this.transferMediaTo(r,i),s&&this.startLoadingPrimaryAt(e,s)),s||(this.log(as("attachPrimary",e)),this.timelinePos=e,this.startLoadingPrimaryAt(e,s))}startLoadingPrimaryAt(e,t){var s;const i=this.hls;!i.loadingEnabled||!i.media||Math.abs((((s=i.mainForwardBufferInfo)==null?void 0:s.start)||i.media.currentTime)-e)>.5?i.startLoad(e,t):i.bufferingEnabled||i.resumeBuffering()}onManifestLoading(){var e;this.stopLoad(),(e=this.schedule)==null||e.reset(),this.emptyPlayerQueue(),this.clearScheduleState(),this.shouldPlay=!1,this.bufferedPos=this.timelinePos=-1,this.mediaSelection=this.altSelection=this.manager=this.requiredTracks=null,this.hls.off(m.BUFFER_CODECS,this.onBufferCodecs,this),this.hls.on(m.BUFFER_CODECS,this.onBufferCodecs,this)}onLevelUpdated(e,t){if(t.level===-1||!this.schedule)return;const s=this.hls.levels[t.level];if(!s.details)return;const i=se(se({},this.mediaSelection||this.altSelection),{},{main:s});this.mediaSelection=i,this.schedule.parseInterstitialDateRanges(i,this.hls.config.interstitialAppendInPlace),!this.effectivePlayingItem&&this.schedule.items&&this.checkStart()}onAudioTrackUpdated(e,t){const s=this.hls.audioTracks[t.id],i=this.mediaSelection;if(!i){this.altSelection=se(se({},this.altSelection),{},{audio:s});return}const r=se(se({},i),{},{audio:s});this.mediaSelection=r}onSubtitleTrackUpdated(e,t){const s=this.hls.subtitleTracks[t.id],i=this.mediaSelection;if(!i){this.altSelection=se(se({},this.altSelection),{},{subtitles:s});return}const r=se(se({},i),{},{subtitles:s});this.mediaSelection=r}onAudioTrackSwitching(e,t){const s=Yr(t);this.playerQueue.forEach(({hls:i})=>i&&(i.setAudioOption(t)||i.setAudioOption(s)))}onSubtitleTrackSwitch(e,t){const s=Yr(t);this.playerQueue.forEach(({hls:i})=>i&&(i.setSubtitleOption(t)||t.id!==-1&&i.setSubtitleOption(s)))}onBufferCodecs(e,t){const s=t.tracks;s&&(this.requiredTracks=s)}onBufferAppended(e,t){this.checkBuffer()}onBufferFlushed(e,t){const s=this.playingItem;if(s&&!this.itemsMatch(s,this.bufferingItem)&&!this.isInterstitial(s)){const i=this.timelinePos;this.bufferedPos=i,this.checkBuffer()}}onBufferedToEnd(e){if(!this.schedule)return;const t=this.schedule.events;if(this.bufferedPos<Number.MAX_VALUE&&t){for(let i=0;i<t.length;i++){const r=t[i];if(r.cue.post){var s;const a=this.schedule.findEventIndex(r.identifier),o=(s=this.schedule.items)==null?void 0:s[a];this.isInterstitial(o)&&this.eventItemsMatch(o,this.bufferingItem)&&this.bufferedToItem(o,0);break}}this.bufferedPos=Number.MAX_VALUE}}onMediaEnded(e){const t=this.playingItem;if(!this.playingLastItem&&t){const s=this.findItemIndex(t);this.setSchedulePosition(s+1)}else this.shouldPlay=!1}updateItem(e,t){var s;const i=(s=this.schedule)==null?void 0:s.items;if(e&&i){const r=this.findItemIndex(e,t);return i[r]||null}return null}trimInPlace(e,t){if(this.isInterstitial(e)&&e.event.appendInPlace&&t.end-e.end>.25){e.event.assetList.forEach((r,a)=>{e.event.isAssetPastPlayoutLimit(a)&&this.clearAssetPlayer(r.identifier,null)});const s=e.end+.25,i=q.bufferInfo(this.primaryMedia,s,0);(i.end>s||(i.nextStart||0)>s)&&(this.log(`trim buffered interstitial ${Ne(e)} (was ${Ne(t)})`),this.attachPrimary(s,null,!0),this.flushFrontBuffer(s))}}itemsMatch(e,t){return!!t&&(e===t||e.event&&t.event&&this.eventItemsMatch(e,t)||!e.event&&!t.event&&this.findItemIndex(e)===this.findItemIndex(t))}eventItemsMatch(e,t){var s;return!!t&&(e===t||e.event.identifier===((s=t.event)==null?void 0:s.identifier))}findItemIndex(e,t){return e&&this.schedule?this.schedule.findItemIndex(e,t):-1}updateSchedule(e=!1){var t;const s=this.mediaSelection;s&&((t=this.schedule)==null||t.updateSchedule(s,[],e))}checkBuffer(e){var t;const s=(t=this.schedule)==null?void 0:t.items;if(!s)return;const i=q.bufferInfo(this.primaryMedia,this.timelinePos,0);e&&(this.bufferedPos=this.timelinePos),e||(e=i.len<1),this.updateBufferedPos(i.end,s,e)}updateBufferedPos(e,t,s){const i=this.schedule,r=this.bufferingItem;if(this.bufferedPos>e||!i)return;if(t.length===1&&this.itemsMatch(t[0],r)){this.bufferedPos=e;return}const a=this.playingItem,o=this.findItemIndex(a);let c=i.findItemIndexAtTime(e);if(this.bufferedPos<e){var l;const h=this.findItemIndex(r),u=Math.min(h+1,t.length-1),d=t[u];if((c===-1&&r&&e>=r.end||(l=d.event)!=null&&l.appendInPlace&&e+.01>=d.start)&&(c=u),this.isInterstitial(r)){const f=r.event;if(u-o>1&&f.appendInPlace===!1||f.assetList.length===0&&f.assetListLoader)return}if(this.bufferedPos=e,c>h&&c>o)this.bufferedToItem(d);else{const f=this.primaryDetails;this.primaryLive&&f&&e>f.edge-f.targetduration&&d.start<f.edge+this.hls.config.interstitialLiveLookAhead&&this.isInterstitial(d)&&this.preloadAssets(d.event,0)}}else s&&a&&!this.itemsMatch(a,r)&&(c===o?this.bufferedToItem(a):c===o+1&&this.bufferedToItem(t[c]))}assetsBuffered(e,t){return e.event.assetList.length===0?!1:!e.event.assetList.some(i=>{const r=this.getAssetPlayer(i.identifier);return!(r!=null&&r.bufferedInPlaceToEnd(t))})}setBufferingItem(e){const t=this.bufferingItem,s=this.schedule;if(!this.itemsMatch(e,t)&&s){const{items:i,events:r}=s;if(!i||!r)return t;const a=this.isInterstitial(e),o=this.getBufferingPlayer();this.bufferingItem=e,this.bufferedPos=Math.max(e.start,Math.min(e.end,this.timelinePos));const c=o?o.remaining:t?t.end-this.timelinePos:0;if(this.log(`INTERSTITIALS_BUFFERED_TO_BOUNDARY ${Ne(e)}`+(t?` (${c.toFixed(2)} remaining)`:"")),!this.playbackDisabled)if(a){const l=s.findAssetIndex(e.event,this.bufferedPos);e.event.assetList.forEach((h,u)=>{const d=this.getAssetPlayer(h.identifier);d&&(u===l&&d.loadSource(),d.resumeBuffering())})}else this.hls.resumeBuffering(),this.playerQueue.forEach(l=>l.pauseBuffering());this.hls.trigger(m.INTERSTITIALS_BUFFERED_TO_BOUNDARY,{events:r.slice(0),schedule:i.slice(0),bufferingIndex:this.findItemIndex(e),playingIndex:this.findItemIndex(this.playingItem)})}else this.bufferingItem!==e&&(this.bufferingItem=e);return t}bufferedToItem(e,t=0){const s=this.setBufferingItem(e);if(!this.playbackDisabled){if(this.isInterstitial(e))this.bufferedToEvent(e,t);else if(s!==null){this.bufferingAsset=null;const i=this.detachedData;i?i.mediaSource?this.attachPrimary(e.start,e,!0):this.preloadPrimary(e):this.preloadPrimary(e)}}}preloadPrimary(e){const t=this.findItemIndex(e),s=this.getPrimaryResumption(e,t);this.startLoadingPrimaryAt(s)}bufferedToEvent(e,t){const s=e.event,i=s.assetList.length===0&&!s.assetListLoader,r=s.cue.once;if(i||!r){const a=this.preloadAssets(s,t);if(a!=null&&a.interstitial.appendInPlace){const o=this.primaryMedia;o&&this.bufferAssetPlayer(a,o)}}}preloadAssets(e,t){const s=e.assetUrl,i=e.assetList.length,r=i===0&&!e.assetListLoader,a=e.cue.once;if(r){const c=e.timelineStart;if(e.appendInPlace){var o;const d=this.playingItem;!this.isInterstitial(d)&&(d==null||(o=d.nextEvent)==null?void 0:o.identifier)===e.identifier&&this.flushFrontBuffer(c+.25)}let l,h=0;if(!this.playingItem&&this.primaryLive&&(h=this.hls.startPosition,h===-1&&(h=this.hls.liveSyncPosition||0)),h&&!(e.cue.pre||e.cue.post)){const d=h-c;d>0&&(l=Math.round(d*1e3)/1e3)}if(this.log(`Load interstitial asset ${t+1}/${s?1:i} ${e}${l?` live-start: ${h} start-offset: ${l}`:""}`),s)return this.createAsset(e,0,0,c,e.duration,s);const u=this.assetListLoader.loadAssetList(e,l);u&&(e.assetListLoader=u)}else if(!a&&i){for(let l=t;l<i;l++){const h=e.assetList[l],u=this.getAssetPlayerQueueIndex(h.identifier);(u===-1||this.playerQueue[u].destroyed)&&!h.error&&this.createAssetPlayer(e,h,l)}const c=e.assetList[t];if(c){const l=this.getAssetPlayer(c.identifier);return l&&l.loadSource(),l}}return null}flushFrontBuffer(e){const t=this.requiredTracks;if(!t)return;this.log(`Removing front buffer starting at ${e}`),Object.keys(t).forEach(i=>{this.hls.trigger(m.BUFFER_FLUSHING,{startOffset:e,endOffset:1/0,type:i})})}getAssetPlayerQueueIndex(e){const t=this.playerQueue;for(let s=0;s<t.length;s++)if(e===t[s].assetId)return s;return-1}getAssetPlayer(e){const t=this.getAssetPlayerQueueIndex(e);return this.playerQueue[t]||null}getBufferingPlayer(){const{playerQueue:e,primaryMedia:t}=this;if(t){for(let s=0;s<e.length;s++)if(e[s].media===t)return e[s]}return null}createAsset(e,t,s,i,r,a){const o={parentIdentifier:e.identifier,identifier:Pd(e,a,t),duration:r,startOffset:s,timelineStart:i,uri:a};return this.createAssetPlayer(e,o,t)}createAssetPlayer(e,t,s){const i=this.hls,r=i.userConfig;let a=r.videoPreference;const o=i.loadLevelObj||i.levels[i.currentLevel];(a||o)&&(a=re({},a),o.videoCodec&&(a.videoCodec=o.videoCodec),o.videoRange&&(a.allowedVideoRanges=[o.videoRange]));const c=i.audioTracks[i.audioTrack],l=i.subtitleTracks[i.subtitleTrack];let h=0;if(this.primaryLive||e.appendInPlace){const v=this.timelinePos-t.timelineStart;if(v>1){const x=t.duration;x&&v<x&&(h=v)}}const u=t.identifier,d=se(se({},r),{},{maxMaxBufferLength:Math.min(180,i.config.maxMaxBufferLength),autoStartLoad:!0,startFragPrefetch:!0,primarySessionId:i.sessionId,assetPlayerId:u,abrEwmaDefaultEstimate:i.bandwidthEstimate,interstitialsController:void 0,startPosition:h,liveDurationInfinity:!1,testBandwidth:!1,videoPreference:a,audioPreference:c||r.audioPreference,subtitlePreference:l||r.subtitlePreference});e.appendInPlace&&(e.appendInPlaceStarted=!0,t.timelineStart&&(d.timelineOffset=t.timelineStart));const f=d.cmcd;f!=null&&f.sessionId&&f.contentId&&(d.cmcd=re({},f,{contentId:Ut(t.uri)})),this.getAssetPlayer(u)&&this.warn(`Duplicate date range identifier ${e} and asset ${u}`);const g=new Od(this.HlsPlayerClass,d,e,t);this.playerQueue.push(g),e.assetList[s]=t;let p=!0;const y=v=>{if(v.live){var x;const b=new Error(`Interstitials MUST be VOD assets ${e}`),I={fatal:!0,type:H.OTHER_ERROR,details:R.INTERSTITIAL_ASSET_ITEM_ERROR,error:b},_=((x=this.schedule)==null?void 0:x.findEventIndex(e.identifier))||-1;this.handleAssetItemError(I,e,_,s,b.message);return}const D=v.edge-v.fragmentStart,A=t.duration;(p||A===null||D>A)&&(p=!1,this.log(`Interstitial asset "${u}" duration change ${A} > ${D}`),t.duration=D,this.updateSchedule())};g.on(m.LEVEL_UPDATED,(v,{details:x})=>y(x)),g.on(m.LEVEL_PTS_UPDATED,(v,{details:x})=>y(x)),g.on(m.EVENT_CUE_ENTER,()=>this.onInterstitialCueEnter());const E=(v,x)=>{const D=this.getAssetPlayer(u);if(D&&x.tracks){D.off(m.BUFFER_CODECS,E),D.tracks=x.tracks;const A=this.primaryMedia;this.bufferingAsset===D.assetItem&&A&&!D.media&&this.bufferAssetPlayer(D,A)}};g.on(m.BUFFER_CODECS,E);const T=()=>{var v;const x=this.getAssetPlayer(u);if(this.log(`buffered to end of asset ${x}`),!x||!this.schedule)return;const D=this.schedule.findEventIndex(e.identifier),A=(v=this.schedule.items)==null?void 0:v[D];this.isInterstitial(A)&&this.advanceAssetBuffering(A,t)};g.on(m.BUFFERED_TO_END,T);const S=v=>()=>{if(!this.getAssetPlayer(u)||!this.schedule)return;this.shouldPlay=!0;const D=this.schedule.findEventIndex(e.identifier);this.advanceAfterAssetEnded(e,D,v)};return g.once(m.MEDIA_ENDED,S(s)),g.once(m.PLAYOUT_LIMIT_REACHED,S(1/0)),g.on(m.ERROR,(v,x)=>{if(!this.schedule)return;const D=this.getAssetPlayer(u);if(x.details===R.BUFFER_STALLED_ERROR){if(D!=null&&D.appendInPlace){this.handleInPlaceStall(e);return}this.onTimeupdate(),this.checkBuffer(!0);return}this.handleAssetItemError(x,e,this.schedule.findEventIndex(e.identifier),s,`Asset player error ${x.error} ${e}`)}),g.on(m.DESTROYING,()=>{if(!this.getAssetPlayer(u)||!this.schedule)return;const x=new Error(`Asset player destroyed unexpectedly ${u}`),D={fatal:!0,type:H.OTHER_ERROR,details:R.INTERSTITIAL_ASSET_ITEM_ERROR,error:x};this.handleAssetItemError(D,e,this.schedule.findEventIndex(e.identifier),s,x.message)}),this.log(`INTERSTITIAL_ASSET_PLAYER_CREATED ${xt(t)}`),this.hls.trigger(m.INTERSTITIAL_ASSET_PLAYER_CREATED,{asset:t,assetListIndex:s,event:e,player:g}),g}clearInterstitial(e,t){this.clearAssetPlayers(e,t),e.reset()}clearAssetPlayers(e,t){e.assetList.forEach(s=>{this.clearAssetPlayer(s.identifier,t)})}resetAssetPlayer(e){const t=this.getAssetPlayerQueueIndex(e);if(t!==-1){this.log(`reset asset player "${e}" after error`);const s=this.playerQueue[t];this.transferMediaFromPlayer(s,null),s.resetDetails()}}clearAssetPlayer(e,t){const s=this.getAssetPlayerQueueIndex(e);if(s!==-1){const i=this.playerQueue[s];this.log(`clear ${i} toSegment: ${t&&Ne(t)}`),this.transferMediaFromPlayer(i,t),this.playerQueue.splice(s,1),i.destroy()}}emptyPlayerQueue(){let e;for(;e=this.playerQueue.pop();)e.destroy();this.playerQueue=[]}startAssetPlayer(e,t,s,i,r){const{interstitial:a,assetItem:o,assetId:c}=e,l=a.assetList.length,h=this.playingAsset;this.endedAsset=null,this.playingAsset=o,(!h||h.identifier!==c)&&(h&&(this.clearAssetPlayer(h.identifier,s[i]),delete h.error),this.log(`INTERSTITIAL_ASSET_STARTED ${t+1}/${l} ${xt(o)}`),this.hls.trigger(m.INTERSTITIAL_ASSET_STARTED,{asset:o,assetListIndex:t,event:a,schedule:s.slice(0),scheduleIndex:i,player:e})),this.bufferAssetPlayer(e,r)}bufferAssetPlayer(e,t){var s,i;if(!this.schedule)return;const{interstitial:r,assetItem:a}=e,o=this.schedule.findEventIndex(r.identifier),c=(s=this.schedule.items)==null?void 0:s[o];if(!c)return;e.loadSource(),this.setBufferingItem(c),this.bufferingAsset=a;const l=this.getBufferingPlayer();if(l===e)return;const h=r.appendInPlace;if(h&&(l==null?void 0:l.interstitial.appendInPlace)===!1)return;const u=(l==null?void 0:l.tracks)||((i=this.detachedData)==null?void 0:i.tracks)||this.requiredTracks;if(h&&a!==this.playingAsset){if(!e.tracks){this.log(`Waiting for track info before buffering ${e}`);return}if(u&&!Ta(u,e.tracks)){const d=new Error(`Asset ${xt(a)} SourceBuffer tracks ('${Object.keys(e.tracks)}') are not compatible with primary content tracks ('${Object.keys(u)}')`),f={fatal:!0,type:H.OTHER_ERROR,details:R.INTERSTITIAL_ASSET_ITEM_ERROR,error:d},g=r.findAssetIndex(a);this.handleAssetItemError(f,r,o,g,d.message);return}}this.transferMediaTo(e,t)}handleInPlaceStall(e){const t=this.schedule,s=this.primaryMedia;if(!t||!s)return;const i=s.currentTime,r=t.findAssetIndex(e,i),a=e.assetList[r];if(a){const o=this.getAssetPlayer(a.identifier);if(o){const c=o.currentTime||i-a.timelineStart,l=o.duration-c;if(this.warn(`Stalled at ${c} of ${c+l} in ${o} ${e} (media.currentTime: ${i})`),c&&(l/s.playbackRate<.5||o.bufferedInPlaceToEnd(s))&&o.hls){const h=t.findEventIndex(e.identifier);this.advanceAfterAssetEnded(e,h,r)}}}}advanceInPlace(e){const t=this.primaryMedia;t&&t.currentTime<e&&(t.currentTime=e)}handleAssetItemError(e,t,s,i,r){if(e.details===R.BUFFER_STALLED_ERROR)return;const a=t.assetList[i]||null;if(this.warn(`INTERSTITIAL_ASSET_ERROR ${a&&xt(a)} ${e.error}`),!this.schedule)return;const o=(a==null?void 0:a.identifier)||"",c=this.getAssetPlayerQueueIndex(o),l=this.playerQueue[c]||null,h=this.schedule.items,u=re({},e,{fatal:!1,errorAction:_t(!0),asset:a,assetListIndex:i,event:t,schedule:h,scheduleIndex:s,player:l});if(this.hls.trigger(m.INTERSTITIAL_ASSET_ERROR,u),!e.fatal)return;const d=this.playingAsset,f=this.bufferingAsset,g=new Error(r);if(a&&(this.clearAssetPlayer(o,null),a.error=g),!t.assetList.some(p=>!p.error))t.error=g;else for(let p=i;p<t.assetList.length;p++)this.resetAssetPlayer(t.assetList[p].identifier);this.updateSchedule(!0),t.error?this.primaryFallback(t):d&&d.identifier===o?this.advanceAfterAssetEnded(t,s,i):f&&f.identifier===o&&this.isInterstitial(this.bufferingItem)&&this.advanceAssetBuffering(this.bufferingItem,f)}primaryFallback(e){const t=e.timelineStart,s=this.effectivePlayingItem;let i=this.timelinePos;if(s){this.log(`Fallback to primary from event "${e.identifier}" start: ${t} pos: ${i} playing: ${Ne(s)} error: ${e.error}`),i===-1&&(i=this.hls.startPosition);const a=this.updateItem(s,i);this.itemsMatch(s,a)&&this.clearInterstitial(e,null),e.appendInPlace&&(this.attachPrimary(t,null),this.flushFrontBuffer(t))}else if(i===-1){this.checkStart();return}if(!this.schedule)return;const r=this.schedule.findItemIndexAtTime(i);this.setSchedulePosition(r)}onAssetListLoaded(e,t){var s,i;const r=t.event,a=r.identifier,o=t.assetListResponse.ASSETS;if(!((s=this.schedule)!=null&&s.hasEvent(a)))return;const c=r.timelineStart,l=r.duration;let h=0;o.forEach((p,y)=>{const E=parseFloat(p.DURATION);this.createAsset(r,y,h,c+h,E,p.URI),h+=E}),r.duration=h,this.log(`Loaded asset-list with duration: ${h} (was: ${l}) ${r}`);const u=this.waitingItem,d=(u==null?void 0:u.event.identifier)===a;this.updateSchedule();const f=(i=this.bufferingItem)==null?void 0:i.event;if(d){var g;const p=this.schedule.findEventIndex(a),y=(g=this.schedule.items)==null?void 0:g[p];if(y){if(!this.playingItem&&this.timelinePos>y.end&&this.schedule.findItemIndexAtTime(this.timelinePos)!==p){r.error=new Error(`Interstitial ${o.length?"no longer within playback range":"asset-list is empty"} ${this.timelinePos} ${r}`),this.log(r.error.message),this.updateSchedule(!0),this.primaryFallback(r);return}this.setBufferingItem(y)}this.setSchedulePosition(p)}else if((f==null?void 0:f.identifier)===a){const p=r.assetList[0];if(p){const y=this.getAssetPlayer(p.identifier);if(f.appendInPlace){const E=this.primaryMedia;y&&E&&this.bufferAssetPlayer(y,E)}else y&&y.loadSource()}}}onError(e,t){if(this.schedule)switch(t.details){case R.ASSET_LIST_PARSING_ERROR:case R.ASSET_LIST_LOAD_ERROR:case R.ASSET_LIST_LOAD_TIMEOUT:{const s=t.interstitial;s&&(this.updateSchedule(!0),this.primaryFallback(s));break}case R.BUFFER_STALLED_ERROR:{const s=this.endedItem||this.waitingItem||this.playingItem;if(this.isInterstitial(s)&&s.event.appendInPlace){this.handleInPlaceStall(s.event);return}this.log(`Primary player stall @${this.timelinePos} bufferedPos: ${this.bufferedPos}`),this.onTimeupdate(),this.checkBuffer(!0);break}}}}const Un=500;class Bd extends sr{constructor(e,t,s){super(e,t,s,"subtitle-stream-controller",U.SUBTITLE),this.currentTrackId=-1,this.tracksBuffered=[],this.mainDetails=null,this.registerListeners()}onHandlerDestroying(){this.unregisterListeners(),super.onHandlerDestroying(),this.mainDetails=null}registerListeners(){super.registerListeners();const{hls:e}=this;e.on(m.LEVEL_LOADED,this.onLevelLoaded,this),e.on(m.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(m.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.on(m.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(m.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.on(m.BUFFER_FLUSHING,this.onBufferFlushing,this)}unregisterListeners(){super.unregisterListeners();const{hls:e}=this;e.off(m.LEVEL_LOADED,this.onLevelLoaded,this),e.off(m.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(m.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.off(m.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(m.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.off(m.BUFFER_FLUSHING,this.onBufferFlushing,this)}startLoad(e,t){this.stopLoad(),this.state=P.IDLE,this.setInterval(Un),this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,this.tick()}onManifestLoading(){super.onManifestLoading(),this.mainDetails=null}onMediaDetaching(e,t){this.tracksBuffered=[],super.onMediaDetaching(e,t)}onLevelLoaded(e,t){this.mainDetails=t.details}onSubtitleFragProcessed(e,t){const{frag:s,success:i}=t;if(this.fragContextChanged(s)||(de(s)&&(this.fragPrevious=s),this.state=P.IDLE),!i)return;const r=this.tracksBuffered[this.currentTrackId];if(!r)return;let a;const o=s.start;for(let l=0;l<r.length;l++)if(o>=r[l].start&&o<=r[l].end){a=r[l];break}const c=s.start+s.duration;a?a.end=c:(a={start:o,end:c},r.push(a)),this.fragmentTracker.fragBuffered(s),this.fragBufferedComplete(s,null),this.media&&this.tick()}onBufferFlushing(e,t){const{startOffset:s,endOffset:i}=t;if(s===0&&i!==Number.POSITIVE_INFINITY){const r=i-1;if(r<=0)return;t.endOffsetSubtitles=Math.max(0,r),this.tracksBuffered.forEach(a=>{for(let o=0;o<a.length;){if(a[o].end<=r){a.shift();continue}else if(a[o].start<r)a[o].start=r;else break;o++}}),this.fragmentTracker.removeFragmentsInRange(s,r,U.SUBTITLE)}}onError(e,t){const s=t.frag;(s==null?void 0:s.type)===U.SUBTITLE&&(t.details===R.FRAG_GAP&&this.fragmentTracker.fragBuffered(s,!0),this.fragCurrent&&this.fragCurrent.abortRequests(),this.state!==P.STOPPED&&(this.state=P.IDLE))}onSubtitleTracksUpdated(e,{subtitleTracks:t}){if(this.levels&&Ao(this.levels,t)){this.levels=t.map(s=>new Kt(s));return}this.tracksBuffered=[],this.levels=t.map(s=>{const i=new Kt(s);return this.tracksBuffered[i.id]=[],i}),this.fragmentTracker.removeFragmentsInRange(0,Number.POSITIVE_INFINITY,U.SUBTITLE),this.fragPrevious=null,this.mediaBuffer=null}onSubtitleTrackSwitch(e,t){var s;if(this.currentTrackId=t.id,!((s=this.levels)!=null&&s.length)||this.currentTrackId===-1){this.clearInterval();return}const i=this.levels[this.currentTrackId];i!=null&&i.details?this.mediaBuffer=this.mediaBufferTimeRanges:this.mediaBuffer=null,i&&this.state!==P.STOPPED&&this.setInterval(Un)}onSubtitleTrackLoaded(e,t){var s;const{currentTrackId:i,levels:r}=this,{details:a,id:o}=t;if(!r){this.warn(`Subtitle tracks were reset while loading level ${o}`);return}const c=r[o];if(o>=r.length||!c)return;this.log(`Subtitle track ${o} loaded [${a.startSN},${a.endSN}]${a.lastPartSn?`[part-${a.lastPartSn}-${a.lastPartIndex}]`:""},duration:${a.totalduration}`),this.mediaBuffer=this.mediaBufferTimeRanges;let l=0;if(a.live||(s=c.details)!=null&&s.live){if(a.deltaUpdateFailed)return;const u=this.mainDetails;if(!u){this.startFragRequested=!1;return}const d=u.fragments[0];if(!c.details)a.hasProgramDateTime&&u.hasProgramDateTime?(Ms(a,u),l=a.fragmentStart):d&&(l=d.start,Pi(a,l));else{var h;l=this.alignPlaylists(a,c.details,(h=this.levelLastLoaded)==null?void 0:h.details),l===0&&d&&(l=d.start,Pi(a,l))}u&&!this.startFragRequested&&this.setStartPosition(u,l)}c.details=a,this.levelLastLoaded=c,o===i&&(this.hls.trigger(m.SUBTITLE_TRACK_UPDATED,{details:a,id:o,groupId:t.groupId}),this.tick(),a.live&&!this.fragCurrent&&this.media&&this.state===P.IDLE&&(mt(null,a.fragments,this.media.currentTime,0)||(this.warn("Subtitle playlist not aligned with playback"),c.details=void 0)))}_handleFragmentLoadComplete(e){const{frag:t,payload:s}=e,i=t.decryptdata,r=this.hls;if(!this.fragContextChanged(t)&&s&&s.byteLength>0&&i!=null&&i.key&&i.iv&&It(i.method)){const a=performance.now();this.decrypter.decrypt(new Uint8Array(s),i.key.buffer,i.iv.buffer,er(i.method)).catch(o=>{throw r.trigger(m.ERROR,{type:H.MEDIA_ERROR,details:R.FRAG_DECRYPT_ERROR,fatal:!1,error:o,reason:o.message,frag:t}),o}).then(o=>{const c=performance.now();r.trigger(m.FRAG_DECRYPTED,{frag:t,payload:o,stats:{tstart:a,tdecrypt:c}})}).catch(o=>{this.warn(`${o.name}: ${o.message}`),this.state=P.IDLE})}}doTick(){if(!this.media){this.state=P.IDLE;return}if(this.state===P.IDLE){const{currentTrackId:e,levels:t}=this,s=t==null?void 0:t[e];if(!s||!t.length||!s.details||this.waitForLive(s))return;const{config:i}=this,r=this.getLoadPosition(),a=q.bufferedInfo(this.tracksBuffered[this.currentTrackId]||[],r,i.maxBufferHole),{end:o,len:c}=a,l=s.details,h=this.hls.maxBufferLength+l.levelTargetDuration;if(c>h)return;const u=l.fragments,d=u.length,f=l.edge;let g=null;const p=this.fragPrevious;if(o<f){const T=i.maxFragLookUpTolerance,S=o>f-T?0:T;g=mt(p,u,Math.max(u[0].start,o),S),!g&&p&&p.start<u[0].start&&(g=u[0])}else g=u[d-1];if(g=this.filterReplacedPrimary(g,s.details),!g)return;const y=g.sn-l.startSN,E=u[y-1];if(E&&E.cc===g.cc&&this.fragmentTracker.getState(E)===me.NOT_LOADED&&(g=E),this.fragmentTracker.getState(g)===me.NOT_LOADED){const T=this.mapToInitFragWhenRequired(g);T&&this.loadFragment(T,s,o)}}}loadFragment(e,t,s){de(e)?super.loadFragment(e,t,s):this._loadInitSegment(e,t)}get mediaBufferTimeRanges(){return new Ud(this.tracksBuffered[this.currentTrackId]||[])}}class Ud{constructor(e){this.buffered=void 0;const t=(s,i,r)=>{if(i=i>>>0,i>r-1)throw new DOMException(`Failed to execute '${s}' on 'TimeRanges': The index provided (${i}) is greater than the maximum bound (${r})`);return e[i][s]};this.buffered={get length(){return e.length},end(s){return t("end",s,e.length)},start(s){return t("start",s,e.length)}}}}const $d={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},Uo=n=>String.fromCharCode($d[n]||n),Be=15,Xe=100,Gd={17:1,18:3,21:5,22:7,23:9,16:11,19:12,20:14},Kd={17:2,18:4,21:6,22:8,23:10,19:13,20:15},Vd={25:1,26:3,29:5,30:7,31:9,24:11,27:12,28:14},Hd={25:2,26:4,29:6,30:8,31:10,27:13,28:15},Wd=["white","green","blue","cyan","red","yellow","magenta","black","transparent"];class Yd{constructor(){this.time=null,this.verboseLevel=0}log(e,t){if(this.verboseLevel>=e){const s=typeof t=="function"?t():t;ie.log(`${this.time} [${e}] ${s}`)}}}const dt=function(e){const t=[];for(let s=0;s<e.length;s++)t.push(e[s].toString(16));return t};class $o{constructor(){this.foreground="white",this.underline=!1,this.italics=!1,this.background="black",this.flash=!1}reset(){this.foreground="white",this.underline=!1,this.italics=!1,this.background="black",this.flash=!1}setStyles(e){const t=["foreground","underline","italics","background","flash"];for(let s=0;s<t.length;s++){const i=t[s];e.hasOwnProperty(i)&&(this[i]=e[i])}}isDefault(){return this.foreground==="white"&&!this.underline&&!this.italics&&this.background==="black"&&!this.flash}equals(e){return this.foreground===e.foreground&&this.underline===e.underline&&this.italics===e.italics&&this.background===e.background&&this.flash===e.flash}copy(e){this.foreground=e.foreground,this.underline=e.underline,this.italics=e.italics,this.background=e.background,this.flash=e.flash}toString(){return"color="+this.foreground+", underline="+this.underline+", italics="+this.italics+", background="+this.background+", flash="+this.flash}}class qd{constructor(){this.uchar=" ",this.penState=new $o}reset(){this.uchar=" ",this.penState.reset()}setChar(e,t){this.uchar=e,this.penState.copy(t)}setPenState(e){this.penState.copy(e)}equals(e){return this.uchar===e.uchar&&this.penState.equals(e.penState)}copy(e){this.uchar=e.uchar,this.penState.copy(e.penState)}isEmpty(){return this.uchar===" "&&this.penState.isDefault()}}class jd{constructor(e){this.chars=[],this.pos=0,this.currPenState=new $o,this.cueStartTime=null,this.logger=void 0;for(let t=0;t<Xe;t++)this.chars.push(new qd);this.logger=e}equals(e){for(let t=0;t<Xe;t++)if(!this.chars[t].equals(e.chars[t]))return!1;return!0}copy(e){for(let t=0;t<Xe;t++)this.chars[t].copy(e.chars[t])}isEmpty(){let e=!0;for(let t=0;t<Xe;t++)if(!this.chars[t].isEmpty()){e=!1;break}return e}setCursor(e){this.pos!==e&&(this.pos=e),this.pos<0?(this.logger.log(3,"Negative cursor position "+this.pos),this.pos=0):this.pos>Xe&&(this.logger.log(3,"Too large cursor position "+this.pos),this.pos=Xe)}moveCursor(e){const t=this.pos+e;if(e>1)for(let s=this.pos+1;s<t+1;s++)this.chars[s].setPenState(this.currPenState);this.setCursor(t)}backSpace(){this.moveCursor(-1),this.chars[this.pos].setChar(" ",this.currPenState)}insertChar(e){e>=144&&this.backSpace();const t=Uo(e);if(this.pos>=Xe){this.logger.log(0,()=>"Cannot insert "+e.toString(16)+" ("+t+") at position "+this.pos+". Skipping it!");return}this.chars[this.pos].setChar(t,this.currPenState),this.moveCursor(1)}clearFromPos(e){let t;for(t=e;t<Xe;t++)this.chars[t].reset()}clear(){this.clearFromPos(0),this.pos=0,this.currPenState.reset()}clearToEndOfRow(){this.clearFromPos(this.pos)}getTextString(){const e=[];let t=!0;for(let s=0;s<Xe;s++){const i=this.chars[s].uchar;i!==" "&&(t=!1),e.push(i)}return t?"":e.join("")}setPenStyles(e){this.currPenState.setStyles(e),this.chars[this.pos].setPenState(this.currPenState)}}class li{constructor(e){this.rows=[],this.currRow=Be-1,this.nrRollUpRows=null,this.lastOutputScreen=null,this.logger=void 0;for(let t=0;t<Be;t++)this.rows.push(new jd(e));this.logger=e}reset(){for(let e=0;e<Be;e++)this.rows[e].clear();this.currRow=Be-1}equals(e){let t=!0;for(let s=0;s<Be;s++)if(!this.rows[s].equals(e.rows[s])){t=!1;break}return t}copy(e){for(let t=0;t<Be;t++)this.rows[t].copy(e.rows[t])}isEmpty(){let e=!0;for(let t=0;t<Be;t++)if(!this.rows[t].isEmpty()){e=!1;break}return e}backSpace(){this.rows[this.currRow].backSpace()}clearToEndOfRow(){this.rows[this.currRow].clearToEndOfRow()}insertChar(e){this.rows[this.currRow].insertChar(e)}setPen(e){this.rows[this.currRow].setPenStyles(e)}moveCursor(e){this.rows[this.currRow].moveCursor(e)}setCursor(e){this.logger.log(2,"setCursor: "+e),this.rows[this.currRow].setCursor(e)}setPAC(e){this.logger.log(2,()=>"pacData = "+oe(e));let t=e.row-1;if(this.nrRollUpRows&&t<this.nrRollUpRows-1&&(t=this.nrRollUpRows-1),this.nrRollUpRows&&this.currRow!==t){for(let o=0;o<Be;o++)this.rows[o].clear();const r=this.currRow+1-this.nrRollUpRows,a=this.lastOutputScreen;if(a){const o=a.rows[r].cueStartTime,c=this.logger.time;if(o!==null&&c!==null&&o<c)for(let l=0;l<this.nrRollUpRows;l++)this.rows[t-this.nrRollUpRows+l+1].copy(a.rows[r+l])}}this.currRow=t;const s=this.rows[this.currRow];if(e.indent!==null){const r=e.indent,a=Math.max(r-1,0);s.setCursor(e.indent),e.color=s.chars[a].penState.foreground}const i={foreground:e.color,underline:e.underline,italics:e.italics,background:"black",flash:!1};this.setPen(i)}setBkgData(e){this.logger.log(2,()=>"bkgData = "+oe(e)),this.backSpace(),this.setPen(e),this.insertChar(32)}setRollUpRows(e){this.nrRollUpRows=e}rollUp(){if(this.nrRollUpRows===null){this.logger.log(3,"roll_up but nrRollUpRows not set yet");return}this.logger.log(1,()=>this.getDisplayText());const e=this.currRow+1-this.nrRollUpRows,t=this.rows.splice(e,1)[0];t.clear(),this.rows.splice(this.currRow,0,t),this.logger.log(2,"Rolling up")}getDisplayText(e){e=e||!1;const t=[];let s="",i=-1;for(let r=0;r<Be;r++){const a=this.rows[r].getTextString();a&&(i=r+1,e?t.push("Row "+i+": '"+a+"'"):t.push(a.trim()))}return t.length>0&&(e?s="["+t.join(" | ")+"]":s=t.join(`
118118+`)),s}getTextAndFormat(){return this.rows}}class $n{constructor(e,t,s){this.chNr=void 0,this.outputFilter=void 0,this.mode=void 0,this.verbose=void 0,this.displayedMemory=void 0,this.nonDisplayedMemory=void 0,this.lastOutputScreen=void 0,this.currRollUpRow=void 0,this.writeScreen=void 0,this.cueStartTime=void 0,this.logger=void 0,this.chNr=e,this.outputFilter=t,this.mode=null,this.verbose=0,this.displayedMemory=new li(s),this.nonDisplayedMemory=new li(s),this.lastOutputScreen=new li(s),this.currRollUpRow=this.displayedMemory.rows[Be-1],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null,this.logger=s}reset(){this.mode=null,this.displayedMemory.reset(),this.nonDisplayedMemory.reset(),this.lastOutputScreen.reset(),this.outputFilter.reset(),this.currRollUpRow=this.displayedMemory.rows[Be-1],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null}getHandler(){return this.outputFilter}setHandler(e){this.outputFilter=e}setPAC(e){this.writeScreen.setPAC(e)}setBkgData(e){this.writeScreen.setBkgData(e)}setMode(e){e!==this.mode&&(this.mode=e,this.logger.log(2,()=>"MODE="+e),this.mode==="MODE_POP-ON"?this.writeScreen=this.nonDisplayedMemory:(this.writeScreen=this.displayedMemory,this.writeScreen.reset()),this.mode!=="MODE_ROLL-UP"&&(this.displayedMemory.nrRollUpRows=null,this.nonDisplayedMemory.nrRollUpRows=null),this.mode=e)}insertChars(e){for(let s=0;s<e.length;s++)this.writeScreen.insertChar(e[s]);const t=this.writeScreen===this.displayedMemory?"DISP":"NON_DISP";this.logger.log(2,()=>t+": "+this.writeScreen.getDisplayText(!0)),(this.mode==="MODE_PAINT-ON"||this.mode==="MODE_ROLL-UP")&&(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"),this.mode!=="MODE_TEXT"&&(this.writeScreen.backSpace(),this.writeScreen===this.displayedMemory&&this.outputDataUpdate())}ccAOF(){}ccAON(){}ccDER(){this.logger.log(2,"DER- Delete to End of Row"),this.writeScreen.clearToEndOfRow(),this.outputDataUpdate()}ccRU(e){this.logger.log(2,"RU("+e+") - Roll Up"),this.writeScreen=this.displayedMemory,this.setMode("MODE_ROLL-UP"),this.writeScreen.setRollUpRows(e)}ccFON(){this.logger.log(2,"FON - Flash On"),this.writeScreen.setPen({flash:!0})}ccRDC(){this.logger.log(2,"RDC - Resume Direct Captioning"),this.setMode("MODE_PAINT-ON")}ccTR(){this.logger.log(2,"TR"),this.setMode("MODE_TEXT")}ccRTD(){this.logger.log(2,"RTD"),this.setMode("MODE_TEXT")}ccEDM(){this.logger.log(2,"EDM - Erase Displayed Memory"),this.displayedMemory.reset(),this.outputDataUpdate(!0)}ccCR(){this.logger.log(2,"CR - Carriage Return"),this.writeScreen.rollUp(),this.outputDataUpdate(!0)}ccENM(){this.logger.log(2,"ENM - Erase Non-displayed Memory"),this.nonDisplayedMemory.reset()}ccEOC(){if(this.logger.log(2,"EOC - End Of Caption"),this.mode==="MODE_POP-ON"){const e=this.displayedMemory;this.displayedMemory=this.nonDisplayedMemory,this.nonDisplayedMemory=e,this.writeScreen=this.nonDisplayedMemory,this.logger.log(1,()=>"DISP: "+this.displayedMemory.getDisplayText())}this.outputDataUpdate(!0)}ccTO(e){this.logger.log(2,"TO("+e+") - Tab Offset"),this.writeScreen.moveCursor(e)}ccMIDROW(e){const t={flash:!1};if(t.underline=e%2===1,t.italics=e>=46,t.italics)t.foreground="white";else{const s=Math.floor(e/2)-16,i=["white","green","blue","cyan","red","yellow","magenta"];t.foreground=i[s]}this.logger.log(2,"MIDROW: "+oe(t)),this.writeScreen.setPen(t)}outputDataUpdate(e=!1){const t=this.logger.time;t!==null&&this.outputFilter&&(this.cueStartTime===null&&!this.displayedMemory.isEmpty()?this.cueStartTime=t:this.displayedMemory.equals(this.lastOutputScreen)||(this.outputFilter.newCue(this.cueStartTime,t,this.lastOutputScreen),e&&this.outputFilter.dispatchCue&&this.outputFilter.dispatchCue(),this.cueStartTime=this.displayedMemory.isEmpty()?null:t),this.lastOutputScreen.copy(this.displayedMemory))}cueSplitAtTime(e){this.outputFilter&&(this.displayedMemory.isEmpty()||(this.outputFilter.newCue&&this.outputFilter.newCue(this.cueStartTime,e,this.displayedMemory),this.cueStartTime=e))}}class Gn{constructor(e,t,s){this.channels=void 0,this.currentChannel=0,this.cmdHistory=zd(),this.logger=void 0;const i=this.logger=new Yd;this.channels=[null,new $n(e,t,i),new $n(e+1,s,i)]}getHandler(e){return this.channels[e].getHandler()}setHandler(e,t){this.channels[e].setHandler(t)}addData(e,t){this.logger.time=e;for(let s=0;s<t.length;s+=2){const i=t[s]&127,r=t[s+1]&127;let a=!1,o=null;if(i===0&&r===0)continue;this.logger.log(3,()=>"["+dt([t[s],t[s+1]])+"] -> ("+dt([i,r])+")");const c=this.cmdHistory;if(i>=16&&i<=31){if(Xd(i,r,c)){os(null,null,c),this.logger.log(3,()=>"Repeated command ("+dt([i,r])+") is dropped");continue}os(i,r,this.cmdHistory),a=this.parseCmd(i,r),a||(a=this.parseMidrow(i,r)),a||(a=this.parsePAC(i,r)),a||(a=this.parseBackgroundAttributes(i,r))}else os(null,null,c);if(!a&&(o=this.parseChars(i,r),o)){const h=this.currentChannel;h&&h>0?this.channels[h].insertChars(o):this.logger.log(2,"No channel found yet. TEXT-MODE?")}!a&&!o&&this.logger.log(2,()=>"Couldn't parse cleaned data "+dt([i,r])+" orig: "+dt([t[s],t[s+1]]))}}parseCmd(e,t){const s=(e===20||e===28||e===21||e===29)&&t>=32&&t<=47,i=(e===23||e===31)&&t>=33&&t<=35;if(!(s||i))return!1;const r=e===20||e===21||e===23?1:2,a=this.channels[r];return e===20||e===21||e===28||e===29?t===32?a.ccRCL():t===33?a.ccBS():t===34?a.ccAOF():t===35?a.ccAON():t===36?a.ccDER():t===37?a.ccRU(2):t===38?a.ccRU(3):t===39?a.ccRU(4):t===40?a.ccFON():t===41?a.ccRDC():t===42?a.ccTR():t===43?a.ccRTD():t===44?a.ccEDM():t===45?a.ccCR():t===46?a.ccENM():t===47&&a.ccEOC():a.ccTO(t-32),this.currentChannel=r,!0}parseMidrow(e,t){let s=0;if((e===17||e===25)&&t>=32&&t<=47){if(e===17?s=1:s=2,s!==this.currentChannel)return this.logger.log(0,"Mismatch channel in midrow parsing"),!1;const i=this.channels[s];return i?(i.ccMIDROW(t),this.logger.log(3,()=>"MIDROW ("+dt([e,t])+")"),!0):!1}return!1}parsePAC(e,t){let s;const i=(e>=17&&e<=23||e>=25&&e<=31)&&t>=64&&t<=127,r=(e===16||e===24)&&t>=64&&t<=95;if(!(i||r))return!1;const a=e<=23?1:2;t>=64&&t<=95?s=a===1?Gd[e]:Vd[e]:s=a===1?Kd[e]:Hd[e];const o=this.channels[a];return o?(o.setPAC(this.interpretPAC(s,t)),this.currentChannel=a,!0):!1}interpretPAC(e,t){let s;const i={color:null,italics:!1,indent:null,underline:!1,row:e};return t>95?s=t-96:s=t-64,i.underline=(s&1)===1,s<=13?i.color=["white","green","blue","cyan","red","yellow","magenta","white"][Math.floor(s/2)]:s<=15?(i.italics=!0,i.color="white"):i.indent=Math.floor((s-16)/2)*4,i}parseChars(e,t){let s,i=null,r=null;if(e>=25?(s=2,r=e-8):(s=1,r=e),r>=17&&r<=19){let a;r===17?a=t+80:r===18?a=t+112:a=t+144,this.logger.log(2,()=>"Special char '"+Uo(a)+"' in channel "+s),i=[a]}else e>=32&&e<=127&&(i=t===0?[e]:[e,t]);return i&&this.logger.log(3,()=>"Char codes = "+dt(i).join(",")),i}parseBackgroundAttributes(e,t){const s=(e===16||e===24)&&t>=32&&t<=47,i=(e===23||e===31)&&t>=45&&t<=47;if(!(s||i))return!1;let r;const a={};e===16||e===24?(r=Math.floor((t-32)/2),a.background=Wd[r],t%2===1&&(a.background=a.background+"_semi")):t===45?a.background="transparent":(a.foreground="black",t===47&&(a.underline=!0));const o=e<=23?1:2;return this.channels[o].setBkgData(a),!0}reset(){for(let e=0;e<Object.keys(this.channels).length;e++){const t=this.channels[e];t&&t.reset()}os(null,null,this.cmdHistory)}cueSplitAtTime(e){for(let t=0;t<this.channels.length;t++){const s=this.channels[t];s&&s.cueSplitAtTime(e)}}}function os(n,e,t){t.a=n,t.b=e}function Xd(n,e,t){return t.a===n&&t.b===e}function zd(){return{a:null,b:null}}var gr=function(){if(Fs!=null&&Fs.VTTCue)return self.VTTCue;const n=["","lr","rl"],e=["start","middle","end","left","right"];function t(o,c){if(typeof c!="string"||!Array.isArray(o))return!1;const l=c.toLowerCase();return~o.indexOf(l)?l:!1}function s(o){return t(n,o)}function i(o){return t(e,o)}function r(o,...c){let l=1;for(;l<arguments.length;l++){const h=arguments[l];for(const u in h)o[u]=h[u]}return o}function a(o,c,l){const h=this,u={enumerable:!0};h.hasBeenReset=!1;let d="",f=!1,g=o,p=c,y=l,E=null,T="",S=!0,v="auto",x="start",D=50,A="middle",b=50,I="middle";Object.defineProperty(h,"id",r({},u,{get:function(){return d},set:function(_){d=""+_}})),Object.defineProperty(h,"pauseOnExit",r({},u,{get:function(){return f},set:function(_){f=!!_}})),Object.defineProperty(h,"startTime",r({},u,{get:function(){return g},set:function(_){if(typeof _!="number")throw new TypeError("Start time must be set to a number.");g=_,this.hasBeenReset=!0}})),Object.defineProperty(h,"endTime",r({},u,{get:function(){return p},set:function(_){if(typeof _!="number")throw new TypeError("End time must be set to a number.");p=_,this.hasBeenReset=!0}})),Object.defineProperty(h,"text",r({},u,{get:function(){return y},set:function(_){y=""+_,this.hasBeenReset=!0}})),Object.defineProperty(h,"region",r({},u,{get:function(){return E},set:function(_){E=_,this.hasBeenReset=!0}})),Object.defineProperty(h,"vertical",r({},u,{get:function(){return T},set:function(_){const C=s(_);if(C===!1)throw new SyntaxError("An invalid or illegal string was specified.");T=C,this.hasBeenReset=!0}})),Object.defineProperty(h,"snapToLines",r({},u,{get:function(){return S},set:function(_){S=!!_,this.hasBeenReset=!0}})),Object.defineProperty(h,"line",r({},u,{get:function(){return v},set:function(_){if(typeof _!="number"&&_!=="auto")throw new SyntaxError("An invalid number or illegal string was specified.");v=_,this.hasBeenReset=!0}})),Object.defineProperty(h,"lineAlign",r({},u,{get:function(){return x},set:function(_){const C=i(_);if(!C)throw new SyntaxError("An invalid or illegal string was specified.");x=C,this.hasBeenReset=!0}})),Object.defineProperty(h,"position",r({},u,{get:function(){return D},set:function(_){if(_<0||_>100)throw new Error("Position must be between 0 and 100.");D=_,this.hasBeenReset=!0}})),Object.defineProperty(h,"positionAlign",r({},u,{get:function(){return A},set:function(_){const C=i(_);if(!C)throw new SyntaxError("An invalid or illegal string was specified.");A=C,this.hasBeenReset=!0}})),Object.defineProperty(h,"size",r({},u,{get:function(){return b},set:function(_){if(_<0||_>100)throw new Error("Size must be between 0 and 100.");b=_,this.hasBeenReset=!0}})),Object.defineProperty(h,"align",r({},u,{get:function(){return I},set:function(_){const C=i(_);if(!C)throw new SyntaxError("An invalid or illegal string was specified.");I=C,this.hasBeenReset=!0}})),h.displayState=void 0}return a.prototype.getCueAsHTML=function(){return self.WebVTT.convertCueToDOMTree(self,this.text)},a}();class Qd{decode(e,t){if(!e)return"";if(typeof e!="string")throw new Error("Error - expected string data.");return decodeURIComponent(encodeURIComponent(e))}}function Go(n){function e(s,i,r,a){return(s|0)*3600+(i|0)*60+(r|0)+parseFloat(a||0)}const t=n.match(/^(?:(\d+):)?(\d{2}):(\d{2})(\.\d+)?/);return t?parseFloat(t[2])>59?e(t[2],t[3],0,t[4]):e(t[1],t[2],t[3],t[4]):null}class Zd{constructor(){this.values=Object.create(null)}set(e,t){!this.get(e)&&t!==""&&(this.values[e]=t)}get(e,t,s){return s?this.has(e)?this.values[e]:t[s]:this.has(e)?this.values[e]:t}has(e){return e in this.values}alt(e,t,s){for(let i=0;i<s.length;++i)if(t===s[i]){this.set(e,t);break}}integer(e,t){/^-?\d+$/.test(t)&&this.set(e,parseInt(t,10))}percent(e,t){if(/^([\d]{1,3})(\.[\d]*)?%$/.test(t)){const s=parseFloat(t);if(s>=0&&s<=100)return this.set(e,s),!0}return!1}}function Ko(n,e,t,s){const i=s?n.split(s):[n];for(const r in i){if(typeof i[r]!="string")continue;const a=i[r].split(t);if(a.length!==2)continue;const o=a[0],c=a[1];e(o,c)}}const Ui=new gr(0,0,""),ls=Ui.align==="middle"?"middle":"center";function Jd(n,e,t){const s=n;function i(){const o=Go(n);if(o===null)throw new Error("Malformed timestamp: "+s);return n=n.replace(/^[^\sa-zA-Z-]+/,""),o}function r(o,c){const l=new Zd;Ko(o,function(d,f){let g;switch(d){case"region":for(let p=t.length-1;p>=0;p--)if(t[p].id===f){l.set(d,t[p].region);break}break;case"vertical":l.alt(d,f,["rl","lr"]);break;case"line":g=f.split(","),l.integer(d,g[0]),l.percent(d,g[0])&&l.set("snapToLines",!1),l.alt(d,g[0],["auto"]),g.length===2&&l.alt("lineAlign",g[1],["start",ls,"end"]);break;case"position":g=f.split(","),l.percent(d,g[0]),g.length===2&&l.alt("positionAlign",g[1],["start",ls,"end","line-left","line-right","auto"]);break;case"size":l.percent(d,f);break;case"align":l.alt(d,f,["start",ls,"end","left","right"]);break}},/:/,/\s/),c.region=l.get("region",null),c.vertical=l.get("vertical","");let h=l.get("line","auto");h==="auto"&&Ui.line===-1&&(h=-1),c.line=h,c.lineAlign=l.get("lineAlign","start"),c.snapToLines=l.get("snapToLines",!0),c.size=l.get("size",100),c.align=l.get("align",ls);let u=l.get("position","auto");u==="auto"&&Ui.position===50&&(u=c.align==="start"||c.align==="left"?0:c.align==="end"||c.align==="right"?100:50),c.position=u}function a(){n=n.replace(/^\s+/,"")}if(a(),e.startTime=i(),a(),n.slice(0,3)!=="-->")throw new Error("Malformed time stamp (time stamps must be separated by '-->'): "+s);n=n.slice(3),a(),e.endTime=i(),a(),r(n,e)}function Vo(n){return n.replace(/<br(?: \/)?>/gi,`
119119+`)}class ef{constructor(){this.state="INITIAL",this.buffer="",this.decoder=new Qd,this.regionList=[],this.cue=null,this.oncue=void 0,this.onparsingerror=void 0,this.onflush=void 0}parse(e){const t=this;e&&(t.buffer+=t.decoder.decode(e,{stream:!0}));function s(){let r=t.buffer,a=0;for(r=Vo(r);a<r.length&&r[a]!=="\r"&&r[a]!==`
120120+`;)++a;const o=r.slice(0,a);return r[a]==="\r"&&++a,r[a]===`
121121+`&&++a,t.buffer=r.slice(a),o}function i(r){Ko(r,function(a,o){},/:/)}try{let r="";if(t.state==="INITIAL"){if(!/\r\n|\n/.test(t.buffer))return this;r=s();const o=r.match(/^()?WEBVTT([ \t].*)?$/);if(!(o!=null&&o[0]))throw new Error("Malformed WebVTT signature.");t.state="HEADER"}let a=!1;for(;t.buffer;){if(!/\r\n|\n/.test(t.buffer))return this;switch(a?a=!1:r=s(),t.state){case"HEADER":/:/.test(r)?i(r):r||(t.state="ID");continue;case"NOTE":r||(t.state="ID");continue;case"ID":if(/^NOTE($|[ \t])/.test(r)){t.state="NOTE";break}if(!r)continue;if(t.cue=new gr(0,0,""),t.state="CUE",r.indexOf("-->")===-1){t.cue.id=r;continue}case"CUE":if(!t.cue){t.state="BADCUE";continue}try{Jd(r,t.cue,t.regionList)}catch{t.cue=null,t.state="BADCUE";continue}t.state="CUETEXT";continue;case"CUETEXT":{const o=r.indexOf("-->")!==-1;if(!r||o&&(a=!0)){t.oncue&&t.cue&&t.oncue(t.cue),t.cue=null,t.state="ID";continue}if(t.cue===null)continue;t.cue.text&&(t.cue.text+=`
257122`),t.cue.text+=r}continue;case"BADCUE":r||(t.state="ID")}}}catch{t.state==="CUETEXT"&&t.cue&&t.oncue&&t.oncue(t.cue),t.cue=null,t.state=t.state==="INITIAL"?"BADWEBVTT":"BADCUE"}return this}flush(){const e=this;try{if((e.cue||e.state==="HEADER")&&(e.buffer+=`
258123259259-`,e.parse()),e.state==="INITIAL"||e.state==="BADWEBVTT")throw new Error("Malformed WebVTT signature.")}catch(t){e.onparsingerror&&e.onparsingerror(t)}return e.onflush&&e.onflush(),this}}const Ed=/\r\n|\n\r|\n|\r/g,zs=function(e,t,s=0){return e.slice(s,s+t.length)===t},Td=function(e){let t=parseInt(e.slice(-3));const s=parseInt(e.slice(-6,-4)),i=parseInt(e.slice(-9,-7)),r=e.length>9?parseInt(e.substring(0,e.indexOf(":"))):0;if(!M(t)||!M(s)||!M(i)||!M(r))throw Error(`Malformed X-TIMESTAMP-MAP: Local:${e}`);return t+=1e3*s,t+=60*1e3*i,t+=60*60*1e3*r,t};function qi(a,e,t){return Mt(a.toString())+Mt(e.toString())+Mt(t)}const Sd=function(e,t,s){let i=e[t],r=e[i.prevCC];if(!r||!r.new&&i.new){e.ccOffset=e.presentationOffset=i.start,i.new=!1;return}for(;(n=r)!=null&&n.new;){var n;e.ccOffset+=i.start-r.start,i.new=!1,i=r,r=e[i.prevCC]}e.presentationOffset=s};function vd(a,e,t,s,i,r,n){const o=new yd,c=be(new Uint8Array(a)).trim().replace(Ed,`
124124+`,e.parse()),e.state==="INITIAL"||e.state==="BADWEBVTT")throw new Error("Malformed WebVTT signature.")}catch(t){e.onparsingerror&&e.onparsingerror(t)}return e.onflush&&e.onflush(),this}}const tf=/\r\n|\n\r|\n|\r/g,ci=function(e,t,s=0){return e.slice(s,s+t.length)===t},sf=function(e){let t=parseInt(e.slice(-3));const s=parseInt(e.slice(-6,-4)),i=parseInt(e.slice(-9,-7)),r=e.length>9?parseInt(e.substring(0,e.indexOf(":"))):0;if(!M(t)||!M(s)||!M(i)||!M(r))throw Error(`Malformed X-TIMESTAMP-MAP: Local:${e}`);return t+=1e3*s,t+=60*1e3*i,t+=60*60*1e3*r,t};function mr(n,e,t){return Ut(n.toString())+Ut(e.toString())+Ut(t)}const rf=function(e,t,s){let i=e[t],r=e[i.prevCC];if(!r||!r.new&&i.new){e.ccOffset=e.presentationOffset=i.start,i.new=!1;return}for(;(a=r)!=null&&a.new;){var a;e.ccOffset+=i.start-r.start,i.new=!1,i=r,r=e[i.prevCC]}e.presentationOffset=s};function nf(n,e,t,s,i,r,a){const o=new ef,c=Ce(new Uint8Array(n)).trim().replace(tf,`
260125`).split(`
261261-`),l=[],h=e?bc(e.baseTime,e.timescale):0;let d="00:00.000",u=0,f=0,g,y=!0;o.oncue=function(p){const E=t[s];let T=t.ccOffset;const S=(u-h)/9e4;if(E!=null&&E.new&&(f!==void 0?T=t.ccOffset=E.start:Sd(t,s,S)),S){if(!e){g=new Error("Missing initPTS for VTT MPEGTS");return}T=S-t.presentationOffset}const v=p.endTime-p.startTime,A=Le((p.startTime+T-f)*9e4,i*9e4)/9e4;p.startTime=Math.max(A,0),p.endTime=Math.max(A+v,0);const D=p.text.trim();p.text=decodeURIComponent(encodeURIComponent(D)),p.id||(p.id=qi(p.startTime,p.endTime,D)),p.endTime>0&&l.push(p)},o.onparsingerror=function(p){g=p},o.onflush=function(){if(g){n(g);return}r(l)},c.forEach(p=>{if(y)if(zs(p,"X-TIMESTAMP-MAP=")){y=!1,p.slice(16).split(",").forEach(E=>{zs(E,"LOCAL:")?d=E.slice(6):zs(E,"MPEGTS:")&&(u=parseInt(E.slice(7)))});try{f=Td(d)/1e3}catch(E){g=E}return}else p===""&&(y=!1);o.parse(p+`
262262-`)}),o.flush()}const Qs="stpp.ttml.im1t",Ha=/^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/,Ya=/^(\d*(?:\.\d*)?)(h|m|s|ms|f|t)$/,xd={left:"start",center:"center",right:"end",start:"start",end:"end"};function on(a,e,t,s){const i=z(new Uint8Array(a),["mdat"]);if(i.length===0){s(new Error("Could not parse IMSC1 mdat"));return}const r=i.map(o=>be(o)),n=Rc(e.baseTime,1,e.timescale);try{r.forEach(o=>t(Ad(o,n)))}catch(o){s(o)}}function Ad(a,e){const i=new DOMParser().parseFromString(a,"text/xml").getElementsByTagName("tt")[0];if(!i)throw new Error("Invalid ttml");const r={frameRate:30,subFrameRate:1,frameRateMultiplier:0,tickRate:0},n=Object.keys(r).reduce((d,u)=>(d[u]=i.getAttribute(`ttp:${u}`)||r[u],d),{}),o=i.getAttribute("xml:space")!=="preserve",c=ln(Zs(i,"styling","style")),l=ln(Zs(i,"layout","region")),h=Zs(i,"body","[begin]");return[].map.call(h,d=>{const u=Wa(d,o);if(!u||!d.hasAttribute("begin"))return null;const f=ei(d.getAttribute("begin"),n),g=ei(d.getAttribute("dur"),n);let y=ei(d.getAttribute("end"),n);if(f===null)throw cn(d);if(y===null){if(g===null)throw cn(d);y=f+g}const p=new Wi(f-e,y-e,u);p.id=qi(p.startTime,p.endTime,p.text);const E=l[d.getAttribute("region")],T=c[d.getAttribute("style")],S=Id(E,T,c),{textAlign:v}=S;if(v){const A=xd[v];A&&(p.lineAlign=A),p.align=v}return ie(p,S),p}).filter(d=>d!==null)}function Zs(a,e,t){const s=a.getElementsByTagName(e)[0];return s?[].slice.call(s.querySelectorAll(t)):[]}function ln(a){return a.reduce((e,t)=>{const s=t.getAttribute("xml:id");return s&&(e[s]=t),e},{})}function Wa(a,e){return[].slice.call(a.childNodes).reduce((t,s,i)=>{var r;return s.nodeName==="br"&&i?t+`
263263-`:(r=s.childNodes)!=null&&r.length?Wa(s,e):e?t+s.textContent.trim().replace(/\s+/g," "):t+s.textContent},"")}function Id(a,e,t){const s="http://www.w3.org/ns/ttml#styling";let i=null;const r=["displayAlign","textAlign","color","backgroundColor","fontSize","fontFamily"],n=a!=null&&a.hasAttribute("style")?a.getAttribute("style"):null;return n&&t.hasOwnProperty(n)&&(i=t[n]),r.reduce((o,c)=>{const l=Js(e,s,c)||Js(a,s,c)||Js(i,s,c);return l&&(o[c]=l),o},{})}function Js(a,e,t){return a&&a.hasAttributeNS(e,t)?a.getAttributeNS(e,t):null}function cn(a){return new Error(`Could not parse ttml timestamp ${a}`)}function ei(a,e){if(!a)return null;let t=Ga(a);return t===null&&(Ha.test(a)?t=Ld(a,e):Ya.test(a)&&(t=Rd(a,e))),t}function Ld(a,e){const t=Ha.exec(a),s=(t[4]|0)+(t[5]|0)/e.subFrameRate;return(t[1]|0)*3600+(t[2]|0)*60+(t[3]|0)+s/e.frameRate}function Rd(a,e){const t=Ya.exec(a),s=Number(t[1]);switch(t[2]){case"h":return s*3600;case"m":return s*60;case"ms":return s*1e3;case"f":return s/e.frameRate;case"t":return s/e.tickRate}return s}class rs{constructor(e,t){this.timelineController=void 0,this.cueRanges=[],this.trackName=void 0,this.startTime=null,this.endTime=null,this.screen=null,this.timelineController=e,this.trackName=t}dispatchCue(){this.startTime!==null&&(this.timelineController.addCues(this.trackName,this.startTime,this.endTime,this.screen,this.cueRanges),this.startTime=null)}newCue(e,t,s){(this.startTime===null||this.startTime>e)&&(this.startTime=e),this.endTime=t,this.screen=s,this.timelineController.createCaptionsTrack(this.trackName)}reset(){this.cueRanges=[],this.startTime=null}}class bd{constructor(e){this.hls=void 0,this.media=null,this.config=void 0,this.enabled=!0,this.Cues=void 0,this.textTracks=[],this.tracks=[],this.initPTS=[],this.unparsedVttFrags=[],this.captionsTracks={},this.nonNativeCaptionsTracks={},this.cea608Parser1=void 0,this.cea608Parser2=void 0,this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs=dn(),this.captionsProperties=void 0,this.hls=e,this.config=e.config,this.Cues=e.config.cueHandler,this.captionsProperties={textTrack1:{label:this.config.captionsTextTrack1Label,languageCode:this.config.captionsTextTrack1LanguageCode},textTrack2:{label:this.config.captionsTextTrack2Label,languageCode:this.config.captionsTextTrack2LanguageCode},textTrack3:{label:this.config.captionsTextTrack3Label,languageCode:this.config.captionsTextTrack3LanguageCode},textTrack4:{label:this.config.captionsTextTrack4Label,languageCode:this.config.captionsTextTrack4LanguageCode}},e.on(m.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(m.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(m.MANIFEST_LOADING,this.onManifestLoading,this),e.on(m.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(m.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(m.FRAG_LOADING,this.onFragLoading,this),e.on(m.FRAG_LOADED,this.onFragLoaded,this),e.on(m.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.on(m.FRAG_DECRYPTED,this.onFragDecrypted,this),e.on(m.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(m.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.on(m.BUFFER_FLUSHING,this.onBufferFlushing,this)}destroy(){const{hls:e}=this;e.off(m.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(m.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(m.MANIFEST_LOADING,this.onManifestLoading,this),e.off(m.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(m.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(m.FRAG_LOADING,this.onFragLoading,this),e.off(m.FRAG_LOADED,this.onFragLoaded,this),e.off(m.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.off(m.FRAG_DECRYPTED,this.onFragDecrypted,this),e.off(m.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(m.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.off(m.BUFFER_FLUSHING,this.onBufferFlushing,this),this.hls=this.config=this.media=null,this.cea608Parser1=this.cea608Parser2=void 0}initCea608Parsers(){const e=new rs(this,"textTrack1"),t=new rs(this,"textTrack2"),s=new rs(this,"textTrack3"),i=new rs(this,"textTrack4");this.cea608Parser1=new an(1,e,t),this.cea608Parser2=new an(3,s,i)}addCues(e,t,s,i,r){let n=!1;for(let o=r.length;o--;){const c=r[o],l=_d(c[0],c[1],t,s);if(l>=0&&(c[0]=Math.min(c[0],t),c[1]=Math.max(c[1],s),n=!0,l/(s-t)>.5))return}if(n||r.push([t,s]),this.config.renderTextTracksNatively){const o=this.captionsTracks[e];this.Cues.newCue(o,t,s,i)}else{const o=this.Cues.newCue(null,t,s,i);this.hls.trigger(m.CUES_PARSED,{type:"captions",cues:o,track:e})}}onInitPtsFound(e,{frag:t,id:s,initPTS:i,timescale:r,trackId:n}){const{unparsedVttFrags:o}=this;s===B.MAIN&&(this.initPTS[t.cc]={baseTime:i,timescale:r,trackId:n}),o.length&&(this.unparsedVttFrags=[],o.forEach(c=>{this.initPTS[c.frag.cc]?this.onFragLoaded(m.FRAG_LOADED,c):this.hls.trigger(m.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:c.frag,error:new Error("Subtitle discontinuity domain does not match main")})}))}getExistingTrack(e,t){const{media:s}=this;if(s)for(let i=0;i<s.textTracks.length;i++){const r=s.textTracks[i];if(hn(r,{name:e,lang:t,characteristics:"transcribes-spoken-dialog,describes-music-and-sound"}))return r}return null}createCaptionsTrack(e){this.config.renderTextTracksNatively?this.createNativeTrack(e):this.createNonNativeTrack(e)}createNativeTrack(e){if(this.captionsTracks[e])return;const{captionsProperties:t,captionsTracks:s,media:i}=this,{label:r,languageCode:n}=t[e],o=this.getExistingTrack(r,n);if(o)s[e]=o,At(s[e]),Ma(s[e],i);else{const c=this.createTextTrack("captions",r,n);c&&(c[e]=!0,s[e]=c)}}createNonNativeTrack(e){if(this.nonNativeCaptionsTracks[e])return;const t=this.captionsProperties[e];if(!t)return;const s=t.label,i={_id:e,label:s,kind:"captions",default:t.media?!!t.media.default:!1,closedCaptions:t.media};this.nonNativeCaptionsTracks[e]=i,this.hls.trigger(m.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:[i]})}createTextTrack(e,t,s){const i=this.media;if(i)return i.addTextTrack(e,t,s)}onMediaAttaching(e,t){this.media=t.media,t.mediaSource||this._cleanTracks()}onMediaDetaching(e,t){const s=!!t.transferMedia;if(this.media=null,s)return;const{captionsTracks:i}=this;Object.keys(i).forEach(r=>{At(i[r]),delete i[r]}),this.nonNativeCaptionsTracks={}}onManifestLoading(){this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs=dn(),this._cleanTracks(),this.tracks=[],this.captionsTracks={},this.nonNativeCaptionsTracks={},this.textTracks=[],this.unparsedVttFrags=[],this.initPTS=[],this.cea608Parser1&&this.cea608Parser2&&(this.cea608Parser1.reset(),this.cea608Parser2.reset())}_cleanTracks(){const{media:e}=this;if(!e)return;const t=e.textTracks;if(t)for(let s=0;s<t.length;s++)At(t[s])}onSubtitleTracksUpdated(e,t){const s=t.subtitleTracks||[],i=s.some(r=>r.textCodec===Qs);if(this.config.enableWebVTT||i&&this.config.enableIMSC1){if(Aa(this.tracks,s)){this.tracks=s;return}if(this.textTracks=[],this.tracks=s,this.config.renderTextTracksNatively){const n=this.media,o=n?ms(n.textTracks):null;if(this.tracks.forEach((c,l)=>{let h;if(o){let d=null;for(let u=0;u<o.length;u++)if(o[u]&&hn(o[u],c)){d=o[u],o[u]=null;break}d&&(h=d)}if(h)At(h);else{const d=qa(c);h=this.createTextTrack(d,c.name,c.lang),h&&(h.mode="disabled")}h&&this.textTracks.push(h)}),o!=null&&o.length){const c=o.filter(l=>l!==null).map(l=>l.label);c.length&&this.hls.logger.warn(`Media element contains unused subtitle tracks: ${c.join(", ")}. Replace media element for each source to clear TextTracks and captions menu.`)}}else if(this.tracks.length){const n=this.tracks.map(o=>({label:o.name,kind:o.type.toLowerCase(),default:o.default,subtitleTrack:o}));this.hls.trigger(m.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:n})}}}onManifestLoaded(e,t){this.config.enableCEA708Captions&&t.captions&&t.captions.forEach(s=>{const i=/(?:CC|SERVICE)([1-4])/.exec(s.instreamId);if(!i)return;const r=`textTrack${i[1]}`,n=this.captionsProperties[r];n&&(n.label=s.name,s.lang&&(n.languageCode=s.lang),n.media=s)})}closedCaptionsForLevel(e){const t=this.hls.levels[e.level];return t==null?void 0:t.attrs["CLOSED-CAPTIONS"]}onFragLoading(e,t){if(this.enabled&&t.frag.type===B.MAIN){var s,i;const{cea608Parser1:r,cea608Parser2:n,lastSn:o}=this,{cc:c,sn:l}=t.frag,h=(s=(i=t.part)==null?void 0:i.index)!=null?s:-1;r&&n&&(l!==o+1||l===o&&h!==this.lastPartIndex+1||c!==this.lastCc)&&(r.reset(),n.reset()),this.lastCc=c,this.lastSn=l,this.lastPartIndex=h}}onFragLoaded(e,t){const{frag:s,payload:i}=t;if(s.type===B.SUBTITLE)if(i.byteLength){const r=s.decryptdata,n="stats"in t;if(r==null||!r.encrypted||n){const o=this.tracks[s.level],c=this.vttCCs;c[s.cc]||(c[s.cc]={start:s.start,prevCC:this.prevCC,new:!0},this.prevCC=s.cc),o&&o.textCodec===Qs?this._parseIMSC1(s,i):this._parseVTTs(t)}}else this.hls.trigger(m.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:s,error:new Error("Empty subtitle payload")})}_parseIMSC1(e,t){const s=this.hls;on(t,this.initPTS[e.cc],i=>{this._appendCues(i,e.level),s.trigger(m.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:e})},i=>{s.logger.log(`Failed to parse IMSC1: ${i}`),s.trigger(m.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:e,error:i})})}_parseVTTs(e){var t;const{frag:s,payload:i}=e,{initPTS:r,unparsedVttFrags:n}=this,o=r.length-1;if(!r[s.cc]&&o===-1){n.push(e);return}const c=this.hls,l=(t=s.initSegment)!=null&&t.data?ke(s.initSegment.data,new Uint8Array(i)).buffer:i;vd(l,this.initPTS[s.cc],this.vttCCs,s.cc,s.start,h=>{this._appendCues(h,s.level),c.trigger(m.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:s})},h=>{const d=h.message==="Missing initPTS for VTT MPEGTS";d?n.push(e):this._fallbackToIMSC1(s,i),c.logger.log(`Failed to parse VTT cue: ${h}`),!(d&&o>s.cc)&&c.trigger(m.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:s,error:h})})}_fallbackToIMSC1(e,t){const s=this.tracks[e.level];s.textCodec||on(t,this.initPTS[e.cc],()=>{s.textCodec=Qs,this._parseIMSC1(e,t)},()=>{s.textCodec="wvtt"})}_appendCues(e,t){const s=this.hls;if(this.config.renderTextTracksNatively){const i=this.textTracks[t];if(!i||i.mode==="disabled")return;e.forEach(r=>Na(i,r))}else{const i=this.tracks[t];if(!i)return;const r=i.default?"default":"subtitles"+t;s.trigger(m.CUES_PARSED,{type:"subtitles",cues:e,track:r})}}onFragDecrypted(e,t){const{frag:s}=t;s.type===B.SUBTITLE&&this.onFragLoaded(m.FRAG_LOADED,t)}onSubtitleTracksCleared(){this.tracks=[],this.captionsTracks={}}onFragParsingUserdata(e,t){if(!this.enabled||!this.config.enableCEA708Captions)return;const{frag:s,samples:i}=t;if(!(s.type===B.MAIN&&this.closedCaptionsForLevel(s)==="NONE"))for(let r=0;r<i.length;r++){const n=i[r].bytes;if(n){this.cea608Parser1||this.initCea608Parsers();const o=this.extractCea608Data(n);this.cea608Parser1.addData(i[r].pts,o[0]),this.cea608Parser2.addData(i[r].pts,o[1])}}}onBufferFlushing(e,{startOffset:t,endOffset:s,endOffsetSubtitles:i,type:r}){const{media:n}=this;if(!(!n||n.currentTime<s)){if(!r||r==="video"){const{captionsTracks:o}=this;Object.keys(o).forEach(c=>Ti(o[c],t,s))}if(this.config.renderTextTracksNatively&&t===0&&i!==void 0){const{textTracks:o}=this;Object.keys(o).forEach(c=>Ti(o[c],t,i))}}}extractCea608Data(e){const t=[[],[]],s=e[0]&31;let i=2;for(let r=0;r<s;r++){const n=e[i++],o=127&e[i++],c=127&e[i++];if(o===0&&c===0)continue;if((4&n)!==0){const h=3&n;(h===0||h===1)&&(t[h].push(o),t[h].push(c))}}return t}}function qa(a){return a.characteristics&&/transcribes-spoken-dialog/gi.test(a.characteristics)&&/describes-music-and-sound/gi.test(a.characteristics)?"captions":"subtitles"}function hn(a,e){return!!a&&a.kind===qa(e)&&mi(e,a)}function _d(a,e,t,s){return Math.min(e,s)-Math.max(a,t)}function dn(){return{ccOffset:0,presentationOffset:0,0:{start:0,prevCC:-1,new:!0}}}const Dd=/\s/,Cd={newCue(a,e,t,s){const i=[];let r,n,o,c,l;const h=self.VTTCue||self.TextTrackCue;for(let u=0;u<s.rows.length;u++)if(r=s.rows[u],o=!0,c=0,l="",!r.isEmpty()){var d;for(let y=0;y<r.chars.length;y++)Dd.test(r.chars[y].uchar)&&o?c++:(l+=r.chars[y].uchar,o=!1);r.cueStartTime=e,e===t&&(t+=1e-4),c>=16?c--:c++;const f=Va(l.trim()),g=qi(e,t,f);a!=null&&(d=a.cues)!=null&&d.getCueById(g)||(n=new h(e,t,f),n.id=g,n.line=u+1,n.align="left",n.position=10+Math.min(80,Math.floor(c*8/32)*10),i.push(n))}return a&&i.length&&(i.sort((u,f)=>u.line==="auto"||f.line==="auto"?0:u.line>8&&f.line>8?f.line-u.line:u.line-f.line),i.forEach(u=>Na(a,u))),i}};function Pd(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch{}return!1}const kd=/(\d+)-(\d+)\/(\d+)/;class un{constructor(e){this.fetchSetup=void 0,this.requestTimeout=void 0,this.request=null,this.response=null,this.controller=void 0,this.context=null,this.config=null,this.callbacks=null,this.stats=void 0,this.loader=null,this.fetchSetup=e.fetchSetup||Md,this.controller=new self.AbortController,this.stats=new Li}destroy(){this.loader=this.callbacks=this.context=this.config=this.request=null,this.abortInternal(),this.response=null,this.fetchSetup=this.controller=this.stats=null}abortInternal(){this.controller&&!this.stats.loading.end&&(this.stats.aborted=!0,this.controller.abort())}abort(){var e;this.abortInternal(),(e=this.callbacks)!=null&&e.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.response)}load(e,t,s){const i=this.stats;if(i.loading.start)throw new Error("Loader can only be used once.");i.loading.start=self.performance.now();const r=wd(e,this.controller.signal),n=e.responseType==="arraybuffer",o=n?"byteLength":"length",{maxTimeToFirstByteMs:c,maxLoadTimeMs:l}=t.loadPolicy;this.context=e,this.config=t,this.callbacks=s,this.request=this.fetchSetup(e,r),self.clearTimeout(this.requestTimeout),t.timeout=c&&M(c)?c:l,this.requestTimeout=self.setTimeout(()=>{this.callbacks&&(this.abortInternal(),this.callbacks.onTimeout(i,e,this.response))},t.timeout),(Vt(this.request)?this.request.then(self.fetch):self.fetch(this.request)).then(d=>{var u;this.response=this.loader=d;const f=Math.max(self.performance.now(),i.loading.start);if(self.clearTimeout(this.requestTimeout),t.timeout=l,this.requestTimeout=self.setTimeout(()=>{this.callbacks&&(this.abortInternal(),this.callbacks.onTimeout(i,e,this.response))},l-(f-i.loading.start)),!d.ok){const{status:y,statusText:p}=d;throw new Nd(p||"fetch, bad network response",y,d)}i.loading.first=f,i.total=Fd(d.headers)||i.total;const g=(u=this.callbacks)==null?void 0:u.onProgress;return g&&M(t.highWaterMark)?this.loadProgressively(d,i,e,t.highWaterMark,g):n?d.arrayBuffer():e.responseType==="json"?d.json():d.text()}).then(d=>{var u,f;const g=this.response;if(!g)throw new Error("loader destroyed");self.clearTimeout(this.requestTimeout),i.loading.end=Math.max(self.performance.now(),i.loading.first);const y=d[o];y&&(i.loaded=i.total=y);const p={url:g.url,data:d,code:g.status},E=(u=this.callbacks)==null?void 0:u.onProgress;E&&!M(t.highWaterMark)&&E(i,e,d,g),(f=this.callbacks)==null||f.onSuccess(p,i,e,g)}).catch(d=>{var u;if(self.clearTimeout(this.requestTimeout),i.aborted)return;const f=d&&d.code||0,g=d?d.message:null;(u=this.callbacks)==null||u.onError({code:f,text:g},e,d?d.details:null,i)})}getCacheAge(){let e=null;if(this.response){const t=this.response.headers.get("age");e=t?parseFloat(t):null}return e}getResponseHeader(e){return this.response?this.response.headers.get(e):null}loadProgressively(e,t,s,i=0,r){const n=new ia,o=e.body.getReader(),c=()=>o.read().then(l=>{if(l.done)return n.dataLength&&r(t,s,n.flush().buffer,e),Promise.resolve(new ArrayBuffer(0));const h=l.value,d=h.length;return t.loaded+=d,d<i||n.dataLength?(n.push(h),n.dataLength>=i&&r(t,s,n.flush().buffer,e)):r(t,s,h.buffer,e),c()}).catch(()=>Promise.reject());return c()}}function wd(a,e){const t={method:"GET",mode:"cors",credentials:"same-origin",signal:e,headers:new self.Headers(ie({},a.headers))};return a.rangeEnd&&t.headers.set("Range","bytes="+a.rangeStart+"-"+String(a.rangeEnd-1)),t}function Od(a){const e=kd.exec(a);if(e)return parseInt(e[2])-parseInt(e[1])+1}function Fd(a){const e=a.get("Content-Range");if(e){const s=Od(e);if(M(s))return s}const t=a.get("Content-Length");if(t)return parseInt(t)}function Md(a,e){return new self.Request(a.url,e)}class Nd extends Error{constructor(e,t,s){super(e),this.code=void 0,this.details=void 0,this.code=t,this.details=s}}const Bd=/^age:\s*[\d.]+\s*$/im;class ja{constructor(e){this.xhrSetup=void 0,this.requestTimeout=void 0,this.retryTimeout=void 0,this.retryDelay=void 0,this.config=null,this.callbacks=null,this.context=null,this.loader=null,this.stats=void 0,this.xhrSetup=e&&e.xhrSetup||null,this.stats=new Li,this.retryDelay=0}destroy(){this.callbacks=null,this.abortInternal(),this.loader=null,this.config=null,this.context=null,this.xhrSetup=null}abortInternal(){const e=this.loader;self.clearTimeout(this.requestTimeout),self.clearTimeout(this.retryTimeout),e&&(e.onreadystatechange=null,e.onprogress=null,e.readyState!==4&&(this.stats.aborted=!0,e.abort()))}abort(){var e;this.abortInternal(),(e=this.callbacks)!=null&&e.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.loader)}load(e,t,s){if(this.stats.loading.start)throw new Error("Loader can only be used once.");this.stats.loading.start=self.performance.now(),this.context=e,this.config=t,this.callbacks=s,this.loadInternal()}loadInternal(){const{config:e,context:t}=this;if(!e||!t)return;const s=this.loader=new self.XMLHttpRequest,i=this.stats;i.loading.first=0,i.loaded=0,i.aborted=!1;const r=this.xhrSetup;r?Promise.resolve().then(()=>{if(!(this.loader!==s||this.stats.aborted))return r(s,t.url)}).catch(n=>{if(!(this.loader!==s||this.stats.aborted))return s.open("GET",t.url,!0),r(s,t.url)}).then(()=>{this.loader!==s||this.stats.aborted||this.openAndSendXhr(s,t,e)}).catch(n=>{var o;(o=this.callbacks)==null||o.onError({code:s.status,text:n.message},t,s,i)}):this.openAndSendXhr(s,t,e)}openAndSendXhr(e,t,s){e.readyState||e.open("GET",t.url,!0);const i=t.headers,{maxTimeToFirstByteMs:r,maxLoadTimeMs:n}=s.loadPolicy;if(i)for(const o in i)e.setRequestHeader(o,i[o]);t.rangeEnd&&e.setRequestHeader("Range","bytes="+t.rangeStart+"-"+(t.rangeEnd-1)),e.onreadystatechange=this.readystatechange.bind(this),e.onprogress=this.loadprogress.bind(this),e.responseType=t.responseType,self.clearTimeout(this.requestTimeout),s.timeout=r&&M(r)?r:n,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),s.timeout),e.send()}readystatechange(){const{context:e,loader:t,stats:s}=this;if(!e||!t)return;const i=t.readyState,r=this.config;if(!s.aborted&&i>=2&&(s.loading.first===0&&(s.loading.first=Math.max(self.performance.now(),s.loading.start),r.timeout!==r.loadPolicy.maxLoadTimeMs&&(self.clearTimeout(this.requestTimeout),r.timeout=r.loadPolicy.maxLoadTimeMs,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),r.loadPolicy.maxLoadTimeMs-(s.loading.first-s.loading.start)))),i===4)){self.clearTimeout(this.requestTimeout),t.onreadystatechange=null,t.onprogress=null;const l=t.status,h=t.responseType==="text"?t.responseText:null;if(l>=200&&l<300){const g=h??t.response;if(g!=null){var n,o;s.loading.end=Math.max(self.performance.now(),s.loading.first);const y=t.responseType==="arraybuffer"?g.byteLength:g.length;s.loaded=s.total=y,s.bwEstimate=s.total*8e3/(s.loading.end-s.loading.first);const p=(n=this.callbacks)==null?void 0:n.onProgress;p&&p(s,e,g,t);const E={url:t.responseURL,data:g,code:l};(o=this.callbacks)==null||o.onSuccess(E,s,e,t);return}}const d=r.loadPolicy.errorRetry,u=s.retry,f={url:e.url,data:void 0,code:l};if(As(d,u,!1,f))this.retry(d);else{var c;se.error(`${l} while loading ${e.url}`),(c=this.callbacks)==null||c.onError({code:l,text:t.statusText},e,t,s)}}}loadtimeout(){if(!this.config)return;const e=this.config.loadPolicy.timeoutRetry,t=this.stats.retry;if(As(e,t,!0))this.retry(e);else{var s;se.warn(`timeout while loading ${(s=this.context)==null?void 0:s.url}`);const i=this.callbacks;i&&(this.abortInternal(),i.onTimeout(this.stats,this.context,this.loader))}}retry(e){const{context:t,stats:s}=this;this.retryDelay=Di(e,s.retry),s.retry++,se.warn(`${status?"HTTP Status "+status:"Timeout"} while loading ${t==null?void 0:t.url}, retrying ${s.retry}/${e.maxNumRetry} in ${this.retryDelay}ms`),this.abortInternal(),this.loader=null,self.clearTimeout(this.retryTimeout),this.retryTimeout=self.setTimeout(this.loadInternal.bind(this),this.retryDelay)}loadprogress(e){const t=this.stats;t.loaded=e.loaded,e.lengthComputable&&(t.total=e.total)}getCacheAge(){let e=null;if(this.loader&&Bd.test(this.loader.getAllResponseHeaders())){const t=this.loader.getResponseHeader("age");e=t?parseFloat(t):null}return e}getResponseHeader(e){return this.loader&&new RegExp(`^${e}:\\s*[\\d.]+\\s*$`,"im").test(this.loader.getAllResponseHeaders())?this.loader.getResponseHeader(e):null}}const Ud={maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:null,errorRetry:null},$d=te(te({autoStartLoad:!0,startPosition:-1,defaultAudioCodec:void 0,debug:!1,capLevelOnFPSDrop:!1,capLevelToPlayerSize:!1,ignoreDevicePixelRatio:!1,maxDevicePixelRatio:Number.POSITIVE_INFINITY,preferManagedMediaSource:!0,initialLiveManifestSize:1,maxBufferLength:30,backBufferLength:1/0,frontBufferFlushThreshold:1/0,startOnSegmentBoundary:!1,maxBufferSize:60*1e3*1e3,maxFragLookUpTolerance:.25,maxBufferHole:.1,detectStallWithCurrentTimeMs:1250,highBufferWatchdogPeriod:2,nudgeOffset:.1,nudgeMaxRetry:3,nudgeOnVideoHole:!0,liveSyncMode:"edge",liveSyncDurationCount:3,liveSyncOnStallIncrease:1,liveMaxLatencyDurationCount:1/0,liveSyncDuration:void 0,liveMaxLatencyDuration:void 0,maxLiveSyncPlaybackRate:1,liveDurationInfinity:!1,liveBackBufferLength:null,maxMaxBufferLength:600,enableWorker:!0,workerPath:null,enableSoftwareAES:!0,startLevel:void 0,startFragPrefetch:!1,fpsDroppedMonitoringPeriod:5e3,fpsDroppedMonitoringThreshold:.2,appendErrorMaxRetry:3,ignorePlaylistParsingErrors:!1,loader:ja,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,licenseXhrSetup:void 0,licenseResponseCallback:void 0,abrController:Zo,bufferController:Kc,capLevelController:Vi,errorController:il,fpsController:Vh,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:Wn,requireKeySystemAccessOnStart:!1,testBandwidth:!0,progressive:!1,lowLatencyMode:!0,cmcd:void 0,enableDateRangeMetadataCues:!0,enableEmsgMetadataCues:!0,enableEmsgKLVMetadata:!1,enableID3MetadataCues:!0,enableInterstitialPlayback:!0,interstitialAppendInPlace:!0,interstitialLiveLookAhead:10,useMediaCapabilities:!0,preserveManualLevelOnError:!1,certLoadPolicy:{default:Ud},keyLoadPolicy:{default:{maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:2e4,backoff:"linear"},errorRetry:{maxNumRetry:8,retryDelayMs:1e3,maxRetryDelayMs:2e4,backoff:"linear"}}},manifestLoadPolicy:{default:{maxTimeToFirstByteMs:1/0,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},playlistLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:2,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},fragLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:12e4,timeoutRetry:{maxNumRetry:4,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:6,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},steeringManifestLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},interstitialAssetListLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:3e4,timeoutRetry:{maxNumRetry:0,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:0,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},manifestLoadingTimeOut:1e4,manifestLoadingMaxRetry:1,manifestLoadingRetryDelay:1e3,manifestLoadingMaxRetryTimeout:64e3,levelLoadingTimeOut:1e4,levelLoadingMaxRetry:4,levelLoadingRetryDelay:1e3,levelLoadingMaxRetryTimeout:64e3,fragLoadingTimeOut:2e4,fragLoadingMaxRetry:6,fragLoadingRetryDelay:1e3,fragLoadingMaxRetryTimeout:64e3},Gd()),{},{subtitleStreamController:td,subtitleTrackController:Wh,timelineController:bd,audioStreamController:Bc,audioTrackController:Uc,emeController:Rt,cmcdController:Uh,contentSteeringController:Gh,interstitialsController:ed});function Gd(){return{cueHandler:Cd,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 Kd(a,e,t){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(e.liveMaxLatencyDurationCount!==void 0&&(e.liveSyncDurationCount===void 0||e.liveMaxLatencyDurationCount<=e.liveSyncDurationCount))throw new Error('Illegal hls.js config: "liveMaxLatencyDurationCount" must be greater than "liveSyncDurationCount"');if(e.liveMaxLatencyDuration!==void 0&&(e.liveSyncDuration===void 0||e.liveMaxLatencyDuration<=e.liveSyncDuration))throw new Error('Illegal hls.js config: "liveMaxLatencyDuration" must be greater than "liveSyncDuration"');const s=vi(a),i=["manifest","level","frag"],r=["TimeOut","MaxRetry","RetryDelay","MaxRetryTimeout"];return i.forEach(n=>{const o=`${n==="level"?"playlist":n}LoadPolicy`,c=e[o]===void 0,l=[];r.forEach(h=>{const d=`${n}Loading${h}`,u=e[d];if(u!==void 0&&c){l.push(d);const f=s[o].default;switch(e[o]={default:f},h){case"TimeOut":f.maxLoadTimeMs=u,f.maxTimeToFirstByteMs=u;break;case"MaxRetry":f.errorRetry.maxNumRetry=u,f.timeoutRetry.maxNumRetry=u;break;case"RetryDelay":f.errorRetry.retryDelayMs=u,f.timeoutRetry.retryDelayMs=u;break;case"MaxRetryTimeout":f.errorRetry.maxRetryDelayMs=u,f.timeoutRetry.maxRetryDelayMs=u;break}}}),l.length&&t.warn(`hls.js config: "${l.join('", "')}" setting(s) are deprecated, use "${o}": ${ne(e[o])}`)}),te(te({},s),e)}function vi(a){return a&&typeof a=="object"?Array.isArray(a)?a.map(vi):Object.keys(a).reduce((e,t)=>(e[t]=vi(a[t]),e),{}):a}function Vd(a,e){const t=a.loader;t!==un&&t!==ja?(e.log("[config]: Custom loader detected, cannot enable progressive streaming"),a.progressive=!1):Pd()&&(a.loader=un,a.progressive=!0,a.enableSoftwareAES=!0,e.log("[config]: Progressive streaming enabled, using FetchLoader"))}const ps=2,Hd=.1,Yd=.05,Wd=100;class qd extends Gn{constructor(e,t){super("gap-controller",e.logger),this.hls=void 0,this.fragmentTracker=void 0,this.media=null,this.mediaSource=void 0,this.nudgeRetry=0,this.stallReported=!1,this.stalled=null,this.moved=!1,this.seeking=!1,this.buffered={},this.lastCurrentTime=0,this.ended=0,this.waiting=0,this.onMediaPlaying=()=>{this.ended=0,this.waiting=0},this.onMediaWaiting=()=>{var s;(s=this.media)!=null&&s.seeking||(this.waiting=self.performance.now(),this.tick())},this.onMediaEnded=()=>{if(this.hls){var s;this.ended=((s=this.media)==null?void 0:s.currentTime)||1,this.hls.trigger(m.MEDIA_ENDED,{stalled:!1})}},this.hls=e,this.fragmentTracker=t,this.registerListeners()}registerListeners(){const{hls:e}=this;e&&(e.on(m.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(m.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(m.BUFFER_APPENDED,this.onBufferAppended,this))}unregisterListeners(){const{hls:e}=this;e&&(e.off(m.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(m.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(m.BUFFER_APPENDED,this.onBufferAppended,this))}destroy(){super.destroy(),this.unregisterListeners(),this.media=this.hls=this.fragmentTracker=null,this.mediaSource=void 0}onMediaAttached(e,t){this.setInterval(Wd),this.mediaSource=t.mediaSource;const s=this.media=t.media;Te(s,"playing",this.onMediaPlaying),Te(s,"waiting",this.onMediaWaiting),Te(s,"ended",this.onMediaEnded)}onMediaDetaching(e,t){this.clearInterval();const{media:s}=this;s&&(ve(s,"playing",this.onMediaPlaying),ve(s,"waiting",this.onMediaWaiting),ve(s,"ended",this.onMediaEnded),this.media=null),this.mediaSource=void 0}onBufferAppended(e,t){this.buffered=t.timeRanges}get hasBuffered(){return Object.keys(this.buffered).length>0}tick(){var e;if(!((e=this.media)!=null&&e.readyState)||!this.hasBuffered)return;const t=this.media.currentTime;this.poll(t,this.lastCurrentTime),this.lastCurrentTime=t}poll(e,t){var s,i;const r=(s=this.hls)==null?void 0:s.config;if(!r)return;const n=this.media;if(!n)return;const{seeking:o}=n,c=this.seeking&&!o,l=!this.seeking&&o,h=n.paused&&!o||n.ended||n.playbackRate===0;if(this.seeking=o,e!==t){t&&(this.ended=0),this.moved=!0,o||(this.nudgeRetry=0,r.nudgeOnVideoHole&&!h&&e>t&&this.nudgeOnVideoHole(e,t)),this.waiting===0&&this.stallResolved(e);return}if(l||c){c&&this.stallResolved(e);return}if(h){this.nudgeRetry=0,this.stallResolved(e),!this.ended&&n.ended&&this.hls&&(this.ended=e||1,this.hls.trigger(m.MEDIA_ENDED,{stalled:!1}));return}if(!q.getBuffered(n).length){this.nudgeRetry=0;return}const d=q.bufferInfo(n,e,0),u=d.nextStart||0,f=this.fragmentTracker;if(o&&f&&this.hls){const D=fn(this.hls.inFlightFragments,e),x=d.len>ps,b=!u||D||u-e>ps&&!f.getPartialFragment(e);if(x||b)return;this.moved=!1}const g=(i=this.hls)==null?void 0:i.latestLevelDetails;if(!this.moved&&this.stalled!==null&&f){if(!(d.len>0)&&!u)return;const x=Math.max(u,d.start||0)-e,_=!!(g!=null&&g.live)?g.targetduration*2:ps,I=ns(e,f);if(x>0&&(x<=_||I)){n.paused||this._trySkipBufferHole(I);return}}const y=r.detectStallWithCurrentTimeMs,p=self.performance.now(),E=this.waiting;let T=this.stalled;if(T===null)if(E>0&&p-E<y)T=this.stalled=E;else{this.stalled=p;return}const S=p-T;if(!o&&(S>=y||E)&&this.hls){var v;if(((v=this.mediaSource)==null?void 0:v.readyState)==="ended"&&!(g!=null&&g.live)&&Math.abs(e-((g==null?void 0:g.edge)||0))<1){if(this.ended)return;this.ended=e||1,this.hls.trigger(m.MEDIA_ENDED,{stalled:!0});return}if(this._reportStall(d),!this.media||!this.hls)return}const A=q.bufferInfo(n,e,r.maxBufferHole);this._tryFixBufferStall(A,S,e)}stallResolved(e){const t=this.stalled;if(t&&this.hls&&(this.stalled=null,this.stallReported)){const s=self.performance.now()-t;this.log(`playback not stuck anymore @${e}, after ${Math.round(s)}ms`),this.stallReported=!1,this.waiting=0,this.hls.trigger(m.STALL_RESOLVED,{})}}nudgeOnVideoHole(e,t){var s;const i=this.buffered.video;if(this.hls&&this.media&&this.fragmentTracker&&(s=this.buffered.audio)!=null&&s.length&&i&&i.length>1&&e>i.end(0)){const r=q.bufferedInfo(q.timeRangesToArray(this.buffered.audio),e,0);if(r.len>1&&t>=r.start){const n=q.timeRangesToArray(i),o=q.bufferedInfo(n,t,0).bufferedIndex;if(o>-1&&o<n.length-1){const c=q.bufferedInfo(n,e,0).bufferedIndex,l=n[o].end,h=n[o+1].start;if((c===-1||c>o)&&h-l<1&&e-l<2){const d=new Error(`nudging playhead to flush pipeline after video hole. currentTime: ${e} hole: ${l} -> ${h} buffered index: ${c}`);this.warn(d.message),this.media.currentTime+=1e-6;let u=ns(e,this.fragmentTracker);u&&"fragment"in u?u=u.fragment:u||(u=void 0);const f=q.bufferInfo(this.media,e,0);this.hls.trigger(m.ERROR,{type:V.MEDIA_ERROR,details:R.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:d,reason:d.message,frag:u,buffer:f.len,bufferInfo:f})}}}}}_tryFixBufferStall(e,t,s){var i,r;const{fragmentTracker:n,media:o}=this,c=(i=this.hls)==null?void 0:i.config;if(!o||!n||!c)return;const l=(r=this.hls)==null?void 0:r.latestLevelDetails,h=ns(s,n);if((h||l!=null&&l.live&&s<l.fragmentStart)&&(this._trySkipBufferHole(h)||!this.media))return;const d=e.buffered,u=this.adjacentTraversal(e,s);(d&&d.length>1&&e.len>c.maxBufferHole||e.nextStart&&(e.nextStart-s<c.maxBufferHole||u))&&(t>c.highBufferWatchdogPeriod*1e3||this.waiting)&&(this.warn("Trying to nudge playhead over buffer-hole"),this._tryNudgeBuffer(e))}adjacentTraversal(e,t){const s=this.fragmentTracker,i=e.nextStart;if(s&&i){const r=s.getFragAtPos(t,B.MAIN),n=s.getFragAtPos(i,B.MAIN);if(r&&n)return n.sn-r.sn<2}return!1}_reportStall(e){const{hls:t,media:s,stallReported:i,stalled:r}=this;if(!i&&r!==null&&s&&t){this.stallReported=!0;const n=new Error(`Playback stalling at @${s.currentTime} due to low buffer (${ne(e)})`);this.warn(n.message),t.trigger(m.ERROR,{type:V.MEDIA_ERROR,details:R.BUFFER_STALLED_ERROR,fatal:!1,error:n,buffer:e.len,bufferInfo:e,stalled:{start:r}})}}_trySkipBufferHole(e){var t;const{fragmentTracker:s,media:i}=this,r=(t=this.hls)==null?void 0:t.config;if(!i||!s||!r)return 0;const n=i.currentTime,o=q.bufferInfo(i,n,0),c=n<o.start?o.start:o.nextStart;if(c&&this.hls){const h=o.len<=r.maxBufferHole,d=o.len>0&&o.len<1&&i.readyState<3,u=c-n;if(u>0&&(h||d)){if(u>r.maxBufferHole){let g=!1;if(n===0){const y=s.getAppendedFrag(0,B.MAIN);y&&c<y.end&&(g=!0)}if(!g&&e){var l;if(!((l=this.hls.loadLevelObj)!=null&&l.details)||fn(this.hls.inFlightFragments,c))return 0;let p=!1,E=e.end;for(;E<c;){const T=ns(E,s);if(T)E+=T.duration;else{p=!0;break}}if(p)return 0}}const f=Math.max(c+Yd,n+Hd);if(this.warn(`skipping hole, adjusting currentTime from ${n} to ${f}`),this.moved=!0,i.currentTime=f,!(e!=null&&e.gap)){const g=new Error(`fragment loaded with buffer holes, seeking from ${n} to ${f}`),y={type:V.MEDIA_ERROR,details:R.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:g,reason:g.message,buffer:o.len,bufferInfo:o};e&&("fragment"in e?y.part=e:y.frag=e),this.hls.trigger(m.ERROR,y)}return f}}return 0}_tryNudgeBuffer(e){const{hls:t,media:s,nudgeRetry:i}=this,r=t==null?void 0:t.config;if(!s||!r)return 0;const n=s.currentTime;if(this.nudgeRetry++,i<r.nudgeMaxRetry){const o=n+(i+1)*r.nudgeOffset,c=new Error(`Nudging 'currentTime' from ${n} to ${o}`);this.warn(c.message),s.currentTime=o,t.trigger(m.ERROR,{type:V.MEDIA_ERROR,details:R.BUFFER_NUDGE_ON_STALL,error:c,fatal:!1,buffer:e.len,bufferInfo:e})}else{const o=new Error(`Playhead still not moving while enough data buffered @${n} after ${r.nudgeMaxRetry} nudges`);this.error(o.message),t.trigger(m.ERROR,{type:V.MEDIA_ERROR,details:R.BUFFER_STALLED_ERROR,error:o,fatal:!0,buffer:e.len,bufferInfo:e})}}}function fn(a,e){const t=gn(a.main);if(t&&t.start<=e)return t;const s=gn(a.audio);return s&&s.start<=e?s:null}function gn(a){if(!a)return null;switch(a.state){case C.IDLE:case C.STOPPED:case C.ENDED:case C.ERROR:return null}return a.frag}function ns(a,e){return e.getAppendedFrag(a,B.MAIN)||e.getPartialFragment(a)}const jd=.25;function xi(){if(!(typeof self>"u"))return self.VTTCue||self.TextTrackCue}function ti(a,e,t,s,i){let r=new a(e,t,"");try{r.value=s,i&&(r.type=i)}catch{r=new a(e,t,ne(i?te({type:i},s):s))}return r}const as=(()=>{const a=xi();try{a&&new a(0,Number.POSITIVE_INFINITY,"")}catch{return Number.MAX_VALUE}return Number.POSITIVE_INFINITY})();class Xd{constructor(e){this.hls=void 0,this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.removeCues=!0,this.assetCue=void 0,this.onEventCueEnter=()=>{this.hls&&this.hls.trigger(m.EVENT_CUE_ENTER,{})},this.hls=e,this._registerListeners()}destroy(){this._unregisterListeners(),this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.hls=this.onEventCueEnter=null}_registerListeners(){const{hls:e}=this;e&&(e.on(m.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(m.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(m.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(m.MANIFEST_LOADING,this.onManifestLoading,this),e.on(m.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.on(m.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(m.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(m.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))}_unregisterListeners(){const{hls:e}=this;e&&(e.off(m.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(m.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(m.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(m.MANIFEST_LOADING,this.onManifestLoading,this),e.off(m.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.off(m.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(m.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(m.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))}onMediaAttaching(e,t){var s;this.media=t.media,((s=t.overrides)==null?void 0:s.cueRemoval)===!1&&(this.removeCues=!1)}onMediaAttached(){var e;const t=(e=this.hls)==null?void 0:e.latestLevelDetails;t&&this.updateDateRangeCues(t)}onMediaDetaching(e,t){this.media=null,!t.transferMedia&&(this.id3Track&&(this.removeCues&&At(this.id3Track,this.onEventCueEnter),this.id3Track=null),this.dateRangeCuesAppended={})}onManifestLoading(){this.dateRangeCuesAppended={}}createTrack(e){const t=this.getID3Track(e.textTracks);return t.mode="hidden",t}getID3Track(e){if(this.media){for(let t=0;t<e.length;t++){const s=e[t];if(s.kind==="metadata"&&s.label==="id3")return Ma(s,this.media),s}return this.media.addTextTrack("metadata","id3")}}onFragParsingMetadata(e,t){if(!this.media||!this.hls)return;const{enableEmsgMetadataCues:s,enableID3MetadataCues:i}=this.hls.config;if(!s&&!i)return;const{samples:r}=t;this.id3Track||(this.id3Track=this.createTrack(this.media));const n=xi();if(n)for(let o=0;o<r.length;o++){const c=r[o].type;if(c===Re.emsg&&!s||!i)continue;const l=ha(r[o].data),h=r[o].pts;let d=h+r[o].duration;d>as&&(d=as),d-h<=0&&(d=h+jd);for(let f=0;f<l.length;f++){const g=l[f];if(!da(g)){this.updateId3CueEnds(h,c);const y=ti(n,h,d,g,c);y&&this.id3Track.addCue(y)}}}}updateId3CueEnds(e,t){var s;const i=(s=this.id3Track)==null?void 0:s.cues;if(i)for(let r=i.length;r--;){const n=i[r];n.type===t&&n.startTime<e&&n.endTime===as&&(n.endTime=e)}}onBufferFlushing(e,{startOffset:t,endOffset:s,type:i}){const{id3Track:r,hls:n}=this;if(!n)return;const{config:{enableEmsgMetadataCues:o,enableID3MetadataCues:c}}=n;if(r&&(o||c)){let l;i==="audio"?l=h=>h.type===Re.audioId3&&c:i==="video"?l=h=>h.type===Re.emsg&&o:l=h=>h.type===Re.audioId3&&c||h.type===Re.emsg&&o,Ti(r,t,s,l)}}onLevelUpdated(e,{details:t}){this.updateDateRangeCues(t,!0)}onLevelPtsUpdated(e,t){Math.abs(t.drift)>.01&&this.updateDateRangeCues(t.details)}updateDateRangeCues(e,t){if(!this.hls||!this.media)return;const{assetPlayerId:s,timelineOffset:i,enableDateRangeMetadataCues:r,interstitialsController:n}=this.hls.config;if(!r)return;const o=xi();if(s&&i&&!n){const{fragmentStart:y,fragmentEnd:p}=e;let E=this.assetCue;E?(E.startTime=y,E.endTime=p):o&&(E=this.assetCue=ti(o,y,p,{assetPlayerId:this.hls.config.assetPlayerId},"hlsjs.interstitial.asset"),E&&(E.id=s,this.id3Track||(this.id3Track=this.createTrack(this.media)),this.id3Track.addCue(E),E.addEventListener("enter",this.onEventCueEnter)))}if(!e.hasProgramDateTime)return;const{id3Track:c}=this,{dateRanges:l}=e,h=Object.keys(l);let d=this.dateRangeCuesAppended;if(c&&t){var u;if((u=c.cues)!=null&&u.length){const y=Object.keys(d).filter(p=>!h.includes(p));for(let p=y.length;p--;){var f;const E=y[p],T=(f=d[E])==null?void 0:f.cues;delete d[E],T&&Object.keys(T).forEach(S=>{const v=T[S];if(v){v.removeEventListener("enter",this.onEventCueEnter);try{c.removeCue(v)}catch{}}})}}else d=this.dateRangeCuesAppended={}}const g=e.fragments[e.fragments.length-1];if(!(h.length===0||!M(g==null?void 0:g.programDateTime))){this.id3Track||(this.id3Track=this.createTrack(this.media));for(let y=0;y<h.length;y++){const p=h[y],E=l[p],T=E.startTime,S=d[p],v=(S==null?void 0:S.cues)||{};let A=(S==null?void 0:S.durationKnown)||!1,D=as;const{duration:x,endDate:b}=E;if(b&&x!==null)D=T+x,A=!0;else if(E.endOnNext&&!A){const I=h.reduce((P,F)=>{if(F!==E.id){const U=l[F];if(U.class===E.class&&U.startDate>E.startDate&&(!P||E.startDate<P.startDate))return U}return P},null);I&&(D=I.startTime,A=!0)}const _=Object.keys(E.attr);for(let I=0;I<_.length;I++){const P=_[I];if(!pl(P))continue;const F=v[P];if(F)A&&!(S!=null&&S.durationKnown)?F.endTime=D:Math.abs(F.startTime-T)>.01&&(F.startTime=T,F.endTime=D);else if(o){let U=E.attr[P];yl(P)&&(U=vn(U));const $=ti(o,T,D,{key:P,data:U},Re.dateRange);$&&($.id=p,this.id3Track.addCue($),v[P]=$,n&&(P==="X-ASSET-LIST"||P==="X-ASSET-URL")&&$.addEventListener("enter",this.onEventCueEnter))}}d[p]={cues:v,dateRange:E,durationKnown:A}}}}}class zd{constructor(e){this.hls=void 0,this.config=void 0,this.media=null,this.currentTime=0,this.stallCount=0,this._latency=null,this._targetLatencyUpdated=!1,this.onTimeupdate=()=>{const{media:t}=this,s=this.levelDetails;if(!t||!s)return;this.currentTime=t.currentTime;const i=this.computeLatency();if(i===null)return;this._latency=i;const{lowLatencyMode:r,maxLiveSyncPlaybackRate:n}=this.config;if(!r||n===1||!s.live)return;const o=this.targetLatency;if(o===null)return;const c=i-o,l=Math.min(this.maxLatency,o+s.targetduration);if(c<l&&c>.05&&this.forwardBufferLength>1){const d=Math.min(2,Math.max(1,n)),u=Math.round(2/(1+Math.exp(-.75*c-this.edgeStalled))*20)/20,f=Math.min(d,Math.max(1,u));this.changeMediaPlaybackRate(t,f)}else t.playbackRate!==1&&t.playbackRate!==0&&this.changeMediaPlaybackRate(t,1)},this.hls=e,this.config=e.config,this.registerListeners()}get levelDetails(){var e;return((e=this.hls)==null?void 0:e.latestLevelDetails)||null}get latency(){return this._latency||0}get maxLatency(){const{config:e}=this;if(e.liveMaxLatencyDuration!==void 0)return e.liveMaxLatencyDuration;const t=this.levelDetails;return t?e.liveMaxLatencyDurationCount*t.targetduration:0}get targetLatency(){const e=this.levelDetails;if(e===null||this.hls===null)return null;const{holdBack:t,partHoldBack:s,targetduration:i}=e,{liveSyncDuration:r,liveSyncDurationCount:n,lowLatencyMode:o}=this.config,c=this.hls.userConfig;let l=o&&s||t;(this._targetLatencyUpdated||c.liveSyncDuration||c.liveSyncDurationCount||l===0)&&(l=r!==void 0?r:n*i);const h=i;return l+Math.min(this.stallCount*this.config.liveSyncOnStallIncrease,h)}set targetLatency(e){this.stallCount=0,this.config.liveSyncDuration=e,this._targetLatencyUpdated=!0}get liveSyncPosition(){const e=this.estimateLiveEdge(),t=this.targetLatency;if(e===null||t===null)return null;const s=this.levelDetails;if(s===null)return null;const i=s.edge,r=e-t-this.edgeStalled,n=i-s.totalduration,o=i-(this.config.lowLatencyMode&&s.partTarget||s.targetduration);return Math.min(Math.max(n,r),o)}get drift(){const e=this.levelDetails;return e===null?1:e.drift}get edgeStalled(){const e=this.levelDetails;if(e===null)return 0;const t=(this.config.lowLatencyMode&&e.partTarget||e.targetduration)*3;return Math.max(e.age-t,0)}get forwardBufferLength(){const{media:e}=this,t=this.levelDetails;if(!e||!t)return 0;const s=e.buffered.length;return(s?e.buffered.end(s-1):t.edge)-this.currentTime}destroy(){this.unregisterListeners(),this.onMediaDetaching(),this.hls=null}registerListeners(){const{hls:e}=this;e&&(e.on(m.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(m.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(m.MANIFEST_LOADING,this.onManifestLoading,this),e.on(m.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(m.ERROR,this.onError,this))}unregisterListeners(){const{hls:e}=this;e&&(e.off(m.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(m.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(m.MANIFEST_LOADING,this.onManifestLoading,this),e.off(m.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(m.ERROR,this.onError,this))}onMediaAttached(e,t){this.media=t.media,this.media.addEventListener("timeupdate",this.onTimeupdate)}onMediaDetaching(){this.media&&(this.media.removeEventListener("timeupdate",this.onTimeupdate),this.media=null)}onManifestLoading(){this._latency=null,this.stallCount=0}onLevelUpdated(e,{details:t}){t.advanced&&this.onTimeupdate(),!t.live&&this.media&&this.media.removeEventListener("timeupdate",this.onTimeupdate)}onError(e,t){var s;t.details===R.BUFFER_STALLED_ERROR&&(this.stallCount++,this.hls&&(s=this.levelDetails)!=null&&s.live&&this.hls.logger.warn("[latency-controller]: Stall detected, adjusting target latency"))}changeMediaPlaybackRate(e,t){var s,i;e.playbackRate!==t&&((s=this.hls)==null||s.logger.debug(`[latency-controller]: latency=${this.latency.toFixed(3)}, targetLatency=${(i=this.targetLatency)==null?void 0:i.toFixed(3)}, forwardBufferLength=${this.forwardBufferLength.toFixed(3)}: adjusting playback rate from ${e.playbackRate} to ${t}`),e.playbackRate=t)}estimateLiveEdge(){const e=this.levelDetails;return e===null?null:e.edge+e.age}computeLatency(){const e=this.estimateLiveEdge();return e===null?null:e-this.currentTime}}class Qd extends Ki{constructor(e,t){super(e,"level-controller"),this._levels=[],this._firstLevel=-1,this._maxAutoLevel=-1,this._startLevel=void 0,this.currentLevel=null,this.currentLevelIndex=-1,this.manualLevelIndex=-1,this.steering=void 0,this.onParsedComplete=void 0,this.steering=t,this._registerListeners()}_registerListeners(){const{hls:e}=this;e.on(m.MANIFEST_LOADING,this.onManifestLoading,this),e.on(m.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(m.LEVEL_LOADED,this.onLevelLoaded,this),e.on(m.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(m.FRAG_BUFFERED,this.onFragBuffered,this),e.on(m.ERROR,this.onError,this)}_unregisterListeners(){const{hls:e}=this;e.off(m.MANIFEST_LOADING,this.onManifestLoading,this),e.off(m.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(m.LEVEL_LOADED,this.onLevelLoaded,this),e.off(m.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(m.FRAG_BUFFERED,this.onFragBuffered,this),e.off(m.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(e,t){this.resetLevels()}onManifestLoaded(e,t){const s=this.hls.config.preferManagedMediaSource,i=[],r={},n={};let o=!1,c=!1,l=!1;t.levels.forEach(h=>{const d=h.attrs;let{audioCodec:u,videoCodec:f}=h;u&&(h.audioCodec=u=Ts(u,s)||void 0),f&&(f=h.videoCodec=wo(f));const{width:g,height:y,unknownCodecs:p}=h,E=(p==null?void 0:p.length)||0;if(o||(o=!!(g&&y)),c||(c=!!f),l||(l=!!u),E||u&&!this.isAudioSupported(u)||f&&!this.isVideoSupported(f)){this.log(`Some or all CODECS not supported "${d.CODECS}"`);return}const{CODECS:T,"FRAME-RATE":S,"HDCP-LEVEL":v,"PATHWAY-ID":A,RESOLUTION:D,"VIDEO-RANGE":x}=d,_=`${`${A||"."}-`}${h.bitrate}-${D}-${S}-${T}-${x}-${v}`;if(r[_])if(r[_].uri!==h.url&&!h.attrs["PATHWAY-ID"]){const I=n[_]+=1;h.attrs["PATHWAY-ID"]=new Array(I+1).join(".");const P=this.createLevel(h);r[_]=P,i.push(P)}else r[_].addGroupId("audio",d.AUDIO),r[_].addGroupId("text",d.SUBTITLES);else{const I=this.createLevel(h);r[_]=I,n[_]=1,i.push(I)}}),this.filterAndSortMediaOptions(i,t,o,c,l)}createLevel(e){const t=new $t(e),s=e.supplemental;if(s!=null&&s.videoCodec&&!this.isVideoSupported(s.videoCodec)){const i=new Error(`SUPPLEMENTAL-CODECS not supported "${s.videoCodec}"`);this.log(i.message),t.supportedResult=wn(i,[])}return t}isAudioSupported(e){return Bt(e,"audio",this.hls.config.preferManagedMediaSource)}isVideoSupported(e){return Bt(e,"video",this.hls.config.preferManagedMediaSource)}filterAndSortMediaOptions(e,t,s,i,r){var n;let o=[],c=[],l=e;const h=((n=t.stats)==null?void 0:n.parsing)||{};if((s||i)&&r&&(l=l.filter(({videoCodec:T,videoRange:S,width:v,height:A})=>(!!T||!!(v&&A))&&Vo(S))),l.length===0){Promise.resolve().then(()=>{if(this.hls){let T="no level with compatible codecs found in manifest",S=T;t.levels.length&&(S=`one or more CODECS in variant not supported: ${ne(t.levels.map(A=>A.attrs.CODECS).filter((A,D,x)=>x.indexOf(A)===D))}`,this.warn(S),T+=` (${S})`);const v=new Error(T);this.hls.trigger(m.ERROR,{type:V.MEDIA_ERROR,details:R.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:t.url,error:v,reason:S})}}),h.end=performance.now();return}t.audioTracks&&(o=t.audioTracks.filter(T=>!T.audioCodec||this.isAudioSupported(T.audioCodec)),mn(o)),t.subtitles&&(c=t.subtitles,mn(c));const d=l.slice(0);l.sort((T,S)=>{if(T.attrs["HDCP-LEVEL"]!==S.attrs["HDCP-LEVEL"])return(T.attrs["HDCP-LEVEL"]||"")>(S.attrs["HDCP-LEVEL"]||"")?1:-1;if(s&&T.height!==S.height)return T.height-S.height;if(T.frameRate!==S.frameRate)return T.frameRate-S.frameRate;if(T.videoRange!==S.videoRange)return Ss.indexOf(T.videoRange)-Ss.indexOf(S.videoRange);if(T.videoCodec!==S.videoCodec){const v=nr(T.videoCodec),A=nr(S.videoCodec);if(v!==A)return A-v}if(T.uri===S.uri&&T.codecSet!==S.codecSet){const v=Es(T.codecSet),A=Es(S.codecSet);if(v!==A)return A-v}return T.averageBitrate!==S.averageBitrate?T.averageBitrate-S.averageBitrate:0});let u=d[0];if(this.steering&&(l=this.steering.filterParsedLevels(l),l.length!==d.length)){for(let T=0;T<d.length;T++)if(d[T].pathwayId===l[0].pathwayId){u=d[T];break}}this._levels=l;for(let T=0;T<l.length;T++)if(l[T]===u){var f;this._firstLevel=T;const S=u.bitrate,v=this.hls.bandwidthEstimate;if(this.log(`manifest loaded, ${l.length} level(s) found, first bitrate: ${S}`),((f=this.hls.userConfig)==null?void 0:f.abrEwmaDefaultEstimate)===void 0){const A=Math.min(S,this.hls.config.abrEwmaDefaultEstimateMax);A>v&&v===this.hls.abrEwmaDefaultEstimate&&(this.hls.bandwidthEstimate=A)}break}const g=r&&!i,y=this.hls.config,p=!!(y.audioStreamController&&y.audioTrackController),E={levels:l,audioTracks:o,subtitleTracks:c,sessionData:t.sessionData,sessionKeys:t.sessionKeys,firstLevel:this._firstLevel,stats:t.stats,audio:r,video:i,altAudio:p&&!g&&o.some(T=>!!T.url)};h.end=performance.now(),this.hls.trigger(m.MANIFEST_PARSED,E)}get levels(){return this._levels.length===0?null:this._levels}get loadLevelObj(){return this.currentLevel}get level(){return this.currentLevelIndex}set level(e){const t=this._levels;if(t.length===0)return;if(e<0||e>=t.length){const h=new Error("invalid level idx"),d=e<0;if(this.hls.trigger(m.ERROR,{type:V.OTHER_ERROR,details:R.LEVEL_SWITCH_ERROR,level:e,fatal:d,error:h,reason:h.message}),d)return;e=Math.min(e,t.length-1)}const s=this.currentLevelIndex,i=this.currentLevel,r=i?i.attrs["PATHWAY-ID"]:void 0,n=t[e],o=n.attrs["PATHWAY-ID"];if(this.currentLevelIndex=e,this.currentLevel=n,s===e&&i&&r===o)return;this.log(`Switching to level ${e} (${n.height?n.height+"p ":""}${n.videoRange?n.videoRange+" ":""}${n.codecSet?n.codecSet+" ":""}@${n.bitrate})${o?" with Pathway "+o:""} from level ${s}${r?" with Pathway "+r:""}`);const c={level:e,attrs:n.attrs,details:n.details,bitrate:n.bitrate,averageBitrate:n.averageBitrate,maxBitrate:n.maxBitrate,realBitrate:n.realBitrate,width:n.width,height:n.height,codecSet:n.codecSet,audioCodec:n.audioCodec,videoCodec:n.videoCodec,audioGroups:n.audioGroups,subtitleGroups:n.subtitleGroups,loaded:n.loaded,loadError:n.loadError,fragmentError:n.fragmentError,name:n.name,id:n.id,uri:n.uri,url:n.url,urlId:0,audioGroupIds:n.audioGroupIds,textGroupIds:n.textGroupIds};this.hls.trigger(m.LEVEL_SWITCHING,c);const l=n.details;if(!l||l.live){const h=this.switchParams(n.uri,i==null?void 0:i.details,l);this.loadPlaylist(h)}}get manualLevel(){return this.manualLevelIndex}set manualLevel(e){this.manualLevelIndex=e,this._startLevel===void 0&&(this._startLevel=e),e!==-1&&(this.level=e)}get firstLevel(){return this._firstLevel}set firstLevel(e){this._firstLevel=e}get startLevel(){if(this._startLevel===void 0){const e=this.hls.config.startLevel;return e!==void 0?e:this.hls.firstAutoLevel}return this._startLevel}set startLevel(e){this._startLevel=e}get pathways(){return this.steering?this.steering.pathways():[]}get pathwayPriority(){return this.steering?this.steering.pathwayPriority:null}set pathwayPriority(e){if(this.steering){const t=this.steering.pathways(),s=e.filter(i=>t.indexOf(i)!==-1);if(e.length<1){this.warn(`pathwayPriority ${e} should contain at least one pathway from list: ${t}`);return}this.steering.pathwayPriority=s}}onError(e,t){t.fatal||!t.context||t.context.type===Q.LEVEL&&t.context.level===this.level&&this.checkRetry(t)}onFragBuffered(e,{frag:t}){if(t!==void 0&&t.type===B.MAIN){const s=t.elementaryStreams;if(!Object.keys(s).some(r=>!!s[r]))return;const i=this._levels[t.level];i!=null&&i.loadError&&(this.log(`Resetting level error count of ${i.loadError} on frag buffered`),i.loadError=0)}}onLevelLoaded(e,t){var s;const{level:i,details:r}=t,n=t.levelInfo;if(!n){var o;this.warn(`Invalid level index ${i}`),(o=t.deliveryDirectives)!=null&&o.skip&&(r.deltaUpdateFailed=!0);return}if(n===this.currentLevel||t.withoutMultiVariant){n.fragmentError===0&&(n.loadError=0);let c=n.details;c===t.details&&c.advanced&&(c=void 0),this.playlistLoaded(i,t,c)}else(s=t.deliveryDirectives)!=null&&s.skip&&(r.deltaUpdateFailed=!0)}loadPlaylist(e){super.loadPlaylist(),this.shouldLoadPlaylist(this.currentLevel)&&this.scheduleLoading(this.currentLevel,e)}loadingPlaylist(e,t){super.loadingPlaylist(e,t);const s=this.getUrlWithDirectives(e.uri,t),i=this.currentLevelIndex,r=e.attrs["PATHWAY-ID"],n=e.details,o=n==null?void 0:n.age;this.log(`Loading level index ${i}${(t==null?void 0:t.msn)!==void 0?" at sn "+t.msn+" part "+t.part:""}${r?" Pathway "+r:""}${o&&n.live?" age "+o.toFixed(1)+(n.type&&" "+n.type||""):""} ${s}`),this.hls.trigger(m.LEVEL_LOADING,{url:s,level:i,levelInfo:e,pathwayId:e.attrs["PATHWAY-ID"],id:0,deliveryDirectives:t||null})}get nextLoadLevel(){return this.manualLevelIndex!==-1?this.manualLevelIndex:this.hls.nextAutoLevel}set nextLoadLevel(e){this.level=e,this.manualLevelIndex===-1&&(this.hls.nextAutoLevel=e)}removeLevel(e){var t;if(this._levels.length===1)return;const s=this._levels.filter((r,n)=>n!==e?!0:(this.steering&&this.steering.removeLevel(r),r===this.currentLevel&&(this.currentLevel=null,this.currentLevelIndex=-1,r.details&&r.details.fragments.forEach(o=>o.level=-1)),!1));ea(s),this._levels=s,this.currentLevelIndex>-1&&(t=this.currentLevel)!=null&&t.details&&(this.currentLevelIndex=this.currentLevel.details.fragments[0].level),this.manualLevelIndex>-1&&(this.manualLevelIndex=this.currentLevelIndex);const i=s.length-1;this._firstLevel=Math.min(this._firstLevel,i),this._startLevel&&(this._startLevel=Math.min(this._startLevel,i)),this.hls.trigger(m.LEVELS_UPDATED,{levels:s})}onLevelsUpdated(e,{levels:t}){this._levels=t}checkMaxAutoUpdated(){const{autoLevelCapping:e,maxAutoLevel:t,maxHdcpLevel:s}=this.hls;this._maxAutoLevel!==t&&(this._maxAutoLevel=t,this.hls.trigger(m.MAX_AUTO_LEVEL_UPDATED,{autoLevelCapping:e,levels:this.levels,maxAutoLevel:t,minAutoLevel:this.hls.minAutoLevel,maxHdcpLevel:s}))}}function mn(a){const e={};a.forEach(t=>{const s=t.groupId||"";t.id=e[s]=e[s]||0,e[s]++})}function Xa(){return self.SourceBuffer||self.WebKitSourceBuffer}function za(){if(!rt())return!1;const e=Xa();return!e||e.prototype&&typeof e.prototype.appendBuffer=="function"&&typeof e.prototype.remove=="function"}function Zd(){if(!za())return!1;const a=rt();return typeof(a==null?void 0:a.isTypeSupported)=="function"&&(["avc1.42E01E,mp4a.40.2","av01.0.01M.08","vp09.00.50.08"].some(e=>a.isTypeSupported(Ut(e,"video")))||["mp4a.40.2","fLaC"].some(e=>a.isTypeSupported(Ut(e,"audio"))))}function Jd(){var a;const e=Xa();return typeof(e==null||(a=e.prototype)==null?void 0:a.changeType)=="function"}const eu=100;class tu extends Oi{constructor(e,t,s){super(e,t,s,"stream-controller",B.MAIN),this.audioCodecSwap=!1,this.level=-1,this._forceStartLoad=!1,this._hasEnoughToStart=!1,this.altAudio=0,this.audioOnly=!1,this.fragPlaying=null,this.fragLastKbps=0,this.couldBacktrack=!1,this.backtrackFragment=null,this.audioCodecSwitch=!1,this.videoBuffer=null,this.onMediaPlaying=()=>{this.tick()},this.onMediaSeeked=()=>{const i=this.media,r=i?i.currentTime:null;if(r===null||!M(r)||(this.log(`Media seeked to ${r.toFixed(3)}`),!this.getBufferedFrag(r)))return;const n=this.getFwdBufferInfoAtPos(i,r,B.MAIN,0);if(n===null||n.len===0){this.warn(`Main forward buffer length at ${r} on "seeked" event ${n?n.len:"empty"})`);return}this.tick()},this.registerListeners()}registerListeners(){super.registerListeners();const{hls:e}=this;e.on(m.MANIFEST_PARSED,this.onManifestParsed,this),e.on(m.LEVEL_LOADING,this.onLevelLoading,this),e.on(m.LEVEL_LOADED,this.onLevelLoaded,this),e.on(m.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.on(m.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(m.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.on(m.BUFFER_CREATED,this.onBufferCreated,this),e.on(m.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(m.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(m.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){super.unregisterListeners();const{hls:e}=this;e.off(m.MANIFEST_PARSED,this.onManifestParsed,this),e.off(m.LEVEL_LOADED,this.onLevelLoaded,this),e.off(m.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.off(m.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(m.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.off(m.BUFFER_CREATED,this.onBufferCreated,this),e.off(m.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(m.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(m.FRAG_BUFFERED,this.onFragBuffered,this)}onHandlerDestroying(){this.onMediaPlaying=this.onMediaSeeked=null,this.unregisterListeners(),super.onHandlerDestroying()}startLoad(e,t){if(this.levels){const{lastCurrentTime:s,hls:i}=this;if(this.stopLoad(),this.setInterval(eu),this.level=-1,!this.startFragRequested){let r=i.startLevel;r===-1&&(i.config.testBandwidth&&this.levels.length>1?(r=0,this.bitrateTest=!0):r=i.firstAutoLevel),i.nextLoadLevel=r,this.level=i.loadLevel,this._hasEnoughToStart=!!t}s>0&&e===-1&&!t&&(this.log(`Override startPosition with lastCurrentTime @${s.toFixed(3)}`),e=s),this.state=C.IDLE,this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,this.tick()}else this._forceStartLoad=!0,this.state=C.STOPPED}stopLoad(){this._forceStartLoad=!1,super.stopLoad()}doTick(){switch(this.state){case C.WAITING_LEVEL:{const{levels:e,level:t}=this,s=e==null?void 0:e[t],i=s==null?void 0:s.details;if(i&&(!i.live||this.levelLastLoaded===s&&!this.waitForLive(s))){if(this.waitForCdnTuneIn(i))break;this.state=C.IDLE;break}else if(this.hls.nextLoadLevel!==this.level){this.state=C.IDLE;break}break}case C.FRAG_LOADING_WAITING_RETRY:this.checkRetryDate();break}this.state===C.IDLE&&this.doTickIdle(),this.onTickEnd()}onTickEnd(){var e;super.onTickEnd(),(e=this.media)!=null&&e.readyState&&this.media.seeking===!1&&(this.lastCurrentTime=this.media.currentTime),this.checkFragmentChanged()}doTickIdle(){const{hls:e,levelLastLoaded:t,levels:s,media:i}=this;if(t===null||!i&&!this.primaryPrefetch&&(this.startFragRequested||!e.config.startFragPrefetch)||this.altAudio&&this.audioOnly)return;const r=this.buffering?e.nextLoadLevel:e.loadLevel;if(!(s!=null&&s[r]))return;const n=s[r],o=this.getMainFwdBufferInfo();if(o===null)return;const c=this.getLevelDetails();if(c&&this._streamEnded(o,c)){const y={};this.altAudio===2&&(y.type="video"),this.hls.trigger(m.BUFFER_EOS,y),this.state=C.ENDED;return}if(!this.buffering)return;e.loadLevel!==r&&e.manualLevel===-1&&this.log(`Adapting to level ${r} from level ${this.level}`),this.level=e.nextLoadLevel=r;const l=n.details;if(!l||this.state===C.WAITING_LEVEL||this.waitForLive(n)){this.level=r,this.state=C.WAITING_LEVEL,this.startFragRequested=!1;return}const h=o.len,d=this.getMaxBufferLength(n.maxBitrate);if(h>=d)return;this.backtrackFragment&&this.backtrackFragment.start>o.end&&(this.backtrackFragment=null);const u=this.backtrackFragment?this.backtrackFragment.start:o.end;let f=this.getNextFragment(u,l);if(this.couldBacktrack&&!this.fragPrevious&&f&&ce(f)&&this.fragmentTracker.getState(f)!==de.OK){var g;const p=((g=this.backtrackFragment)!=null?g:f).sn-l.startSN,E=l.fragments[p-1];E&&f.cc===E.cc&&(f=E,this.fragmentTracker.removeFragment(E))}else this.backtrackFragment&&o.len&&(this.backtrackFragment=null);if(f&&this.isLoopLoading(f,u)){if(!f.gap){const p=this.audioOnly&&!this.altAudio?re.AUDIO:re.VIDEO,E=(p===re.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;E&&this.afterBufferFlushed(E,p,B.MAIN)}f=this.getNextFragmentLoopLoading(f,l,o,B.MAIN,d)}f&&(f.initSegment&&!f.initSegment.data&&!this.bitrateTest&&(f=f.initSegment),this.loadFragment(f,n,u))}loadFragment(e,t,s){const i=this.fragmentTracker.getState(e);i===de.NOT_LOADED||i===de.PARTIAL?ce(e)?this.bitrateTest?(this.log(`Fragment ${e.sn} of level ${e.level} is being downloaded to test bitrate and will not be buffered`),this._loadBitrateTestFrag(e,t)):super.loadFragment(e,t,s):this._loadInitSegment(e,t):this.clearTrackerIfNeeded(e)}getBufferedFrag(e){return this.fragmentTracker.getBufferedFrag(e,B.MAIN)}followingBufferedFrag(e){return e?this.getBufferedFrag(e.end+.5):null}immediateLevelSwitch(){this.abortCurrentFrag(),this.flushMainBuffer(0,Number.POSITIVE_INFINITY)}nextLevelSwitch(){const{levels:e,media:t}=this;if(t!=null&&t.readyState){let s;const i=this.getAppendedFrag(t.currentTime);i&&i.start>1&&this.flushMainBuffer(0,i.start-1);const r=this.getLevelDetails();if(r!=null&&r.live){const o=this.getMainFwdBufferInfo();if(!o||o.len<r.targetduration*2)return}if(!t.paused&&e){const o=this.hls.nextLoadLevel,c=e[o],l=this.fragLastKbps;l&&this.fragCurrent?s=this.fragCurrent.duration*c.maxBitrate/(1e3*l)+1:s=0}else s=0;const n=this.getBufferedFrag(t.currentTime+s);if(n){const o=this.followingBufferedFrag(n);if(o){this.abortCurrentFrag();const c=o.maxStartPTS?o.maxStartPTS:o.start,l=o.duration,h=Math.max(n.end,c+Math.min(Math.max(l-this.config.maxFragLookUpTolerance,l*(this.couldBacktrack?.5:.125)),l*(this.couldBacktrack?.75:.25)));this.flushMainBuffer(h,Number.POSITIVE_INFINITY)}}}}abortCurrentFrag(){const e=this.fragCurrent;switch(this.fragCurrent=null,this.backtrackFragment=null,e&&(e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.state){case C.KEY_LOADING:case C.FRAG_LOADING:case C.FRAG_LOADING_WAITING_RETRY:case C.PARSING:case C.PARSED:this.state=C.IDLE;break}this.nextLoadPosition=this.getLoadPosition()}flushMainBuffer(e,t){super.flushMainBuffer(e,t,this.altAudio===2?"video":null)}onMediaAttached(e,t){super.onMediaAttached(e,t);const s=t.media;Te(s,"playing",this.onMediaPlaying),Te(s,"seeked",this.onMediaSeeked)}onMediaDetaching(e,t){const{media:s}=this;s&&(ve(s,"playing",this.onMediaPlaying),ve(s,"seeked",this.onMediaSeeked)),this.videoBuffer=null,this.fragPlaying=null,super.onMediaDetaching(e,t),!t.transferMedia&&(this._hasEnoughToStart=!1)}onManifestLoading(){super.onManifestLoading(),this.log("Trigger BUFFER_RESET"),this.hls.trigger(m.BUFFER_RESET,void 0),this.couldBacktrack=!1,this.fragLastKbps=0,this.fragPlaying=this.backtrackFragment=null,this.altAudio=0,this.audioOnly=!1}onManifestParsed(e,t){let s=!1,i=!1;for(let r=0;r<t.levels.length;r++){const n=t.levels[r].audioCodec;n&&(s=s||n.indexOf("mp4a.40.2")!==-1,i=i||n.indexOf("mp4a.40.5")!==-1)}this.audioCodecSwitch=s&&i&&!Jd(),this.audioCodecSwitch&&this.log("Both AAC/HE-AAC audio found in levels; declaring level codec as HE-AAC"),this.levels=t.levels,this.startFragRequested=!1}onLevelLoading(e,t){const{levels:s}=this;if(!s||this.state!==C.IDLE)return;const i=t.levelInfo;(!i.details||i.details.live&&(this.levelLastLoaded!==i||i.details.expired)||this.waitForCdnTuneIn(i.details))&&(this.state=C.WAITING_LEVEL)}onLevelLoaded(e,t){var s;const{levels:i,startFragRequested:r}=this,n=t.level,o=t.details,c=o.totalduration;if(!i){this.warn(`Levels were reset while loading level ${n}`);return}this.log(`Level ${n} loaded [${o.startSN},${o.endSN}]${o.lastPartSn?`[part-${o.lastPartSn}-${o.lastPartIndex}]`:""}, cc [${o.startCC}, ${o.endCC}] duration:${c}`);const l=t.levelInfo,h=this.fragCurrent;h&&(this.state===C.FRAG_LOADING||this.state===C.FRAG_LOADING_WAITING_RETRY)&&h.level!==t.level&&h.loader&&this.abortCurrentFrag();let d=0;if(o.live||(s=l.details)!=null&&s.live){var u;if(this.checkLiveUpdate(o),o.deltaUpdateFailed)return;d=this.alignPlaylists(o,l.details,(u=this.levelLastLoaded)==null?void 0:u.details)}if(l.details=o,this.levelLastLoaded=l,r||this.setStartPosition(o,d),this.hls.trigger(m.LEVEL_UPDATED,{details:o,level:n}),this.state===C.WAITING_LEVEL){if(this.waitForCdnTuneIn(o))return;this.state=C.IDLE}r&&o.live&&this.synchronizeToLiveEdge(o),this.tick()}synchronizeToLiveEdge(e){const{config:t,media:s}=this;if(!s)return;const i=this.hls.liveSyncPosition,r=this.getLoadPosition(),n=e.fragmentStart,o=e.edge,c=r>=n-t.maxFragLookUpTolerance&&r<=o;if(i!==null&&s.duration>i&&(r<i||!c)){const h=t.liveMaxLatencyDuration!==void 0?t.liveMaxLatencyDuration:t.liveMaxLatencyDurationCount*e.targetduration;if((!c&&s.readyState<4||r<o-h)&&(this._hasEnoughToStart||(this.nextLoadPosition=i),s.readyState))if(this.warn(`Playback: ${r.toFixed(3)} is located too far from the end of live sliding playlist: ${o}, reset currentTime to : ${i.toFixed(3)}`),this.config.liveSyncMode==="buffered"){var l;const d=q.bufferInfo(s,i,0);if(!((l=d.buffered)!=null&&l.length)){s.currentTime=i;return}if(d.start<=r){s.currentTime=i;return}const{nextStart:f}=q.bufferedInfo(d.buffered,r,0);f&&(s.currentTime=f)}else s.currentTime=i}}_handleFragmentLoadProgress(e){var t;const s=e.frag,{part:i,payload:r}=e,{levels:n}=this;if(!n){this.warn(`Levels were reset while fragment load was in progress. Fragment ${s.sn} of level ${s.level} will not be buffered`);return}const o=n[s.level];if(!o){this.warn(`Level ${s.level} not found on progress`);return}const c=o.details;if(!c){this.warn(`Dropping fragment ${s.sn} of level ${s.level} after level details were reset`),this.fragmentTracker.removeFragment(s);return}const l=o.videoCodec,h=c.PTSKnown||!c.live,d=(t=s.initSegment)==null?void 0:t.data,u=this._getAudioCodec(o),f=this.transmuxer=this.transmuxer||new xa(this.hls,B.MAIN,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)),g=i?i.index:-1,y=g!==-1,p=new Pi(s.level,s.sn,s.stats.chunkCount,r.byteLength,g,y),E=this.initPTS[s.cc];f.push(r,d,u,l,s,i,c.totalduration,h,p,E)}onAudioTrackSwitching(e,t){const s=this.hls,i=this.altAudio!==0;if(vs(t.url,s))this.altAudio=1;else{if(this.mediaBuffer!==this.media){this.log("Switching on main audio, use media.buffered to schedule main fragment loading"),this.mediaBuffer=this.media;const n=this.fragCurrent;n&&(this.log("Switching to main audio track, cancel main fragment load"),n.abortRequests(),this.fragmentTracker.removeFragment(n)),this.resetTransmuxer(),this.resetLoadingState()}else this.audioOnly&&this.resetTransmuxer();if(i){this.altAudio=0,this.fragmentTracker.removeAllFragments(),s.once(m.BUFFER_FLUSHED,()=>{this.hls&&this.hls.trigger(m.AUDIO_TRACK_SWITCHED,t)}),s.trigger(m.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:null});return}s.trigger(m.AUDIO_TRACK_SWITCHED,t)}}onAudioTrackSwitched(e,t){const s=vs(t.url,this.hls);if(s){const i=this.videoBuffer;i&&this.mediaBuffer!==i&&(this.log("Switching on alternate audio, use video.buffered to schedule main fragment loading"),this.mediaBuffer=i)}this.altAudio=s?2:0,this.tick()}onBufferCreated(e,t){const s=t.tracks;let i,r,n=!1;for(const o in s){const c=s[o];if(c.id==="main"){if(r=o,i=c,o==="video"){const l=s[o];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}onFragBuffered(e,t){const{frag:s,part:i}=t,r=s.type===B.MAIN;if(r){if(this.fragContextChanged(s)){this.warn(`Fragment ${s.sn}${i?" p: "+i.index:""} of level ${s.level} finished buffering, but was aborted. state: ${this.state}`),this.state===C.PARSED&&(this.state=C.IDLE);return}const o=i?i.stats:s.stats;this.fragLastKbps=Math.round(8*o.total/(o.buffering.end-o.loading.first)),ce(s)&&(this.fragPrevious=s),this.fragBufferedComplete(s,i)}const n=this.media;n&&(!this._hasEnoughToStart&&q.getBuffered(n).length&&(this._hasEnoughToStart=!0,this.seekToStartPos()),r&&this.tick())}get hasEnoughToStart(){return this._hasEnoughToStart}onError(e,t){var s;if(t.fatal){this.state=C.ERROR;return}switch(t.details){case R.FRAG_GAP:case R.FRAG_PARSING_ERROR:case R.FRAG_DECRYPT_ERROR:case R.FRAG_LOAD_ERROR:case R.FRAG_LOAD_TIMEOUT:case R.KEY_LOAD_ERROR:case R.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(B.MAIN,t);break;case R.LEVEL_LOAD_ERROR:case R.LEVEL_LOAD_TIMEOUT:case R.LEVEL_PARSING_ERROR:!t.levelRetry&&this.state===C.WAITING_LEVEL&&((s=t.context)==null?void 0:s.type)===Q.LEVEL&&(this.state=C.IDLE);break;case R.BUFFER_ADD_CODEC_ERROR:case R.BUFFER_APPEND_ERROR:if(t.parent!=="main")return;this.reduceLengthAndFlushBuffer(t)&&this.resetLoadingState();break;case R.BUFFER_FULL_ERROR:if(t.parent!=="main")return;this.reduceLengthAndFlushBuffer(t)&&(!this.config.interstitialsController&&this.config.assetPlayerId?this._hasEnoughToStart=!0:this.flushMainBuffer(0,Number.POSITIVE_INFINITY));break;case R.INTERNAL_EXCEPTION:this.recoverWorkerError(t);break}}onFragLoadEmergencyAborted(){this.state=C.IDLE,this._hasEnoughToStart||(this.startFragRequested=!1,this.nextLoadPosition=this.lastCurrentTime),this.tickImmediate()}onBufferFlushed(e,{type:t}){if(t!==re.AUDIO||!this.altAudio){const s=(t===re.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;s&&(this.afterBufferFlushed(s,t,B.MAIN),this.tick())}}onLevelsUpdated(e,t){this.level>-1&&this.fragCurrent&&(this.level=this.fragCurrent.level,this.level===-1&&this.resetWhenMissingContext(this.fragCurrent)),this.levels=t.levels}swapAudioCodec(){this.audioCodecSwap=!this.audioCodecSwap}seekToStartPos(){const{media:e}=this;if(!e)return;const t=e.currentTime;let s=this.startPosition;if(s>=0&&t<s){if(e.seeking){this.log(`could not seek to ${s}, already seeking at ${t}`);return}const i=this.timelineOffset;i&&s&&(s+=i);const r=this.getLevelDetails(),n=q.getBuffered(e),o=n.length?n.start(0):0,c=o-s,l=Math.max(this.config.maxBufferHole,this.config.maxFragLookUpTolerance);(this.config.startOnSegmentBoundary||c>0&&(c<l||this.loadingParts&&c<2*((r==null?void 0:r.partTarget)||0)))&&(this.log(`adjusting start position by ${c} to match buffer start`),s+=c,this.startPosition=s),t<s&&(this.log(`seek to target start position ${s} from current time ${t} buffer start ${o}`),e.currentTime=s)}}_getAudioCodec(e){let t=this.config.defaultAudioCodec||e.audioCodec;return this.audioCodecSwap&&t&&(this.log("Swapping audio codec"),t.indexOf("mp4a.40.5")!==-1?t="mp4a.40.2":t="mp4a.40.5"),t}_loadBitrateTestFrag(e,t){e.bitrateTest=!0,this._doFragLoad(e,t).then(s=>{const{hls:i}=this,r=s==null?void 0:s.frag;if(!r||this.fragContextChanged(r))return;t.fragmentError=0,this.state=C.IDLE,this.startFragRequested=!1,this.bitrateTest=!1;const n=r.stats;n.parsing.start=n.parsing.end=n.buffering.start=n.buffering.end=self.performance.now(),i.trigger(m.FRAG_LOADED,s),r.bitrateTest=!1}).catch(s=>{this.state===C.STOPPED||this.state===C.ERROR||(this.warn(s),this.resetFragmentLoading(e))})}_handleTransmuxComplete(e){const t=this.playlistType,{hls:s}=this,{remuxResult:i,chunkMeta:r}=e,n=this.getCurrentContext(r);if(!n){this.resetWhenMissingContext(r);return}const{frag:o,part:c,level:l}=n,{video:h,text:d,id3:u,initSegment:f}=i,{details:g}=l,y=this.altAudio?void 0:i.audio;if(this.fragContextChanged(o)){this.fragmentTracker.removeFragment(o);return}if(this.state=C.PARSING,f){const p=f.tracks;if(p){const v=o.initSegment||o;if(this.unhandledEncryptionError(f,o))return;this._bufferInitSegment(l,p,v,r),s.trigger(m.FRAG_PARSING_INIT_SEGMENT,{frag:v,id:t,tracks:p})}const E=f.initPTS,T=f.timescale,S=this.initPTS[o.cc];if(M(E)&&(!S||S.baseTime!==E||S.timescale!==T)){const v=f.trackId;this.initPTS[o.cc]={baseTime:E,timescale:T,trackId:v},s.trigger(m.INIT_PTS_FOUND,{frag:o,id:t,initPTS:E,timescale:T,trackId:v})}}if(h&&g){y&&h.type==="audiovideo"&&this.logMuxedErr(o);const p=g.fragments[o.sn-1-g.startSN],E=o.sn===g.startSN,T=!p||o.cc>p.cc;if(i.independent!==!1){const{startPTS:S,endPTS:v,startDTS:A,endDTS:D}=h;if(c)c.elementaryStreams[h.type]={startPTS:S,endPTS:v,startDTS:A,endDTS:D};else if(h.firstKeyFrame&&h.independent&&r.id===1&&!T&&(this.couldBacktrack=!0),h.dropped&&h.independent){const x=this.getMainFwdBufferInfo(),b=(x?x.end:this.getLoadPosition())+this.config.maxBufferHole,_=h.firstKeyFramePTS?h.firstKeyFramePTS:S;if(!E&&b<_-this.config.maxBufferHole&&!T){this.backtrack(o);return}else T&&(o.gap=!0);o.setElementaryStreamInfo(h.type,o.start,v,o.start,D,!0)}else E&&S-(g.appliedTimelineOffset||0)>ps&&(o.gap=!0);o.setElementaryStreamInfo(h.type,S,v,A,D),this.backtrackFragment&&(this.backtrackFragment=o),this.bufferFragmentData(h,o,c,r,E||T)}else if(E||T)o.gap=!0;else{this.backtrack(o);return}}if(y){const{startPTS:p,endPTS:E,startDTS:T,endDTS:S}=y;c&&(c.elementaryStreams[re.AUDIO]={startPTS:p,endPTS:E,startDTS:T,endDTS:S}),o.setElementaryStreamInfo(re.AUDIO,p,E,T,S),this.bufferFragmentData(y,o,c,r)}if(g&&u!=null&&u.samples.length){const p={id:t,frag:o,details:g,samples:u.samples};s.trigger(m.FRAG_PARSING_METADATA,p)}if(g&&d){const p={id:t,frag:o,details:g,samples:d.samples};s.trigger(m.FRAG_PARSING_USERDATA,p)}}logMuxedErr(e){this.warn(`${ce(e)?"Media":"Init"} segment with muxed audiovideo where only video expected: ${e.url}`)}_bufferInitSegment(e,t,s,i){if(this.state!==C.PARSING)return;this.audioOnly=!!t.audio&&!t.video,this.altAudio&&!this.audioOnly&&(delete t.audio,t.audiovideo&&this.logMuxedErr(s));const{audio:r,video:n,audiovideo:o}=t;if(r){const l=e.audioCodec;let h=cs(r.codec,l);h==="mp4a"&&(h="mp4a.40.5");const d=navigator.userAgent.toLowerCase();if(this.audioCodecSwitch){h&&(h.indexOf("mp4a.40.5")!==-1?h="mp4a.40.2":h="mp4a.40.5");const u=r.metadata;u&&"channelCount"in u&&(u.channelCount||1)!==1&&d.indexOf("firefox")===-1&&(h="mp4a.40.5")}h&&h.indexOf("mp4a.40.5")!==-1&&d.indexOf("android")!==-1&&r.container!=="audio/mpeg"&&(h="mp4a.40.2",this.log(`Android: force audio codec to ${h}`)),l&&l!==h&&this.log(`Swapping manifest audio codec "${l}" for "${h}"`),r.levelCodec=h,r.id=B.MAIN,this.log(`Init audio buffer, container:${r.container}, codecs[selected/level/parsed]=[${h||""}/${l||""}/${r.codec}]`),delete t.audiovideo}if(n){n.levelCodec=e.videoCodec,n.id=B.MAIN;const l=n.codec;if((l==null?void 0:l.length)===4)switch(l){case"hvc1":case"hev1":n.codec="hvc1.1.6.L120.90";break;case"av01":n.codec="av01.0.04M.08";break;case"avc1":n.codec="avc1.42e01e";break}this.log(`Init video buffer, container:${n.container}, codecs[level/parsed]=[${e.videoCodec||""}/${l}]${n.codec!==l?" parsed-corrected="+n.codec:""}${n.supplemental?" supplemental="+n.supplemental:""}`),delete t.audiovideo}o&&(this.log(`Init audiovideo buffer, container:${o.container}, codecs[level/parsed]=[${e.codecs}/${o.codec}]`),delete t.video,delete t.audio);const c=Object.keys(t);if(c.length){if(this.hls.trigger(m.BUFFER_CODECS,t),!this.hls)return;c.forEach(l=>{const d=t[l].initSegment;d!=null&&d.byteLength&&this.hls.trigger(m.BUFFER_APPENDING,{type:l,data:d,frag:s,part:null,chunkMeta:i,parent:s.type})})}this.tickImmediate()}getMainFwdBufferInfo(){const e=this.mediaBuffer&&this.altAudio===2?this.mediaBuffer:this.media;return this.getFwdBufferInfo(e,B.MAIN)}get maxBufferLength(){const{levels:e,level:t}=this,s=e==null?void 0:e[t];return s?this.getMaxBufferLength(s.maxBitrate):this.config.maxBufferLength}backtrack(e){this.couldBacktrack=!0,this.backtrackFragment=e,this.resetTransmuxer(),this.flushBufferGap(e),this.fragmentTracker.removeFragment(e),this.fragPrevious=null,this.nextLoadPosition=e.start,this.state=C.IDLE}checkFragmentChanged(){const e=this.media;let t=null;if(e&&e.readyState>1&&e.seeking===!1){const s=e.currentTime;if(q.isBuffered(e,s)?t=this.getAppendedFrag(s):q.isBuffered(e,s+.1)&&(t=this.getAppendedFrag(s+.1)),t){this.backtrackFragment=null;const i=this.fragPlaying,r=t.level;(!i||t.sn!==i.sn||i.level!==r)&&(this.fragPlaying=t,this.hls.trigger(m.FRAG_CHANGED,{frag:t}),(!i||i.level!==r)&&this.hls.trigger(m.LEVEL_SWITCHED,{level:r}))}}}get nextLevel(){const e=this.nextBufferedFrag;return e?e.level:-1}get currentFrag(){var e;if(this.fragPlaying)return this.fragPlaying;const t=((e=this.media)==null?void 0:e.currentTime)||this.lastCurrentTime;return M(t)?this.getAppendedFrag(t):null}get currentProgramDateTime(){var e;const t=((e=this.media)==null?void 0:e.currentTime)||this.lastCurrentTime;if(M(t)){const s=this.getLevelDetails(),i=this.currentFrag||(s?gt(null,s.fragments,t):null);if(i){const r=i.programDateTime;if(r!==null){const n=r+(t-i.start)*1e3;return new Date(n)}}}return null}get currentLevel(){const e=this.currentFrag;return e?e.level:-1}get nextBufferedFrag(){const e=this.currentFrag;return e?this.followingBufferedFrag(e):null}get forceStartLoad(){return this._forceStartLoad}}class su extends we{constructor(e,t){super("key-loader",t),this.config=void 0,this.keyIdToKeyInfo={},this.emeController=null,this.config=e}abort(e){for(const s in this.keyIdToKeyInfo){const i=this.keyIdToKeyInfo[s].loader;if(i){var t;if(e&&e!==((t=i.context)==null?void 0:t.frag.type))return;i.abort()}}}detach(){for(const e in this.keyIdToKeyInfo){const t=this.keyIdToKeyInfo[e];(t.mediaKeySessionContext||t.decryptdata.isCommonEncryption)&&delete this.keyIdToKeyInfo[e]}}destroy(){this.detach();for(const e in this.keyIdToKeyInfo){const t=this.keyIdToKeyInfo[e].loader;t&&t.destroy()}this.keyIdToKeyInfo={}}createKeyLoadError(e,t=R.KEY_LOAD_ERROR,s,i,r){return new Xe({type:V.NETWORK_ERROR,details:t,fatal:!1,frag:e,response:r,error:s,networkDetails:i})}loadClear(e,t,s){if(this.emeController&&this.config.emeEnabled&&!this.emeController.getSelectedKeySystemFormats().length){if(t.length)for(let i=0,r=t.length;i<r;i++){const n=t[i];if(e.cc<=n.cc&&(!ce(e)||!ce(n)||e.sn<n.sn)||!s&&i==r-1)return this.emeController.selectKeySystemFormat(n).then(o=>{if(!this.emeController)return;n.setKeyFormat(o);const c=ds(o);if(c)return this.emeController.getKeySystemAccess([c])})}if(this.config.requireKeySystemAccessOnStart){const i=wt(this.config);if(i.length)return this.emeController.getKeySystemAccess(i)}}return null}load(e){return!e.decryptdata&&e.encrypted&&this.emeController&&this.config.emeEnabled?this.emeController.selectKeySystemFormat(e).then(t=>this.loadInternal(e,t)):this.loadInternal(e)}loadInternal(e,t){var s,i;t&&e.setKeyFormat(t);const r=e.decryptdata;if(!r){const l=new Error(t?`Expected frag.decryptdata to be defined after setting format ${t}`:`Missing decryption data on fragment in onKeyLoading (emeEnabled with controller: ${this.emeController&&this.config.emeEnabled})`);return Promise.reject(this.createKeyLoadError(e,R.KEY_LOAD_ERROR,l))}const n=r.uri;if(!n)return Promise.reject(this.createKeyLoadError(e,R.KEY_LOAD_ERROR,new Error(`Invalid key URI: "${n}"`)));const o=si(r);let c=this.keyIdToKeyInfo[o];if((s=c)!=null&&s.decryptdata.key)return r.key=c.decryptdata.key,Promise.resolve({frag:e,keyInfo:c});if(this.emeController&&(i=c)!=null&&i.keyLoadPromise)switch(this.emeController.getKeyStatus(c.decryptdata)){case"usable":case"usable-in-future":return c.keyLoadPromise.then(h=>{const{keyInfo:d}=h;return r.key=d.decryptdata.key,{frag:e,keyInfo:d}})}switch(this.log(`${this.keyIdToKeyInfo[o]?"Rel":"L"}oading${r.keyId?" keyId: "+me(r.keyId):""} URI: ${r.uri} from ${e.type} ${e.level}`),c=this.keyIdToKeyInfo[o]={decryptdata:r,keyLoadPromise:null,loader:null,mediaKeySessionContext:null},r.method){case"SAMPLE-AES":case"SAMPLE-AES-CENC":case"SAMPLE-AES-CTR":return r.keyFormat==="identity"?this.loadKeyHTTP(c,e):this.loadKeyEME(c,e);case"AES-128":case"AES-256":case"AES-256-CTR":return this.loadKeyHTTP(c,e);default:return Promise.reject(this.createKeyLoadError(e,R.KEY_LOAD_ERROR,new Error(`Key supplied with unsupported METHOD: "${r.method}"`)))}}loadKeyEME(e,t){const s={frag:t,keyInfo:e};if(this.emeController&&this.config.emeEnabled){var i;if(!e.decryptdata.keyId&&(i=t.initSegment)!=null&&i.data){const n=vo(t.initSegment.data);if(n.length){let o=n[0];o.some(c=>c!==0)?(this.log(`Using keyId found in init segment ${me(o)}`),it.setKeyIdForUri(e.decryptdata.uri,o)):(o=it.addKeyIdForUri(e.decryptdata.uri),this.log(`Generating keyId to patch media ${me(o)}`)),e.decryptdata.keyId=o}}if(!e.decryptdata.keyId&&!ce(t))return Promise.resolve(s);const r=this.emeController.loadKey(s);return(e.keyLoadPromise=r.then(n=>(e.mediaKeySessionContext=n,s))).catch(n=>{throw e.keyLoadPromise=null,"data"in n&&(n.data.frag=t),n})}return Promise.resolve(s)}loadKeyHTTP(e,t){const s=this.config,i=s.loader,r=new i(s);return t.keyLoader=e.loader=r,e.keyLoadPromise=new Promise((n,o)=>{const c={keyInfo:e,frag:t,responseType:"arraybuffer",url:e.decryptdata.uri},l=s.keyLoadPolicy.default,h={loadPolicy:l,timeout:l.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},d={onSuccess:(u,f,g,y)=>{const{frag:p,keyInfo:E}=g,T=si(E.decryptdata);if(!p.decryptdata||E!==this.keyIdToKeyInfo[T])return o(this.createKeyLoadError(p,R.KEY_LOAD_ERROR,new Error("after key load, decryptdata unset or changed"),y));E.decryptdata.key=p.decryptdata.key=new Uint8Array(u.data),p.keyLoader=null,E.loader=null,n({frag:p,keyInfo:E})},onError:(u,f,g,y)=>{this.resetLoader(f),o(this.createKeyLoadError(t,R.KEY_LOAD_ERROR,new Error(`HTTP Error ${u.code} loading key ${u.text}`),g,te({url:c.url,data:void 0},u)))},onTimeout:(u,f,g)=>{this.resetLoader(f),o(this.createKeyLoadError(t,R.KEY_LOAD_TIMEOUT,new Error("key loading timed out"),g))},onAbort:(u,f,g)=>{this.resetLoader(f),o(this.createKeyLoadError(t,R.INTERNAL_ABORTED,new Error("key loading aborted"),g))}};r.load(c,h,d)})}resetLoader(e){const{frag:t,keyInfo:s,url:i}=e,r=s.loader;t.keyLoader===r&&(t.keyLoader=null,s.loader=null);const n=si(s.decryptdata)||i;delete this.keyIdToKeyInfo[n],r&&r.destroy()}}function si(a){if(a.keyFormat!==pe.FAIRPLAY){const e=a.keyId;if(e)return me(e)}return a.uri}function pn(a){const{type:e}=a;switch(e){case Q.AUDIO_TRACK:return B.AUDIO;case Q.SUBTITLE_TRACK:return B.SUBTITLE;default:return B.MAIN}}function ii(a,e){let t=a.url;return(t===void 0||t.indexOf("data:")===0)&&(t=e.url),t}class iu{constructor(e){this.hls=void 0,this.loaders=Object.create(null),this.variableList=null,this.onManifestLoaded=this.checkAutostartLoad,this.hls=e,this.registerListeners()}startLoad(e){}stopLoad(){this.destroyInternalLoaders()}registerListeners(){const{hls:e}=this;e.on(m.MANIFEST_LOADING,this.onManifestLoading,this),e.on(m.LEVEL_LOADING,this.onLevelLoading,this),e.on(m.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.on(m.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),e.on(m.LEVELS_UPDATED,this.onLevelsUpdated,this)}unregisterListeners(){const{hls:e}=this;e.off(m.MANIFEST_LOADING,this.onManifestLoading,this),e.off(m.LEVEL_LOADING,this.onLevelLoading,this),e.off(m.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.off(m.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),e.off(m.LEVELS_UPDATED,this.onLevelsUpdated,this)}createInternalLoader(e){const t=this.hls.config,s=t.pLoader,i=t.loader,r=s||i,n=new r(t);return this.loaders[e.type]=n,n}getInternalLoader(e){return this.loaders[e.type]}resetInternalLoader(e){this.loaders[e]&&delete this.loaders[e]}destroyInternalLoaders(){for(const e in this.loaders){const t=this.loaders[e];t&&t.destroy(),this.resetInternalLoader(e)}}destroy(){this.variableList=null,this.unregisterListeners(),this.destroyInternalLoaders()}onManifestLoading(e,t){const{url:s}=t;this.variableList=null,this.load({id:null,level:0,responseType:"text",type:Q.MANIFEST,url:s,deliveryDirectives:null,levelOrTrack:null})}onLevelLoading(e,t){const{id:s,level:i,pathwayId:r,url:n,deliveryDirectives:o,levelInfo:c}=t;this.load({id:s,level:i,pathwayId:r,responseType:"text",type:Q.LEVEL,url:n,deliveryDirectives:o,levelOrTrack:c})}onAudioTrackLoading(e,t){const{id:s,groupId:i,url:r,deliveryDirectives:n,track:o}=t;this.load({id:s,groupId:i,level:null,responseType:"text",type:Q.AUDIO_TRACK,url:r,deliveryDirectives:n,levelOrTrack:o})}onSubtitleTrackLoading(e,t){const{id:s,groupId:i,url:r,deliveryDirectives:n,track:o}=t;this.load({id:s,groupId:i,level:null,responseType:"text",type:Q.SUBTITLE_TRACK,url:r,deliveryDirectives:n,levelOrTrack:o})}onLevelsUpdated(e,t){const s=this.loaders[Q.LEVEL];if(s){const i=s.context;i&&!t.levels.some(r=>r===i.levelOrTrack)&&(s.abort(),delete this.loaders[Q.LEVEL])}}load(e){var t;const s=this.hls.config;let i=this.getInternalLoader(e);if(i){const l=this.hls.logger,h=i.context;if(h&&h.levelOrTrack===e.levelOrTrack&&(h.url===e.url||h.deliveryDirectives&&!e.deliveryDirectives)){h.url===e.url?l.log(`[playlist-loader]: ignore ${e.url} ongoing request`):l.log(`[playlist-loader]: ignore ${e.url} in favor of ${h.url}`);return}l.log(`[playlist-loader]: aborting previous loader for type: ${e.type}`),i.abort()}let r;if(e.type===Q.MANIFEST?r=s.manifestLoadPolicy.default:r=ie({},s.playlistLoadPolicy.default,{timeoutRetry:null,errorRetry:null}),i=this.createInternalLoader(e),M((t=e.deliveryDirectives)==null?void 0:t.part)){let l;if(e.type===Q.LEVEL&&e.level!==null?l=this.hls.levels[e.level].details:e.type===Q.AUDIO_TRACK&&e.id!==null?l=this.hls.audioTracks[e.id].details:e.type===Q.SUBTITLE_TRACK&&e.id!==null&&(l=this.hls.subtitleTracks[e.id].details),l){const h=l.partTarget,d=l.targetduration;if(h&&d){const u=Math.max(h*3,d*.8)*1e3;r=ie({},r,{maxTimeToFirstByteMs:Math.min(u,r.maxTimeToFirstByteMs),maxLoadTimeMs:Math.min(u,r.maxTimeToFirstByteMs)})}}}const n=r.errorRetry||r.timeoutRetry||{},o={loadPolicy:r,timeout:r.maxLoadTimeMs,maxRetry:n.maxNumRetry||0,retryDelay:n.retryDelayMs||0,maxRetryDelay:n.maxRetryDelayMs||0},c={onSuccess:(l,h,d,u)=>{const f=this.getInternalLoader(d);this.resetInternalLoader(d.type);const g=l.data;h.parsing.start=performance.now(),He.isMediaPlaylist(g)||d.type!==Q.MANIFEST?this.handleTrackOrLevelPlaylist(l,h,d,u||null,f):this.handleMasterPlaylist(l,h,d,u)},onError:(l,h,d,u)=>{this.handleNetworkError(h,d,!1,l,u)},onTimeout:(l,h,d)=>{this.handleNetworkError(h,d,!0,void 0,l)}};i.load(e,o,c)}checkAutostartLoad(){if(!this.hls)return;const{config:{autoStartLoad:e,startPosition:t},forceStartLoad:s}=this.hls;(e||s)&&(this.hls.logger.log(`${e?"auto":"force"} startLoad with configured startPosition ${t}`),this.hls.startLoad(t))}handleMasterPlaylist(e,t,s,i){const r=this.hls,n=e.data,o=ii(e,s),c=He.parseMasterPlaylist(n,o);if(c.playlistParsingError){t.parsing.end=performance.now(),this.handleManifestParsingError(e,s,c.playlistParsingError,i,t);return}const{contentSteering:l,levels:h,sessionData:d,sessionKeys:u,startTimeOffset:f,variableList:g}=c;this.variableList=g,h.forEach(T=>{const{unknownCodecs:S}=T;if(S){const{preferManagedMediaSource:v}=this.hls.config;let{audioCodec:A,videoCodec:D}=T;for(let x=S.length;x--;){const b=S[x];Bt(b,"audio",v)?(T.audioCodec=A=A?`${A},${b}`:b,_t.audio[A.substring(0,4)]=2,S.splice(x,1)):Bt(b,"video",v)&&(T.videoCodec=D=D?`${D},${b}`:b,_t.video[D.substring(0,4)]=2,S.splice(x,1))}}});const{AUDIO:y=[],SUBTITLES:p,"CLOSED-CAPTIONS":E}=He.parseMasterPlaylistMedia(n,o,c);y.length&&!y.some(S=>!S.url)&&h[0].audioCodec&&!h[0].attrs.AUDIO&&(this.hls.logger.log("[playlist-loader]: audio codec signaled in quality level, but no embedded audio track signaled, create one"),y.unshift({type:"main",name:"main",groupId:"main",default:!1,autoselect:!1,forced:!1,id:-1,attrs:new ae({}),bitrate:0,url:""})),r.trigger(m.MANIFEST_LOADED,{levels:h,audioTracks:y,subtitles:p,captions:E,contentSteering:l,url:o,stats:t,networkDetails:i,sessionData:d,sessionKeys:u,startTimeOffset:f,variableList:g})}handleTrackOrLevelPlaylist(e,t,s,i,r){const n=this.hls,{id:o,level:c,type:l}=s,h=ii(e,s),d=M(c)?c:M(o)?o:0,u=pn(s),f=He.parseLevelPlaylist(e.data,h,d,u,0,this.variableList);if(l===Q.MANIFEST){const g={attrs:new ae({}),bitrate:0,details:f,name:"",url:h};f.requestScheduled=t.loading.start+Qn(f,0),n.trigger(m.MANIFEST_LOADED,{levels:[g],audioTracks:[],url:h,stats:t,networkDetails:i,sessionData:null,sessionKeys:null,contentSteering:null,startTimeOffset:null,variableList:null})}t.parsing.end=performance.now(),s.levelDetails=f,this.handlePlaylistLoaded(f,e,t,s,i,r)}handleManifestParsingError(e,t,s,i,r){this.hls.trigger(m.ERROR,{type:V.NETWORK_ERROR,details:R.MANIFEST_PARSING_ERROR,fatal:t.type===Q.MANIFEST,url:e.url,err:s,error:s,reason:s.message,response:e,context:t,networkDetails:i,stats:r})}handleNetworkError(e,t,s=!1,i,r){let n=`A network ${s?"timeout":"error"+(i?" (status "+i.code+")":"")} occurred while loading ${e.type}`;e.type===Q.LEVEL?n+=`: ${e.level} id: ${e.id}`:(e.type===Q.AUDIO_TRACK||e.type===Q.SUBTITLE_TRACK)&&(n+=` id: ${e.id} group-id: "${e.groupId}"`);const o=new Error(n);this.hls.logger.warn(`[playlist-loader]: ${n}`);let c=R.UNKNOWN,l=!1;const h=this.getInternalLoader(e);switch(e.type){case Q.MANIFEST:c=s?R.MANIFEST_LOAD_TIMEOUT:R.MANIFEST_LOAD_ERROR,l=!0;break;case Q.LEVEL:c=s?R.LEVEL_LOAD_TIMEOUT:R.LEVEL_LOAD_ERROR,l=!1;break;case Q.AUDIO_TRACK:c=s?R.AUDIO_TRACK_LOAD_TIMEOUT:R.AUDIO_TRACK_LOAD_ERROR,l=!1;break;case Q.SUBTITLE_TRACK:c=s?R.SUBTITLE_TRACK_LOAD_TIMEOUT:R.SUBTITLE_LOAD_ERROR,l=!1;break}h&&this.resetInternalLoader(e.type);const d={type:V.NETWORK_ERROR,details:c,fatal:l,url:e.url,loader:h,context:e,error:o,networkDetails:t,stats:r};if(i){const u=(t==null?void 0:t.url)||e.url;d.response=te({url:u,data:void 0},i)}this.hls.trigger(m.ERROR,d)}handlePlaylistLoaded(e,t,s,i,r,n){const o=this.hls,{type:c,level:l,levelOrTrack:h,id:d,groupId:u,deliveryDirectives:f}=i,g=ii(t,i),y=pn(i);let p=typeof i.level=="number"&&y===B.MAIN?l:void 0;const E=e.playlistParsingError;if(E){if(this.hls.logger.warn(`${E} ${e.url}`),!o.config.ignorePlaylistParsingErrors){o.trigger(m.ERROR,{type:V.NETWORK_ERROR,details:R.LEVEL_PARSING_ERROR,fatal:!1,url:g,error:E,reason:E.message,response:t,context:i,level:p,parent:y,networkDetails:r,stats:s});return}e.playlistParsingError=null}if(!e.fragments.length){const T=e.playlistParsingError=new Error("No Segments found in Playlist");o.trigger(m.ERROR,{type:V.NETWORK_ERROR,details:R.LEVEL_EMPTY_ERROR,fatal:!1,url:g,error:T,reason:T.message,response:t,context:i,level:p,parent:y,networkDetails:r,stats:s});return}switch(e.live&&n&&(n.getCacheAge&&(e.ageHeader=n.getCacheAge()||0),(!n.getCacheAge||isNaN(e.ageHeader))&&(e.ageHeader=0)),c){case Q.MANIFEST:case Q.LEVEL:if(p){if(!h)p=0;else if(h!==o.levels[p]){const T=o.levels.indexOf(h);T>-1&&(p=T)}}o.trigger(m.LEVEL_LOADED,{details:e,levelInfo:h||o.levels[0],level:p||0,id:d||0,stats:s,networkDetails:r,deliveryDirectives:f,withoutMultiVariant:c===Q.MANIFEST});break;case Q.AUDIO_TRACK:o.trigger(m.AUDIO_TRACK_LOADED,{details:e,track:h,id:d||0,groupId:u||"",stats:s,networkDetails:r,deliveryDirectives:f});break;case Q.SUBTITLE_TRACK:o.trigger(m.SUBTITLE_TRACK_LOADED,{details:e,track:h,id:d||0,groupId:u||"",stats:s,networkDetails:r,deliveryDirectives:f});break}}}class Pe{static get version(){return Gt}static isMSESupported(){return za()}static isSupported(){return Zd()}static getMediaSource(){return rt()}static get Events(){return m}static get MetadataSchema(){return Re}static get ErrorTypes(){return V}static get ErrorDetails(){return R}static get DefaultConfig(){return Pe.defaultConfig?Pe.defaultConfig:$d}static set DefaultConfig(e){Pe.defaultConfig=e}constructor(e={}){this.config=void 0,this.userConfig=void 0,this.logger=void 0,this.coreComponents=void 0,this.networkControllers=void 0,this._emitter=new Fi,this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.abrController=void 0,this.bufferController=void 0,this.capLevelController=void 0,this.latencyController=void 0,this.levelController=void 0,this.streamController=void 0,this.audioStreamController=void 0,this.subtititleStreamController=void 0,this.audioTrackController=void 0,this.subtitleTrackController=void 0,this.interstitialsController=void 0,this.gapController=void 0,this.emeController=void 0,this.cmcdController=void 0,this._media=null,this._url=null,this._sessionId=void 0,this.triggeringException=void 0,this.started=!1;const t=this.logger=lo(e.debug||!1,"Hls instance",e.assetPlayerId),s=this.config=Kd(Pe.DefaultConfig,e,t);this.userConfig=e,s.progressive&&Vd(s,t);const{abrController:i,bufferController:r,capLevelController:n,errorController:o,fpsController:c}=s,l=new o(this),h=this.abrController=new i(this),d=new rl(this),u=s.interstitialsController,f=u?this.interstitialsController=new u(this,Pe):null,g=this.bufferController=new r(this,d),y=this.capLevelController=new n(this),p=new c(this),E=new iu(this),T=s.contentSteeringController,S=T?new T(this):null,v=this.levelController=new Qd(this,S),A=new Xd(this),D=new su(this.config,this.logger),x=this.streamController=new tu(this,d,D),b=this.gapController=new qd(this,d);y.setStreamController(x),p.setStreamController(x);const _=[E,v,x];f&&_.splice(1,0,f),S&&_.splice(1,0,S),this.networkControllers=_;const I=[h,g,b,y,p,A,d];this.audioTrackController=this.createController(s.audioTrackController,_);const P=s.audioStreamController;P&&_.push(this.audioStreamController=new P(this,d,D)),this.subtitleTrackController=this.createController(s.subtitleTrackController,_);const F=s.subtitleStreamController;F&&_.push(this.subtititleStreamController=new F(this,d,D)),this.createController(s.timelineController,I),D.emeController=this.emeController=this.createController(s.emeController,I),this.cmcdController=this.createController(s.cmcdController,I),this.latencyController=this.createController(zd,I),this.coreComponents=I,_.push(l);const U=l.onErrorOut;typeof U=="function"&&this.on(m.ERROR,U,l),this.on(m.MANIFEST_LOADED,E.onManifestLoaded,E)}createController(e,t){if(e){const s=new e(this);return t&&t.push(s),s}return null}on(e,t,s=this){this._emitter.on(e,t,s)}once(e,t,s=this){this._emitter.once(e,t,s)}removeAllListeners(e){this._emitter.removeAllListeners(e)}off(e,t,s=this,i){this._emitter.off(e,t,s,i)}listeners(e){return this._emitter.listeners(e)}emit(e,t,s){return this._emitter.emit(e,t,s)}trigger(e,t){if(this.config.debug)return this.emit(e,e,t);try{return this.emit(e,e,t)}catch(s){if(this.logger.error("An internal error happened while handling event "+e+'. Error message: "'+s.message+'". Here is a stacktrace:',s),!this.triggeringException){this.triggeringException=!0;const i=e===m.ERROR;this.trigger(m.ERROR,{type:V.OTHER_ERROR,details:R.INTERNAL_EXCEPTION,fatal:i,event:e,error:s}),this.triggeringException=!1}}return!1}listenerCount(e){return this._emitter.listenerCount(e)}destroy(){this.logger.log("destroy"),this.trigger(m.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 e=this.config;e.xhrSetup=e.fetchSetup=void 0,this.userConfig=null}attachMedia(e){if(!e||"media"in e&&!e.media){const r=new Error(`attachMedia failed: invalid argument (${e})`);this.trigger(m.ERROR,{type:V.OTHER_ERROR,details:R.ATTACH_MEDIA_ERROR,fatal:!0,error:r});return}this.logger.log("attachMedia"),this._media&&(this.logger.warn("media must be detached before attaching"),this.detachMedia());const t="media"in e,s=t?e.media:e,i=t?e:{media:s};this._media=s,this.trigger(m.MEDIA_ATTACHING,i)}detachMedia(){this.logger.log("detachMedia"),this.trigger(m.MEDIA_DETACHING,{}),this._media=null}transferMedia(){this._media=null;const e=this.bufferController.transferMedia();return this.trigger(m.MEDIA_DETACHING,{transferMedia:e}),e}loadSource(e){this.stopLoad();const t=this.media,s=this._url,i=this._url=Ii.buildAbsoluteURL(self.location.href,e,{alwaysNormalize:!0});this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.logger.log(`loadSource:${i}`),t&&s&&(s!==i||this.bufferController.hasSourceTypes())&&(this.detachMedia(),this.attachMedia(t)),this.trigger(m.MANIFEST_LOADING,{url:e})}get url(){return this._url}get hasEnoughToStart(){return this.streamController.hasEnoughToStart}get startPosition(){return this.streamController.startPositionValue}startLoad(e=-1,t){this.logger.log(`startLoad(${e+(t?", <skip seek to start>":"")})`),this.started=!0,this.resumeBuffering();for(let s=0;s<this.networkControllers.length&&(this.networkControllers[s].startLoad(e,t),!(!this.started||!this.networkControllers));s++);}stopLoad(){this.logger.log("stopLoad"),this.started=!1;for(let e=0;e<this.networkControllers.length&&(this.networkControllers[e].stopLoad(),!(this.started||!this.networkControllers));e++);}get loadingEnabled(){return this.started}get bufferingEnabled(){return this.streamController.bufferingEnabled}resumeBuffering(){this.bufferingEnabled||(this.logger.log("resume buffering"),this.networkControllers.forEach(e=>{e.resumeBuffering&&e.resumeBuffering()}))}pauseBuffering(){this.bufferingEnabled&&(this.logger.log("pause buffering"),this.networkControllers.forEach(e=>{e.pauseBuffering&&e.pauseBuffering()}))}get inFlightFragments(){const e={[B.MAIN]:this.streamController.inFlightFrag};return this.audioStreamController&&(e[B.AUDIO]=this.audioStreamController.inFlightFrag),this.subtititleStreamController&&(e[B.SUBTITLE]=this.subtititleStreamController.inFlightFrag),e}swapAudioCodec(){this.logger.log("swapAudioCodec"),this.streamController.swapAudioCodec()}recoverMediaError(){this.logger.log("recoverMediaError");const e=this._media,t=e==null?void 0:e.currentTime;this.detachMedia(),e&&(this.attachMedia(e),t&&this.startLoad(t))}removeLevel(e){this.levelController.removeLevel(e)}get sessionId(){let e=this._sessionId;return e||(e=this._sessionId=qh()),e}get levels(){const e=this.levelController.levels;return e||[]}get latestLevelDetails(){return this.streamController.getLevelDetails()||null}get loadLevelObj(){return this.levelController.loadLevelObj}get currentLevel(){return this.streamController.currentLevel}set currentLevel(e){this.logger.log(`set currentLevel:${e}`),this.levelController.manualLevel=e,this.streamController.immediateLevelSwitch()}get nextLevel(){return this.streamController.nextLevel}set nextLevel(e){this.logger.log(`set nextLevel:${e}`),this.levelController.manualLevel=e,this.streamController.nextLevelSwitch()}get loadLevel(){return this.levelController.level}set loadLevel(e){this.logger.log(`set loadLevel:${e}`),this.levelController.manualLevel=e}get nextLoadLevel(){return this.levelController.nextLoadLevel}set nextLoadLevel(e){this.levelController.nextLoadLevel=e}get firstLevel(){return Math.max(this.levelController.firstLevel,this.minAutoLevel)}set firstLevel(e){this.logger.log(`set firstLevel:${e}`),this.levelController.firstLevel=e}get startLevel(){const e=this.levelController.startLevel;return e===-1&&this.abrController.forcedAutoLevel>-1?this.abrController.forcedAutoLevel:e}set startLevel(e){this.logger.log(`set startLevel:${e}`),e!==-1&&(e=Math.max(e,this.minAutoLevel)),this.levelController.startLevel=e}get capLevelToPlayerSize(){return this.config.capLevelToPlayerSize}set capLevelToPlayerSize(e){const t=!!e;t!==this.config.capLevelToPlayerSize&&(t?this.capLevelController.startCapping():(this.capLevelController.stopCapping(),this.autoLevelCapping=-1,this.streamController.nextLevelSwitch()),this.config.capLevelToPlayerSize=t)}get autoLevelCapping(){return this._autoLevelCapping}get bandwidthEstimate(){const{bwEstimator:e}=this.abrController;return e?e.getEstimate():NaN}set bandwidthEstimate(e){this.abrController.resetEstimator(e)}get abrEwmaDefaultEstimate(){const{bwEstimator:e}=this.abrController;return e?e.defaultEstimate:NaN}get ttfbEstimate(){const{bwEstimator:e}=this.abrController;return e?e.getEstimateTTFB():NaN}set autoLevelCapping(e){this._autoLevelCapping!==e&&(this.logger.log(`set autoLevelCapping:${e}`),this._autoLevelCapping=e,this.levelController.checkMaxAutoUpdated())}get maxHdcpLevel(){return this._maxHdcpLevel}set maxHdcpLevel(e){Ko(e)&&this._maxHdcpLevel!==e&&(this._maxHdcpLevel=e,this.levelController.checkMaxAutoUpdated())}get autoLevelEnabled(){return this.levelController.manualLevel===-1}get manualLevel(){return this.levelController.manualLevel}get minAutoLevel(){const{levels:e,config:{minAutoBitrate:t}}=this;if(!e)return 0;const s=e.length;for(let i=0;i<s;i++)if(e[i].maxBitrate>=t)return i;return 0}get maxAutoLevel(){const{levels:e,autoLevelCapping:t,maxHdcpLevel:s}=this;let i;if(t===-1&&e!=null&&e.length?i=e.length-1:i=t,s)for(let r=i;r--;){const n=e[r].attrs["HDCP-LEVEL"];if(n&&n<=s)return r}return i}get firstAutoLevel(){return this.abrController.firstAutoLevel}get nextAutoLevel(){return this.abrController.nextAutoLevel}set nextAutoLevel(e){this.abrController.nextAutoLevel=e}get playingDate(){return this.streamController.currentProgramDateTime}get mainForwardBufferInfo(){return this.streamController.getMainFwdBufferInfo()}get maxBufferLength(){return this.streamController.maxBufferLength}setAudioOption(e){var t;return((t=this.audioTrackController)==null?void 0:t.setAudioOption(e))||null}setSubtitleOption(e){var t;return((t=this.subtitleTrackController)==null?void 0:t.setSubtitleOption(e))||null}get allAudioTracks(){const e=this.audioTrackController;return e?e.allAudioTracks:[]}get audioTracks(){const e=this.audioTrackController;return e?e.audioTracks:[]}get audioTrack(){const e=this.audioTrackController;return e?e.audioTrack:-1}set audioTrack(e){const t=this.audioTrackController;t&&(t.audioTrack=e)}get allSubtitleTracks(){const e=this.subtitleTrackController;return e?e.allSubtitleTracks:[]}get subtitleTracks(){const e=this.subtitleTrackController;return e?e.subtitleTracks:[]}get subtitleTrack(){const e=this.subtitleTrackController;return e?e.subtitleTrack:-1}get media(){return this._media}set subtitleTrack(e){const t=this.subtitleTrackController;t&&(t.subtitleTrack=e)}get subtitleDisplay(){const e=this.subtitleTrackController;return e?e.subtitleDisplay:!1}set subtitleDisplay(e){const t=this.subtitleTrackController;t&&(t.subtitleDisplay=e)}get lowLatencyMode(){return this.config.lowLatencyMode}set lowLatencyMode(e){this.config.lowLatencyMode=e}get liveSyncPosition(){return this.latencyController.liveSyncPosition}get latency(){return this.latencyController.latency}get maxLatency(){return this.latencyController.maxLatency}get targetLatency(){return this.latencyController.targetLatency}set targetLatency(e){this.latencyController.targetLatency=e}get drift(){return this.latencyController.drift}get forceStartLoad(){return this.streamController.forceStartLoad}get pathways(){return this.levelController.pathways}get pathwayPriority(){return this.levelController.pathwayPriority}set pathwayPriority(e){this.levelController.pathwayPriority=e}get bufferedToEnd(){var e;return!!((e=this.bufferController)!=null&&e.bufferedToEnd)}get interstitialsManager(){var e;return((e=this.interstitialsController)==null?void 0:e.interstitialsManager)||null}getMediaDecodingInfo(e,t=this.allAudioTracks){const s=Mn(t);return On(e,s,navigator.mediaCapabilities)}}Pe.defaultConfig=void 0;const ys="https://vod-beta.stream.place/xrpc",ru="https://iameli.com",nu="did:plc:rbvrr34edl5ddpuwcubjiost",au="place.stream.video";async function ou(){let a=[],e;do{const t=new URLSearchParams({repo:nu,collection:au,limit:"100"});e&&t.set("cursor",e);const s=await(await fetch(`${ru}/xrpc/com.atproto.repo.listRecords?${t}`)).json();a=a.concat(s.records||[]),e=s.cursor}while(e);return console.info(a),a.reverse()}const xe=document.getElementById("video"),Ce=document.getElementById("audio"),lu=document.getElementById("standby"),cu=document.getElementById("channelOverlay"),hu=document.getElementById("channelNumber"),yn=document.getElementById("channelTitle"),os=document.getElementById("loadingIndicator"),ls=document.getElementById("mutedIndicator"),dt=document.getElementById("videoListContainer"),Nt=document.getElementById("videoCounter");let Qe=[],st=-1,En=0,du=null,vt=!1,Me=null;function uu(a){const e=a.split(`
264264-`);let t=null;const s=[];let i=0,r=0,n=0;for(const o of e){const c=o.trim();if(c.startsWith("#EXT-X-MAP:")){const l=c.match(/URI="([^"]+)"/);l&&(t=l[1])}else if(c.startsWith("#EXTINF:"))i=parseFloat(c.split(":")[1]);else if(c.startsWith("#EXT-X-BYTERANGE:")){const l=c.split(":")[1].split("@");n=parseInt(l[0]),l[1]!==void 0&&(r=parseInt(l[1]))}else c&&!c.startsWith("#")&&(s.push({uri:c,duration:i,offset:r,length:n}),r+=n)}return{initUri:t,segments:s}}function Tn(a){return`${ys}/${a}`}function fu(a,e,t){hu.textContent="CH "+String(a).padStart(2,"0"),yn.textContent=e,yn.href="https://pds.ls/"+t,cu.classList.add("visible"),clearTimeout(du)}function gu(){document.querySelectorAll(".video-list-item").forEach((e,t)=>{t===st?e.classList.add("currently-playing"):e.classList.remove("currently-playing")})}function Qa(){if(!dt||!Nt)return;Qe.length>0?Nt.textContent=`${st+1}/${Qe.length}`:Nt.textContent="0/0",dt.innerHTML="";const a=document.createElement("div");if(a.className="video-list-loading",a.textContent="Loading videos...",dt.appendChild(a),Qe.forEach((t,s)=>{const i=t.value.title||"Unknown Programme",r=(t.value.duration||0)/1e9,n=r>0?` (${Math.round(r)}s)`:"",o=document.createElement("div");o.className="video-list-item",o.dataset.index=s.toString(),o.innerHTML=`
265265- <div class="video-list-number">CH ${String(s+1).padStart(2,"0")}</div>
266266- <div class="video-list-title">${i}${n}</div>
267267- <div class="video-list-actions">
268268- <button class="play-video-btn" data-index="${s}" aria-label="Play video ${s+1}">Play</button>
269269- </div>
270270- `,dt.appendChild(o),o.addEventListener("mouseenter",c=>{const l=o.getBoundingClientRect(),h=document.createElement("div");h.className="video-tooltip";const d=t.value.title||"Unknown Programme",u=(t.value.duration||0)/1e9,f=t.index?new Date(t.index).toLocaleString():"Unknown";h.innerHTML=`
271271- <div class="tooltip-title">${d}</div>
272272- <div class="tooltip-detail">Duration: ${u>0?Math.round(u)+"s":"Unknown"}</div>
273273- <div class="tooltip-detail">Created: ${f}</div>
274274- `,document.body.appendChild(h),h.style.left=`${l.left+window.scrollX+10}px`,h.style.top=`${l.top+window.scrollY-5}px`,h.style.opacity="1",o._tooltip=h}),o.addEventListener("mouseleave",()=>{o._tooltip&&(o._tooltip.style.opacity="0",setTimeout(()=>{o._tooltip&&o._tooltip.parentNode&&o._tooltip.remove()},200))})}),dt.querySelectorAll(".video-list-loading").forEach(t=>t.remove()),document.querySelectorAll(".play-video-btn").forEach(t=>{t.addEventListener("click",s=>{const i=parseInt(s.target.dataset.index||"");isNaN(i)||(st=i,Ai())})}),document.querySelectorAll(".video-list-item").forEach(t=>{t.addEventListener("click",s=>{if(s.target.classList.contains("play-video-btn"))return;const i=parseInt(t.dataset.index||"");isNaN(i)||(st=i,Ai())})}),Qe.length===0){dt.querySelectorAll(".video-list-loading").forEach(i=>i.remove());const s=document.createElement("div");s.className="video-list-empty",s.textContent="No videos available. Click Refresh to try again.",dt.appendChild(s)}}async function Ai(){if(vt||Qe.length===0)return;vt=!0;const a=++En,e=()=>a!==En;(st===-1||st>=Qe.length)&&(st=0);let t=st;gu();const s=Qe[t],i=s.value.title||"Unknown Programme",r=(s.value.duration||0)/1e9,n=s.uri,o=encodeURIComponent(n);if(console.log("[TV] Switching to:",i,`(${Math.round(r)}s)`),lu.classList.add("hidden"),os.classList.add("visible"),ls.classList.remove("visible","fade-out"),fu(t+1,i,n),Qa(),Me&&(Me.destroy(),Me=null),xe.pause(),xe.removeAttribute("src"),xe.load(),Ce.pause(),Ce.removeAttribute("src"),await new Promise(d=>setTimeout(d,250)),e()){vt=!1;return}const c=0;console.log("[TV] Starting playback from beginning");const l=`${ys}/place.stream.playback.getVideoPlaylist?uri=${o}&track=1`;if(!Pe.isSupported()){const d=`${ys}/place.stream.playback.getVideoPlaylist?uri=${o}`;xe.src=d,xe.currentTime=c;try{await xe.play(),os.classList.remove("visible")}catch(u){console.warn("[TV] Playback error:",u),os.classList.remove("visible")}vt=!1;return}Me=new Pe({startPosition:c,maxBufferLength:30,maxMaxBufferLength:60}),Me.loadSource(l),Me.attachMedia(xe),Me.on(Pe.Events.MANIFEST_PARSED,()=>{e()||(console.log("[TV] Video manifest parsed"),xe.muted=!0,xe.play().catch(d=>console.warn("[TV] Play failed:",d)))});const h=()=>{e()||(xe.removeEventListener("playing",h),console.log("[TV] Video playing!"),os.classList.remove("visible"),ls.classList.add("visible"))};xe.addEventListener("playing",h),Me.on(Pe.Events.ERROR,(d,u)=>{e()||(console.warn("[TV] HLS error:",u.type,u.details,u.fatal),u.fatal&&(u.type===Pe.ErrorTypes.MEDIA_ERROR?Me.recoverMediaError():(Me.destroy(),Me=null,vt=!1,Ai())))}),(async()=>{try{const d=`${ys}/place.stream.playback.getVideoPlaylist?uri=${o}&track=2`,u=await(await fetch(d)).text();if(e())return;const f=uu(u);if(!f.segments.length)return;const g=f.segments[0],y=Tn(f.initUri),p=Tn(g.uri);console.log(`[TV] Loading audio: ${(g.length/1024/1024).toFixed(1)}MB`);const E=await fetch(y,{cache:"no-store"}).then(x=>x.arrayBuffer());if(e())return;const T=g.offset+g.length-1,S=await fetch(p,{headers:{Range:`bytes=${g.offset}-${T}`},cache:"no-store"});let v;if(S.status===206)v=await S.arrayBuffer();else{const x=await S.arrayBuffer();if(e())return;v=x.slice(g.offset,g.offset+g.length)}if(e())return;console.log(`[TV] Audio fetched: ${(v.byteLength/1024/1024).toFixed(1)}MB`);const A=new Blob([E,v],{type:"video/mp4"});if(Ce.src=URL.createObjectURL(A),await new Promise(x=>{if(Ce.readyState>=1){x();return}Ce.addEventListener("loadedmetadata",()=>x(),{once:!0}),Ce.addEventListener("canplay",()=>x(),{once:!0}),setTimeout(x,1e3)}),e()||(Ce.currentTime=xe.currentTime,console.log("[TV] Audio seeking to",xe.currentTime.toFixed(1)+"s"),await new Promise(x=>{if(!Ce.seeking){x();return}Ce.addEventListener("seeked",()=>x(),{once:!0}),setTimeout(x,2e3)}),e()))return;Ce.volume=0,await Ce.play();const D=performance.now();(function x(){const b=Math.min(1,(performance.now()-D)/1500);Ce.volume=b,b<1&&requestAnimationFrame(x)})(),ls.classList.add("fade-out"),ls.classList.remove("visible"),console.log("[TV] Audio playing!")}catch(d){console.warn("[TV] Audio load failed (non-fatal):",d)}})(),vt=!1}(async()=>{try{Nt&&(Nt.textContent="Loading..."),Qe=await ou(),console.log(`Loaded ${Qe.length} VODs`),Qa()}catch(a){console.error("Failed to load VODs:",a)}})();</script>
275275- </head>
276276- <body>
277277- <div class="tv-wrapper">
278278- <div class="tv">
279279- <div class="screen-bezel">
280280- <div class="screen" id="screen">
281281- <video id="video" controls></video>
282282- <audio id="audio" preload="none"></audio>
283283- <div class="screen-glare"></div>
284284-285285- <div class="screen-flash" id="flash"></div>
286286- <div class="channel-overlay" id="channelOverlay">
287287- <div class="channel-number" id="channelNumber">
288288- CH 00
289289- </div>
290290- <a
291291- class="channel-title"
292292- id="channelTitle"
293293- target="_blank"
294294- rel="noopener"
295295- ></a>
296296- </div>
297297- <div class="loading-indicator" id="loadingIndicator">
298298- TUNING...
299299- </div>
300300- <div class="muted-indicator" id="mutedIndicator">
301301- LOADING SOUND ///
302302- </div>
303303- <div class="standby" id="standby">
304304- <div class="standby-text">ATmosphereConf 2026</div>
305305- </div>
306306- </div>
307307- </div>
308308-309309- <div id="Video List" class="video-list">
310310- <div class="video-list-header">
311311- <h3>
312312- Available Videos
313313- <span id="videoCounter">Loading...</span>
314314- </h3>
315315- </div>
316316- <div class="video-list-container" id="videoListContainer">
317317- <!-- Video items will be inserted here -->
318318- </div>
319319- </div>
320320- </div>
321321-322322- <a
323323- class="source-link"
324324- href="https://tangled.org/timryan.org/atmosphereconf2026"
325325- target="_blank"
326326- rel="noopener"
327327- >View Source</a
328328- >
329329- </div>
330330-331331- <div class="safari-warning" id="safariWarning">
332332- ⚠ Desktop Safari isn't supported yet — try Firefox or Chrome for the
333333- best experience
334334- <button
335335- class="safari-warning-close"
336336- id="safariWarningClose"
337337- aria-label="Dismiss"
338338- >
339339- ✕
340340- </button>
341341- </div>
342342-343343- <script>
344344- // Desktop Safari detection: Safari UA without mobile indicators
345345- (function () {
346346- var ua = navigator.userAgent;
347347- var isSafari =
348348- /Safari/.test(ua) &&
349349- !/Chrome|Chromium|CriOS|FxiOS|EdgA|Edg/.test(ua);
350350- var isMobile =
351351- /iPhone|iPad|iPod|Android/.test(ua) ||
352352- (navigator.maxTouchPoints > 1 && /Macintosh/.test(ua));
353353- if (isSafari && !isMobile) {
354354- document
355355- .getElementById("safariWarning")
356356- .classList.add("visible");
357357- document
358358- .getElementById("safariWarningClose")
359359- .addEventListener("click", function () {
360360- document
361361- .getElementById("safariWarning")
362362- .classList.remove("visible");
363363- });
364364- }
365365- })();
366366- </script>
367367- </body>
126126+`),l=[],h=e?hu(e.baseTime,e.timescale):0;let u="00:00.000",d=0,f=0,g,p=!0;o.oncue=function(y){const E=t[s];let T=t.ccOffset;const S=(d-h)/9e4;if(E!=null&&E.new&&(f!==void 0?T=t.ccOffset=E.start:rf(t,s,S)),S){if(!e){g=new Error("Missing initPTS for VTT MPEGTS");return}T=S-t.presentationOffset}const v=y.endTime-y.startTime,x=be((y.startTime+T-f)*9e4,i*9e4)/9e4;y.startTime=Math.max(x,0),y.endTime=Math.max(x+v,0);const D=y.text.trim();y.text=decodeURIComponent(encodeURIComponent(D)),y.id||(y.id=mr(y.startTime,y.endTime,D)),y.endTime>0&&l.push(y)},o.onparsingerror=function(y){g=y},o.onflush=function(){if(g){a(g);return}r(l)},c.forEach(y=>{if(p)if(ci(y,"X-TIMESTAMP-MAP=")){p=!1,y.slice(16).split(",").forEach(E=>{ci(E,"LOCAL:")?u=E.slice(6):ci(E,"MPEGTS:")&&(d=parseInt(E.slice(7)))});try{f=sf(u)/1e3}catch(E){g=E}return}else y===""&&(p=!1);o.parse(y+`
127127+`)}),o.flush()}const hi="stpp.ttml.im1t",Ho=/^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/,Wo=/^(\d*(?:\.\d*)?)(h|m|s|ms|f|t)$/,af={left:"start",center:"center",right:"end",start:"start",end:"end"};function Kn(n,e,t,s){const i=z(new Uint8Array(n),["mdat"]);if(i.length===0){s(new Error("Could not parse IMSC1 mdat"));return}const r=i.map(o=>Ce(o)),a=cu(e.baseTime,1,e.timescale);try{r.forEach(o=>t(of(o,a)))}catch(o){s(o)}}function of(n,e){const i=new DOMParser().parseFromString(n,"text/xml").getElementsByTagName("tt")[0];if(!i)throw new Error("Invalid ttml");const r={frameRate:30,subFrameRate:1,frameRateMultiplier:0,tickRate:0},a=Object.keys(r).reduce((u,d)=>(u[d]=i.getAttribute(`ttp:${d}`)||r[d],u),{}),o=i.getAttribute("xml:space")!=="preserve",c=Vn(ui(i,"styling","style")),l=Vn(ui(i,"layout","region")),h=ui(i,"body","[begin]");return[].map.call(h,u=>{const d=Yo(u,o);if(!d||!u.hasAttribute("begin"))return null;const f=fi(u.getAttribute("begin"),a),g=fi(u.getAttribute("dur"),a);let p=fi(u.getAttribute("end"),a);if(f===null)throw Hn(u);if(p===null){if(g===null)throw Hn(u);p=f+g}const y=new gr(f-e,p-e,d);y.id=mr(y.startTime,y.endTime,y.text);const E=l[u.getAttribute("region")],T=c[u.getAttribute("style")],S=lf(E,T,c),{textAlign:v}=S;if(v){const x=af[v];x&&(y.lineAlign=x),y.align=v}return re(y,S),y}).filter(u=>u!==null)}function ui(n,e,t){const s=n.getElementsByTagName(e)[0];return s?[].slice.call(s.querySelectorAll(t)):[]}function Vn(n){return n.reduce((e,t)=>{const s=t.getAttribute("xml:id");return s&&(e[s]=t),e},{})}function Yo(n,e){return[].slice.call(n.childNodes).reduce((t,s,i)=>{var r;return s.nodeName==="br"&&i?t+`
128128+`:(r=s.childNodes)!=null&&r.length?Yo(s,e):e?t+s.textContent.trim().replace(/\s+/g," "):t+s.textContent},"")}function lf(n,e,t){const s="http://www.w3.org/ns/ttml#styling";let i=null;const r=["displayAlign","textAlign","color","backgroundColor","fontSize","fontFamily"],a=n!=null&&n.hasAttribute("style")?n.getAttribute("style"):null;return a&&t.hasOwnProperty(a)&&(i=t[a]),r.reduce((o,c)=>{const l=di(e,s,c)||di(n,s,c)||di(i,s,c);return l&&(o[c]=l),o},{})}function di(n,e,t){return n&&n.hasAttributeNS(e,t)?n.getAttributeNS(e,t):null}function Hn(n){return new Error(`Could not parse ttml timestamp ${n}`)}function fi(n,e){if(!n)return null;let t=Go(n);return t===null&&(Ho.test(n)?t=cf(n,e):Wo.test(n)&&(t=hf(n,e))),t}function cf(n,e){const t=Ho.exec(n),s=(t[4]|0)+(t[5]|0)/e.subFrameRate;return(t[1]|0)*3600+(t[2]|0)*60+(t[3]|0)+s/e.frameRate}function hf(n,e){const t=Wo.exec(n),s=Number(t[1]);switch(t[2]){case"h":return s*3600;case"m":return s*60;case"ms":return s*1e3;case"f":return s/e.frameRate;case"t":return s/e.tickRate}return s}class cs{constructor(e,t){this.timelineController=void 0,this.cueRanges=[],this.trackName=void 0,this.startTime=null,this.endTime=null,this.screen=null,this.timelineController=e,this.trackName=t}dispatchCue(){this.startTime!==null&&(this.timelineController.addCues(this.trackName,this.startTime,this.endTime,this.screen,this.cueRanges),this.startTime=null)}newCue(e,t,s){(this.startTime===null||this.startTime>e)&&(this.startTime=e),this.endTime=t,this.screen=s,this.timelineController.createCaptionsTrack(this.trackName)}reset(){this.cueRanges=[],this.startTime=null}}class uf{constructor(e){this.hls=void 0,this.media=null,this.config=void 0,this.enabled=!0,this.Cues=void 0,this.textTracks=[],this.tracks=[],this.initPTS=[],this.unparsedVttFrags=[],this.captionsTracks={},this.nonNativeCaptionsTracks={},this.cea608Parser1=void 0,this.cea608Parser2=void 0,this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs=Yn(),this.captionsProperties=void 0,this.hls=e,this.config=e.config,this.Cues=e.config.cueHandler,this.captionsProperties={textTrack1:{label:this.config.captionsTextTrack1Label,languageCode:this.config.captionsTextTrack1LanguageCode},textTrack2:{label:this.config.captionsTextTrack2Label,languageCode:this.config.captionsTextTrack2LanguageCode},textTrack3:{label:this.config.captionsTextTrack3Label,languageCode:this.config.captionsTextTrack3LanguageCode},textTrack4:{label:this.config.captionsTextTrack4Label,languageCode:this.config.captionsTextTrack4LanguageCode}},e.on(m.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(m.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(m.MANIFEST_LOADING,this.onManifestLoading,this),e.on(m.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(m.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(m.FRAG_LOADING,this.onFragLoading,this),e.on(m.FRAG_LOADED,this.onFragLoaded,this),e.on(m.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.on(m.FRAG_DECRYPTED,this.onFragDecrypted,this),e.on(m.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(m.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.on(m.BUFFER_FLUSHING,this.onBufferFlushing,this)}destroy(){const{hls:e}=this;e.off(m.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(m.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(m.MANIFEST_LOADING,this.onManifestLoading,this),e.off(m.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(m.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(m.FRAG_LOADING,this.onFragLoading,this),e.off(m.FRAG_LOADED,this.onFragLoaded,this),e.off(m.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.off(m.FRAG_DECRYPTED,this.onFragDecrypted,this),e.off(m.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(m.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.off(m.BUFFER_FLUSHING,this.onBufferFlushing,this),this.hls=this.config=this.media=null,this.cea608Parser1=this.cea608Parser2=void 0}initCea608Parsers(){const e=new cs(this,"textTrack1"),t=new cs(this,"textTrack2"),s=new cs(this,"textTrack3"),i=new cs(this,"textTrack4");this.cea608Parser1=new Gn(1,e,t),this.cea608Parser2=new Gn(3,s,i)}addCues(e,t,s,i,r){let a=!1;for(let o=r.length;o--;){const c=r[o],l=df(c[0],c[1],t,s);if(l>=0&&(c[0]=Math.min(c[0],t),c[1]=Math.max(c[1],s),a=!0,l/(s-t)>.5))return}if(a||r.push([t,s]),this.config.renderTextTracksNatively){const o=this.captionsTracks[e];this.Cues.newCue(o,t,s,i)}else{const o=this.Cues.newCue(null,t,s,i);this.hls.trigger(m.CUES_PARSED,{type:"captions",cues:o,track:e})}}onInitPtsFound(e,{frag:t,id:s,initPTS:i,timescale:r,trackId:a}){const{unparsedVttFrags:o}=this;s===U.MAIN&&(this.initPTS[t.cc]={baseTime:i,timescale:r,trackId:a}),o.length&&(this.unparsedVttFrags=[],o.forEach(c=>{this.initPTS[c.frag.cc]?this.onFragLoaded(m.FRAG_LOADED,c):this.hls.trigger(m.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:c.frag,error:new Error("Subtitle discontinuity domain does not match main")})}))}getExistingTrack(e,t){const{media:s}=this;if(s)for(let i=0;i<s.textTracks.length;i++){const r=s.textTracks[i];if(Wn(r,{name:e,lang:t,characteristics:"transcribes-spoken-dialog,describes-music-and-sound"}))return r}return null}createCaptionsTrack(e){this.config.renderTextTracksNatively?this.createNativeTrack(e):this.createNonNativeTrack(e)}createNativeTrack(e){if(this.captionsTracks[e])return;const{captionsProperties:t,captionsTracks:s,media:i}=this,{label:r,languageCode:a}=t[e],o=this.getExistingTrack(r,a);if(o)s[e]=o,At(s[e]),Mo(s[e],i);else{const c=this.createTextTrack("captions",r,a);c&&(c[e]=!0,s[e]=c)}}createNonNativeTrack(e){if(this.nonNativeCaptionsTracks[e])return;const t=this.captionsProperties[e];if(!t)return;const s=t.label,i={_id:e,label:s,kind:"captions",default:t.media?!!t.media.default:!1,closedCaptions:t.media};this.nonNativeCaptionsTracks[e]=i,this.hls.trigger(m.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:[i]})}createTextTrack(e,t,s){const i=this.media;if(i)return i.addTextTrack(e,t,s)}onMediaAttaching(e,t){this.media=t.media,t.mediaSource||this._cleanTracks()}onMediaDetaching(e,t){const s=!!t.transferMedia;if(this.media=null,s)return;const{captionsTracks:i}=this;Object.keys(i).forEach(r=>{At(i[r]),delete i[r]}),this.nonNativeCaptionsTracks={}}onManifestLoading(){this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs=Yn(),this._cleanTracks(),this.tracks=[],this.captionsTracks={},this.nonNativeCaptionsTracks={},this.textTracks=[],this.unparsedVttFrags=[],this.initPTS=[],this.cea608Parser1&&this.cea608Parser2&&(this.cea608Parser1.reset(),this.cea608Parser2.reset())}_cleanTracks(){const{media:e}=this;if(!e)return;const t=e.textTracks;if(t)for(let s=0;s<t.length;s++)At(t[s])}onSubtitleTracksUpdated(e,t){const s=t.subtitleTracks||[],i=s.some(r=>r.textCodec===hi);if(this.config.enableWebVTT||i&&this.config.enableIMSC1){if(Ao(this.tracks,s)){this.tracks=s;return}if(this.textTracks=[],this.tracks=s,this.config.renderTextTracksNatively){const a=this.media,o=a?vs(a.textTracks):null;if(this.tracks.forEach((c,l)=>{let h;if(o){let u=null;for(let d=0;d<o.length;d++)if(o[d]&&Wn(o[d],c)){u=o[d],o[d]=null;break}u&&(h=u)}if(h)At(h);else{const u=qo(c);h=this.createTextTrack(u,c.name,c.lang),h&&(h.mode="disabled")}h&&this.textTracks.push(h)}),o!=null&&o.length){const c=o.filter(l=>l!==null).map(l=>l.label);c.length&&this.hls.logger.warn(`Media element contains unused subtitle tracks: ${c.join(", ")}. Replace media element for each source to clear TextTracks and captions menu.`)}}else if(this.tracks.length){const a=this.tracks.map(o=>({label:o.name,kind:o.type.toLowerCase(),default:o.default,subtitleTrack:o}));this.hls.trigger(m.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:a})}}}onManifestLoaded(e,t){this.config.enableCEA708Captions&&t.captions&&t.captions.forEach(s=>{const i=/(?:CC|SERVICE)([1-4])/.exec(s.instreamId);if(!i)return;const r=`textTrack${i[1]}`,a=this.captionsProperties[r];a&&(a.label=s.name,s.lang&&(a.languageCode=s.lang),a.media=s)})}closedCaptionsForLevel(e){const t=this.hls.levels[e.level];return t==null?void 0:t.attrs["CLOSED-CAPTIONS"]}onFragLoading(e,t){if(this.enabled&&t.frag.type===U.MAIN){var s,i;const{cea608Parser1:r,cea608Parser2:a,lastSn:o}=this,{cc:c,sn:l}=t.frag,h=(s=(i=t.part)==null?void 0:i.index)!=null?s:-1;r&&a&&(l!==o+1||l===o&&h!==this.lastPartIndex+1||c!==this.lastCc)&&(r.reset(),a.reset()),this.lastCc=c,this.lastSn=l,this.lastPartIndex=h}}onFragLoaded(e,t){const{frag:s,payload:i}=t;if(s.type===U.SUBTITLE)if(i.byteLength){const r=s.decryptdata,a="stats"in t;if(r==null||!r.encrypted||a){const o=this.tracks[s.level],c=this.vttCCs;c[s.cc]||(c[s.cc]={start:s.start,prevCC:this.prevCC,new:!0},this.prevCC=s.cc),o&&o.textCodec===hi?this._parseIMSC1(s,i):this._parseVTTs(t)}}else this.hls.trigger(m.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:s,error:new Error("Empty subtitle payload")})}_parseIMSC1(e,t){const s=this.hls;Kn(t,this.initPTS[e.cc],i=>{this._appendCues(i,e.level),s.trigger(m.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:e})},i=>{s.logger.log(`Failed to parse IMSC1: ${i}`),s.trigger(m.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:e,error:i})})}_parseVTTs(e){var t;const{frag:s,payload:i}=e,{initPTS:r,unparsedVttFrags:a}=this,o=r.length-1;if(!r[s.cc]&&o===-1){a.push(e);return}const c=this.hls,l=(t=s.initSegment)!=null&&t.data?Oe(s.initSegment.data,new Uint8Array(i)).buffer:i;nf(l,this.initPTS[s.cc],this.vttCCs,s.cc,s.start,h=>{this._appendCues(h,s.level),c.trigger(m.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:s})},h=>{const u=h.message==="Missing initPTS for VTT MPEGTS";u?a.push(e):this._fallbackToIMSC1(s,i),c.logger.log(`Failed to parse VTT cue: ${h}`),!(u&&o>s.cc)&&c.trigger(m.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:s,error:h})})}_fallbackToIMSC1(e,t){const s=this.tracks[e.level];s.textCodec||Kn(t,this.initPTS[e.cc],()=>{s.textCodec=hi,this._parseIMSC1(e,t)},()=>{s.textCodec="wvtt"})}_appendCues(e,t){const s=this.hls;if(this.config.renderTextTracksNatively){const i=this.textTracks[t];if(!i||i.mode==="disabled")return;e.forEach(r=>No(i,r))}else{const i=this.tracks[t];if(!i)return;const r=i.default?"default":"subtitles"+t;s.trigger(m.CUES_PARSED,{type:"subtitles",cues:e,track:r})}}onFragDecrypted(e,t){const{frag:s}=t;s.type===U.SUBTITLE&&this.onFragLoaded(m.FRAG_LOADED,t)}onSubtitleTracksCleared(){this.tracks=[],this.captionsTracks={}}onFragParsingUserdata(e,t){if(!this.enabled||!this.config.enableCEA708Captions)return;const{frag:s,samples:i}=t;if(!(s.type===U.MAIN&&this.closedCaptionsForLevel(s)==="NONE"))for(let r=0;r<i.length;r++){const a=i[r].bytes;if(a){this.cea608Parser1||this.initCea608Parsers();const o=this.extractCea608Data(a);this.cea608Parser1.addData(i[r].pts,o[0]),this.cea608Parser2.addData(i[r].pts,o[1])}}}onBufferFlushing(e,{startOffset:t,endOffset:s,endOffsetSubtitles:i,type:r}){const{media:a}=this;if(!(!a||a.currentTime<s)){if(!r||r==="video"){const{captionsTracks:o}=this;Object.keys(o).forEach(c=>Bi(o[c],t,s))}if(this.config.renderTextTracksNatively&&t===0&&i!==void 0){const{textTracks:o}=this;Object.keys(o).forEach(c=>Bi(o[c],t,i))}}}extractCea608Data(e){const t=[[],[]],s=e[0]&31;let i=2;for(let r=0;r<s;r++){const a=e[i++],o=127&e[i++],c=127&e[i++];if(o===0&&c===0)continue;if((4&a)!==0){const h=3&a;(h===0||h===1)&&(t[h].push(o),t[h].push(c))}}return t}}function qo(n){return n.characteristics&&/transcribes-spoken-dialog/gi.test(n.characteristics)&&/describes-music-and-sound/gi.test(n.characteristics)?"captions":"subtitles"}function Wn(n,e){return!!n&&n.kind===qo(e)&&Oi(e,n)}function df(n,e,t,s){return Math.min(e,s)-Math.max(n,t)}function Yn(){return{ccOffset:0,presentationOffset:0,0:{start:0,prevCC:-1,new:!0}}}const ff=/\s/,gf={newCue(n,e,t,s){const i=[];let r,a,o,c,l;const h=self.VTTCue||self.TextTrackCue;for(let d=0;d<s.rows.length;d++)if(r=s.rows[d],o=!0,c=0,l="",!r.isEmpty()){var u;for(let p=0;p<r.chars.length;p++)ff.test(r.chars[p].uchar)&&o?c++:(l+=r.chars[p].uchar,o=!1);r.cueStartTime=e,e===t&&(t+=1e-4),c>=16?c--:c++;const f=Vo(l.trim()),g=mr(e,t,f);n!=null&&(u=n.cues)!=null&&u.getCueById(g)||(a=new h(e,t,f),a.id=g,a.line=d+1,a.align="left",a.position=10+Math.min(80,Math.floor(c*8/32)*10),i.push(a))}return n&&i.length&&(i.sort((d,f)=>d.line==="auto"||f.line==="auto"?0:d.line>8&&f.line>8?f.line-d.line:d.line-f.line),i.forEach(d=>No(n,d))),i}};function mf(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch{}return!1}const pf=/(\d+)-(\d+)\/(\d+)/;class qn{constructor(e){this.fetchSetup=void 0,this.requestTimeout=void 0,this.request=null,this.response=null,this.controller=void 0,this.context=null,this.config=null,this.callbacks=null,this.stats=void 0,this.loader=null,this.fetchSetup=e.fetchSetup||Sf,this.controller=new self.AbortController,this.stats=new qi}destroy(){this.loader=this.callbacks=this.context=this.config=this.request=null,this.abortInternal(),this.response=null,this.fetchSetup=this.controller=this.stats=null}abortInternal(){this.controller&&!this.stats.loading.end&&(this.stats.aborted=!0,this.controller.abort())}abort(){var e;this.abortInternal(),(e=this.callbacks)!=null&&e.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.response)}load(e,t,s){const i=this.stats;if(i.loading.start)throw new Error("Loader can only be used once.");i.loading.start=self.performance.now();const r=yf(e,this.controller.signal),a=e.responseType==="arraybuffer",o=a?"byteLength":"length",{maxTimeToFirstByteMs:c,maxLoadTimeMs:l}=t.loadPolicy;this.context=e,this.config=t,this.callbacks=s,this.request=this.fetchSetup(e,r),self.clearTimeout(this.requestTimeout),t.timeout=c&&M(c)?c:l,this.requestTimeout=self.setTimeout(()=>{this.callbacks&&(this.abortInternal(),this.callbacks.onTimeout(i,e,this.response))},t.timeout),(Wt(this.request)?this.request.then(self.fetch):self.fetch(this.request)).then(u=>{var d;this.response=this.loader=u;const f=Math.max(self.performance.now(),i.loading.start);if(self.clearTimeout(this.requestTimeout),t.timeout=l,this.requestTimeout=self.setTimeout(()=>{this.callbacks&&(this.abortInternal(),this.callbacks.onTimeout(i,e,this.response))},l-(f-i.loading.start)),!u.ok){const{status:p,statusText:y}=u;throw new vf(y||"fetch, bad network response",p,u)}i.loading.first=f,i.total=Tf(u.headers)||i.total;const g=(d=this.callbacks)==null?void 0:d.onProgress;return g&&M(t.highWaterMark)?this.loadProgressively(u,i,e,t.highWaterMark,g):a?u.arrayBuffer():e.responseType==="json"?u.json():u.text()}).then(u=>{var d,f;const g=this.response;if(!g)throw new Error("loader destroyed");self.clearTimeout(this.requestTimeout),i.loading.end=Math.max(self.performance.now(),i.loading.first);const p=u[o];p&&(i.loaded=i.total=p);const y={url:g.url,data:u,code:g.status},E=(d=this.callbacks)==null?void 0:d.onProgress;E&&!M(t.highWaterMark)&&E(i,e,u,g),(f=this.callbacks)==null||f.onSuccess(y,i,e,g)}).catch(u=>{var d;if(self.clearTimeout(this.requestTimeout),i.aborted)return;const f=u&&u.code||0,g=u?u.message:null;(d=this.callbacks)==null||d.onError({code:f,text:g},e,u?u.details:null,i)})}getCacheAge(){let e=null;if(this.response){const t=this.response.headers.get("age");e=t?parseFloat(t):null}return e}getResponseHeader(e){return this.response?this.response.headers.get(e):null}loadProgressively(e,t,s,i=0,r){const a=new so,o=e.body.getReader(),c=()=>o.read().then(l=>{if(l.done)return a.dataLength&&r(t,s,a.flush().buffer,e),Promise.resolve(new ArrayBuffer(0));const h=l.value,u=h.length;return t.loaded+=u,u<i||a.dataLength?(a.push(h),a.dataLength>=i&&r(t,s,a.flush().buffer,e)):r(t,s,h.buffer,e),c()}).catch(()=>Promise.reject());return c()}}function yf(n,e){const t={method:"GET",mode:"cors",credentials:"same-origin",signal:e,headers:new self.Headers(re({},n.headers))};return n.rangeEnd&&t.headers.set("Range","bytes="+n.rangeStart+"-"+String(n.rangeEnd-1)),t}function Ef(n){const e=pf.exec(n);if(e)return parseInt(e[2])-parseInt(e[1])+1}function Tf(n){const e=n.get("Content-Range");if(e){const s=Ef(e);if(M(s))return s}const t=n.get("Content-Length");if(t)return parseInt(t)}function Sf(n,e){return new self.Request(n.url,e)}class vf extends Error{constructor(e,t,s){super(e),this.code=void 0,this.details=void 0,this.code=t,this.details=s}}const xf=/^age:\s*[\d.]+\s*$/im;class jo{constructor(e){this.xhrSetup=void 0,this.requestTimeout=void 0,this.retryTimeout=void 0,this.retryDelay=void 0,this.config=null,this.callbacks=null,this.context=null,this.loader=null,this.stats=void 0,this.xhrSetup=e&&e.xhrSetup||null,this.stats=new qi,this.retryDelay=0}destroy(){this.callbacks=null,this.abortInternal(),this.loader=null,this.config=null,this.context=null,this.xhrSetup=null}abortInternal(){const e=this.loader;self.clearTimeout(this.requestTimeout),self.clearTimeout(this.retryTimeout),e&&(e.onreadystatechange=null,e.onprogress=null,e.readyState!==4&&(this.stats.aborted=!0,e.abort()))}abort(){var e;this.abortInternal(),(e=this.callbacks)!=null&&e.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.loader)}load(e,t,s){if(this.stats.loading.start)throw new Error("Loader can only be used once.");this.stats.loading.start=self.performance.now(),this.context=e,this.config=t,this.callbacks=s,this.loadInternal()}loadInternal(){const{config:e,context:t}=this;if(!e||!t)return;const s=this.loader=new self.XMLHttpRequest,i=this.stats;i.loading.first=0,i.loaded=0,i.aborted=!1;const r=this.xhrSetup;r?Promise.resolve().then(()=>{if(!(this.loader!==s||this.stats.aborted))return r(s,t.url)}).catch(a=>{if(!(this.loader!==s||this.stats.aborted))return s.open("GET",t.url,!0),r(s,t.url)}).then(()=>{this.loader!==s||this.stats.aborted||this.openAndSendXhr(s,t,e)}).catch(a=>{var o;(o=this.callbacks)==null||o.onError({code:s.status,text:a.message},t,s,i)}):this.openAndSendXhr(s,t,e)}openAndSendXhr(e,t,s){e.readyState||e.open("GET",t.url,!0);const i=t.headers,{maxTimeToFirstByteMs:r,maxLoadTimeMs:a}=s.loadPolicy;if(i)for(const o in i)e.setRequestHeader(o,i[o]);t.rangeEnd&&e.setRequestHeader("Range","bytes="+t.rangeStart+"-"+(t.rangeEnd-1)),e.onreadystatechange=this.readystatechange.bind(this),e.onprogress=this.loadprogress.bind(this),e.responseType=t.responseType,self.clearTimeout(this.requestTimeout),s.timeout=r&&M(r)?r:a,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),s.timeout),e.send()}readystatechange(){const{context:e,loader:t,stats:s}=this;if(!e||!t)return;const i=t.readyState,r=this.config;if(!s.aborted&&i>=2&&(s.loading.first===0&&(s.loading.first=Math.max(self.performance.now(),s.loading.start),r.timeout!==r.loadPolicy.maxLoadTimeMs&&(self.clearTimeout(this.requestTimeout),r.timeout=r.loadPolicy.maxLoadTimeMs,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),r.loadPolicy.maxLoadTimeMs-(s.loading.first-s.loading.start)))),i===4)){self.clearTimeout(this.requestTimeout),t.onreadystatechange=null,t.onprogress=null;const l=t.status,h=t.responseType==="text"?t.responseText:null;if(l>=200&&l<300){const g=h??t.response;if(g!=null){var a,o;s.loading.end=Math.max(self.performance.now(),s.loading.first);const p=t.responseType==="arraybuffer"?g.byteLength:g.length;s.loaded=s.total=p,s.bwEstimate=s.total*8e3/(s.loading.end-s.loading.first);const y=(a=this.callbacks)==null?void 0:a.onProgress;y&&y(s,e,g,t);const E={url:t.responseURL,data:g,code:l};(o=this.callbacks)==null||o.onSuccess(E,s,e,t);return}}const u=r.loadPolicy.errorRetry,d=s.retry,f={url:e.url,data:void 0,code:l};if(ws(u,d,!1,f))this.retry(u);else{var c;ie.error(`${l} while loading ${e.url}`),(c=this.callbacks)==null||c.onError({code:l,text:t.statusText},e,t,s)}}}loadtimeout(){if(!this.config)return;const e=this.config.loadPolicy.timeoutRetry,t=this.stats.retry;if(ws(e,t,!0))this.retry(e);else{var s;ie.warn(`timeout while loading ${(s=this.context)==null?void 0:s.url}`);const i=this.callbacks;i&&(this.abortInternal(),i.onTimeout(this.stats,this.context,this.loader))}}retry(e){const{context:t,stats:s}=this;this.retryDelay=Qi(e,s.retry),s.retry++,ie.warn(`${status?"HTTP Status "+status:"Timeout"} while loading ${t==null?void 0:t.url}, retrying ${s.retry}/${e.maxNumRetry} in ${this.retryDelay}ms`),this.abortInternal(),this.loader=null,self.clearTimeout(this.retryTimeout),this.retryTimeout=self.setTimeout(this.loadInternal.bind(this),this.retryDelay)}loadprogress(e){const t=this.stats;t.loaded=e.loaded,e.lengthComputable&&(t.total=e.total)}getCacheAge(){let e=null;if(this.loader&&xf.test(this.loader.getAllResponseHeaders())){const t=this.loader.getResponseHeader("age");e=t?parseFloat(t):null}return e}getResponseHeader(e){return this.loader&&new RegExp(`^${e}:\\s*[\\d.]+\\s*$`,"im").test(this.loader.getAllResponseHeaders())?this.loader.getResponseHeader(e):null}}const Af={maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:null,errorRetry:null},_f=se(se({autoStartLoad:!0,startPosition:-1,defaultAudioCodec:void 0,debug:!1,capLevelOnFPSDrop:!1,capLevelToPlayerSize:!1,ignoreDevicePixelRatio:!1,maxDevicePixelRatio:Number.POSITIVE_INFINITY,preferManagedMediaSource:!0,initialLiveManifestSize:1,maxBufferLength:30,backBufferLength:1/0,frontBufferFlushThreshold:1/0,startOnSegmentBoundary:!1,maxBufferSize:60*1e3*1e3,maxFragLookUpTolerance:.25,maxBufferHole:.1,detectStallWithCurrentTimeMs:1250,highBufferWatchdogPeriod:2,nudgeOffset:.1,nudgeMaxRetry:3,nudgeOnVideoHole:!0,liveSyncMode:"edge",liveSyncDurationCount:3,liveSyncOnStallIncrease:1,liveMaxLatencyDurationCount:1/0,liveSyncDuration:void 0,liveMaxLatencyDuration:void 0,maxLiveSyncPlaybackRate:1,liveDurationInfinity:!1,liveBackBufferLength:null,maxMaxBufferLength:600,enableWorker:!0,workerPath:null,enableSoftwareAES:!0,startLevel:void 0,startFragPrefetch:!1,fpsDroppedMonitoringPeriod:5e3,fpsDroppedMonitoringThreshold:.2,appendErrorMaxRetry:3,ignorePlaylistParsingErrors:!1,loader:jo,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,licenseXhrSetup:void 0,licenseResponseCallback:void 0,abrController:Fc,bufferController:Iu,capLevelController:ur,errorController:$c,fpsController:Ld,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:Wa,requireKeySystemAccessOnStart:!1,testBandwidth:!0,progressive:!1,lowLatencyMode:!0,cmcd:void 0,enableDateRangeMetadataCues:!0,enableEmsgMetadataCues:!0,enableEmsgKLVMetadata:!1,enableID3MetadataCues:!0,enableInterstitialPlayback:!0,interstitialAppendInPlace:!0,interstitialLiveLookAhead:10,useMediaCapabilities:!0,preserveManualLevelOnError:!1,certLoadPolicy:{default:Af},keyLoadPolicy:{default:{maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:2e4,backoff:"linear"},errorRetry:{maxNumRetry:8,retryDelayMs:1e3,maxRetryDelayMs:2e4,backoff:"linear"}}},manifestLoadPolicy:{default:{maxTimeToFirstByteMs:1/0,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},playlistLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:2,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},fragLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:12e4,timeoutRetry:{maxNumRetry:4,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:6,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},steeringManifestLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},interstitialAssetListLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:3e4,timeoutRetry:{maxNumRetry:0,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:0,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},manifestLoadingTimeOut:1e4,manifestLoadingMaxRetry:1,manifestLoadingRetryDelay:1e3,manifestLoadingMaxRetryTimeout:64e3,levelLoadingTimeOut:1e4,levelLoadingMaxRetry:4,levelLoadingRetryDelay:1e3,levelLoadingMaxRetryTimeout:64e3,fragLoadingTimeOut:2e4,fragLoadingMaxRetry:6,fragLoadingRetryDelay:1e3,fragLoadingMaxRetryTimeout:64e3},If()),{},{subtitleStreamController:Bd,subtitleTrackController:Dd,timelineController:uf,audioStreamController:vu,audioTrackController:xu,emeController:Lt,cmcdController:xd,contentSteeringController:_d,interstitialsController:Nd});function If(){return{cueHandler:gf,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 Lf(n,e,t){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(e.liveMaxLatencyDurationCount!==void 0&&(e.liveSyncDurationCount===void 0||e.liveMaxLatencyDurationCount<=e.liveSyncDurationCount))throw new Error('Illegal hls.js config: "liveMaxLatencyDurationCount" must be greater than "liveSyncDurationCount"');if(e.liveMaxLatencyDuration!==void 0&&(e.liveSyncDuration===void 0||e.liveMaxLatencyDuration<=e.liveSyncDuration))throw new Error('Illegal hls.js config: "liveMaxLatencyDuration" must be greater than "liveSyncDuration"');const s=$i(n),i=["manifest","level","frag"],r=["TimeOut","MaxRetry","RetryDelay","MaxRetryTimeout"];return i.forEach(a=>{const o=`${a==="level"?"playlist":a}LoadPolicy`,c=e[o]===void 0,l=[];r.forEach(h=>{const u=`${a}Loading${h}`,d=e[u];if(d!==void 0&&c){l.push(u);const f=s[o].default;switch(e[o]={default:f},h){case"TimeOut":f.maxLoadTimeMs=d,f.maxTimeToFirstByteMs=d;break;case"MaxRetry":f.errorRetry.maxNumRetry=d,f.timeoutRetry.maxNumRetry=d;break;case"RetryDelay":f.errorRetry.retryDelayMs=d,f.timeoutRetry.retryDelayMs=d;break;case"MaxRetryTimeout":f.errorRetry.maxRetryDelayMs=d,f.timeoutRetry.maxRetryDelayMs=d;break}}}),l.length&&t.warn(`hls.js config: "${l.join('", "')}" setting(s) are deprecated, use "${o}": ${oe(e[o])}`)}),se(se({},s),e)}function $i(n){return n&&typeof n=="object"?Array.isArray(n)?n.map($i):Object.keys(n).reduce((e,t)=>(e[t]=$i(n[t]),e),{}):n}function Rf(n,e){const t=n.loader;t!==qn&&t!==jo?(e.log("[config]: Custom loader detected, cannot enable progressive streaming"),n.progressive=!1):mf()&&(n.loader=qn,n.progressive=!0,n.enableSoftwareAES=!0,e.log("[config]: Progressive streaming enabled, using FetchLoader"))}const xs=2,bf=.1,Df=.05,Cf=100;class Pf extends $a{constructor(e,t){super("gap-controller",e.logger),this.hls=void 0,this.fragmentTracker=void 0,this.media=null,this.mediaSource=void 0,this.nudgeRetry=0,this.stallReported=!1,this.stalled=null,this.moved=!1,this.seeking=!1,this.buffered={},this.lastCurrentTime=0,this.ended=0,this.waiting=0,this.onMediaPlaying=()=>{this.ended=0,this.waiting=0},this.onMediaWaiting=()=>{var s;(s=this.media)!=null&&s.seeking||(this.waiting=self.performance.now(),this.tick())},this.onMediaEnded=()=>{if(this.hls){var s;this.ended=((s=this.media)==null?void 0:s.currentTime)||1,this.hls.trigger(m.MEDIA_ENDED,{stalled:!1})}},this.hls=e,this.fragmentTracker=t,this.registerListeners()}registerListeners(){const{hls:e}=this;e&&(e.on(m.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(m.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(m.BUFFER_APPENDED,this.onBufferAppended,this))}unregisterListeners(){const{hls:e}=this;e&&(e.off(m.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(m.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(m.BUFFER_APPENDED,this.onBufferAppended,this))}destroy(){super.destroy(),this.unregisterListeners(),this.media=this.hls=this.fragmentTracker=null,this.mediaSource=void 0}onMediaAttached(e,t){this.setInterval(Cf),this.mediaSource=t.mediaSource;const s=this.media=t.media;Ae(s,"playing",this.onMediaPlaying),Ae(s,"waiting",this.onMediaWaiting),Ae(s,"ended",this.onMediaEnded)}onMediaDetaching(e,t){this.clearInterval();const{media:s}=this;s&&(Ie(s,"playing",this.onMediaPlaying),Ie(s,"waiting",this.onMediaWaiting),Ie(s,"ended",this.onMediaEnded),this.media=null),this.mediaSource=void 0}onBufferAppended(e,t){this.buffered=t.timeRanges}get hasBuffered(){return Object.keys(this.buffered).length>0}tick(){var e;if(!((e=this.media)!=null&&e.readyState)||!this.hasBuffered)return;const t=this.media.currentTime;this.poll(t,this.lastCurrentTime),this.lastCurrentTime=t}poll(e,t){var s,i;const r=(s=this.hls)==null?void 0:s.config;if(!r)return;const a=this.media;if(!a)return;const{seeking:o}=a,c=this.seeking&&!o,l=!this.seeking&&o,h=a.paused&&!o||a.ended||a.playbackRate===0;if(this.seeking=o,e!==t){t&&(this.ended=0),this.moved=!0,o||(this.nudgeRetry=0,r.nudgeOnVideoHole&&!h&&e>t&&this.nudgeOnVideoHole(e,t)),this.waiting===0&&this.stallResolved(e);return}if(l||c){c&&this.stallResolved(e);return}if(h){this.nudgeRetry=0,this.stallResolved(e),!this.ended&&a.ended&&this.hls&&(this.ended=e||1,this.hls.trigger(m.MEDIA_ENDED,{stalled:!1}));return}if(!q.getBuffered(a).length){this.nudgeRetry=0;return}const u=q.bufferInfo(a,e,0),d=u.nextStart||0,f=this.fragmentTracker;if(o&&f&&this.hls){const D=jn(this.hls.inFlightFragments,e),A=u.len>xs,b=!d||D||d-e>xs&&!f.getPartialFragment(e);if(A||b)return;this.moved=!1}const g=(i=this.hls)==null?void 0:i.latestLevelDetails;if(!this.moved&&this.stalled!==null&&f){if(!(u.len>0)&&!d)return;const A=Math.max(d,u.start||0)-e,I=!!(g!=null&&g.live)?g.targetduration*2:xs,_=hs(e,f);if(A>0&&(A<=I||_)){a.paused||this._trySkipBufferHole(_);return}}const p=r.detectStallWithCurrentTimeMs,y=self.performance.now(),E=this.waiting;let T=this.stalled;if(T===null)if(E>0&&y-E<p)T=this.stalled=E;else{this.stalled=y;return}const S=y-T;if(!o&&(S>=p||E)&&this.hls){var v;if(((v=this.mediaSource)==null?void 0:v.readyState)==="ended"&&!(g!=null&&g.live)&&Math.abs(e-((g==null?void 0:g.edge)||0))<1){if(this.ended)return;this.ended=e||1,this.hls.trigger(m.MEDIA_ENDED,{stalled:!0});return}if(this._reportStall(u),!this.media||!this.hls)return}const x=q.bufferInfo(a,e,r.maxBufferHole);this._tryFixBufferStall(x,S,e)}stallResolved(e){const t=this.stalled;if(t&&this.hls&&(this.stalled=null,this.stallReported)){const s=self.performance.now()-t;this.log(`playback not stuck anymore @${e}, after ${Math.round(s)}ms`),this.stallReported=!1,this.waiting=0,this.hls.trigger(m.STALL_RESOLVED,{})}}nudgeOnVideoHole(e,t){var s;const i=this.buffered.video;if(this.hls&&this.media&&this.fragmentTracker&&(s=this.buffered.audio)!=null&&s.length&&i&&i.length>1&&e>i.end(0)){const r=q.bufferedInfo(q.timeRangesToArray(this.buffered.audio),e,0);if(r.len>1&&t>=r.start){const a=q.timeRangesToArray(i),o=q.bufferedInfo(a,t,0).bufferedIndex;if(o>-1&&o<a.length-1){const c=q.bufferedInfo(a,e,0).bufferedIndex,l=a[o].end,h=a[o+1].start;if((c===-1||c>o)&&h-l<1&&e-l<2){const u=new Error(`nudging playhead to flush pipeline after video hole. currentTime: ${e} hole: ${l} -> ${h} buffered index: ${c}`);this.warn(u.message),this.media.currentTime+=1e-6;let d=hs(e,this.fragmentTracker);d&&"fragment"in d?d=d.fragment:d||(d=void 0);const f=q.bufferInfo(this.media,e,0);this.hls.trigger(m.ERROR,{type:H.MEDIA_ERROR,details:R.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:u,reason:u.message,frag:d,buffer:f.len,bufferInfo:f})}}}}}_tryFixBufferStall(e,t,s){var i,r;const{fragmentTracker:a,media:o}=this,c=(i=this.hls)==null?void 0:i.config;if(!o||!a||!c)return;const l=(r=this.hls)==null?void 0:r.latestLevelDetails,h=hs(s,a);if((h||l!=null&&l.live&&s<l.fragmentStart)&&(this._trySkipBufferHole(h)||!this.media))return;const u=e.buffered,d=this.adjacentTraversal(e,s);(u&&u.length>1&&e.len>c.maxBufferHole||e.nextStart&&(e.nextStart-s<c.maxBufferHole||d))&&(t>c.highBufferWatchdogPeriod*1e3||this.waiting)&&(this.warn("Trying to nudge playhead over buffer-hole"),this._tryNudgeBuffer(e))}adjacentTraversal(e,t){const s=this.fragmentTracker,i=e.nextStart;if(s&&i){const r=s.getFragAtPos(t,U.MAIN),a=s.getFragAtPos(i,U.MAIN);if(r&&a)return a.sn-r.sn<2}return!1}_reportStall(e){const{hls:t,media:s,stallReported:i,stalled:r}=this;if(!i&&r!==null&&s&&t){this.stallReported=!0;const a=new Error(`Playback stalling at @${s.currentTime} due to low buffer (${oe(e)})`);this.warn(a.message),t.trigger(m.ERROR,{type:H.MEDIA_ERROR,details:R.BUFFER_STALLED_ERROR,fatal:!1,error:a,buffer:e.len,bufferInfo:e,stalled:{start:r}})}}_trySkipBufferHole(e){var t;const{fragmentTracker:s,media:i}=this,r=(t=this.hls)==null?void 0:t.config;if(!i||!s||!r)return 0;const a=i.currentTime,o=q.bufferInfo(i,a,0),c=a<o.start?o.start:o.nextStart;if(c&&this.hls){const h=o.len<=r.maxBufferHole,u=o.len>0&&o.len<1&&i.readyState<3,d=c-a;if(d>0&&(h||u)){if(d>r.maxBufferHole){let g=!1;if(a===0){const p=s.getAppendedFrag(0,U.MAIN);p&&c<p.end&&(g=!0)}if(!g&&e){var l;if(!((l=this.hls.loadLevelObj)!=null&&l.details)||jn(this.hls.inFlightFragments,c))return 0;let y=!1,E=e.end;for(;E<c;){const T=hs(E,s);if(T)E+=T.duration;else{y=!0;break}}if(y)return 0}}const f=Math.max(c+Df,a+bf);if(this.warn(`skipping hole, adjusting currentTime from ${a} to ${f}`),this.moved=!0,i.currentTime=f,!(e!=null&&e.gap)){const g=new Error(`fragment loaded with buffer holes, seeking from ${a} to ${f}`),p={type:H.MEDIA_ERROR,details:R.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:g,reason:g.message,buffer:o.len,bufferInfo:o};e&&("fragment"in e?p.part=e:p.frag=e),this.hls.trigger(m.ERROR,p)}return f}}return 0}_tryNudgeBuffer(e){const{hls:t,media:s,nudgeRetry:i}=this,r=t==null?void 0:t.config;if(!s||!r)return 0;const a=s.currentTime;if(this.nudgeRetry++,i<r.nudgeMaxRetry){const o=a+(i+1)*r.nudgeOffset,c=new Error(`Nudging 'currentTime' from ${a} to ${o}`);this.warn(c.message),s.currentTime=o,t.trigger(m.ERROR,{type:H.MEDIA_ERROR,details:R.BUFFER_NUDGE_ON_STALL,error:c,fatal:!1,buffer:e.len,bufferInfo:e})}else{const o=new Error(`Playhead still not moving while enough data buffered @${a} after ${r.nudgeMaxRetry} nudges`);this.error(o.message),t.trigger(m.ERROR,{type:H.MEDIA_ERROR,details:R.BUFFER_STALLED_ERROR,error:o,fatal:!0,buffer:e.len,bufferInfo:e})}}}function jn(n,e){const t=Xn(n.main);if(t&&t.start<=e)return t;const s=Xn(n.audio);return s&&s.start<=e?s:null}function Xn(n){if(!n)return null;switch(n.state){case P.IDLE:case P.STOPPED:case P.ENDED:case P.ERROR:return null}return n.frag}function hs(n,e){return e.getAppendedFrag(n,U.MAIN)||e.getPartialFragment(n)}const kf=.25;function Gi(){if(!(typeof self>"u"))return self.VTTCue||self.TextTrackCue}function gi(n,e,t,s,i){let r=new n(e,t,"");try{r.value=s,i&&(r.type=i)}catch{r=new n(e,t,oe(i?se({type:i},s):s))}return r}const us=(()=>{const n=Gi();try{n&&new n(0,Number.POSITIVE_INFINITY,"")}catch{return Number.MAX_VALUE}return Number.POSITIVE_INFINITY})();class wf{constructor(e){this.hls=void 0,this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.removeCues=!0,this.assetCue=void 0,this.onEventCueEnter=()=>{this.hls&&this.hls.trigger(m.EVENT_CUE_ENTER,{})},this.hls=e,this._registerListeners()}destroy(){this._unregisterListeners(),this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.hls=this.onEventCueEnter=null}_registerListeners(){const{hls:e}=this;e&&(e.on(m.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(m.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(m.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(m.MANIFEST_LOADING,this.onManifestLoading,this),e.on(m.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.on(m.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(m.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(m.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))}_unregisterListeners(){const{hls:e}=this;e&&(e.off(m.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(m.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(m.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(m.MANIFEST_LOADING,this.onManifestLoading,this),e.off(m.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.off(m.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(m.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(m.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))}onMediaAttaching(e,t){var s;this.media=t.media,((s=t.overrides)==null?void 0:s.cueRemoval)===!1&&(this.removeCues=!1)}onMediaAttached(){var e;const t=(e=this.hls)==null?void 0:e.latestLevelDetails;t&&this.updateDateRangeCues(t)}onMediaDetaching(e,t){this.media=null,!t.transferMedia&&(this.id3Track&&(this.removeCues&&At(this.id3Track,this.onEventCueEnter),this.id3Track=null),this.dateRangeCuesAppended={})}onManifestLoading(){this.dateRangeCuesAppended={}}createTrack(e){const t=this.getID3Track(e.textTracks);return t.mode="hidden",t}getID3Track(e){if(this.media){for(let t=0;t<e.length;t++){const s=e[t];if(s.kind==="metadata"&&s.label==="id3")return Mo(s,this.media),s}return this.media.addTextTrack("metadata","id3")}}onFragParsingMetadata(e,t){if(!this.media||!this.hls)return;const{enableEmsgMetadataCues:s,enableID3MetadataCues:i}=this.hls.config;if(!s&&!i)return;const{samples:r}=t;this.id3Track||(this.id3Track=this.createTrack(this.media));const a=Gi();if(a)for(let o=0;o<r.length;o++){const c=r[o].type;if(c===De.emsg&&!s||!i)continue;const l=co(r[o].data),h=r[o].pts;let u=h+r[o].duration;u>us&&(u=us),u-h<=0&&(u=h+kf);for(let f=0;f<l.length;f++){const g=l[f];if(!ho(g)){this.updateId3CueEnds(h,c);const p=gi(a,h,u,g,c);p&&this.id3Track.addCue(p)}}}}updateId3CueEnds(e,t){var s;const i=(s=this.id3Track)==null?void 0:s.cues;if(i)for(let r=i.length;r--;){const a=i[r];a.type===t&&a.startTime<e&&a.endTime===us&&(a.endTime=e)}}onBufferFlushing(e,{startOffset:t,endOffset:s,type:i}){const{id3Track:r,hls:a}=this;if(!a)return;const{config:{enableEmsgMetadataCues:o,enableID3MetadataCues:c}}=a;if(r&&(o||c)){let l;i==="audio"?l=h=>h.type===De.audioId3&&c:i==="video"?l=h=>h.type===De.emsg&&o:l=h=>h.type===De.audioId3&&c||h.type===De.emsg&&o,Bi(r,t,s,l)}}onLevelUpdated(e,{details:t}){this.updateDateRangeCues(t,!0)}onLevelPtsUpdated(e,t){Math.abs(t.drift)>.01&&this.updateDateRangeCues(t.details)}updateDateRangeCues(e,t){if(!this.hls||!this.media)return;const{assetPlayerId:s,timelineOffset:i,enableDateRangeMetadataCues:r,interstitialsController:a}=this.hls.config;if(!r)return;const o=Gi();if(s&&i&&!a){const{fragmentStart:p,fragmentEnd:y}=e;let E=this.assetCue;E?(E.startTime=p,E.endTime=y):o&&(E=this.assetCue=gi(o,p,y,{assetPlayerId:this.hls.config.assetPlayerId},"hlsjs.interstitial.asset"),E&&(E.id=s,this.id3Track||(this.id3Track=this.createTrack(this.media)),this.id3Track.addCue(E),E.addEventListener("enter",this.onEventCueEnter)))}if(!e.hasProgramDateTime)return;const{id3Track:c}=this,{dateRanges:l}=e,h=Object.keys(l);let u=this.dateRangeCuesAppended;if(c&&t){var d;if((d=c.cues)!=null&&d.length){const p=Object.keys(u).filter(y=>!h.includes(y));for(let y=p.length;y--;){var f;const E=p[y],T=(f=u[E])==null?void 0:f.cues;delete u[E],T&&Object.keys(T).forEach(S=>{const v=T[S];if(v){v.removeEventListener("enter",this.onEventCueEnter);try{c.removeCue(v)}catch{}}})}}else u=this.dateRangeCuesAppended={}}const g=e.fragments[e.fragments.length-1];if(!(h.length===0||!M(g==null?void 0:g.programDateTime))){this.id3Track||(this.id3Track=this.createTrack(this.media));for(let p=0;p<h.length;p++){const y=h[p],E=l[y],T=E.startTime,S=u[y],v=(S==null?void 0:S.cues)||{};let x=(S==null?void 0:S.durationKnown)||!1,D=us;const{duration:A,endDate:b}=E;if(b&&A!==null)D=T+A,x=!0;else if(E.endOnNext&&!x){const _=h.reduce((C,k)=>{if(k!==E.id){const B=l[k];if(B.class===E.class&&B.startDate>E.startDate&&(!C||E.startDate<C.startDate))return B}return C},null);_&&(D=_.startTime,x=!0)}const I=Object.keys(E.attr);for(let _=0;_<I.length;_++){const C=I[_];if(!Jc(C))continue;const k=v[C];if(k)x&&!(S!=null&&S.durationKnown)?k.endTime=D:Math.abs(k.startTime-T)>.01&&(k.startTime=T,k.endTime=D);else if(o){let B=E.attr[C];eh(C)&&(B=Sa(B));const $=gi(o,T,D,{key:C,data:B},De.dateRange);$&&($.id=y,this.id3Track.addCue($),v[C]=$,a&&(C==="X-ASSET-LIST"||C==="X-ASSET-URL")&&$.addEventListener("enter",this.onEventCueEnter))}}u[y]={cues:v,dateRange:E,durationKnown:x}}}}}class Of{constructor(e){this.hls=void 0,this.config=void 0,this.media=null,this.currentTime=0,this.stallCount=0,this._latency=null,this._targetLatencyUpdated=!1,this.onTimeupdate=()=>{const{media:t}=this,s=this.levelDetails;if(!t||!s)return;this.currentTime=t.currentTime;const i=this.computeLatency();if(i===null)return;this._latency=i;const{lowLatencyMode:r,maxLiveSyncPlaybackRate:a}=this.config;if(!r||a===1||!s.live)return;const o=this.targetLatency;if(o===null)return;const c=i-o,l=Math.min(this.maxLatency,o+s.targetduration);if(c<l&&c>.05&&this.forwardBufferLength>1){const u=Math.min(2,Math.max(1,a)),d=Math.round(2/(1+Math.exp(-.75*c-this.edgeStalled))*20)/20,f=Math.min(u,Math.max(1,d));this.changeMediaPlaybackRate(t,f)}else t.playbackRate!==1&&t.playbackRate!==0&&this.changeMediaPlaybackRate(t,1)},this.hls=e,this.config=e.config,this.registerListeners()}get levelDetails(){var e;return((e=this.hls)==null?void 0:e.latestLevelDetails)||null}get latency(){return this._latency||0}get maxLatency(){const{config:e}=this;if(e.liveMaxLatencyDuration!==void 0)return e.liveMaxLatencyDuration;const t=this.levelDetails;return t?e.liveMaxLatencyDurationCount*t.targetduration:0}get targetLatency(){const e=this.levelDetails;if(e===null||this.hls===null)return null;const{holdBack:t,partHoldBack:s,targetduration:i}=e,{liveSyncDuration:r,liveSyncDurationCount:a,lowLatencyMode:o}=this.config,c=this.hls.userConfig;let l=o&&s||t;(this._targetLatencyUpdated||c.liveSyncDuration||c.liveSyncDurationCount||l===0)&&(l=r!==void 0?r:a*i);const h=i;return l+Math.min(this.stallCount*this.config.liveSyncOnStallIncrease,h)}set targetLatency(e){this.stallCount=0,this.config.liveSyncDuration=e,this._targetLatencyUpdated=!0}get liveSyncPosition(){const e=this.estimateLiveEdge(),t=this.targetLatency;if(e===null||t===null)return null;const s=this.levelDetails;if(s===null)return null;const i=s.edge,r=e-t-this.edgeStalled,a=i-s.totalduration,o=i-(this.config.lowLatencyMode&&s.partTarget||s.targetduration);return Math.min(Math.max(a,r),o)}get drift(){const e=this.levelDetails;return e===null?1:e.drift}get edgeStalled(){const e=this.levelDetails;if(e===null)return 0;const t=(this.config.lowLatencyMode&&e.partTarget||e.targetduration)*3;return Math.max(e.age-t,0)}get forwardBufferLength(){const{media:e}=this,t=this.levelDetails;if(!e||!t)return 0;const s=e.buffered.length;return(s?e.buffered.end(s-1):t.edge)-this.currentTime}destroy(){this.unregisterListeners(),this.onMediaDetaching(),this.hls=null}registerListeners(){const{hls:e}=this;e&&(e.on(m.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(m.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(m.MANIFEST_LOADING,this.onManifestLoading,this),e.on(m.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(m.ERROR,this.onError,this))}unregisterListeners(){const{hls:e}=this;e&&(e.off(m.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(m.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(m.MANIFEST_LOADING,this.onManifestLoading,this),e.off(m.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(m.ERROR,this.onError,this))}onMediaAttached(e,t){this.media=t.media,this.media.addEventListener("timeupdate",this.onTimeupdate)}onMediaDetaching(){this.media&&(this.media.removeEventListener("timeupdate",this.onTimeupdate),this.media=null)}onManifestLoading(){this._latency=null,this.stallCount=0}onLevelUpdated(e,{details:t}){t.advanced&&this.onTimeupdate(),!t.live&&this.media&&this.media.removeEventListener("timeupdate",this.onTimeupdate)}onError(e,t){var s;t.details===R.BUFFER_STALLED_ERROR&&(this.stallCount++,this.hls&&(s=this.levelDetails)!=null&&s.live&&this.hls.logger.warn("[latency-controller]: Stall detected, adjusting target latency"))}changeMediaPlaybackRate(e,t){var s,i;e.playbackRate!==t&&((s=this.hls)==null||s.logger.debug(`[latency-controller]: latency=${this.latency.toFixed(3)}, targetLatency=${(i=this.targetLatency)==null?void 0:i.toFixed(3)}, forwardBufferLength=${this.forwardBufferLength.toFixed(3)}: adjusting playback rate from ${e.playbackRate} to ${t}`),e.playbackRate=t)}estimateLiveEdge(){const e=this.levelDetails;return e===null?null:e.edge+e.age}computeLatency(){const e=this.estimateLiveEdge();return e===null?null:e-this.currentTime}}class Ff extends hr{constructor(e,t){super(e,"level-controller"),this._levels=[],this._firstLevel=-1,this._maxAutoLevel=-1,this._startLevel=void 0,this.currentLevel=null,this.currentLevelIndex=-1,this.manualLevelIndex=-1,this.steering=void 0,this.onParsedComplete=void 0,this.steering=t,this._registerListeners()}_registerListeners(){const{hls:e}=this;e.on(m.MANIFEST_LOADING,this.onManifestLoading,this),e.on(m.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(m.LEVEL_LOADED,this.onLevelLoaded,this),e.on(m.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(m.FRAG_BUFFERED,this.onFragBuffered,this),e.on(m.ERROR,this.onError,this)}_unregisterListeners(){const{hls:e}=this;e.off(m.MANIFEST_LOADING,this.onManifestLoading,this),e.off(m.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(m.LEVEL_LOADED,this.onLevelLoaded,this),e.off(m.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(m.FRAG_BUFFERED,this.onFragBuffered,this),e.off(m.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(e,t){this.resetLevels()}onManifestLoaded(e,t){const s=this.hls.config.preferManagedMediaSource,i=[],r={},a={};let o=!1,c=!1,l=!1;t.levels.forEach(h=>{const u=h.attrs;let{audioCodec:d,videoCodec:f}=h;d&&(h.audioCodec=d=Ds(d,s)||void 0),f&&(f=h.videoCodec=pc(f));const{width:g,height:p,unknownCodecs:y}=h,E=(y==null?void 0:y.length)||0;if(o||(o=!!(g&&p)),c||(c=!!f),l||(l=!!d),E||d&&!this.isAudioSupported(d)||f&&!this.isVideoSupported(f)){this.log(`Some or all CODECS not supported "${u.CODECS}"`);return}const{CODECS:T,"FRAME-RATE":S,"HDCP-LEVEL":v,"PATHWAY-ID":x,RESOLUTION:D,"VIDEO-RANGE":A}=u,I=`${`${x||"."}-`}${h.bitrate}-${D}-${S}-${T}-${A}-${v}`;if(r[I])if(r[I].uri!==h.url&&!h.attrs["PATHWAY-ID"]){const _=a[I]+=1;h.attrs["PATHWAY-ID"]=new Array(_+1).join(".");const C=this.createLevel(h);r[I]=C,i.push(C)}else r[I].addGroupId("audio",u.AUDIO),r[I].addGroupId("text",u.SUBTITLES);else{const _=this.createLevel(h);r[I]=_,a[I]=1,i.push(_)}}),this.filterAndSortMediaOptions(i,t,o,c,l)}createLevel(e){const t=new Kt(e),s=e.supplemental;if(s!=null&&s.videoCodec&&!this.isVideoSupported(s.videoCodec)){const i=new Error(`SUPPLEMENTAL-CODECS not supported "${s.videoCodec}"`);this.log(i.message),t.supportedResult=ka(i,[])}return t}isAudioSupported(e){return $t(e,"audio",this.hls.config.preferManagedMediaSource)}isVideoSupported(e){return $t(e,"video",this.hls.config.preferManagedMediaSource)}filterAndSortMediaOptions(e,t,s,i,r){var a;let o=[],c=[],l=e;const h=((a=t.stats)==null?void 0:a.parsing)||{};if((s||i)&&r&&(l=l.filter(({videoCodec:T,videoRange:S,width:v,height:x})=>(!!T||!!(v&&x))&&Lc(S))),l.length===0){Promise.resolve().then(()=>{if(this.hls){let T="no level with compatible codecs found in manifest",S=T;t.levels.length&&(S=`one or more CODECS in variant not supported: ${oe(t.levels.map(x=>x.attrs.CODECS).filter((x,D,A)=>A.indexOf(x)===D))}`,this.warn(S),T+=` (${S})`);const v=new Error(T);this.hls.trigger(m.ERROR,{type:H.MEDIA_ERROR,details:R.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:t.url,error:v,reason:S})}}),h.end=performance.now();return}t.audioTracks&&(o=t.audioTracks.filter(T=>!T.audioCodec||this.isAudioSupported(T.audioCodec)),zn(o)),t.subtitles&&(c=t.subtitles,zn(c));const u=l.slice(0);l.sort((T,S)=>{if(T.attrs["HDCP-LEVEL"]!==S.attrs["HDCP-LEVEL"])return(T.attrs["HDCP-LEVEL"]||"")>(S.attrs["HDCP-LEVEL"]||"")?1:-1;if(s&&T.height!==S.height)return T.height-S.height;if(T.frameRate!==S.frameRate)return T.frameRate-S.frameRate;if(T.videoRange!==S.videoRange)return Cs.indexOf(T.videoRange)-Cs.indexOf(S.videoRange);if(T.videoCodec!==S.videoCodec){const v=$r(T.videoCodec),x=$r(S.videoCodec);if(v!==x)return x-v}if(T.uri===S.uri&&T.codecSet!==S.codecSet){const v=bs(T.codecSet),x=bs(S.codecSet);if(v!==x)return x-v}return T.averageBitrate!==S.averageBitrate?T.averageBitrate-S.averageBitrate:0});let d=u[0];if(this.steering&&(l=this.steering.filterParsedLevels(l),l.length!==u.length)){for(let T=0;T<u.length;T++)if(u[T].pathwayId===l[0].pathwayId){d=u[T];break}}this._levels=l;for(let T=0;T<l.length;T++)if(l[T]===d){var f;this._firstLevel=T;const S=d.bitrate,v=this.hls.bandwidthEstimate;if(this.log(`manifest loaded, ${l.length} level(s) found, first bitrate: ${S}`),((f=this.hls.userConfig)==null?void 0:f.abrEwmaDefaultEstimate)===void 0){const x=Math.min(S,this.hls.config.abrEwmaDefaultEstimateMax);x>v&&v===this.hls.abrEwmaDefaultEstimate&&(this.hls.bandwidthEstimate=x)}break}const g=r&&!i,p=this.hls.config,y=!!(p.audioStreamController&&p.audioTrackController),E={levels:l,audioTracks:o,subtitleTracks:c,sessionData:t.sessionData,sessionKeys:t.sessionKeys,firstLevel:this._firstLevel,stats:t.stats,audio:r,video:i,altAudio:y&&!g&&o.some(T=>!!T.url)};h.end=performance.now(),this.hls.trigger(m.MANIFEST_PARSED,E)}get levels(){return this._levels.length===0?null:this._levels}get loadLevelObj(){return this.currentLevel}get level(){return this.currentLevelIndex}set level(e){const t=this._levels;if(t.length===0)return;if(e<0||e>=t.length){const h=new Error("invalid level idx"),u=e<0;if(this.hls.trigger(m.ERROR,{type:H.OTHER_ERROR,details:R.LEVEL_SWITCH_ERROR,level:e,fatal:u,error:h,reason:h.message}),u)return;e=Math.min(e,t.length-1)}const s=this.currentLevelIndex,i=this.currentLevel,r=i?i.attrs["PATHWAY-ID"]:void 0,a=t[e],o=a.attrs["PATHWAY-ID"];if(this.currentLevelIndex=e,this.currentLevel=a,s===e&&i&&r===o)return;this.log(`Switching to level ${e} (${a.height?a.height+"p ":""}${a.videoRange?a.videoRange+" ":""}${a.codecSet?a.codecSet+" ":""}@${a.bitrate})${o?" with Pathway "+o:""} from level ${s}${r?" with Pathway "+r:""}`);const c={level:e,attrs:a.attrs,details:a.details,bitrate:a.bitrate,averageBitrate:a.averageBitrate,maxBitrate:a.maxBitrate,realBitrate:a.realBitrate,width:a.width,height:a.height,codecSet:a.codecSet,audioCodec:a.audioCodec,videoCodec:a.videoCodec,audioGroups:a.audioGroups,subtitleGroups:a.subtitleGroups,loaded:a.loaded,loadError:a.loadError,fragmentError:a.fragmentError,name:a.name,id:a.id,uri:a.uri,url:a.url,urlId:0,audioGroupIds:a.audioGroupIds,textGroupIds:a.textGroupIds};this.hls.trigger(m.LEVEL_SWITCHING,c);const l=a.details;if(!l||l.live){const h=this.switchParams(a.uri,i==null?void 0:i.details,l);this.loadPlaylist(h)}}get manualLevel(){return this.manualLevelIndex}set manualLevel(e){this.manualLevelIndex=e,this._startLevel===void 0&&(this._startLevel=e),e!==-1&&(this.level=e)}get firstLevel(){return this._firstLevel}set firstLevel(e){this._firstLevel=e}get startLevel(){if(this._startLevel===void 0){const e=this.hls.config.startLevel;return e!==void 0?e:this.hls.firstAutoLevel}return this._startLevel}set startLevel(e){this._startLevel=e}get pathways(){return this.steering?this.steering.pathways():[]}get pathwayPriority(){return this.steering?this.steering.pathwayPriority:null}set pathwayPriority(e){if(this.steering){const t=this.steering.pathways(),s=e.filter(i=>t.indexOf(i)!==-1);if(e.length<1){this.warn(`pathwayPriority ${e} should contain at least one pathway from list: ${t}`);return}this.steering.pathwayPriority=s}}onError(e,t){t.fatal||!t.context||t.context.type===Q.LEVEL&&t.context.level===this.level&&this.checkRetry(t)}onFragBuffered(e,{frag:t}){if(t!==void 0&&t.type===U.MAIN){const s=t.elementaryStreams;if(!Object.keys(s).some(r=>!!s[r]))return;const i=this._levels[t.level];i!=null&&i.loadError&&(this.log(`Resetting level error count of ${i.loadError} on frag buffered`),i.loadError=0)}}onLevelLoaded(e,t){var s;const{level:i,details:r}=t,a=t.levelInfo;if(!a){var o;this.warn(`Invalid level index ${i}`),(o=t.deliveryDirectives)!=null&&o.skip&&(r.deltaUpdateFailed=!0);return}if(a===this.currentLevel||t.withoutMultiVariant){a.fragmentError===0&&(a.loadError=0);let c=a.details;c===t.details&&c.advanced&&(c=void 0),this.playlistLoaded(i,t,c)}else(s=t.deliveryDirectives)!=null&&s.skip&&(r.deltaUpdateFailed=!0)}loadPlaylist(e){super.loadPlaylist(),this.shouldLoadPlaylist(this.currentLevel)&&this.scheduleLoading(this.currentLevel,e)}loadingPlaylist(e,t){super.loadingPlaylist(e,t);const s=this.getUrlWithDirectives(e.uri,t),i=this.currentLevelIndex,r=e.attrs["PATHWAY-ID"],a=e.details,o=a==null?void 0:a.age;this.log(`Loading level index ${i}${(t==null?void 0:t.msn)!==void 0?" at sn "+t.msn+" part "+t.part:""}${r?" Pathway "+r:""}${o&&a.live?" age "+o.toFixed(1)+(a.type&&" "+a.type||""):""} ${s}`),this.hls.trigger(m.LEVEL_LOADING,{url:s,level:i,levelInfo:e,pathwayId:e.attrs["PATHWAY-ID"],id:0,deliveryDirectives:t||null})}get nextLoadLevel(){return this.manualLevelIndex!==-1?this.manualLevelIndex:this.hls.nextAutoLevel}set nextLoadLevel(e){this.level=e,this.manualLevelIndex===-1&&(this.hls.nextAutoLevel=e)}removeLevel(e){var t;if(this._levels.length===1)return;const s=this._levels.filter((r,a)=>a!==e?!0:(this.steering&&this.steering.removeLevel(r),r===this.currentLevel&&(this.currentLevel=null,this.currentLevelIndex=-1,r.details&&r.details.fragments.forEach(o=>o.level=-1)),!1));Ja(s),this._levels=s,this.currentLevelIndex>-1&&(t=this.currentLevel)!=null&&t.details&&(this.currentLevelIndex=this.currentLevel.details.fragments[0].level),this.manualLevelIndex>-1&&(this.manualLevelIndex=this.currentLevelIndex);const i=s.length-1;this._firstLevel=Math.min(this._firstLevel,i),this._startLevel&&(this._startLevel=Math.min(this._startLevel,i)),this.hls.trigger(m.LEVELS_UPDATED,{levels:s})}onLevelsUpdated(e,{levels:t}){this._levels=t}checkMaxAutoUpdated(){const{autoLevelCapping:e,maxAutoLevel:t,maxHdcpLevel:s}=this.hls;this._maxAutoLevel!==t&&(this._maxAutoLevel=t,this.hls.trigger(m.MAX_AUTO_LEVEL_UPDATED,{autoLevelCapping:e,levels:this.levels,maxAutoLevel:t,minAutoLevel:this.hls.minAutoLevel,maxHdcpLevel:s}))}}function zn(n){const e={};n.forEach(t=>{const s=t.groupId||"";t.id=e[s]=e[s]||0,e[s]++})}function Xo(){return self.SourceBuffer||self.WebKitSourceBuffer}function zo(){if(!at())return!1;const e=Xo();return!e||e.prototype&&typeof e.prototype.appendBuffer=="function"&&typeof e.prototype.remove=="function"}function Mf(){if(!zo())return!1;const n=at();return typeof(n==null?void 0:n.isTypeSupported)=="function"&&(["avc1.42E01E,mp4a.40.2","av01.0.01M.08","vp09.00.50.08"].some(e=>n.isTypeSupported(Gt(e,"video")))||["mp4a.40.2","fLaC"].some(e=>n.isTypeSupported(Gt(e,"audio"))))}function Nf(){var n;const e=Xo();return typeof(e==null||(n=e.prototype)==null?void 0:n.changeType)=="function"}const Bf=100;class Uf extends sr{constructor(e,t,s){super(e,t,s,"stream-controller",U.MAIN),this.audioCodecSwap=!1,this.level=-1,this._forceStartLoad=!1,this._hasEnoughToStart=!1,this.altAudio=0,this.audioOnly=!1,this.fragPlaying=null,this.fragLastKbps=0,this.couldBacktrack=!1,this.backtrackFragment=null,this.audioCodecSwitch=!1,this.videoBuffer=null,this.onMediaPlaying=()=>{this.tick()},this.onMediaSeeked=()=>{const i=this.media,r=i?i.currentTime:null;if(r===null||!M(r)||(this.log(`Media seeked to ${r.toFixed(3)}`),!this.getBufferedFrag(r)))return;const a=this.getFwdBufferInfoAtPos(i,r,U.MAIN,0);if(a===null||a.len===0){this.warn(`Main forward buffer length at ${r} on "seeked" event ${a?a.len:"empty"})`);return}this.tick()},this.registerListeners()}registerListeners(){super.registerListeners();const{hls:e}=this;e.on(m.MANIFEST_PARSED,this.onManifestParsed,this),e.on(m.LEVEL_LOADING,this.onLevelLoading,this),e.on(m.LEVEL_LOADED,this.onLevelLoaded,this),e.on(m.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.on(m.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(m.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.on(m.BUFFER_CREATED,this.onBufferCreated,this),e.on(m.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(m.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(m.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){super.unregisterListeners();const{hls:e}=this;e.off(m.MANIFEST_PARSED,this.onManifestParsed,this),e.off(m.LEVEL_LOADED,this.onLevelLoaded,this),e.off(m.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.off(m.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(m.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.off(m.BUFFER_CREATED,this.onBufferCreated,this),e.off(m.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(m.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(m.FRAG_BUFFERED,this.onFragBuffered,this)}onHandlerDestroying(){this.onMediaPlaying=this.onMediaSeeked=null,this.unregisterListeners(),super.onHandlerDestroying()}startLoad(e,t){if(this.levels){const{lastCurrentTime:s,hls:i}=this;if(this.stopLoad(),this.setInterval(Bf),this.level=-1,!this.startFragRequested){let r=i.startLevel;r===-1&&(i.config.testBandwidth&&this.levels.length>1?(r=0,this.bitrateTest=!0):r=i.firstAutoLevel),i.nextLoadLevel=r,this.level=i.loadLevel,this._hasEnoughToStart=!!t}s>0&&e===-1&&!t&&(this.log(`Override startPosition with lastCurrentTime @${s.toFixed(3)}`),e=s),this.state=P.IDLE,this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,this.tick()}else this._forceStartLoad=!0,this.state=P.STOPPED}stopLoad(){this._forceStartLoad=!1,super.stopLoad()}doTick(){switch(this.state){case P.WAITING_LEVEL:{const{levels:e,level:t}=this,s=e==null?void 0:e[t],i=s==null?void 0:s.details;if(i&&(!i.live||this.levelLastLoaded===s&&!this.waitForLive(s))){if(this.waitForCdnTuneIn(i))break;this.state=P.IDLE;break}else if(this.hls.nextLoadLevel!==this.level){this.state=P.IDLE;break}break}case P.FRAG_LOADING_WAITING_RETRY:this.checkRetryDate();break}this.state===P.IDLE&&this.doTickIdle(),this.onTickEnd()}onTickEnd(){var e;super.onTickEnd(),(e=this.media)!=null&&e.readyState&&this.media.seeking===!1&&(this.lastCurrentTime=this.media.currentTime),this.checkFragmentChanged()}doTickIdle(){const{hls:e,levelLastLoaded:t,levels:s,media:i}=this;if(t===null||!i&&!this.primaryPrefetch&&(this.startFragRequested||!e.config.startFragPrefetch)||this.altAudio&&this.audioOnly)return;const r=this.buffering?e.nextLoadLevel:e.loadLevel;if(!(s!=null&&s[r]))return;const a=s[r],o=this.getMainFwdBufferInfo();if(o===null)return;const c=this.getLevelDetails();if(c&&this._streamEnded(o,c)){const p={};this.altAudio===2&&(p.type="video"),this.hls.trigger(m.BUFFER_EOS,p),this.state=P.ENDED;return}if(!this.buffering)return;e.loadLevel!==r&&e.manualLevel===-1&&this.log(`Adapting to level ${r} from level ${this.level}`),this.level=e.nextLoadLevel=r;const l=a.details;if(!l||this.state===P.WAITING_LEVEL||this.waitForLive(a)){this.level=r,this.state=P.WAITING_LEVEL,this.startFragRequested=!1;return}const h=o.len,u=this.getMaxBufferLength(a.maxBitrate);if(h>=u)return;this.backtrackFragment&&this.backtrackFragment.start>o.end&&(this.backtrackFragment=null);const d=this.backtrackFragment?this.backtrackFragment.start:o.end;let f=this.getNextFragment(d,l);if(this.couldBacktrack&&!this.fragPrevious&&f&&de(f)&&this.fragmentTracker.getState(f)!==me.OK){var g;const y=((g=this.backtrackFragment)!=null?g:f).sn-l.startSN,E=l.fragments[y-1];E&&f.cc===E.cc&&(f=E,this.fragmentTracker.removeFragment(E))}else this.backtrackFragment&&o.len&&(this.backtrackFragment=null);if(f&&this.isLoopLoading(f,d)){if(!f.gap){const y=this.audioOnly&&!this.altAudio?ne.AUDIO:ne.VIDEO,E=(y===ne.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;E&&this.afterBufferFlushed(E,y,U.MAIN)}f=this.getNextFragmentLoopLoading(f,l,o,U.MAIN,u)}f&&(f.initSegment&&!f.initSegment.data&&!this.bitrateTest&&(f=f.initSegment),this.loadFragment(f,a,d))}loadFragment(e,t,s){const i=this.fragmentTracker.getState(e);i===me.NOT_LOADED||i===me.PARTIAL?de(e)?this.bitrateTest?(this.log(`Fragment ${e.sn} of level ${e.level} is being downloaded to test bitrate and will not be buffered`),this._loadBitrateTestFrag(e,t)):super.loadFragment(e,t,s):this._loadInitSegment(e,t):this.clearTrackerIfNeeded(e)}getBufferedFrag(e){return this.fragmentTracker.getBufferedFrag(e,U.MAIN)}followingBufferedFrag(e){return e?this.getBufferedFrag(e.end+.5):null}immediateLevelSwitch(){this.abortCurrentFrag(),this.flushMainBuffer(0,Number.POSITIVE_INFINITY)}nextLevelSwitch(){const{levels:e,media:t}=this;if(t!=null&&t.readyState){let s;const i=this.getAppendedFrag(t.currentTime);i&&i.start>1&&this.flushMainBuffer(0,i.start-1);const r=this.getLevelDetails();if(r!=null&&r.live){const o=this.getMainFwdBufferInfo();if(!o||o.len<r.targetduration*2)return}if(!t.paused&&e){const o=this.hls.nextLoadLevel,c=e[o],l=this.fragLastKbps;l&&this.fragCurrent?s=this.fragCurrent.duration*c.maxBitrate/(1e3*l)+1:s=0}else s=0;const a=this.getBufferedFrag(t.currentTime+s);if(a){const o=this.followingBufferedFrag(a);if(o){this.abortCurrentFrag();const c=o.maxStartPTS?o.maxStartPTS:o.start,l=o.duration,h=Math.max(a.end,c+Math.min(Math.max(l-this.config.maxFragLookUpTolerance,l*(this.couldBacktrack?.5:.125)),l*(this.couldBacktrack?.75:.25)));this.flushMainBuffer(h,Number.POSITIVE_INFINITY)}}}}abortCurrentFrag(){const e=this.fragCurrent;switch(this.fragCurrent=null,this.backtrackFragment=null,e&&(e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.state){case P.KEY_LOADING:case P.FRAG_LOADING:case P.FRAG_LOADING_WAITING_RETRY:case P.PARSING:case P.PARSED:this.state=P.IDLE;break}this.nextLoadPosition=this.getLoadPosition()}flushMainBuffer(e,t){super.flushMainBuffer(e,t,this.altAudio===2?"video":null)}onMediaAttached(e,t){super.onMediaAttached(e,t);const s=t.media;Ae(s,"playing",this.onMediaPlaying),Ae(s,"seeked",this.onMediaSeeked)}onMediaDetaching(e,t){const{media:s}=this;s&&(Ie(s,"playing",this.onMediaPlaying),Ie(s,"seeked",this.onMediaSeeked)),this.videoBuffer=null,this.fragPlaying=null,super.onMediaDetaching(e,t),!t.transferMedia&&(this._hasEnoughToStart=!1)}onManifestLoading(){super.onManifestLoading(),this.log("Trigger BUFFER_RESET"),this.hls.trigger(m.BUFFER_RESET,void 0),this.couldBacktrack=!1,this.fragLastKbps=0,this.fragPlaying=this.backtrackFragment=null,this.altAudio=0,this.audioOnly=!1}onManifestParsed(e,t){let s=!1,i=!1;for(let r=0;r<t.levels.length;r++){const a=t.levels[r].audioCodec;a&&(s=s||a.indexOf("mp4a.40.2")!==-1,i=i||a.indexOf("mp4a.40.5")!==-1)}this.audioCodecSwitch=s&&i&&!Nf(),this.audioCodecSwitch&&this.log("Both AAC/HE-AAC audio found in levels; declaring level codec as HE-AAC"),this.levels=t.levels,this.startFragRequested=!1}onLevelLoading(e,t){const{levels:s}=this;if(!s||this.state!==P.IDLE)return;const i=t.levelInfo;(!i.details||i.details.live&&(this.levelLastLoaded!==i||i.details.expired)||this.waitForCdnTuneIn(i.details))&&(this.state=P.WAITING_LEVEL)}onLevelLoaded(e,t){var s;const{levels:i,startFragRequested:r}=this,a=t.level,o=t.details,c=o.totalduration;if(!i){this.warn(`Levels were reset while loading level ${a}`);return}this.log(`Level ${a} loaded [${o.startSN},${o.endSN}]${o.lastPartSn?`[part-${o.lastPartSn}-${o.lastPartIndex}]`:""}, cc [${o.startCC}, ${o.endCC}] duration:${c}`);const l=t.levelInfo,h=this.fragCurrent;h&&(this.state===P.FRAG_LOADING||this.state===P.FRAG_LOADING_WAITING_RETRY)&&h.level!==t.level&&h.loader&&this.abortCurrentFrag();let u=0;if(o.live||(s=l.details)!=null&&s.live){var d;if(this.checkLiveUpdate(o),o.deltaUpdateFailed)return;u=this.alignPlaylists(o,l.details,(d=this.levelLastLoaded)==null?void 0:d.details)}if(l.details=o,this.levelLastLoaded=l,r||this.setStartPosition(o,u),this.hls.trigger(m.LEVEL_UPDATED,{details:o,level:a}),this.state===P.WAITING_LEVEL){if(this.waitForCdnTuneIn(o))return;this.state=P.IDLE}r&&o.live&&this.synchronizeToLiveEdge(o),this.tick()}synchronizeToLiveEdge(e){const{config:t,media:s}=this;if(!s)return;const i=this.hls.liveSyncPosition,r=this.getLoadPosition(),a=e.fragmentStart,o=e.edge,c=r>=a-t.maxFragLookUpTolerance&&r<=o;if(i!==null&&s.duration>i&&(r<i||!c)){const h=t.liveMaxLatencyDuration!==void 0?t.liveMaxLatencyDuration:t.liveMaxLatencyDurationCount*e.targetduration;if((!c&&s.readyState<4||r<o-h)&&(this._hasEnoughToStart||(this.nextLoadPosition=i),s.readyState))if(this.warn(`Playback: ${r.toFixed(3)} is located too far from the end of live sliding playlist: ${o}, reset currentTime to : ${i.toFixed(3)}`),this.config.liveSyncMode==="buffered"){var l;const u=q.bufferInfo(s,i,0);if(!((l=u.buffered)!=null&&l.length)){s.currentTime=i;return}if(u.start<=r){s.currentTime=i;return}const{nextStart:f}=q.bufferedInfo(u.buffered,r,0);f&&(s.currentTime=f)}else s.currentTime=i}}_handleFragmentLoadProgress(e){var t;const s=e.frag,{part:i,payload:r}=e,{levels:a}=this;if(!a){this.warn(`Levels were reset while fragment load was in progress. Fragment ${s.sn} of level ${s.level} will not be buffered`);return}const o=a[s.level];if(!o){this.warn(`Level ${s.level} not found on progress`);return}const c=o.details;if(!c){this.warn(`Dropping fragment ${s.sn} of level ${s.level} after level details were reset`),this.fragmentTracker.removeFragment(s);return}const l=o.videoCodec,h=c.PTSKnown||!c.live,u=(t=s.initSegment)==null?void 0:t.data,d=this._getAudioCodec(o),f=this.transmuxer=this.transmuxer||new xo(this.hls,U.MAIN,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)),g=i?i.index:-1,p=g!==-1,y=new Ji(s.level,s.sn,s.stats.chunkCount,r.byteLength,g,p),E=this.initPTS[s.cc];f.push(r,u,d,l,s,i,c.totalduration,h,y,E)}onAudioTrackSwitching(e,t){const s=this.hls,i=this.altAudio!==0;if(Ps(t.url,s))this.altAudio=1;else{if(this.mediaBuffer!==this.media){this.log("Switching on main audio, use media.buffered to schedule main fragment loading"),this.mediaBuffer=this.media;const a=this.fragCurrent;a&&(this.log("Switching to main audio track, cancel main fragment load"),a.abortRequests(),this.fragmentTracker.removeFragment(a)),this.resetTransmuxer(),this.resetLoadingState()}else this.audioOnly&&this.resetTransmuxer();if(i){this.altAudio=0,this.fragmentTracker.removeAllFragments(),s.once(m.BUFFER_FLUSHED,()=>{this.hls&&this.hls.trigger(m.AUDIO_TRACK_SWITCHED,t)}),s.trigger(m.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:null});return}s.trigger(m.AUDIO_TRACK_SWITCHED,t)}}onAudioTrackSwitched(e,t){const s=Ps(t.url,this.hls);if(s){const i=this.videoBuffer;i&&this.mediaBuffer!==i&&(this.log("Switching on alternate audio, use video.buffered to schedule main fragment loading"),this.mediaBuffer=i)}this.altAudio=s?2:0,this.tick()}onBufferCreated(e,t){const s=t.tracks;let i,r,a=!1;for(const o in s){const c=s[o];if(c.id==="main"){if(r=o,i=c,o==="video"){const l=s[o];l&&(this.videoBuffer=l.buffer)}}else a=!0}a&&i?(this.log(`Alternate track found, use ${r}.buffered to schedule main fragment loading`),this.mediaBuffer=i.buffer):this.mediaBuffer=this.media}onFragBuffered(e,t){const{frag:s,part:i}=t,r=s.type===U.MAIN;if(r){if(this.fragContextChanged(s)){this.warn(`Fragment ${s.sn}${i?" p: "+i.index:""} of level ${s.level} finished buffering, but was aborted. state: ${this.state}`),this.state===P.PARSED&&(this.state=P.IDLE);return}const o=i?i.stats:s.stats;this.fragLastKbps=Math.round(8*o.total/(o.buffering.end-o.loading.first)),de(s)&&(this.fragPrevious=s),this.fragBufferedComplete(s,i)}const a=this.media;a&&(!this._hasEnoughToStart&&q.getBuffered(a).length&&(this._hasEnoughToStart=!0,this.seekToStartPos()),r&&this.tick())}get hasEnoughToStart(){return this._hasEnoughToStart}onError(e,t){var s;if(t.fatal){this.state=P.ERROR;return}switch(t.details){case R.FRAG_GAP:case R.FRAG_PARSING_ERROR:case R.FRAG_DECRYPT_ERROR:case R.FRAG_LOAD_ERROR:case R.FRAG_LOAD_TIMEOUT:case R.KEY_LOAD_ERROR:case R.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(U.MAIN,t);break;case R.LEVEL_LOAD_ERROR:case R.LEVEL_LOAD_TIMEOUT:case R.LEVEL_PARSING_ERROR:!t.levelRetry&&this.state===P.WAITING_LEVEL&&((s=t.context)==null?void 0:s.type)===Q.LEVEL&&(this.state=P.IDLE);break;case R.BUFFER_ADD_CODEC_ERROR:case R.BUFFER_APPEND_ERROR:if(t.parent!=="main")return;this.reduceLengthAndFlushBuffer(t)&&this.resetLoadingState();break;case R.BUFFER_FULL_ERROR:if(t.parent!=="main")return;this.reduceLengthAndFlushBuffer(t)&&(!this.config.interstitialsController&&this.config.assetPlayerId?this._hasEnoughToStart=!0:this.flushMainBuffer(0,Number.POSITIVE_INFINITY));break;case R.INTERNAL_EXCEPTION:this.recoverWorkerError(t);break}}onFragLoadEmergencyAborted(){this.state=P.IDLE,this._hasEnoughToStart||(this.startFragRequested=!1,this.nextLoadPosition=this.lastCurrentTime),this.tickImmediate()}onBufferFlushed(e,{type:t}){if(t!==ne.AUDIO||!this.altAudio){const s=(t===ne.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;s&&(this.afterBufferFlushed(s,t,U.MAIN),this.tick())}}onLevelsUpdated(e,t){this.level>-1&&this.fragCurrent&&(this.level=this.fragCurrent.level,this.level===-1&&this.resetWhenMissingContext(this.fragCurrent)),this.levels=t.levels}swapAudioCodec(){this.audioCodecSwap=!this.audioCodecSwap}seekToStartPos(){const{media:e}=this;if(!e)return;const t=e.currentTime;let s=this.startPosition;if(s>=0&&t<s){if(e.seeking){this.log(`could not seek to ${s}, already seeking at ${t}`);return}const i=this.timelineOffset;i&&s&&(s+=i);const r=this.getLevelDetails(),a=q.getBuffered(e),o=a.length?a.start(0):0,c=o-s,l=Math.max(this.config.maxBufferHole,this.config.maxFragLookUpTolerance);(this.config.startOnSegmentBoundary||c>0&&(c<l||this.loadingParts&&c<2*((r==null?void 0:r.partTarget)||0)))&&(this.log(`adjusting start position by ${c} to match buffer start`),s+=c,this.startPosition=s),t<s&&(this.log(`seek to target start position ${s} from current time ${t} buffer start ${o}`),e.currentTime=s)}}_getAudioCodec(e){let t=this.config.defaultAudioCodec||e.audioCodec;return this.audioCodecSwap&&t&&(this.log("Swapping audio codec"),t.indexOf("mp4a.40.5")!==-1?t="mp4a.40.2":t="mp4a.40.5"),t}_loadBitrateTestFrag(e,t){e.bitrateTest=!0,this._doFragLoad(e,t).then(s=>{const{hls:i}=this,r=s==null?void 0:s.frag;if(!r||this.fragContextChanged(r))return;t.fragmentError=0,this.state=P.IDLE,this.startFragRequested=!1,this.bitrateTest=!1;const a=r.stats;a.parsing.start=a.parsing.end=a.buffering.start=a.buffering.end=self.performance.now(),i.trigger(m.FRAG_LOADED,s),r.bitrateTest=!1}).catch(s=>{this.state===P.STOPPED||this.state===P.ERROR||(this.warn(s),this.resetFragmentLoading(e))})}_handleTransmuxComplete(e){const t=this.playlistType,{hls:s}=this,{remuxResult:i,chunkMeta:r}=e,a=this.getCurrentContext(r);if(!a){this.resetWhenMissingContext(r);return}const{frag:o,part:c,level:l}=a,{video:h,text:u,id3:d,initSegment:f}=i,{details:g}=l,p=this.altAudio?void 0:i.audio;if(this.fragContextChanged(o)){this.fragmentTracker.removeFragment(o);return}if(this.state=P.PARSING,f){const y=f.tracks;if(y){const v=o.initSegment||o;if(this.unhandledEncryptionError(f,o))return;this._bufferInitSegment(l,y,v,r),s.trigger(m.FRAG_PARSING_INIT_SEGMENT,{frag:v,id:t,tracks:y})}const E=f.initPTS,T=f.timescale,S=this.initPTS[o.cc];if(M(E)&&(!S||S.baseTime!==E||S.timescale!==T)){const v=f.trackId;this.initPTS[o.cc]={baseTime:E,timescale:T,trackId:v},s.trigger(m.INIT_PTS_FOUND,{frag:o,id:t,initPTS:E,timescale:T,trackId:v})}}if(h&&g){p&&h.type==="audiovideo"&&this.logMuxedErr(o);const y=g.fragments[o.sn-1-g.startSN],E=o.sn===g.startSN,T=!y||o.cc>y.cc;if(i.independent!==!1){const{startPTS:S,endPTS:v,startDTS:x,endDTS:D}=h;if(c)c.elementaryStreams[h.type]={startPTS:S,endPTS:v,startDTS:x,endDTS:D};else if(h.firstKeyFrame&&h.independent&&r.id===1&&!T&&(this.couldBacktrack=!0),h.dropped&&h.independent){const A=this.getMainFwdBufferInfo(),b=(A?A.end:this.getLoadPosition())+this.config.maxBufferHole,I=h.firstKeyFramePTS?h.firstKeyFramePTS:S;if(!E&&b<I-this.config.maxBufferHole&&!T){this.backtrack(o);return}else T&&(o.gap=!0);o.setElementaryStreamInfo(h.type,o.start,v,o.start,D,!0)}else E&&S-(g.appliedTimelineOffset||0)>xs&&(o.gap=!0);o.setElementaryStreamInfo(h.type,S,v,x,D),this.backtrackFragment&&(this.backtrackFragment=o),this.bufferFragmentData(h,o,c,r,E||T)}else if(E||T)o.gap=!0;else{this.backtrack(o);return}}if(p){const{startPTS:y,endPTS:E,startDTS:T,endDTS:S}=p;c&&(c.elementaryStreams[ne.AUDIO]={startPTS:y,endPTS:E,startDTS:T,endDTS:S}),o.setElementaryStreamInfo(ne.AUDIO,y,E,T,S),this.bufferFragmentData(p,o,c,r)}if(g&&d!=null&&d.samples.length){const y={id:t,frag:o,details:g,samples:d.samples};s.trigger(m.FRAG_PARSING_METADATA,y)}if(g&&u){const y={id:t,frag:o,details:g,samples:u.samples};s.trigger(m.FRAG_PARSING_USERDATA,y)}}logMuxedErr(e){this.warn(`${de(e)?"Media":"Init"} segment with muxed audiovideo where only video expected: ${e.url}`)}_bufferInitSegment(e,t,s,i){if(this.state!==P.PARSING)return;this.audioOnly=!!t.audio&&!t.video,this.altAudio&&!this.audioOnly&&(delete t.audio,t.audiovideo&&this.logMuxedErr(s));const{audio:r,video:a,audiovideo:o}=t;if(r){const l=e.audioCodec;let h=ms(r.codec,l);h==="mp4a"&&(h="mp4a.40.5");const u=navigator.userAgent.toLowerCase();if(this.audioCodecSwitch){h&&(h.indexOf("mp4a.40.5")!==-1?h="mp4a.40.2":h="mp4a.40.5");const d=r.metadata;d&&"channelCount"in d&&(d.channelCount||1)!==1&&u.indexOf("firefox")===-1&&(h="mp4a.40.5")}h&&h.indexOf("mp4a.40.5")!==-1&&u.indexOf("android")!==-1&&r.container!=="audio/mpeg"&&(h="mp4a.40.2",this.log(`Android: force audio codec to ${h}`)),l&&l!==h&&this.log(`Swapping manifest audio codec "${l}" for "${h}"`),r.levelCodec=h,r.id=U.MAIN,this.log(`Init audio buffer, container:${r.container}, codecs[selected/level/parsed]=[${h||""}/${l||""}/${r.codec}]`),delete t.audiovideo}if(a){a.levelCodec=e.videoCodec,a.id=U.MAIN;const l=a.codec;if((l==null?void 0:l.length)===4)switch(l){case"hvc1":case"hev1":a.codec="hvc1.1.6.L120.90";break;case"av01":a.codec="av01.0.04M.08";break;case"avc1":a.codec="avc1.42e01e";break}this.log(`Init video buffer, container:${a.container}, codecs[level/parsed]=[${e.videoCodec||""}/${l}]${a.codec!==l?" parsed-corrected="+a.codec:""}${a.supplemental?" supplemental="+a.supplemental:""}`),delete t.audiovideo}o&&(this.log(`Init audiovideo buffer, container:${o.container}, codecs[level/parsed]=[${e.codecs}/${o.codec}]`),delete t.video,delete t.audio);const c=Object.keys(t);if(c.length){if(this.hls.trigger(m.BUFFER_CODECS,t),!this.hls)return;c.forEach(l=>{const u=t[l].initSegment;u!=null&&u.byteLength&&this.hls.trigger(m.BUFFER_APPENDING,{type:l,data:u,frag:s,part:null,chunkMeta:i,parent:s.type})})}this.tickImmediate()}getMainFwdBufferInfo(){const e=this.mediaBuffer&&this.altAudio===2?this.mediaBuffer:this.media;return this.getFwdBufferInfo(e,U.MAIN)}get maxBufferLength(){const{levels:e,level:t}=this,s=e==null?void 0:e[t];return s?this.getMaxBufferLength(s.maxBitrate):this.config.maxBufferLength}backtrack(e){this.couldBacktrack=!0,this.backtrackFragment=e,this.resetTransmuxer(),this.flushBufferGap(e),this.fragmentTracker.removeFragment(e),this.fragPrevious=null,this.nextLoadPosition=e.start,this.state=P.IDLE}checkFragmentChanged(){const e=this.media;let t=null;if(e&&e.readyState>1&&e.seeking===!1){const s=e.currentTime;if(q.isBuffered(e,s)?t=this.getAppendedFrag(s):q.isBuffered(e,s+.1)&&(t=this.getAppendedFrag(s+.1)),t){this.backtrackFragment=null;const i=this.fragPlaying,r=t.level;(!i||t.sn!==i.sn||i.level!==r)&&(this.fragPlaying=t,this.hls.trigger(m.FRAG_CHANGED,{frag:t}),(!i||i.level!==r)&&this.hls.trigger(m.LEVEL_SWITCHED,{level:r}))}}}get nextLevel(){const e=this.nextBufferedFrag;return e?e.level:-1}get currentFrag(){var e;if(this.fragPlaying)return this.fragPlaying;const t=((e=this.media)==null?void 0:e.currentTime)||this.lastCurrentTime;return M(t)?this.getAppendedFrag(t):null}get currentProgramDateTime(){var e;const t=((e=this.media)==null?void 0:e.currentTime)||this.lastCurrentTime;if(M(t)){const s=this.getLevelDetails(),i=this.currentFrag||(s?mt(null,s.fragments,t):null);if(i){const r=i.programDateTime;if(r!==null){const a=r+(t-i.start)*1e3;return new Date(a)}}}return null}get currentLevel(){const e=this.currentFrag;return e?e.level:-1}get nextBufferedFrag(){const e=this.currentFrag;return e?this.followingBufferedFrag(e):null}get forceStartLoad(){return this._forceStartLoad}}class $f extends Fe{constructor(e,t){super("key-loader",t),this.config=void 0,this.keyIdToKeyInfo={},this.emeController=null,this.config=e}abort(e){for(const s in this.keyIdToKeyInfo){const i=this.keyIdToKeyInfo[s].loader;if(i){var t;if(e&&e!==((t=i.context)==null?void 0:t.frag.type))return;i.abort()}}}detach(){for(const e in this.keyIdToKeyInfo){const t=this.keyIdToKeyInfo[e];(t.mediaKeySessionContext||t.decryptdata.isCommonEncryption)&&delete this.keyIdToKeyInfo[e]}}destroy(){this.detach();for(const e in this.keyIdToKeyInfo){const t=this.keyIdToKeyInfo[e].loader;t&&t.destroy()}this.keyIdToKeyInfo={}}createKeyLoadError(e,t=R.KEY_LOAD_ERROR,s,i,r){return new ze({type:H.NETWORK_ERROR,details:t,fatal:!1,frag:e,response:r,error:s,networkDetails:i})}loadClear(e,t,s){if(this.emeController&&this.config.emeEnabled&&!this.emeController.getSelectedKeySystemFormats().length){if(t.length)for(let i=0,r=t.length;i<r;i++){const a=t[i];if(e.cc<=a.cc&&(!de(e)||!de(a)||e.sn<a.sn)||!s&&i==r-1)return this.emeController.selectKeySystemFormat(a).then(o=>{if(!this.emeController)return;a.setKeyFormat(o);const c=ys(o);if(c)return this.emeController.getKeySystemAccess([c])})}if(this.config.requireKeySystemAccessOnStart){const i=Ft(this.config);if(i.length)return this.emeController.getKeySystemAccess(i)}}return null}load(e){return!e.decryptdata&&e.encrypted&&this.emeController&&this.config.emeEnabled?this.emeController.selectKeySystemFormat(e).then(t=>this.loadInternal(e,t)):this.loadInternal(e)}loadInternal(e,t){var s,i;t&&e.setKeyFormat(t);const r=e.decryptdata;if(!r){const l=new Error(t?`Expected frag.decryptdata to be defined after setting format ${t}`:`Missing decryption data on fragment in onKeyLoading (emeEnabled with controller: ${this.emeController&&this.config.emeEnabled})`);return Promise.reject(this.createKeyLoadError(e,R.KEY_LOAD_ERROR,l))}const a=r.uri;if(!a)return Promise.reject(this.createKeyLoadError(e,R.KEY_LOAD_ERROR,new Error(`Invalid key URI: "${a}"`)));const o=mi(r);let c=this.keyIdToKeyInfo[o];if((s=c)!=null&&s.decryptdata.key)return r.key=c.decryptdata.key,Promise.resolve({frag:e,keyInfo:c});if(this.emeController&&(i=c)!=null&&i.keyLoadPromise)switch(this.emeController.getKeyStatus(c.decryptdata)){case"usable":case"usable-in-future":return c.keyLoadPromise.then(h=>{const{keyInfo:u}=h;return r.key=u.decryptdata.key,{frag:e,keyInfo:u}})}switch(this.log(`${this.keyIdToKeyInfo[o]?"Rel":"L"}oading${r.keyId?" keyId: "+Te(r.keyId):""} URI: ${r.uri} from ${e.type} ${e.level}`),c=this.keyIdToKeyInfo[o]={decryptdata:r,keyLoadPromise:null,loader:null,mediaKeySessionContext:null},r.method){case"SAMPLE-AES":case"SAMPLE-AES-CENC":case"SAMPLE-AES-CTR":return r.keyFormat==="identity"?this.loadKeyHTTP(c,e):this.loadKeyEME(c,e);case"AES-128":case"AES-256":case"AES-256-CTR":return this.loadKeyHTTP(c,e);default:return Promise.reject(this.createKeyLoadError(e,R.KEY_LOAD_ERROR,new Error(`Key supplied with unsupported METHOD: "${r.method}"`)))}}loadKeyEME(e,t){const s={frag:t,keyInfo:e};if(this.emeController&&this.config.emeEnabled){var i;if(!e.decryptdata.keyId&&(i=t.initSegment)!=null&&i.data){const a=rc(t.initSegment.data);if(a.length){let o=a[0];o.some(c=>c!==0)?(this.log(`Using keyId found in init segment ${Te(o)}`),nt.setKeyIdForUri(e.decryptdata.uri,o)):(o=nt.addKeyIdForUri(e.decryptdata.uri),this.log(`Generating keyId to patch media ${Te(o)}`)),e.decryptdata.keyId=o}}if(!e.decryptdata.keyId&&!de(t))return Promise.resolve(s);const r=this.emeController.loadKey(s);return(e.keyLoadPromise=r.then(a=>(e.mediaKeySessionContext=a,s))).catch(a=>{throw e.keyLoadPromise=null,"data"in a&&(a.data.frag=t),a})}return Promise.resolve(s)}loadKeyHTTP(e,t){const s=this.config,i=s.loader,r=new i(s);return t.keyLoader=e.loader=r,e.keyLoadPromise=new Promise((a,o)=>{const c={keyInfo:e,frag:t,responseType:"arraybuffer",url:e.decryptdata.uri},l=s.keyLoadPolicy.default,h={loadPolicy:l,timeout:l.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},u={onSuccess:(d,f,g,p)=>{const{frag:y,keyInfo:E}=g,T=mi(E.decryptdata);if(!y.decryptdata||E!==this.keyIdToKeyInfo[T])return o(this.createKeyLoadError(y,R.KEY_LOAD_ERROR,new Error("after key load, decryptdata unset or changed"),p));E.decryptdata.key=y.decryptdata.key=new Uint8Array(d.data),y.keyLoader=null,E.loader=null,a({frag:y,keyInfo:E})},onError:(d,f,g,p)=>{this.resetLoader(f),o(this.createKeyLoadError(t,R.KEY_LOAD_ERROR,new Error(`HTTP Error ${d.code} loading key ${d.text}`),g,se({url:c.url,data:void 0},d)))},onTimeout:(d,f,g)=>{this.resetLoader(f),o(this.createKeyLoadError(t,R.KEY_LOAD_TIMEOUT,new Error("key loading timed out"),g))},onAbort:(d,f,g)=>{this.resetLoader(f),o(this.createKeyLoadError(t,R.INTERNAL_ABORTED,new Error("key loading aborted"),g))}};r.load(c,h,u)})}resetLoader(e){const{frag:t,keyInfo:s,url:i}=e,r=s.loader;t.keyLoader===r&&(t.keyLoader=null,s.loader=null);const a=mi(s.decryptdata)||i;delete this.keyIdToKeyInfo[a],r&&r.destroy()}}function mi(n){if(n.keyFormat!==Se.FAIRPLAY){const e=n.keyId;if(e)return Te(e)}return n.uri}function Qn(n){const{type:e}=n;switch(e){case Q.AUDIO_TRACK:return U.AUDIO;case Q.SUBTITLE_TRACK:return U.SUBTITLE;default:return U.MAIN}}function pi(n,e){let t=n.url;return(t===void 0||t.indexOf("data:")===0)&&(t=e.url),t}class Gf{constructor(e){this.hls=void 0,this.loaders=Object.create(null),this.variableList=null,this.onManifestLoaded=this.checkAutostartLoad,this.hls=e,this.registerListeners()}startLoad(e){}stopLoad(){this.destroyInternalLoaders()}registerListeners(){const{hls:e}=this;e.on(m.MANIFEST_LOADING,this.onManifestLoading,this),e.on(m.LEVEL_LOADING,this.onLevelLoading,this),e.on(m.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.on(m.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),e.on(m.LEVELS_UPDATED,this.onLevelsUpdated,this)}unregisterListeners(){const{hls:e}=this;e.off(m.MANIFEST_LOADING,this.onManifestLoading,this),e.off(m.LEVEL_LOADING,this.onLevelLoading,this),e.off(m.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.off(m.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),e.off(m.LEVELS_UPDATED,this.onLevelsUpdated,this)}createInternalLoader(e){const t=this.hls.config,s=t.pLoader,i=t.loader,r=s||i,a=new r(t);return this.loaders[e.type]=a,a}getInternalLoader(e){return this.loaders[e.type]}resetInternalLoader(e){this.loaders[e]&&delete this.loaders[e]}destroyInternalLoaders(){for(const e in this.loaders){const t=this.loaders[e];t&&t.destroy(),this.resetInternalLoader(e)}}destroy(){this.variableList=null,this.unregisterListeners(),this.destroyInternalLoaders()}onManifestLoading(e,t){const{url:s}=t;this.variableList=null,this.load({id:null,level:0,responseType:"text",type:Q.MANIFEST,url:s,deliveryDirectives:null,levelOrTrack:null})}onLevelLoading(e,t){const{id:s,level:i,pathwayId:r,url:a,deliveryDirectives:o,levelInfo:c}=t;this.load({id:s,level:i,pathwayId:r,responseType:"text",type:Q.LEVEL,url:a,deliveryDirectives:o,levelOrTrack:c})}onAudioTrackLoading(e,t){const{id:s,groupId:i,url:r,deliveryDirectives:a,track:o}=t;this.load({id:s,groupId:i,level:null,responseType:"text",type:Q.AUDIO_TRACK,url:r,deliveryDirectives:a,levelOrTrack:o})}onSubtitleTrackLoading(e,t){const{id:s,groupId:i,url:r,deliveryDirectives:a,track:o}=t;this.load({id:s,groupId:i,level:null,responseType:"text",type:Q.SUBTITLE_TRACK,url:r,deliveryDirectives:a,levelOrTrack:o})}onLevelsUpdated(e,t){const s=this.loaders[Q.LEVEL];if(s){const i=s.context;i&&!t.levels.some(r=>r===i.levelOrTrack)&&(s.abort(),delete this.loaders[Q.LEVEL])}}load(e){var t;const s=this.hls.config;let i=this.getInternalLoader(e);if(i){const l=this.hls.logger,h=i.context;if(h&&h.levelOrTrack===e.levelOrTrack&&(h.url===e.url||h.deliveryDirectives&&!e.deliveryDirectives)){h.url===e.url?l.log(`[playlist-loader]: ignore ${e.url} ongoing request`):l.log(`[playlist-loader]: ignore ${e.url} in favor of ${h.url}`);return}l.log(`[playlist-loader]: aborting previous loader for type: ${e.type}`),i.abort()}let r;if(e.type===Q.MANIFEST?r=s.manifestLoadPolicy.default:r=re({},s.playlistLoadPolicy.default,{timeoutRetry:null,errorRetry:null}),i=this.createInternalLoader(e),M((t=e.deliveryDirectives)==null?void 0:t.part)){let l;if(e.type===Q.LEVEL&&e.level!==null?l=this.hls.levels[e.level].details:e.type===Q.AUDIO_TRACK&&e.id!==null?l=this.hls.audioTracks[e.id].details:e.type===Q.SUBTITLE_TRACK&&e.id!==null&&(l=this.hls.subtitleTracks[e.id].details),l){const h=l.partTarget,u=l.targetduration;if(h&&u){const d=Math.max(h*3,u*.8)*1e3;r=re({},r,{maxTimeToFirstByteMs:Math.min(d,r.maxTimeToFirstByteMs),maxLoadTimeMs:Math.min(d,r.maxTimeToFirstByteMs)})}}}const a=r.errorRetry||r.timeoutRetry||{},o={loadPolicy:r,timeout:r.maxLoadTimeMs,maxRetry:a.maxNumRetry||0,retryDelay:a.retryDelayMs||0,maxRetryDelay:a.maxRetryDelayMs||0},c={onSuccess:(l,h,u,d)=>{const f=this.getInternalLoader(u);this.resetInternalLoader(u.type);const g=l.data;h.parsing.start=performance.now(),We.isMediaPlaylist(g)||u.type!==Q.MANIFEST?this.handleTrackOrLevelPlaylist(l,h,u,d||null,f):this.handleMasterPlaylist(l,h,u,d)},onError:(l,h,u,d)=>{this.handleNetworkError(h,u,!1,l,d)},onTimeout:(l,h,u)=>{this.handleNetworkError(h,u,!0,void 0,l)}};i.load(e,o,c)}checkAutostartLoad(){if(!this.hls)return;const{config:{autoStartLoad:e,startPosition:t},forceStartLoad:s}=this.hls;(e||s)&&(this.hls.logger.log(`${e?"auto":"force"} startLoad with configured startPosition ${t}`),this.hls.startLoad(t))}handleMasterPlaylist(e,t,s,i){const r=this.hls,a=e.data,o=pi(e,s),c=We.parseMasterPlaylist(a,o);if(c.playlistParsingError){t.parsing.end=performance.now(),this.handleManifestParsingError(e,s,c.playlistParsingError,i,t);return}const{contentSteering:l,levels:h,sessionData:u,sessionKeys:d,startTimeOffset:f,variableList:g}=c;this.variableList=g,h.forEach(T=>{const{unknownCodecs:S}=T;if(S){const{preferManagedMediaSource:v}=this.hls.config;let{audioCodec:x,videoCodec:D}=T;for(let A=S.length;A--;){const b=S[A];$t(b,"audio",v)?(T.audioCodec=x=x?`${x},${b}`:b,Ct.audio[x.substring(0,4)]=2,S.splice(A,1)):$t(b,"video",v)&&(T.videoCodec=D=D?`${D},${b}`:b,Ct.video[D.substring(0,4)]=2,S.splice(A,1))}}});const{AUDIO:p=[],SUBTITLES:y,"CLOSED-CAPTIONS":E}=We.parseMasterPlaylistMedia(a,o,c);p.length&&!p.some(S=>!S.url)&&h[0].audioCodec&&!h[0].attrs.AUDIO&&(this.hls.logger.log("[playlist-loader]: audio codec signaled in quality level, but no embedded audio track signaled, create one"),p.unshift({type:"main",name:"main",groupId:"main",default:!1,autoselect:!1,forced:!1,id:-1,attrs:new le({}),bitrate:0,url:""})),r.trigger(m.MANIFEST_LOADED,{levels:h,audioTracks:p,subtitles:y,captions:E,contentSteering:l,url:o,stats:t,networkDetails:i,sessionData:u,sessionKeys:d,startTimeOffset:f,variableList:g})}handleTrackOrLevelPlaylist(e,t,s,i,r){const a=this.hls,{id:o,level:c,type:l}=s,h=pi(e,s),u=M(c)?c:M(o)?o:0,d=Qn(s),f=We.parseLevelPlaylist(e.data,h,u,d,0,this.variableList);if(l===Q.MANIFEST){const g={attrs:new le({}),bitrate:0,details:f,name:"",url:h};f.requestScheduled=t.loading.start+za(f,0),a.trigger(m.MANIFEST_LOADED,{levels:[g],audioTracks:[],url:h,stats:t,networkDetails:i,sessionData:null,sessionKeys:null,contentSteering:null,startTimeOffset:null,variableList:null})}t.parsing.end=performance.now(),s.levelDetails=f,this.handlePlaylistLoaded(f,e,t,s,i,r)}handleManifestParsingError(e,t,s,i,r){this.hls.trigger(m.ERROR,{type:H.NETWORK_ERROR,details:R.MANIFEST_PARSING_ERROR,fatal:t.type===Q.MANIFEST,url:e.url,err:s,error:s,reason:s.message,response:e,context:t,networkDetails:i,stats:r})}handleNetworkError(e,t,s=!1,i,r){let a=`A network ${s?"timeout":"error"+(i?" (status "+i.code+")":"")} occurred while loading ${e.type}`;e.type===Q.LEVEL?a+=`: ${e.level} id: ${e.id}`:(e.type===Q.AUDIO_TRACK||e.type===Q.SUBTITLE_TRACK)&&(a+=` id: ${e.id} group-id: "${e.groupId}"`);const o=new Error(a);this.hls.logger.warn(`[playlist-loader]: ${a}`);let c=R.UNKNOWN,l=!1;const h=this.getInternalLoader(e);switch(e.type){case Q.MANIFEST:c=s?R.MANIFEST_LOAD_TIMEOUT:R.MANIFEST_LOAD_ERROR,l=!0;break;case Q.LEVEL:c=s?R.LEVEL_LOAD_TIMEOUT:R.LEVEL_LOAD_ERROR,l=!1;break;case Q.AUDIO_TRACK:c=s?R.AUDIO_TRACK_LOAD_TIMEOUT:R.AUDIO_TRACK_LOAD_ERROR,l=!1;break;case Q.SUBTITLE_TRACK:c=s?R.SUBTITLE_TRACK_LOAD_TIMEOUT:R.SUBTITLE_LOAD_ERROR,l=!1;break}h&&this.resetInternalLoader(e.type);const u={type:H.NETWORK_ERROR,details:c,fatal:l,url:e.url,loader:h,context:e,error:o,networkDetails:t,stats:r};if(i){const d=(t==null?void 0:t.url)||e.url;u.response=se({url:d,data:void 0},i)}this.hls.trigger(m.ERROR,u)}handlePlaylistLoaded(e,t,s,i,r,a){const o=this.hls,{type:c,level:l,levelOrTrack:h,id:u,groupId:d,deliveryDirectives:f}=i,g=pi(t,i),p=Qn(i);let y=typeof i.level=="number"&&p===U.MAIN?l:void 0;const E=e.playlistParsingError;if(E){if(this.hls.logger.warn(`${E} ${e.url}`),!o.config.ignorePlaylistParsingErrors){o.trigger(m.ERROR,{type:H.NETWORK_ERROR,details:R.LEVEL_PARSING_ERROR,fatal:!1,url:g,error:E,reason:E.message,response:t,context:i,level:y,parent:p,networkDetails:r,stats:s});return}e.playlistParsingError=null}if(!e.fragments.length){const T=e.playlistParsingError=new Error("No Segments found in Playlist");o.trigger(m.ERROR,{type:H.NETWORK_ERROR,details:R.LEVEL_EMPTY_ERROR,fatal:!1,url:g,error:T,reason:T.message,response:t,context:i,level:y,parent:p,networkDetails:r,stats:s});return}switch(e.live&&a&&(a.getCacheAge&&(e.ageHeader=a.getCacheAge()||0),(!a.getCacheAge||isNaN(e.ageHeader))&&(e.ageHeader=0)),c){case Q.MANIFEST:case Q.LEVEL:if(y){if(!h)y=0;else if(h!==o.levels[y]){const T=o.levels.indexOf(h);T>-1&&(y=T)}}o.trigger(m.LEVEL_LOADED,{details:e,levelInfo:h||o.levels[0],level:y||0,id:u||0,stats:s,networkDetails:r,deliveryDirectives:f,withoutMultiVariant:c===Q.MANIFEST});break;case Q.AUDIO_TRACK:o.trigger(m.AUDIO_TRACK_LOADED,{details:e,track:h,id:u||0,groupId:d||"",stats:s,networkDetails:r,deliveryDirectives:f});break;case Q.SUBTITLE_TRACK:o.trigger(m.SUBTITLE_TRACK_LOADED,{details:e,track:h,id:u||0,groupId:d||"",stats:s,networkDetails:r,deliveryDirectives:f});break}}}class we{static get version(){return Vt}static isMSESupported(){return zo()}static isSupported(){return Mf()}static getMediaSource(){return at()}static get Events(){return m}static get MetadataSchema(){return De}static get ErrorTypes(){return H}static get ErrorDetails(){return R}static get DefaultConfig(){return we.defaultConfig?we.defaultConfig:_f}static set DefaultConfig(e){we.defaultConfig=e}constructor(e={}){this.config=void 0,this.userConfig=void 0,this.logger=void 0,this.coreComponents=void 0,this.networkControllers=void 0,this._emitter=new ir,this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.abrController=void 0,this.bufferController=void 0,this.capLevelController=void 0,this.latencyController=void 0,this.levelController=void 0,this.streamController=void 0,this.audioStreamController=void 0,this.subtititleStreamController=void 0,this.audioTrackController=void 0,this.subtitleTrackController=void 0,this.interstitialsController=void 0,this.gapController=void 0,this.emeController=void 0,this.cmcdController=void 0,this._media=null,this._url=null,this._sessionId=void 0,this.triggeringException=void 0,this.started=!1;const t=this.logger=Yl(e.debug||!1,"Hls instance",e.assetPlayerId),s=this.config=Lf(we.DefaultConfig,e,t);this.userConfig=e,s.progressive&&Rf(s,t);const{abrController:i,bufferController:r,capLevelController:a,errorController:o,fpsController:c}=s,l=new o(this),h=this.abrController=new i(this),u=new Gc(this),d=s.interstitialsController,f=d?this.interstitialsController=new d(this,we):null,g=this.bufferController=new r(this,u),p=this.capLevelController=new a(this),y=new c(this),E=new Gf(this),T=s.contentSteeringController,S=T?new T(this):null,v=this.levelController=new Ff(this,S),x=new wf(this),D=new $f(this.config,this.logger),A=this.streamController=new Uf(this,u,D),b=this.gapController=new Pf(this,u);p.setStreamController(A),y.setStreamController(A);const I=[E,v,A];f&&I.splice(1,0,f),S&&I.splice(1,0,S),this.networkControllers=I;const _=[h,g,b,p,y,x,u];this.audioTrackController=this.createController(s.audioTrackController,I);const C=s.audioStreamController;C&&I.push(this.audioStreamController=new C(this,u,D)),this.subtitleTrackController=this.createController(s.subtitleTrackController,I);const k=s.subtitleStreamController;k&&I.push(this.subtititleStreamController=new k(this,u,D)),this.createController(s.timelineController,_),D.emeController=this.emeController=this.createController(s.emeController,_),this.cmcdController=this.createController(s.cmcdController,_),this.latencyController=this.createController(Of,_),this.coreComponents=_,I.push(l);const B=l.onErrorOut;typeof B=="function"&&this.on(m.ERROR,B,l),this.on(m.MANIFEST_LOADED,E.onManifestLoaded,E)}createController(e,t){if(e){const s=new e(this);return t&&t.push(s),s}return null}on(e,t,s=this){this._emitter.on(e,t,s)}once(e,t,s=this){this._emitter.once(e,t,s)}removeAllListeners(e){this._emitter.removeAllListeners(e)}off(e,t,s=this,i){this._emitter.off(e,t,s,i)}listeners(e){return this._emitter.listeners(e)}emit(e,t,s){return this._emitter.emit(e,t,s)}trigger(e,t){if(this.config.debug)return this.emit(e,e,t);try{return this.emit(e,e,t)}catch(s){if(this.logger.error("An internal error happened while handling event "+e+'. Error message: "'+s.message+'". Here is a stacktrace:',s),!this.triggeringException){this.triggeringException=!0;const i=e===m.ERROR;this.trigger(m.ERROR,{type:H.OTHER_ERROR,details:R.INTERNAL_EXCEPTION,fatal:i,event:e,error:s}),this.triggeringException=!1}}return!1}listenerCount(e){return this._emitter.listenerCount(e)}destroy(){this.logger.log("destroy"),this.trigger(m.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 e=this.config;e.xhrSetup=e.fetchSetup=void 0,this.userConfig=null}attachMedia(e){if(!e||"media"in e&&!e.media){const r=new Error(`attachMedia failed: invalid argument (${e})`);this.trigger(m.ERROR,{type:H.OTHER_ERROR,details:R.ATTACH_MEDIA_ERROR,fatal:!0,error:r});return}this.logger.log("attachMedia"),this._media&&(this.logger.warn("media must be detached before attaching"),this.detachMedia());const t="media"in e,s=t?e.media:e,i=t?e:{media:s};this._media=s,this.trigger(m.MEDIA_ATTACHING,i)}detachMedia(){this.logger.log("detachMedia"),this.trigger(m.MEDIA_DETACHING,{}),this._media=null}transferMedia(){this._media=null;const e=this.bufferController.transferMedia();return this.trigger(m.MEDIA_DETACHING,{transferMedia:e}),e}loadSource(e){this.stopLoad();const t=this.media,s=this._url,i=this._url=Yi.buildAbsoluteURL(self.location.href,e,{alwaysNormalize:!0});this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.logger.log(`loadSource:${i}`),t&&s&&(s!==i||this.bufferController.hasSourceTypes())&&(this.detachMedia(),this.attachMedia(t)),this.trigger(m.MANIFEST_LOADING,{url:e})}get url(){return this._url}get hasEnoughToStart(){return this.streamController.hasEnoughToStart}get startPosition(){return this.streamController.startPositionValue}startLoad(e=-1,t){this.logger.log(`startLoad(${e+(t?", <skip seek to start>":"")})`),this.started=!0,this.resumeBuffering();for(let s=0;s<this.networkControllers.length&&(this.networkControllers[s].startLoad(e,t),!(!this.started||!this.networkControllers));s++);}stopLoad(){this.logger.log("stopLoad"),this.started=!1;for(let e=0;e<this.networkControllers.length&&(this.networkControllers[e].stopLoad(),!(this.started||!this.networkControllers));e++);}get loadingEnabled(){return this.started}get bufferingEnabled(){return this.streamController.bufferingEnabled}resumeBuffering(){this.bufferingEnabled||(this.logger.log("resume buffering"),this.networkControllers.forEach(e=>{e.resumeBuffering&&e.resumeBuffering()}))}pauseBuffering(){this.bufferingEnabled&&(this.logger.log("pause buffering"),this.networkControllers.forEach(e=>{e.pauseBuffering&&e.pauseBuffering()}))}get inFlightFragments(){const e={[U.MAIN]:this.streamController.inFlightFrag};return this.audioStreamController&&(e[U.AUDIO]=this.audioStreamController.inFlightFrag),this.subtititleStreamController&&(e[U.SUBTITLE]=this.subtititleStreamController.inFlightFrag),e}swapAudioCodec(){this.logger.log("swapAudioCodec"),this.streamController.swapAudioCodec()}recoverMediaError(){this.logger.log("recoverMediaError");const e=this._media,t=e==null?void 0:e.currentTime;this.detachMedia(),e&&(this.attachMedia(e),t&&this.startLoad(t))}removeLevel(e){this.levelController.removeLevel(e)}get sessionId(){let e=this._sessionId;return e||(e=this._sessionId=Cd()),e}get levels(){const e=this.levelController.levels;return e||[]}get latestLevelDetails(){return this.streamController.getLevelDetails()||null}get loadLevelObj(){return this.levelController.loadLevelObj}get currentLevel(){return this.streamController.currentLevel}set currentLevel(e){this.logger.log(`set currentLevel:${e}`),this.levelController.manualLevel=e,this.streamController.immediateLevelSwitch()}get nextLevel(){return this.streamController.nextLevel}set nextLevel(e){this.logger.log(`set nextLevel:${e}`),this.levelController.manualLevel=e,this.streamController.nextLevelSwitch()}get loadLevel(){return this.levelController.level}set loadLevel(e){this.logger.log(`set loadLevel:${e}`),this.levelController.manualLevel=e}get nextLoadLevel(){return this.levelController.nextLoadLevel}set nextLoadLevel(e){this.levelController.nextLoadLevel=e}get firstLevel(){return Math.max(this.levelController.firstLevel,this.minAutoLevel)}set firstLevel(e){this.logger.log(`set firstLevel:${e}`),this.levelController.firstLevel=e}get startLevel(){const e=this.levelController.startLevel;return e===-1&&this.abrController.forcedAutoLevel>-1?this.abrController.forcedAutoLevel:e}set startLevel(e){this.logger.log(`set startLevel:${e}`),e!==-1&&(e=Math.max(e,this.minAutoLevel)),this.levelController.startLevel=e}get capLevelToPlayerSize(){return this.config.capLevelToPlayerSize}set capLevelToPlayerSize(e){const t=!!e;t!==this.config.capLevelToPlayerSize&&(t?this.capLevelController.startCapping():(this.capLevelController.stopCapping(),this.autoLevelCapping=-1,this.streamController.nextLevelSwitch()),this.config.capLevelToPlayerSize=t)}get autoLevelCapping(){return this._autoLevelCapping}get bandwidthEstimate(){const{bwEstimator:e}=this.abrController;return e?e.getEstimate():NaN}set bandwidthEstimate(e){this.abrController.resetEstimator(e)}get abrEwmaDefaultEstimate(){const{bwEstimator:e}=this.abrController;return e?e.defaultEstimate:NaN}get ttfbEstimate(){const{bwEstimator:e}=this.abrController;return e?e.getEstimateTTFB():NaN}set autoLevelCapping(e){this._autoLevelCapping!==e&&(this.logger.log(`set autoLevelCapping:${e}`),this._autoLevelCapping=e,this.levelController.checkMaxAutoUpdated())}get maxHdcpLevel(){return this._maxHdcpLevel}set maxHdcpLevel(e){Ic(e)&&this._maxHdcpLevel!==e&&(this._maxHdcpLevel=e,this.levelController.checkMaxAutoUpdated())}get autoLevelEnabled(){return this.levelController.manualLevel===-1}get manualLevel(){return this.levelController.manualLevel}get minAutoLevel(){const{levels:e,config:{minAutoBitrate:t}}=this;if(!e)return 0;const s=e.length;for(let i=0;i<s;i++)if(e[i].maxBitrate>=t)return i;return 0}get maxAutoLevel(){const{levels:e,autoLevelCapping:t,maxHdcpLevel:s}=this;let i;if(t===-1&&e!=null&&e.length?i=e.length-1:i=t,s)for(let r=i;r--;){const a=e[r].attrs["HDCP-LEVEL"];if(a&&a<=s)return r}return i}get firstAutoLevel(){return this.abrController.firstAutoLevel}get nextAutoLevel(){return this.abrController.nextAutoLevel}set nextAutoLevel(e){this.abrController.nextAutoLevel=e}get playingDate(){return this.streamController.currentProgramDateTime}get mainForwardBufferInfo(){return this.streamController.getMainFwdBufferInfo()}get maxBufferLength(){return this.streamController.maxBufferLength}setAudioOption(e){var t;return((t=this.audioTrackController)==null?void 0:t.setAudioOption(e))||null}setSubtitleOption(e){var t;return((t=this.subtitleTrackController)==null?void 0:t.setSubtitleOption(e))||null}get allAudioTracks(){const e=this.audioTrackController;return e?e.allAudioTracks:[]}get audioTracks(){const e=this.audioTrackController;return e?e.audioTracks:[]}get audioTrack(){const e=this.audioTrackController;return e?e.audioTrack:-1}set audioTrack(e){const t=this.audioTrackController;t&&(t.audioTrack=e)}get allSubtitleTracks(){const e=this.subtitleTrackController;return e?e.allSubtitleTracks:[]}get subtitleTracks(){const e=this.subtitleTrackController;return e?e.subtitleTracks:[]}get subtitleTrack(){const e=this.subtitleTrackController;return e?e.subtitleTrack:-1}get media(){return this._media}set subtitleTrack(e){const t=this.subtitleTrackController;t&&(t.subtitleTrack=e)}get subtitleDisplay(){const e=this.subtitleTrackController;return e?e.subtitleDisplay:!1}set subtitleDisplay(e){const t=this.subtitleTrackController;t&&(t.subtitleDisplay=e)}get lowLatencyMode(){return this.config.lowLatencyMode}set lowLatencyMode(e){this.config.lowLatencyMode=e}get liveSyncPosition(){return this.latencyController.liveSyncPosition}get latency(){return this.latencyController.latency}get maxLatency(){return this.latencyController.maxLatency}get targetLatency(){return this.latencyController.targetLatency}set targetLatency(e){this.latencyController.targetLatency=e}get drift(){return this.latencyController.drift}get forceStartLoad(){return this.streamController.forceStartLoad}get pathways(){return this.levelController.pathways}get pathwayPriority(){return this.levelController.pathwayPriority}set pathwayPriority(e){this.levelController.pathwayPriority=e}get bufferedToEnd(){var e;return!!((e=this.bufferController)!=null&&e.bufferedToEnd)}get interstitialsManager(){var e;return((e=this.interstitialsController)==null?void 0:e.interstitialsManager)||null}getMediaDecodingInfo(e,t=this.allAudioTracks){const s=Fa(t);return wa(e,s,navigator.mediaCapabilities)}}we.defaultConfig=void 0;function Kf(){const n=window.location.pathname,e=n.lastIndexOf("/");return n.substring(0,e+1)}function Vf(){const n=window.location.pathname,e=n.lastIndexOf("/");return n.substring(e+1)||null}function Qo(n){const e=n.split("/");return e[e.length-1]}function Zo(n){return new Date(n.value.createdAt).toISOString().split("T")[0]}function Hf(n){const e=new Map;for(const t of n){const s=Zo(t);e.has(s)||e.set(s,[]),e.get(s).push(t)}return e}function Zn(n){const e=Kf();if(n){const t=Qo(n);history.pushState({channel:n},"",`${e}${t}`)}else history.pushState(null,"",e)}function Wf(n){const e=n.match(/(?:(\d+)h)?(?:(\d+)m)?(\d+)s?/);if(!e)return 0;const t=parseInt(e[1]||"0",10),s=parseInt(e[2]||"0",10),i=parseInt(e[3]||"0",10);return t*3600+s*60+i}function Jo(){const e=new URLSearchParams(window.location.search).get("t");return e?Wf(e):0}const Jn="https://vod-beta.stream.place/xrpc";function Yf(n,e,t,s){const[i,r]=rt(!1),[a,o]=rt(!0),[c,l]=rt(null),[h,u]=rt(null),d=Mt(0),f=Mt(null),g=Mt(!1);return vi(()=>{if(!e||n.length===0||!t.current||!s.current)return;const p=t.current,y=s.current,E=e;async function T(){if(g.current)return;g.current=!0;const S=++d.current,v=()=>S!==d.current,x=n.find(C=>C.uri===E);if(!x){g.current=!1;return}const D=x.value.title||"Unknown Video",A=x.uri,b=encodeURIComponent(A);if(console.log("[Player] Switching to:",D),l(D),u(A),o(!1),r(!0),f.current&&(f.current.destroy(),f.current=null),p.pause(),p.removeAttribute("src"),p.load(),y.pause(),y.removeAttribute("src"),await new Promise(C=>setTimeout(C,250)),v()){g.current=!1;return}const I=Jo(),_=`${Jn}/place.stream.playback.getVideoPlaylist?uri=${b}`;if(!we.isSupported()){const C=`${Jn}/place.stream.playback.getVideoPlaylist?uri=${b}`;p.src=C,p.currentTime=I;try{await p.play(),r(!1)}catch(k){console.warn("[Player] Playback error:",k),r(!1)}g.current=!1;return}f.current=new we({startPosition:I,maxBufferLength:30,maxMaxBufferLength:60}),f.current.loadSource(_),f.current.attachMedia(p),f.current.on(we.Events.MANIFEST_PARSED,()=>{v()||(console.log("[Player] Video manifest parsed"),p.muted=!0,p.play().catch(C=>console.warn("[Player] Play failed:",C)))}),f.current.on(we.Events.ERROR,(C,k)=>{var B,K;v()||(console.warn("[Player] HLS error:",k.type,k.details,k.fatal),k.fatal&&(k.type===we.ErrorTypes.MEDIA_ERROR?(B=f.current)==null||B.recoverMediaError():((K=f.current)==null||K.destroy(),f.current=null,g.current=!1,T())))}),g.current=!1}return T(),()=>{const S=t.current;S==null||S.pause()}},[e,n,t,s]),{isLoading:i,showStandby:a,currentTitle:c,currentUri:h}}function qf(){const[n,e]=rt([]),[t,s]=rt(null),[i,r]=rt(null),[a,o]=rt(!1),c=Mt(null),l=Mt(null),h=Yf(n,t,c,l),u=()=>{o(!a)};vi(()=>{async function g(){try{const p=await Tl();console.log(`Loaded ${p.length} VODs`),e(p);const y=Hf(p),E=Array.from(y.keys()).sort();E.length>0&&r(E[0]);const T=Vf();if(T){const S=p.find(v=>Qo(v.uri)===T);S&&(r(Zo(S)),s(S.uri),Zn(S.uri))}}catch(p){console.error("Failed to load VODs:",p)}}g()},[]);const d=g=>{r(g)},f=g=>{s(g),Zn(g)};return vi(()=>{const g=()=>{const p=c.current;if(!p)return;const y=Jo();y>0&&(p.currentTime=y)};return window.addEventListener("popstate",g),()=>window.removeEventListener("popstate",g)},[c]),Z("div",{class:"flex flex-col h-screen overflow-hidden",style:"background-color: #1a1a1a; color: #7dd3fc; line-height: 1.6; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, sans-serif",children:[Z(Nl,{sidebarCollapsed:a,onToggleSidebar:u}),Z("div",{class:"flex flex-row flex-1 overflow-hidden",children:[Z(Rl,{vods:n,currentChannel:t,selectedDay:i,onSelectDay:d,onSelectVideo:f,collapsed:a}),Z(bl,{currentTitle:h.currentTitle,currentUri:h.currentUri,isLoading:h.isLoading,showStandby:h.showStandby,videoRef:c,audioRef:l})]})]})}const ea=document.getElementById("app-root");ea&&ll(Z(qf,{}),ea);</script>
129129+ </head>
130130+ <body>
131131+ <div id="app-root"></div>
132132+ </body>
368133</html>
···11+/*
22+ * THIS FILE WAS GENERATED BY "@atproto/lex". DO NOT EDIT.
33+ */
44+55+export * as atproto from './com/atproto.js'
+5
src/lexicons/com/atproto.ts
···11+/*
22+ * THIS FILE WAS GENERATED BY "@atproto/lex". DO NOT EDIT.
33+ */
44+55+export * as repo from './atproto/repo.js'
+5
src/lexicons/com/atproto/repo.ts
···11+/*
22+ * THIS FILE WAS GENERATED BY "@atproto/lex". DO NOT EDIT.
33+ */
44+55+export * as listRecords from './repo/listRecords.js'
+60
src/lexicons/com/atproto/repo/listRecords.defs.ts
···11+/*
22+ * THIS FILE WAS GENERATED BY "@atproto/lex". DO NOT EDIT.
33+ */
44+55+import { l } from '@atproto/lex'
66+77+const $nsid = 'com.atproto.repo.listRecords'
88+99+export { $nsid }
1010+1111+/** List a range of records in a repository, matching a specific collection. Does not require auth. */
1212+const main = l.query(
1313+ $nsid,
1414+ l.params({
1515+ repo: l.string({ format: 'at-identifier' }),
1616+ limit: l.optional(
1717+ l.withDefault(l.integer({ maximum: 100, minimum: 1 }), 50),
1818+ ),
1919+ cursor: l.optional(l.string()),
2020+ reverse: l.optional(l.boolean()),
2121+ collection: l.string({ format: 'nsid' }),
2222+ }),
2323+ l.jsonPayload({
2424+ cursor: l.optional(l.string()),
2525+ records: l.array(l.ref<Record$0>((() => record$0) as any)),
2626+ }),
2727+)
2828+export { main }
2929+3030+export type $Params = l.InferMethodParams<typeof main>
3131+export type $Output<B = l.BinaryData> = l.InferMethodOutput<typeof main, B>
3232+export type $OutputBody<B = l.BinaryData> = l.InferMethodOutputBody<
3333+ typeof main,
3434+ B
3535+>
3636+3737+export const $lxm = main.nsid,
3838+ $params = main.parameters,
3939+ $output = main.output
4040+4141+type Record$0 = {
4242+ $type?: 'com.atproto.repo.listRecords#record'
4343+ cid: l.CidString
4444+ uri: l.AtUriString
4545+ value: l.LexMap
4646+}
4747+4848+export type { Record$0 as Record }
4949+5050+const record$0 = l.typedObject<Record$0>(
5151+ $nsid,
5252+ 'record',
5353+ l.object({
5454+ cid: l.string({ format: 'cid' }),
5555+ uri: l.string({ format: 'at-uri' }),
5656+ value: l.lexMap(),
5757+ }),
5858+)
5959+6060+export { record$0 as record }
+6
src/lexicons/com/atproto/repo/listRecords.ts
···11+/*
22+ * THIS FILE WAS GENERATED BY "@atproto/lex". DO NOT EDIT.
33+ */
44+55+export * from './listRecords.defs.js'
66+export * as $defs from './listRecords.defs.js'