PageSourceSearch

https://abonnement.1881.no/_next/static/chunks/0fowh4qs6z~i6.js

js 1881.no collected 2026-09-24 09:23:12 UTC 529,557 bytes, 90 lines download raw bytes

1;!function(){try { var e="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof global?global:"undefined"!=typeof window?window:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&((e._debugIds|| (e._debugIds={}))[n]="448a9f9d-f240-7e99-45d2-8d91745482af")}catch(e){}}();
2(globalThis.TURBOPACK||(globalThis.TURBOPACK=[])).push(["object"==typeof document?document.currentScript:void 0,381245,e=>{"use strict";let t,i;var r,s,a,n=e.i(353606),l=e.i(914543);let o=["abort","canplay","canplaythrough","durationchange","emptied","encrypted","ended","error","loadeddata","loadedmetadata","loadstart","pause","play","playing","progress","ratechange","seeked","seeking","stalled","suspend","timeupdate","volumechange","waiting","waitingforkey","resize","enterpictureinpicture","leavepictureinpicture","webkitbeginfullscreen","webkitendfullscreen","webkitpresentationmodechanged"],h=["autopictureinpicture","disablepictureinpicture","disableremoteplayback","autoplay","controls","controlslist","crossorigin","loop","muted","playsinline","poster","preload","src"];function d(e){return`
3    <style>
4      :host {
5        display: inline-flex;
6        line-height: 0;
7        flex-direction: column;
8        justify-content: end;
9      }
10
11      audio {
12        width: 100%;
13      }
14    </style>
15    <slot name="media">
16      <audio${g(e)}></audio>
17    </slot>
18    <slot></slot>
19  `}function c(e){return`
20    <style>
21      :host {
22        display: inline-block;
23        line-height: 0;
24      }
25
26      video {
27        max-width: 100%;
28        max-height: 100%;
29        min-width: 100%;
30        min-height: 100%;
31        object-fit: var(--media-object-fit, contain);
32        object-position: var(--media-object-position, 50% 50%);
33      }
34
35      video::-webkit-media-text-track-container {
36        transform: var(--media-webkit-text-track-transform);
37        transition: var(--media-webkit-text-track-transition);
38      }
39    </style>
40    <slot name="media">
41      <video${g(e)}></video>
42    </slot>
43    <slot></slot>
44  `}function f(e,{tag:t,is:i}){let r=globalThis.document?.createElement?.(t,{is:i}),s=r?function(e){let t=[];for(let i=Object.getPrototypeOf(e);i&&i!==HTMLElement.prototype;i=Object.getPrototypeOf(i)){let e=Object.getOwnPropertyNames(i);t.push(...e)}return t}(r):[];return class a extends e{static getTemplateHTML=t.endsWith("audio")?d:c;static shadowRootOptions={mode:"open"};static Events=o;static #e=!1;static get observedAttributes(){return a.#t(),[...r?.constructor?.observedAttributes??[],...h]}static #t(){if(this.#e)return;this.#e=!0;let e=new Set(this.observedAttributes);for(let t of(e.delete("muted"),s))if(!(t in this.prototype))if("function"==typeof r[t])this.prototype[t]=function(...e){return this.#i(),this.call?this.call(t,...e):this.nativeEl?.[t]?.apply(this.nativeEl,e)};else{let i={get(){this.#i();let i=t.toLowerCase();if(e.has(i)){let e=this.getAttribute(i);return null!==e&&(""===e||e)}return this.get?.(t)??this.nativeEl?.[t]}};t!==t.toUpperCase()&&(i.set=function(i){this.#i();let r=t.toLowerCase();e.has(r)?!0===i||!1===i||null==i?this.toggleAttribute(r,!!i):this.setAttribute(r,i):this.set?this.set(t,i):this.nativeEl&&(this.nativeEl[t]=i)}),Object.defineProperty(this.prototype,t,i)}}#r=!1;#s=null;#a=new Map;#n;#l;get;set;call;get nativeEl(){return this.#i(),this.#s??this.querySelector(":scope > [slot=media]")??this.querySelector(t)??this.shadowRoot?.querySelector(t)??null}set nativeEl(e){this.#s=e}get defaultMuted(){return this.hasAttribute("muted")}set defaultMuted(e){this.toggleAttribute("muted",e)}get src(){return this.getAttribute("src")}set src(e){this.setAttribute("src",`${e}`)}get preload(){return this.getAttribute("preload")??this.nativeEl?.preload}set preload(e){this.setAttribute("preload",`${e}`)}#i(){this.#r||(this.#r=!0,this.init())}init(){if(!this.shadowRoot){this.attachShadow({mode:"open"});let e=function(e){let t={};for(let i of e)t[i.name]=i.value;return t}(this.attributes);i&&(e.is=i),t&&(e.part=t),this.shadowRoot.innerHTML=this.constructor.getTemplateHTML(e)}for(let e of(this.nativeEl.muted=this.hasAttribute("muted"),s))this.#o(e);this.#h()}#h(){for(let e of(this.#n=new MutationObserver(this.#d.bind(this)),this.#l=()=>this.#u(),this.shadowRoot?.addEventListener("slotchange",this.#l),this.#u(),this.constructor.Events))this.shadowRoot?.addEventListener(e,this,!0)}handleEvent(e){e.target===this.nativeEl&&this.dispatchEvent(new CustomEvent(e.type,{detail:e.detail}))}#u(){let e=new Map(this.#a);(this.shadowRoot?.querySelector("slot:not([name])")?.assignedElements({flatten:!0}).filter(e=>
44["track","source"].includes(e.localName))).forEach(t=>{e.delete(t);let i=this.#a.get(t);i||(i=t.cloneNode(),this.#a.set(t,i),this.#n?.observe(t,{attributes:!0})),this.nativeEl?.append(i),this.#c(i)}),e.forEach((e,t)=>{e.remove(),this.#a.delete(t)})}#d(e){for(let t of e)if("attributes"===t.type){let{target:e,attributeName:i}=t,r=this.#a.get(e);r&&i&&(r.setAttribute(i,e.getAttribute(i)??""),this.#c(r))}}#c(e){e&&"track"===e.localName&&e.default&&("chapters"===e.kind||"metadata"===e.kind)&&"disabled"===e.track.mode&&(e.track.mode="hidden")}#o(e){if(Object.prototype.hasOwnProperty.call(this,e)){let t=this[e];delete this[e],this[e]=t}}attributeChangedCallback(e,t,i){this.#i(),this.#f(e,t,i)}#f(e,t,i){["id","class"].includes(e)||!a.observedAttributes.includes(e)&&this.constructor.observedAttributes.includes(e)||(null===i?this.nativeEl?.removeAttribute(e):this.nativeEl?.getAttribute(e)!==i&&this.nativeEl?.setAttribute(e,i))}connectedCallback(){this.#i(),this.#l||this.#h()}disconnectedCallback(){for(let e of(this.#n?.disconnect(),this.#n=void 0,this.#l&&(this.shadowRoot?.removeEventListener("slotchange",this.#l),this.#l=void 0),this.constructor.Events))this.shadowRoot?.removeEventListener(e,this,!0);this.#a.forEach(e=>e.remove()),this.#a.clear(),this.#s=null}}}function g(e){let t="";for(let i in e){if(!h.includes(i))continue;let r=e[i];""===r?t+=` ${i}`:t+=` ${i}="${r}"`}return t}let m=f(globalThis.HTMLElement??class{},{tag:"video"});f(globalThis.HTMLElement??class{},{tag:"audio"});
44class p extends Event{track;constructor(e,t){super(e),this.track=t.track}}let y=new WeakMap;function v(e){var t,i;let r;return y.get(e)??(t=e,i={},(r=y.get(t))||y.set(t,r={}),Object.assign(r,i))}function E(e,t){let i=e.videoTracks;v(t).media=new WeakRef(e),v(t).renditionSet||(v(t).renditionSet=new Set);let r=v(i).trackSet;r.add(t);let s=r.size-1;s in S.prototype||Object.defineProperty(S.prototype,s,{get(){return[...v(this).trackSet][s]}}),queueMicrotask(()=>{i.dispatchEvent(new p("addtrack",{track:t}))})}function T(e){let t=v(e).media?.deref()?.videoTracks;t&&(v(t).trackSet.delete(e),queueMicrotask(()=>{t.dispatchEvent(new p("removetrack",{track:e}))}))}class S extends EventTarget{#l;#a;#r;constructor(){super(),v(this).trackSet=new Set}get #i(){return v(this).trackSet}[Symbol.iterator](){return this.#i.values()}get length(){return this.#i.size}getTrackById(e){return[...this.#i].find(t=>t.id===e)??null}get selectedIndex(){return[...this.#i].findIndex(e=>e.selected)}get onaddtrack(){return this.#l}set onaddtrack(e){this.#l&&(this.removeEventListener("addtrack",this.#l),this.#l=void 0),"function"==typeof e&&(this.#l=e,this.addEventListener("addtrack",e))}get onremovetrack(){return this.#a}set onremovetrack(e){this.#a&&(this.removeEventListener("removetrack",this.#a),this.#a=void 0),"function"==typeof e&&(this.#a=e,this.addEventListener("removetrack",e))}get onchange(){return this.#r}set onchange(e){this.#r&&(this.removeEventListener("change",this.#r),this.#r=void 0),"function"==typeof e&&(this.#r=e,this.addEventListener("change",e))}}class L extends Event{rendition;constructor(e,t){super(e),this.rendition=t.rendition}}function A(e){let t=v(e).media?.deref();return t?[...t.videoTracks].filter(e=>e.selected).flatMap(e=>[...v(e).renditionSet]):[]}class R extends EventTarget{#l;#a;#i;[Symbol.iterator](){return A(this).values()}get length(){return A(this).length}getRenditionById(e){return A(this).find(t=>`${t.id}`==`${e}`)??null}get selectedIndex(){return A(this).findIndex(e=>e.selected)}set selectedIndex(e){for(let[t,i]of A(this).entries())i.selected=t===e}get onaddrendition(){return this.#l}set onaddrendition(e){this.#l&&(this.removeEventListener("addrendition",this.#l),this.#l=void 0),"function"==typeof e&&(this.#l=e,this.addEventListener("addrendition",e))}get onremoverendition(){return this.#a}set onremoverendition(e){this.#a&&(this.removeEventListener("removerendition",this.#a),this.#a=void 0),"function"==typeof e&&(this.#a=e,this.addEventListener("removerendition",e))}get onchange(){return this.#i}set onchange(e){this.#i&&(this.removeEventListener("change",this.#i),this.#i=void 0),"function"==typeof e&&(this.#i=e,this.addEventListener("change",e))}}class b{src;id;width;height;bitrate;frameRate;codec;#l=!1;get selected(){return this.#l}set selected(e){var t;let i;this.#l!==e&&(this.#l=e,t=this,(i=v(t).media?.deref()?.videoRenditions)&&!v(i).changeRequested&&(v(i).changeRequested=!0,queueMicrotask(()=>{delete v(i).changeRequested,v(t).track.selected&&i.dispatchEvent(new Event("change"))})))}}class k{id;kind;label="";language="";sourceBuffer;#l=!1;addRendition(e,t,i,r,s,a){var n;let l,o,h,d=new b;return d.src=e,d.width=t,d.height=i,d.frameRate=a,d.bitrate=s,d.codec=r,n=this,l=v(n).media?.deref()?.videoRenditions,v(d).media=v(n).media,v(d).track=n,(o=v(n).renditionSet).add(d),(h=o.size-1)in R.prototype||Object.defineProperty(R.prototype,h,{get(){return A(this)[h]}}),queueMicrotask(()=>{l&&n.selected&&l.dispatchEvent(new L("addrendition",{rendition:d}))}),d}removeRendition(e){let t,i;t=v(e).media?.deref()?.videoRenditions,i=v(e).track,v(i).renditionSet.delete(e),queueMicrotask(()=>{let i=v(e).track;t&&i.selected&&t.dispatchEvent(new L("removerendition",{rendition:e}))})}get selected(){return this.#l}set selected(e){this.#l!==e&&(this.#l=e,!0===e&&function(e){let t=v(e).media?.deref()?.videoTracks??[],i=!1;for(let r of t)r!==e&&(r.selected=!1,i=!0);if(i){if(v(t).changeRequested)return;v(t).changeRequested=!0,queueMicrotask(()=>{delete v(t).changeRequested,t.dispatchEvent(new Event("change"))})}}(this))}}function I(e){let t=v(e).media?.deref();return t?[...t.audioTracks].filter(e=>e.enabled).flatMap(e=>[...v(e).renditionSet]):[]}
44class D extends EventTarget{#l;#a;#e;[Symbol.iterator](){return I(this).values()}get length(){return I(this).length}getRenditionById(e){return I(this).find(t=>`${t.id}`==`${e}`)??null}get selectedIndex(){return I(this).findIndex(e=>e.selected)}set selectedIndex(e){for(let[t,i]of I(this).entries())i.selected=t===e}get onaddrendition(){return this.#l}set onaddrendition(e){this.#l&&(this.removeEventListener("addrendition",this.#l),this.#l=void 0),"function"==typeof e&&(this.#l=e,this.addEventListener("addrendition",e))}get onremoverendition(){return this.#a}set onremoverendition(e){this.#a&&(this.removeEventListener("removerendition",this.#a),this.#a=void 0),"function"==typeof e&&(this.#a=e,this.addEventListener("removerendition",e))}get onchange(){return this.#e}set onchange(e){this.#e&&(this.removeEventListener("change",this.#e),this.#e=void 0),"function"==typeof e&&(this.#e=e,this.addEventListener("change",e))}}class _{src;id;bitrate;codec;#l=!1;get selected(){return this.#l}set selected(e){var t;let i;this.#l!==e&&(this.#l=e,t=this,(i=v(t).media?.deref()?.audioRenditions)&&!v(i).changeRequested&&(v(i).changeRequested=!0,queueMicrotask(()=>{delete v(i).changeRequested,v(t).track.enabled&&i.dispatchEvent(new Event("change"))})))}}function P(e,t){let i=e.audioTracks;v(t).media=new WeakRef(e),v(t).renditionSet||(v(t).renditionSet=new Set);let r=v(i).trackSet;r.add(t);let s=r.size-1;s in w.prototype||Object.defineProperty(w.prototype,s,{get(){return[...v(this).trackSet][s]}}),queueMicrotask(()=>{i.dispatchEvent(new p("addtrack",{track:t}))})}function C(e){let t=v(e).media?.deref()?.audioTracks;t&&(v(t).trackSet.delete(e),queueMicrotask(()=>{t.dispatchEvent(new p("removetrack",{track:e}))}))}class w extends EventTarget{#l;#a;#r;constructor(){super(),v(this).trackSet=new Set}get #i(){return v(this).trackSet}[Symbol.iterator](){return this.#i.values()}get length(){return this.#i.size}getTrackById(e){return[...this.#i].find(t=>t.id===e)??null}get onaddtrack(){return this.#l}set onaddtrack(e){this.#l&&(this.removeEventListener("addtrack",this.#l),this.#l=void 0),"function"==typeof e&&(this.#l=e,this.addEventListener("addtrack",e))}get onremovetrack(){return this.#a}set onremovetrack(e){this.#a&&(this.removeEventListener("removetrack",this.#a),this.#a=void 0),"function"==typeof e&&(this.#a=e,this.addEventListener("removetrack",e))}get onchange(){return this.#r}set onchange(e){this.#r&&(this.removeEventListener("change",this.#r),this.#r=void 0),"function"==typeof e&&(this.#r=e,this.addEventListener("change",e))}}class x{id;kind;label="";language="";sourceBuffer;#l=!1;addRendition(e,t,i){var r;let s,a,n,l=new _;return l.src=e,l.codec=t,l.bitrate=i,r=this,s=v(r).media?.deref()?.audioRenditions,v(l).media=v(r).media,v(l).track=r,(a=v(r).renditionSet).add(l),(n=a.size-1)in D.prototype||Object.defineProperty(D.prototype,n,{get(){return I(this)[n]}}),queueMicrotask(()=>{s&&r.enabled&&s.dispatchEvent(new L("addrendition",{rendition:l}))}),l}removeRendition(e){let t,i;t=v(e).media?.deref()?.audioRenditions,i=v(e).track,v(i).renditionSet.delete(e),queueMicrotask(()=>{let i=v(e).track;t&&i.enabled&&t.dispatchEvent(new L("removerendition",{rendition:e}))})}get enabled(){return this.#l}set enabled(e){let t;this.#l!==e&&(this.#l=e,(t=v(this).media?.deref()?.audioTracks)&&!v(t).changeRequested&&(v(t).changeRequested=!0,queueMicrotask(()=>{delete v(t).changeRequested,t.dispatchEvent(new Event("change"))})))}}let M=F(globalThis.HTMLMediaElement,"video"),O=F(globalThis.HTMLMediaElement,"audio");function F(e,t){if(e?.prototype)return Object.getOwnPropertyDescriptor(e.prototype,`${t}Tracks`)?.get}let $=Number.isFinite||function(e){return"number"==typeof e&&isFinite(e)},B=Number.isSafeInteger||function(e){return"number"==typeof e&&Math.abs(e)<=U},U=Number.MAX_SAFE_INTEGER||0x1fffffffffffff,N=((ey={}).NETWORK_ERROR="networkError",ey.MEDIA_ERROR="mediaError",ey.KEY_SYSTEM_ERROR="keySystemError",ey.MUX_ERROR="muxError",ey.OTHER_ERROR="otherError",ey),G=((ev={}).KEY_SYSTEM_NO_KEYS="keySystemNoKeys",ev.KEY_SYSTEM_NO_ACCESS="keySystemNoAccess",ev.KEY_SYSTEM_NO_SESSION="keySystemNoSession",ev.KEY_SYSTEM_NO_CONFIGURED_LICENSE="keySystemNoConfiguredLicense",ev.KEY_SYSTEM_LICENSE_REQUEST_FAILED="keySystemLicenseRequestFailed",ev.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED="keySystemServerCertificateRequestFailed",ev.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED="keySystemServerCertificateUpdateFailed",ev.KEY_SYSTEM_SESSION_UPDATE_FAILED="keySystemSessionUpdateFailed",ev.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED="keySystemStatusOutputRestricted",ev.KEY_SYSTEM_STATUS_INTERNAL_ERROR="keySystemStatusInternalError",ev.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR="keySystemDestroyMediaKeysError",ev.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR="keySystemDestroyCloseSessionError",ev.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR="keySystemDestroyRemoveSessionError",ev.MANIFEST_LOAD_ERROR="manifestLoadError",ev.MANIFEST_LOAD_TIMEOUT="manifestLoadTimeOut",ev.MANIFEST_PARSING_ERROR="manifestParsingError",ev.MANIFEST_INCOMPATIBLE_CODECS_ERROR="manifestIncompatibleCodecsError",ev.LEVEL_EMPTY_ERROR="levelEmptyError",ev.LEVEL_LOAD_ERROR="levelLoadError",ev.LEVEL_LOAD_TIMEOUT="levelLoadTimeOut",ev.LEVEL_PARSING_ERROR="levelParsingError",ev.LEVEL_SWITCH_ERROR="levelSwitchError",ev.AUDIO_TRACK_LOAD_ERROR="audioTrackLoadError",ev.AUDIO_TRACK_LOAD_TIMEOUT="audioTrackLoadTimeOut",ev.SUBTITLE_LOAD_ERROR="subtitleTrackLoadError",ev.SUBTITLE_TRACK_LOAD_TIMEOUT="subtitleTrackLoadTimeOut",ev.FRAG_LOAD_ERROR="fragLoadError",ev.FRAG_LOAD_TIMEOUT="fragLoadTimeOut",ev.FRAG_DECRYPT_ERROR="fragDecryptError",ev.FRAG_PARSING_ERROR="fragParsingError",ev.FRAG_GAP="fragGap",ev.REMUX_ALLOC_ER
44ROR="remuxAllocError",ev.KEY_LOAD_ERROR="keyLoadError",ev.KEY_LOAD_TIMEOUT="keyLoadTimeOut",ev.BUFFER_ADD_CODEC_ERROR="bufferAddCodecError",ev.BUFFER_INCOMPATIBLE_CODECS_ERROR="bufferIncompatibleCodecsError",ev.BUFFER_APPEND_ERROR="bufferAppendError",ev.BUFFER_APPENDING_ERROR="bufferAppendingError",ev.BUFFER_STALLED_ERROR="bufferStalledError",ev.BUFFER_FULL_ERROR="bufferFullError",ev.BUFFER_SEEK_OVER_HOLE="bufferSeekOverHole",ev.BUFFER_NUDGE_ON_STALL="bufferNudgeOnStall",ev.ASSET_LIST_LOAD_ERROR="assetListLoadError",ev.ASSET_LIST_LOAD_TIMEOUT="assetListLoadTimeout",ev.ASSET_LIST_PARSING_ERROR="assetListParsingError",ev.INTERSTITIAL_ASSET_ITEM_ERROR="interstitialAssetItemError",ev.INTERNAL_EXCEPTION="internalException",ev.INTERNAL_ABORTED="aborted",ev.ATTACH_MEDIA_ERROR="attachMediaError",ev.UNKNOWN="unknown",ev),K=((eE={}).MEDIA_ATTACHING="hlsMediaAttaching",eE.MEDIA_ATTACHED="hlsMediaAttached",eE.MEDIA_DETACHING="hlsMediaDetaching",eE.MEDIA_DETACHED="hlsMediaDetached",eE.MEDIA_ENDED="hlsMediaEnded",eE.STALL_RESOLVED="hlsStallResolved",eE.BUFFER_RESET="hlsBufferReset",eE.BUFFER_CODECS="hlsBufferCodecs",eE.BUFFER_CREATED="hlsBufferCreated",eE.BUFFER_APPENDING="hlsBufferAppending",eE.BUFFER_APPENDED="hlsBufferAppended",eE.BUFFER_EOS="hlsBufferEos",eE.BUFFERED_TO_END="hlsBufferedToEnd",eE.BUFFER_FLUSHING="hlsBufferFlushing",eE.BUFFER_FLUSHED="hlsBufferFlushed",eE.MANIFEST_LOADING="hlsManifestLoading",eE.MANIFEST_LOADED="hlsManifestLoaded",eE.MANIFEST_PARSED="hlsManifestParsed",eE.LEVEL_SWITCHING="hlsLevelSwitching",eE.LEVEL_SWITCHED="hlsLevelSwitched",eE.LEVEL_LOADING="hlsLevelLoading",eE.LEVEL_LOADED="hlsLevelLoaded",eE.LEVEL_UPDATED="hlsLevelUpdated",eE.LEVEL_PTS_UPDATED="hlsLevelPtsUpdated",eE.LEVELS_UPDATED="hlsLevelsUpdated",eE.AUDIO_TRACKS_UPDATED="hlsAudioTracksUpdated",eE.AUDIO_TRACK_SWITCHING="hlsAudioTrackSwitching",eE.AUDIO_TRACK_SWITCHED="hlsAudioTrackSwitched",eE.AUDIO_TRACK_LOADING="hlsAudioTrackLoading",eE.AUDIO_TRACK_LOADED="hlsAudioTrackLoaded",eE.AUDIO_TRACK_UPDATED="hlsAudioTrackUpdated",eE.SUBTITLE_TRACKS_UPDATED="hlsSubtitleTracksUpdated",eE.SUBTITLE_TRACKS_CLEARED="hlsSubtitleTracksCleared",eE.SUBTITLE_TRACK_SWITCH="hlsSubtitleTrackSwitch",eE.SUBTITLE_TRACK_LOADING="hlsSubtitleTrackLoading",eE.SUBTITLE_TRACK_LOADED="hlsSubtitleTrackLoaded",eE.SUBTITLE_TRACK_UPDATED="hlsSubtitleTrackUpdated",eE.SUBTITLE_FRAG_PROCESSED="hlsSubtitleFragProcessed",eE.CUES_PARSED="hlsCuesParsed",eE.NON_NATIVE_TEXT_TRACKS_FOUND="hlsNonNativeTextTracksFound",eE.INIT_PTS_FOUND="hlsInitPtsFound",eE.FRAG_LOADING="hlsFragLoading",eE.FRAG_LOAD_EMERGENCY_ABORTED="hlsFragLoadEmergencyAborted",eE.FRAG_LOADED="hlsFragLoaded",eE.FRAG_DECRYPTED="hlsFragDecrypted",eE.FRAG_PARSING_INIT_SEGMENT="hlsFragParsingInitSegment",eE.FRAG_PARSING_USERDATA="hlsFragParsingUserdata",eE.FRAG_PARSING_METADATA="hlsFragParsingMetadata",eE.FRAG_PARSED="hlsFragParsed",eE.FRAG_BUFFERED="hlsFragBuffered",eE.FRAG_CHANGED="hlsFragChanged",eE.FPS_DROP="hlsFpsDrop",eE.FPS_DROP_LEVEL_CAPPING="hlsFpsDropLevelCapping",eE.MAX_AUTO_LEVEL_UPDATED="hlsMaxAutoLevelUpdated",eE.ERROR="hlsError",eE.DESTROYING="hlsDestroying",eE.KEY_LOADING="hlsKeyLoading",eE.KEY_LOADED="hlsKeyLoaded",eE.LIVE_BACK_BUFFER_REACHED="hlsLiveBackBufferReached",eE.BACK_BUFFER_REACHED="hlsBackBufferReached",eE.STEERING_MANIFEST_LOADED="hlsSteeringManifestLoaded",eE.ASSET_LIST_LOADING="hlsAssetListLoading",eE.ASSET_LIST_LOADED="hlsAssetListLoaded",eE.INTERSTITIALS_UPDATED="hlsInterstitialsUpdated",eE.INTERSTITIALS_BUFFERED_TO_BOUNDARY="hlsInterstitialsBufferedToBoundary",eE.INTERSTITIAL_ASSET_PLAYER_CREATED="hlsInterstitialAssetPlayerCreated",eE.INTERSTITIAL_STARTED="hlsInterstitialStarted",eE.INTERSTITIAL_ASSET_STARTED="hlsInterstitialAssetStarted",eE.INTERSTITIAL_ASSET_ENDED="hlsInterstitialAssetEnded",eE.INTERSTITIAL_ASSET_ERROR="hlsInterstitialAssetError",eE.INTERSTITIAL_ENDED="hlsInterstitialEnded",eE.INTERSTITIALS_PRIMARY_RESUMED="hlsInterstitialsPrimaryResumed",eE.PLAYOUT_LIMIT_REACHED="hlsPlayoutLimitReached",eE.EVENT_CUE_ENTER="hlsEventCueEnter",eE);var H="manifest",V="level",j="audioTrack",W="subtitleTrack",q="main",Y="audio",X="subtitle";class z{constructor(e,t=0,i=0){this.halfLife=void 0,this.alpha_=void 0,this.estimate_=void 0,this.totalWeight_=void 0,this.halfLife=e,this.alpha_=e?Math.exp(Math.log(.5)/e):0,this.estimate_=t,this.totalWeight_=i}sample(e,t){let i=Math.pow(this.alpha_,e);this.estimate_=t*(1-i)+i*this.estimate_,this.totalWeight_+=e}
44getTotalWeight(){return this.totalWeight_}getEstimate(){if(this.alpha_){let e=1-Math.pow(this.alpha_,this.totalWeight_);if(e)return this.estimate_/e}return this.estimate_}}class Q{constructor(e,t,i,r=100){this.defaultEstimate_=void 0,this.minWeight_=void 0,this.minDelayMs_=void 0,this.slow_=void 0,this.fast_=void 0,this.defaultTTFB_=void 0,this.ttfb_=void 0,this.defaultEstimate_=i,this.minWeight_=.001,this.minDelayMs_=50,this.slow_=new z(e),this.fast_=new z(t),this.defaultTTFB_=r,this.ttfb_=new z(e)}update(e,t){let{slow_:i,fast_:r,ttfb_:s}=this;i.halfLife!==e&&(this.slow_=new z(e,i.getEstimate(),i.getTotalWeight())),r.halfLife!==t&&(this.fast_=new z(t,r.getEstimate(),r.getTotalWeight())),s.halfLife!==e&&(this.ttfb_=new z(e,s.getEstimate(),s.getTotalWeight()))}sample(e,t){let i=(e=Math.max(e,this.minDelayMs_))/1e3,r=8*t/i;this.fast_.sample(i,r),this.slow_.sample(i,r)}sampleTTFB(e){let t=Math.sqrt(2)*Math.exp(-Math.pow(e/1e3,2)/2);this.ttfb_.sample(t,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 Z(){return(Z=Object.assign.bind()).apply(null,arguments)}function J(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),i.push.apply(i,r)}return i}function ee(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?J(Object(i),!0).forEach(function(t){var r,s;r=t,s=i[t],(r=function(e){var t=function(e,t){if("object"!=typeof e||!e)return e;var i=e[Symbol.toPrimitive];if(void 0!==i){var r=i.call(e,t);if("object"!=typeof r)return r;throw TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");return"symbol"==typeof t?t:t+""}(r))in e?Object.defineProperty(e,r,{value:s,enumerable:!0,configurable:!0,writable:!0}):e[r]=s}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):J(Object(i)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(i,t))})}return e}class et{constructor(e,t){this.trace=void 0,this.debug=void 0,this.log=void 0,this.warn=void 0,this.info=void 0,this.error=void 0;const i=`[${e}]:`;this.trace=ei,this.debug=t.debug.bind(null,i),this.log=t.log.bind(null,i),this.warn=t.warn.bind(null,i),this.info=t.info.bind(null,i),this.error=t.error.bind(null,i)}}let ei=function(){},er={trace:ei,debug:ei,log:ei,warn:ei,info:ei,error:ei};function es(){return Z({},er)}function ea(e,t,i){let r;return t[e]?t[e].bind(t):(r=self.console[e])?r.bind(self.console,`${i?"["+i+"] ":""}[${e}] >`):ei}let en=es();function el(e=!0){return typeof self>"u"?void 0:(e||!self.MediaSource)&&self.ManagedMediaSource||self.MediaSource||self.WebKitMediaSource}function eo(e,t){let i=Object.keys(e),r=Object.keys(t),s=i.length,a=r.length;return!s||!a||s===a&&!i.some(e=>-1===r.indexOf(e))}function eh(e,t=!1){if("u">typeof TextDecoder){let i=new TextDecoder("utf-8").decode(e);if(t){let e=i.indexOf("\0");return -1!==e?i.substring(0,e):i}return i.replace(/\0/g,"")}let i=e.length,r,s,a="",n=0;for(;n<i&&(0!==(r=e[n++])||!t);)if(0!==r&&3!==r)switch(r>>4){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:a+=String.fromCharCode(r);break;case 12:case 13:a+=String.fromCharCode((31&r)<<6|63&(s=e[n++]));break;case 14:a+=String.fromCharCode((15&r)<<12|(63&(s=e[n++]))<<6|63&e[n++])}return a}function ed(e){let t="";for(let i=0;i<e.length;i++){let r=e[i].toString(16);r.length<2&&(r="0"+r),t+=r}return t}function eu(e){return Uint8Array.from(e.replace(/^0x/,"").replace(/([\da-fA-F]{2}) ?/g,"0x$1 ").replace(/ +$/,"").split(" ")).buffer}var ec,ef,eg,em,ep,ey,ev,eE,eT,eS={exports:{}},eL=(eT||(eT=1,ec=/^(?=((?:[a-zA-Z0-9+\-.]+:)?))\1(?=((?:\/\/[^\/?#]*)?))\2(?=((?:(?:[^?#\/]*\/)*[^;?#\/]*)?))\3((?:;[^?#]*)?)(\?[^#]*)?(#[^]*)?$/,ef=/^(?=([^\/?#]*))\1([^]*)$/,eg=/(?:\/|^)\.(?=\/)/g,em=/(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g,eS.exports=ep={buildAbsoluteURL:function(e,t,i){if(i=i||{},e=e.trim(),!(t=t.trim())){if(!i.alwaysNormalize)return e;var r=ep.parseURL(e);if(!r)throw Error("Error trying to parse base URL.");return r.path=ep.normalizePath(r.path),ep.buildURLFromParts(r)}var s=ep.parseURL(t);if(!s)throw Error("Error trying to parse relative URL.");
44if(s.scheme)return i.alwaysNormalize?(s.path=ep.normalizePath(s.path),ep.buildURLFromParts(s)):t;var a=ep.parseURL(e);if(!a)throw Error("Error trying to parse base URL.");if(!a.netLoc&&a.path&&"/"!==a.path[0]){var n=ef.exec(a.path);a.netLoc=n[1],a.path=n[2]}a.netLoc&&!a.path&&(a.path="/");var l={scheme:a.scheme,netLoc:s.netLoc,path:null,params:s.params,query:s.query,fragment:s.fragment};if(!s.netLoc&&(l.netLoc=a.netLoc,"/"!==s.path[0]))if(s.path){var o=a.path,h=o.substring(0,o.lastIndexOf("/")+1)+s.path;l.path=ep.normalizePath(h)}else l.path=a.path,s.params||(l.params=a.params,s.query||(l.query=a.query));return null===l.path&&(l.path=i.alwaysNormalize?ep.normalizePath(s.path):s.path),ep.buildURLFromParts(l)},parseURL:function(e){var t=ec.exec(e);return t?{scheme:t[1]||"",netLoc:t[2]||"",path:t[3]||"",params:t[4]||"",query:t[5]||"",fragment:t[6]||""}:null},normalizePath:function(e){for(e=e.split("").reverse().join("").replace(eg,"");e.length!==(e=e.replace(em,"")).length;);return e.split("").reverse().join("")},buildURLFromParts:function(e){return e.scheme+e.netLoc+e.path+e.params+e.query+e.fragment}}),eS.exports);class eA{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 eR="audio",eb="video",ek="audiovideo";class eI{constructor(e){this._byteRange=null,this._url=null,this._stats=null,this._streams=null,this.base=void 0,this.relurl=void 0,"string"==typeof e&&(e={url:e}),this.base=e,function(e,t){let i=function e(t,i){let r=Object.getPrototypeOf(t);if(r)return Object.getOwnPropertyDescriptor(r,i)||e(r,i)}(e,t);i&&(i.enumerable=!0,Object.defineProperty(e,t,i))}(this,"stats")}setByteRange(e,t){let i,r=e.split("@",2);i=1===r.length?t?.byteRangeEndOffset||0:parseInt(r[1]),this._byteRange=[i,parseInt(r[0])+i]}get baseurl(){return this.base.url}get byteRange(){return null===this._byteRange?[]:this._byteRange}get byteRangeStartOffset(){return this.byteRange[0]}get byteRangeEndOffset(){return this.byteRange[1]}get elementaryStreams(){return null===this._streams&&(this._streams={[eR]:null,[eb]:null,[ek]:null}),this._streams}set elementaryStreams(e){this._streams=e}get hasStats(){return null!==this._stats}get hasStreams(){return null!==this._streams}get stats(){return null===this._stats&&(this._stats=new eA),this._stats}set stats(e){this._stats=e}get url(){return!this._url&&this.baseurl&&this.relurl&&(this._url=eL.buildAbsoluteURL(this.baseurl,this.relurl,{alwaysNormalize:!0})),this._url||""}set url(e){this._url=e}clearElementaryStreamInfo(){let{elementaryStreams:e}=this;e[eR]=null,e[eb]=null,e[ek]=null}}function eD(e){return"initSegment"!==e.sn}class e_ extends eI{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){let e=this.stats.total;if(e)return e}if(this.byteRange.length){let e=this.byteRange[0],t=this.byteRange[1];if($(e)&&$(t))return t-e}return null}get bitrate(){return this.byteLength?8*this.byteLength/this.duration:this._bitrate?this._bitrate:null}set bitrate(e){this._bitrate=e}get decryptdata(){var e;let{levelkeys:t}=this;if(!t||t.NONE)return null;if(t.identity)this._decryptdata||(this._decryptdata=t.identity.getDecryptData(this.sn));else if(!(null!=(e=this._decryptdata)&&e.keyId)){let e=Object.keys(t);if(1===e.length){let i=this._decryptdata=t[e[0]]||null;i&&(this._decryptdata=i.getDecryptData(this.sn,t))}}return this._decryptdata}get end(){return this.start+this.duration}get endProgramDateTime(){if(null===this.programDateTime)return null;let e=$(this.duration)?this.duration:0;return this.programDateTime+1e3*e}get encrypted(){var e,t;if(null!=(e=this._decryptdata)&&e.encrypted)return!0;
44if(this.levelkeys){let e=Object.keys(this.levelkeys),i=e.length;if(i>1||1===i&&null!=(t=this.levelkeys[e[0]])&&t.encrypted)return!0}return!1}get programDateTime(){return null===this._programDateTime&&this.rawProgramDateTime&&(this.programDateTime=Date.parse(this.rawProgramDateTime)),this._programDateTime}set programDateTime(e){if(!$(e)){this._programDateTime=this.rawProgramDateTime=null;return}this._programDateTime=e}get ref(){return eD(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){let t=this.levelkeys;if(t){var i;let r=t[e];r&&!(null!=(i=this._decryptdata)&&i.keyId)&&(this._decryptdata=r.getDecryptData(this.sn,t))}}abortRequests(){var e,t;null==(e=this.loader)||e.abort(),null==(t=this.keyLoader)||t.abort()}setElementaryStreamInfo(e,t,i,r,s,a=!1){let{elementaryStreams:n}=this,l=n[e];if(!l){n[e]={startPTS:t,endPTS:i,startDTS:r,endDTS:s,partial:a};return}l.startPTS=Math.min(l.startPTS,t),l.endPTS=Math.max(l.endPTS,i),l.startDTS=Math.min(l.startDTS,r),l.endDTS=Math.max(l.endDTS,s)}}class eP extends eI{constructor(e,t,i,r,s){super(i),this.fragOffset=0,this.duration=0,this.gap=!1,this.independent=!1,this.relurl=void 0,this.fragment=void 0,this.index=void 0,this.duration=e.decimalFloatingPoint("DURATION"),this.gap=e.bool("GAP"),this.independent=e.bool("INDEPENDENT"),this.relurl=e.enumeratedString("URI"),this.fragment=t,this.index=r;const a=e.enumeratedString("BYTERANGE");a&&this.setByteRange(a,s),s&&(this.fragOffset=s.fragOffset+s.duration)}get start(){return this.fragment.start+this.fragOffset}get end(){return this.start+this.duration}get loaded(){let{elementaryStreams:e}=this;return!!(e.audio||e.video||e.audiovideo)}}let eC=[].push,ew={video:1,audio:2,id3:3,text:4};function ex(e){return String.fromCharCode.apply(null,e)}function eM(e,t){let i=e[t]<<8|e[t+1];return i<0?65536+i:i}function eO(e,t){let i=e$(e,t);return i<0?0x100000000+i:i}function eF(e,t){let i=eO(e,t);return i*=0x100000000,i+=eO(e,t+4)}function e$(e,t){return e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3]}function eB(e,t){let i=[];if(!t.length)return i;let r=e.byteLength;for(let s=0;s<r;){let a=eO(e,s),n=ex(e.subarray(s+4,s+8)),l=a>1?s+a:r;if(n===t[0])if(1===t.length)i.push(e.subarray(s+8,l));else{let r=eB(e.subarray(s+8,l),t.slice(1));r.length&&eC.apply(i,r)}s=l}return i}function eU(e){let t=[],i=eB(e,["moov","trak"]);for(let e=0;e<i.length;e++){let r=i[e],s=eB(r,["tkhd"])[0];if(s){let e=s[0],i=eO(s,0===e?12:20),a=eB(r,["mdia","mdhd"])[0];if(a){e=a[0];let s=eO(a,0===e?12:20),n=eB(r,["mdia","hdlr"])[0];if(n){let e=ex(n.subarray(8,12)),a={soun:eR,vide:eb}[e],l=function(e){let t=e.subarray(8),i=t.subarray(86),r=ex(t.subarray(4,8)),s=r,a,n="enca"===r||"encv"===r;if(n){let e=eB(t,[r])[0].subarray("enca"===r?28:78);eB(e,["sinf"]).forEach(e=>{let t=eB(e,["schm"])[0];if(t){let i=ex(t.subarray(4,8));if("cbcs"===i||"cenc"===i){let t=eB(e,["frma"])[0];t&&(s=ex(t))}}})}let l=s;switch(s){case"avc1":case"avc2":case"avc3":case"avc4":{let e=eB(i,["avcC"])[0];e&&e.length>3&&(s+="."+eK(e[1])+eK(e[2])+eK(e[3]),a=eN("avc1"===l?"dva1":"dvav",i));break}case"mp4a":{let e=eB(t,[r])[0],i=eB(e.subarray(28),["esds"])[0];if(i&&i.length>7){let e=4;if(3!==i[e++])break;e=eG(i,e)+2;let t=i[e++];if(128&t&&(e+=2),64&t&&(e+=i[e++]),4!==i[e++])break;e=eG(i,e);let r=i[e++];if(64===r)s+="."+eK(r);else break;if(e+=12,5!==i[e++])break;e=eG(i,e);let a=i[e++],n=(248&a)>>3;31===n&&(n+=1+((7&a)<<3)+((224&i[e])>>5)),s+="."+n}break}case"hvc1":case"hev1":{let e=eB(i,["hvcC"])[0];if(e&&e.length>12){let t=e[1],i=["","A","B","C"][t>>6],r=eO(e,2),a=e[12],n=e.subarray(6,12);s+="."+i+(31&t),s+="."+(function(e){let t=0;for(let i=0;i<32;i++)t|=(e>>i&1)<<31-i;return t>>>0})(r).toString(16).toUpperCase(),s+="."+((32&t)>>5?"H":"L")+a;let l="";for(let e=n.length;e--;){let t=n[e];(t||l)&&(l="."+t.toString(16).toUpperCase()+l)}s+=l}a=eN("hev1"==l?"dvhe":"dvh1",i);break}case"dvh1":case"dvhe":case"dvav":case"dva1":case"dav1":s=eN(s,i)||s;break;case"vp09":{let e=eB(i,["vpcC"])[0];if(e&&e.length>6){let t=e[4],i=e[5],r=e[6]>>4&15;s+="."+eH(t)+"."+eH(i)+"."+eH(r)}break}case"av01":{let e=eB(i,["av1C"])[0];if(e&&e.length>2){let t=e[1]>>>5,r=31&e[1],n=e[2]>>>7?"H":"M",l=(64&e[2])>>6,o=(32&e[2])>>5,h=(16&e[2])>>4,d=(8&e[2])>>3,c=(4&e[2])>>2,f=3&e[2];s+="."+t+"."+eH(r)+n+"."+eH(2===t&&l?o?12:10:l?10:8)+"."+h+"."+d+c+f+"."+eH(1)+"."+eH(1)+"."+eH(1)+".0",a=eN("dav1",i)}}}return{codec:s,encrypted:n,supplemental:a}}(eB(r,["mdia","minf","stbl","stsd"])[0]);a?(t[i]={timescale:s,type:a,stsd:l},t[a]=ee({timescale:s,id:i},l)):t[i]={timescale:s,type:e,stsd:l}}}}}
44return eB(e,["moov","mvex","trex"]).forEach(e=>{let i=t[eO(e,4)];i&&(i.default={duration:eO(e,12),flags:eO(e,20)})}),t}function eN(e,t){let i=eB(t,["dvvC"]),r=i.length?i[0]:eB(t,["dvcC"])[0];if(r){let t=r[2]>>1&127,i=r[2]<<5&32|r[3]>>3&31;return e+"."+eH(t)+"."+eH(i)}}function eG(e,t){let i=t+5;for(;128&e[t++]&&t<i;);return t}function eK(e){return("0"+e.toString(16).toUpperCase()).slice(-2)}function eH(e){return(e<10?"0":"")+e}function eV(e,t){eB(e,["moov","trak"]).forEach(e=>{let i=eB(e,["mdia","minf","stbl","stsd"])[0];if(!i)return;let r=i.subarray(8),s=eB(r,["enca"]),a=s.length>0;a||(s=eB(r,["encv"])),s.forEach(e=>{eB(a?e.subarray(28):e.subarray(78),["sinf"]).forEach(e=>{let i=ej(e);i&&t(i,a)})})})}function ej(e){let t=eB(e,["schm"])[0];if(t){let i=ex(t.subarray(4,8));if("cbcs"===i||"cenc"===i){let t=eB(e,["schi","tenc"])[0];if(t)return t}}}function eW(e,t){let i=new Uint8Array(e.length+t.length);return i.set(e),i.set(t,e.length),i}function eq(e,t){let i=[],r=t.samples,s=t.timescale,a=t.id,n=!1;return eB(r,["moof"]).map(l
44=>{let o=l.byteOffset-8;eB(l,["traf"]).map(l=>{let h=eB(l,["tfdt"]).map(e=>{let t=e[0],i=eO(e,4);return 1===t&&(i*=0x100000000,i+=eO(e,8)),i/s})[0];return void 0!==h&&(e=h),eB(l,["tfhd"]).map(h=>{let d=eO(h,4),c=0xffffff&eO(h,0),f=0,g=0,m=8;d===a&&((1&c)!=0&&(m+=8),(2&c)!=0&&(m+=4),(8&c)!=0&&(f=eO(h,m),m+=4),(16&c)!=0&&(g=eO(h,m),m+=4),(32&c)!=0&&(m+=4),"video"===t.type&&(n=eY(t.codec)),eB(l,["trun"]).map(a=>{let l=a[0],h=0xffffff&eO(a,0),d=0,c=(256&h)!=0,m=0,p=(512&h)!=0,y=0,v=(1024&h)!=0,E=(2048&h)!=0,T=0,S=eO(a,4),L=8;(1&h)!=0&&(d=eO(a,L),L+=4),(4&h)!=0&&(L+=4);let A=d+o;for(let o=0;o<S;o++){if(c?(m=eO(a,L),L+=4):m=f,p?(y=eO(a,L),L+=4):y=g,v&&(L+=4),E&&(T=0===l?eO(a,L):e$(a,L),L+=4),t.type===eb){let t=0;for(;t<y;){let a=eO(r,A);A+=4,function(e,t){if(!e)return(31&t)==6;{let e=t>>1&63;return 39===e||40===e}}(n,r[A])&&eX(r.subarray(A,A+a),n?2:1,e+T/s,i),A+=a,t+=a+4}}e+=m/s}}))})})}),i}function eY(e){if(!e)return!1;let t=e.substring(0,4);return"hvc1"===t||"hev1"===t||"dvh1"===t||"dvhe"===t}function eX(e,t,i,r){let s,a=ez(e);s=0+t;let n=0,l=0,o=0;for(;s<a.length;){n=0;do{if(s>=a.length)break;n+=o=a[s++]}while(255===o)l=0;do{if(s>=a.length)break;l+=o=a[s++]}while(255===o)let e=a.length-s,t=s;if(l<e)s+=l;else if(l>e){en.error(`Malformed SEI payload. ${l} is too small, only ${e} bytes left to parse.`);break}if(4===n){if(181===a[t++]){let e=eM(a,t);if(t+=2,49===e){let e=eO(a,t);if(t+=4,0x47413934===e){let e=a[t++];if(3===e){let s=a[t++],l=31&s,o=64&s,h=o?2+3*l:0,d=new Uint8Array(h);if(o){d[0]=s;for(let e=1;e<h;e++)d[e]=a[t++]}r.push({type:e,payloadType:n,pts:i,bytes:d})}}}}}else if(5===n&&l>16){let e=[];for(let i=0;i<16;i++){let r=a[t++].toString(16);e.push(1==r.length?"0"+r:r),(3===i||5===i||7===i||9===i)&&e.push("-")}let s=l-16,o=new Uint8Array(s);for(let e=0;e<s;e++)o[e]=a[t++];r.push({payloadType:n,pts:i,uuid:e.join(""),userData:eh(o),userDataBytes:o})}}}function ez(e){let t=e.byteLength,i=[],r=1;for(;r<t-2;)0===e[r]&&0===e[r+1]&&3===e[r+2]?(i.push(r+2),r+=2):r++;if(0===i.length)return e;let s=t-i.length,a=new Uint8Array(s),n=0;for(r=0;r<s;n++,r++)n===i[0]&&(n++,i.shift()),a[r]=e[n];return a}let eQ={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 eZ(e,t){let i=eQ[t];return!!i&&!!i[e.slice(0,4)]}function eJ(e,t,i=!0){return!e.split(",").some(e=>!e0(e,t,i))}function e0(e,t,i=!0){var r;let s=el(i);return null!=(r=s?.isTypeSupported(e1(e,t)))&&r}function e1(e,t){return`${t}/mp4;codecs=${e}`}function e2(e){if(e){let t=e.substring(0,4);return eQ.video[t]}return 2}function e3(e){let t=/\(Windows.+Firefox\//i.test(navigator.userAgent);return e.split(",").reduce((e,i)=>{let r=t&&eY(i)?9:eQ.video[i];return r?(2*r+e)/(e?3:2):(eQ.audio[i]+e)/(e?2:1)},0)}let e4={},e5=/flac|opus|mp4a\.40\.34/i;function e8(e,t=!0){return e.replace(e5,e=>(function(e,t=!0){if(e4[e])return e4[e];let i={flac:["flac","fLaC","FLAC"],opus:["opus","Opus"],"mp4a.40.34":["mp3"]}[e];for(let s=0;s<i.length;s++){var r;if(e0(i[s],"audio",t))return e4[e]=i[s],i[s];if("mp3"===i[s]&&null!=(r=el(t))&&r.isTypeSupported("audio/mpeg"))return""}return e})(e.toLowerCase(),t))}function e6(e,t){if(e&&(e.length>4||-1!==["ac-3","ec-3","alac","fLaC","Opus"].indexOf(e))&&(e9(e,"audio")||e9(e,"video")))return e;if(t){let i=t.split(",");if(i.length>1){if(e){for(let t=i.length;t--;)if(i[t].substring(0,4)===e.substring(0,4))return i[t]}return i[0]}}return t||e}function e9(e,t){return eZ(e,t)&&e0(e,t)}function e7(e){let t=el(e)||{isTypeSupported:()=>!1};return{mpeg:t.isTypeSupported("audio/mpeg"),mp3:t.isTypeSupported('audio/mp4; codecs="mp3"'),ac3:t.isTypeSupported('audio/mp4; codecs="ac-3"')}}function te(e){return e.replace(/^.+codecs=["']?([^"']+).*$/,"$1")}let tt={supported:!1,smooth:!1,powerEfficient:!1},ti={supported:!0,configurations:[],decodingInfoResults:[{supported:!0,powerEfficient:!0,smooth:!0}]};function tr(e,t){return{supported:!1,configurations:t,decodingInfoResults:[tt],error:e}}function ts(e,t,i,r={}){var s,a,n,l,o,h;let d,c,f,g,m,p,y,v,E=e.videoCodec;if(!E&&!e.audioCodec||!i)return Promise.resolve(ti);let T=[],S=(d=null==(a=(s=e).videoCodec)?void 0:a.split(","),c=ta(s),f=s.width||640,g=s.height||480,m=s.frameRate||30,p=s.videoRange.toLowerCase(),d?d.map(e=>{let t={contentType:e1(function(e){if(e.startsWith("av01.")){let t=e.split("."),i=["0","111","01","01","01","0"];for(let e=t.length;e>4&&e<10;e++)t[e]=i[e-4];return t.join(".")}return e}(e),"video"),width:f,height:g,bitrate:c,framerate:m};
44return"sdr"!==p&&(t.transferFunction=p),t}):[]),L=S.length,A=(n=e,l=t,o=L>0,y=null==(h=n.audioCodec)?void 0:h.split(","),v=ta(n),y&&n.audioGroups?n.audioGroups.reduce((e,t)=>{var i;let r=t?null==(i=l.groups[t])?void 0:i.tracks:null;return r?r.reduce((e,i)=>{if(i.groupId===t){let t=parseFloat(i.channels||"");y.forEach(i=>{let r={contentType:e1(i,"audio"),bitrate:o?function(e,t){if(t<=1)return 1;let i=128e3;return"ec-3"===e?i=768e3:"ac-3"===e&&(i=64e4),Math.min(t/2,i)}(i,v):v};t&&(r.channels=""+t),e.push(r)})}return e},e):e},[]):[]),R=A.length;for(let e=L||+R||1;e--;){let t={type:"media-source"};if(L&&(t.video=S[e%L]),R){t.audio=A[e%R];let i=t.audio.bitrate;t.video&&i&&(t.video.bitrate-=i)}T.push(t)}if(E){let e=navigator.userAgent;if(E.split(",").some(e=>eY(e))&&/\(Windows.+Firefox\//i.test(navigator.userAgent))return Promise.resolve(tr(Error(`Overriding Windows Firefox HEVC MediaCapabilities result based on user-agent string: (${e})`),T))}return Promise.all(T.map(e=>{let t=function(e){let t="",{audio:i,video:r}=e;if(r){let e=te(r.contentType);t+=`${e}_r${r.height}x${r.width}f${Math.ceil(r.framerate)}${r.transferFunction||"sd"}_${Math.ceil(r.bitrate/1e5)}`}if(i){let e=te(i.contentType);t+=`${r?"_":""}${e}_c${i.channels}`}return t}(e);return r[t]||(r[t]=i.decodingInfo(e))})).then(e=>({supported:!e.some(e=>!e.supported),configurations:T,decodingInfoResults:e})).catch(e=>({supported:!1,configurations:T,decodingInfoResults:[],error:e}))}function ta(e){return 1e3*Math.ceil(Math.max(.9*e.bitrate,e.averageBitrate)/1e3)||1}let tn=["NONE","TYPE-0","TYPE-1",null],tl=["SDR","PQ","HLG"];function to(e){let{canSkipUntil:t,canSkipDateRanges:i,age:r}=e;return t&&r<t/2?i?"v2":"YES":""}class th{constructor(e,t,i){this.msn=void 0,this.part=void 0,this.skip=void 0,this.msn=e,this.part=t,this.skip=i}addDirectives(e){let t=new self.URL(e);return void 0!==this.msn&&t.searchParams.set("_HLS_msn",this.msn.toString()),void 0!==this.part&&t.searchParams.set("_HLS_part",this.part.toString()),this.skip&&t.searchParams.set("_HLS_skip",this.skip),t.href}}class td{constructor(e){if(this._attrs=void 0,this.audioCodec=void 0,this.bitrate=void 0,this.codecSet=void 0,this.url=void 0,this.frameRate=void 0,this.height=void 0,this.id=void 0,this.name=void 0,this.supplemental=void 0,this.videoCodec=void 0,this.width=void 0,this.details=void 0,this.fragmentError=0,this.loadError=0,this.loaded=void 0,this.realBitrate=0,this.supportedPromise=void 0,this.supportedResult=void 0,this._avgBitrate=0,this._audioGroups=void 0,this._subtitleGroups=void 0,this._urlId=0,this.url=[e.url],this._attrs=[e.attrs],this.bitrate=e.bitrate,e.details&&(this.details=e.details),this.id=e.id||0,this.name=e.name,this.width=e.width||0,this.height=e.height||0,this.frameRate=e.attrs.optionalFloat("FRAME-RATE",0),this._avgBitrate=e.attrs.decimalInteger("AVERAGE-BANDWIDTH"),this.audioCodec=e.audioCodec,this.videoCodec=e.videoCodec,this.codecSet=[e.videoCodec,e.audioCodec].filter(e=>!!e).map(e=>e.substring(0,4)).join(","),"supplemental"in e){var t;this.supplemental=e.supplemental;const i=null==(t=e.supplemental)?void 0:t.videoCodec;i&&i!==e.videoCodec&&(this.codecSet+=`,${i.substring(0,4)}`)}this.addGroupId("audio",e.attrs.AUDIO),this.addGroupId("text",e.attrs.SUBTITLES)}get maxBitrate(){return Math.max(this.realBitrate,this.bitrate)}get averageBitrate(){return this._avgBitrate||this.realBitrate||this.bitrate}get attrs(){return this._attrs[0]}get codecs(){return this.attrs.CODECS||""}get pathwayId(){return this.attrs["PATHWAY-ID"]||"."}get videoRange(){return this.attrs["VIDEO-RANGE"]||"SDR"}get score(){return this.attrs.optionalFloat("SCORE",0)}get uri(){return this.url[0]||""}hasAudioGroup(e){return tu(this._audioGroups,e)}hasSubtitleGroup(e){return tu(this._subtitleGroups,e)}get audioGroups(){return this._audioGroups}get subtitleGroups(){return this._subtitleGroups}addGroupId(e,t){if(t){if("audio"===e){let e=this._audioGroups;e||(e=this._audioGroups=[]),-1===e.indexOf(t)&&e.push(t)}else if("text"===e){let e=this._subtitleGroups;e||(e=this._subtitleGroups=[]),-1===e.indexOf(t)&&e.push(t)}}}get urlId(){return 0}set urlId(e){}get audioGroupIds(){return this.audioGroups?[this.audioGroupId]:void 0}get textGroupIds(){return this.subtitleGroups?[this.textGroupId]:void 0}get audioGroupId(){var e;return null==(e=this.audioGroups)?void 0:e[0]}get textGroupId(){var e;return null==(e=this.subtitleGroups)?void 0:e[0]}addFallback(){}}function tu(e,t){return!!t&&!!e&&-1!==e.indexOf(t)}let tc=(e,t)=>{let i;return JSON.stringify(e,(i=new WeakSet,(e,r)=>{if(t&&(r=t(e,r)),"object"==typeof r&&null!==r){if(i.has(r))return;i.add(r)}return r}))};function tf(e,t){en.log(`[abr] start candidates with "${e}" ignored because ${t}`)}function tg(e){return e.reduce((e,t)=>
44{let i=e.groups[t.groupId];i||(i=e.groups[t.groupId]={tracks:[],channels:{2:0},hasDefault:!1,hasAutoSelect:!1}),i.tracks.push(t);let r=t.channels||"2";return i.channels[r]=(i.channels[r]||0)+1,i.hasDefault=i.hasDefault||t.default,i.hasAutoSelect=i.hasAutoSelect||t.autoselect,i.hasDefault&&(e.hasDefaultAudio=!0),i.hasAutoSelect&&(e.hasAutoSelectAudio=!0),e},{hasDefaultAudio:!1,hasAutoSelectAudio:!1,groups:{}})}function tm(e){if(!e)return e;let{lang:t,assocLang:i,characteristics:r,channels:s,audioCodec:a}=e;return{lang:t,assocLang:i,characteristics:r,channels:s,audioCodec:a}}function tp(e,t,i){if("attrs"in e){let i=t.indexOf(e);if(-1!==i)return i}for(let r=0;r<t.length;r++)if(ty(e,t[r],i))return r;return -1}function ty(e,t,i){let{groupId:r,name:s,lang:a,assocLang:n,default:l}=e,o=e.forced;return(void 0===r||t.groupId===r)&&(void 0===s||t.name===s)&&(void 0===a||function(e,t="--"){return e.length===t.length?e===t:e.startsWith(t)||t.startsWith(e)}(a,t.lang))&&(void 0===a||t.assocLang===n)&&(void 0===l||t.default===l)&&(void 0===o||t.forced===o)&&(!("characteristics"in e)||function(e,t=""){let i=e.split(","),r=t.split(",");return i.length===r.length&&!i.some(e=>-1===r.indexOf(e))}(e.characteristics||"",t.characteristics))&&(void 0===i||i(e,t))}function tv(e,t){let{audioCodec:i,channels:r}=e;return(void 0===i||(t.audioCodec||"").substring(0,4)===i.substring(0,4))&&(void 0===r||r===(t.channels||"2"))}function tE(e,t,i){for(let r=t;r>-1;r--)if(i(e[r]))return r;for(let r=t+1;r<e.length;r++)if(i(e[r]))return r;return -1}function tT(e,t){var i;return!!e&&e!==(null==(i=t.loadLevelObj)?void 0:i.uri)}let tS=function(e,t){let i=0,r=e.length-1,s=null,a=null;for(;i<=r;){let n=t(a=e[s=(i+r)/2|0]);if(n>0)i=s+1;else{if(!(n<0))return a;r=s-1}}return null};function tL(e,t,i=0,r=0,s=.005){let a=null;if(e){a=t[1+e.sn-t[0].sn]||null;let r=e.endDTS-i;r>0&&r<15e-7&&(i+=15e-7),a&&e.level!==a.level&&a.end<=e.end&&(a=t[2+e.sn-t[0].sn]||null)}else 0===i&&0===t[0].start&&(a=t[0]);if(a&&((!e||e.level===a.level)&&0===tA(i,r,a)||function(e,t,i){if(t&&0===t.start&&t.level<e.level&&(t.endPTS||0)>0){let r=t.tagList.reduce((e,t)=>("INF"===t[0]&&(e+=parseFloat(t[1])),e),i);return e.start<=r}return!1}(a,e,Math.min(s,r))))return a;let n=tS(t,tA.bind(null,i,r));return n&&(n!==e||!a)?n:a}function tA(e=0,t=0,i){if(i.start<=e&&i.start+i.duration>e)return 0;let r=Math.min(t,i.duration+(i.deltaPTS?i.deltaPTS:0));return i.start+i.duration-r<=e?1:i.start-r>e&&i.start?-1:0}function tR(e,t,i){if(e&&e.startCC<=t&&e.endCC>=t){let r,s=e.fragments,{fragmentHint:a}=e;return a&&(s=s.concat(a)),tS(s,e=>e.cc<t?1:e.cc>t?-1:(r=e,e.end<=i?1:e.start>i?-1:0)),r||null}return null}function tb(e){switch(e.details){case G.FRAG_LOAD_TIMEOUT:case G.KEY_LOAD_TIMEOUT:case G.LEVEL_LOAD_TIMEOUT:case G.MANIFEST_LOAD_TIMEOUT:return!0}return!1}function tk(e){return e.details.startsWith("key")}function tI(e){return tk(e)&&!!e.frag&&!e.frag.decryptdata}function tD(e,t){let i=tb(t);return e.default[`${i?"timeout":"error"}Retry`]}function t_(e,t){return Math.min(("linear"===e.backoff?1:Math.pow(2,t))*e.retryDelayMs,e.maxRetryDelayMs)}function tP(e){return ee(ee({},e),{errorRetry:null,timeoutRetry:null})}function tC(e,t,i,r){var s;if(!e)return!1;let a=r?.code,n=t<e.maxNumRetry&&(tw(s=a)||!!s&&(s<400||s>499)||!!i);return e.shouldRetry?e.shouldRetry(e,t,i,r,n):n}function tw(e){return 0===e&&!1===navigator.onLine}function tx(e){let t={action:0,flags:0};return e&&(t.resolved=!0),t}var tM="NOT_LOADED",tO="APPENDING",tF="PARTIAL";class t${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(){let{hls:e}=this;e&&(e.on(K.MANIFEST_LOADING,this.onManifestLoading,this),e.on(K.BUFFER_APPENDED,this.onBufferAppended,this),e.on(K.FRAG_BUFFERED,this.onFragBuffered,this),e.on(K.FRAG_LOADED,this.onFragLoaded,this))}_unregisterListeners(){let{hls:e}=this;e&&(e.off(K.MANIFEST_LOADING,this.onManifestLoading,this),e.off(K.BUFFER_APPENDED,this.onBufferAppended,this),e.off(K.FRAG_BUFFERED,this.onFragBuffered,this),e.off(K.FRAG_LOADED,this.onFragLoaded,this))}destroy(){this._unregisterListeners(),this.hls=this.fragments=this.activePartLists=this.endListFragments=this.timeRanges=null}getAppendedFrag(e,t){let i=this.activePartLists[t];if(i)for(let t=i.length;t--;){let r=i[t];if(!r)break;
44if(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,i){let{fragments:r}=this,s=Object.keys(r);for(let a=s.length;a--;){let n=r[s[a]];if(n?.body.type===t&&(!i||n.buffered)){let t=n.body;if(t.start<=e&&e<=t.end)return t}}return null}detectEvictedFragments(e,t,i,r,s){this.timeRanges&&(this.timeRanges[e]=t);let a=r?.fragment.sn||-1;Object.keys(this.fragments).forEach(r=>{let n=this.fragments[r];if(!n||a>=n.body.sn)return;if(!n.buffered&&(!n.loaded||s)){n.body.type===i&&this.removeFragment(n.body);return}let l=n.range[e];if(l){if(0===l.time.length)return void this.removeFragment(n.body);l.time.some(e=>{let i=!this.isTimeBuffered(e.startPTS,e.endPTS,t);return i&&this.removeFragment(n.body),i})}})}detectPartialFragments(e){let t=this.timeRanges;if(!t||"initSegment"===e.frag.sn)return;let i=e.frag,r=tU(i),s=this.fragments[r];if(!s||s.buffered&&i.gap)return;let a=!i.relurl;Object.keys(t).forEach(r=>{let n=i.elementaryStreams[r];if(!n)return;let l=t[r],o=a||!0===n.partial;s.range[r]=this.getBufferedTimes(i,e.part,o,l)}),s.loaded=null,Object.keys(s.range).length?(this.bufferedEnd(s,i),tB(s)||this.removeParts(i.sn-1,i.type)):this.removeFragment(s.body)}bufferedEnd(e,t){e.buffered=!0,(e.body.endList=t.endList||e.body.endList)&&(this.endListFragments[e.body.type]=e)}removeParts(e,t){let i=this.activePartLists[t];i&&(this.activePartLists[t]=tN(i,t=>t.fragment.sn>=e))}fragBuffered(e,t){let i=tU(e),r=this.fragments[i];!r&&t&&(r=this.fragments[i]={body:e,appendedPTS:null,loaded:null,buffered:!1,range:Object.create(null)},e.gap&&(this.hasGaps=!0)),r&&(r.loaded=null,this.bufferedEnd(r,e))}getBufferedTimes(e,t,i,r){let s={time:[],partial:i},a=e.start,n=e.end,l=e.minEndPTS||n,o=e.maxStartPTS||a;for(let e=0;e<r.length;e++){let t=r.start(e)-this.bufferPadding,i=r.end(e)+this.bufferPadding;if(o>=t&&l<=i){s.time.push({startPTS:Math.max(a,r.start(e)),endPTS:Math.min(n,r.end(e))});break}if(a<i&&n>t){let t=Math.max(a,r.start(e)),i=Math.min(n,r.end(e));i>t&&(s.partial=!0,s.time.push({startPTS:t,endPTS:i}))}else if(n<=t)break}return s}getPartialFragment(e){let t=null,i,r,s,a=0,{bufferPadding:n,fragments:l}=this;return Object.keys(l).forEach(o=>{let h=l[o];h&&tB(h)&&(r=h.body.start-n,s=h.body.end+n,e>=r&&e<=s&&a<=(i=Math.min(e-r,s-e))&&(t=h.body,a=i))}),t}isEndListAppended(e){let t=this.endListFragments[e];return void 0!==t&&(t.buffered||tB(t))}getState(e){let t=tU(e),i=this.fragments[t];return i?i.buffered?tB(i)?tF:"OK":tO:tM}isTimeBuffered(e,t,i){let r,s;for(let a=0;a<i.length;a++){if(r=i.start(a)-this.bufferPadding,s=i.end(a)+this.bufferPadding,e>=r&&t<=s)return!0;if(t<=r)break}return!1}onManifestLoading(){this.removeAllFragments()}onFragLoaded(e,t){if("initSegment"===t.frag.sn||t.frag.bitrateTest)return;let i=t.frag,r=t.part?null:t,s=tU(i);this.fragments[s]={body:i,appendedPTS:null,loaded:r,buffered:!1,range:Object.create(null)}}onBufferAppended(e,t){let{frag:i,part:r,timeRanges:s,type:a}=t;if("initSegment"===i.sn)return;let n=i.type;if(r){let e=this.activePartLists[n];e||(this.activePartLists[n]=e=[]),e.push(r)}this.timeRanges=s;let l=s[a];this.detectEvictedFragments(a,l,n,r)}onFragBuffered(e,t){this.detectPartialFragments(t)}hasFragment(e){let t=tU(e);return!!this.fragments[t]}hasFragments(e){let{fragments:t}=this,i=Object.keys(t);if(!e)return i.length>0;for(let r=i.length;r--;){let s=t[i[r]];if(s?.body.type===e)return!0}return!1}hasParts(e){var t;return!!(null!=(t=this.activePartLists[e])&&t.length)}removeFragmentsInRange(e,t,i,r,s){r&&!this.hasGaps||Object.keys(this.fragments).forEach(a=>{let n=this.fragments[a];if(!n)return;let l=n.body;l.type!==i||r&&!l.gap||l.start<t&&l.end>e&&(n.buffered||s)&&this.removeFragment(l)})}removeFragment(e){let t=tU(e);e.clearElementaryStreamInfo();let i=this.activePartLists[e.type];if(i){let t=e.sn;this.activePartLists[e.type]=tN(i,e=>e.fragment.sn!==t)}delete this.fragments[t],e.endList&&delete this.endListFragments[e.type]}removeAllFragments(){var e;this.fragments=Object.create(null),this.endListFragments=Object.create(null),this.activePartLists=Object.create(null),this.hasGaps=!1;let t=null==(e=this.hls)||null==(e=e.latestLevelDetails)?void 0:e.partList;
44t&&t.forEach(e=>e.clearElementaryStreamInfo())}}function tB(e){var t,i,r;return e.buffered&&!!(e.body.gap||null!=(t=e.range.video)&&t.partial||null!=(i=e.range.audio)&&i.partial||null!=(r=e.range.audiovideo)&&r.partial)}function tU(e){return`${e.type}_${e.level}_${e.sn}`}function tN(e,t){return e.filter(e=>{let i=t(e);return i||e.clearElementaryStreamInfo(),i})}class tG{constructor(e,t,i){this.subtle=void 0,this.aesIV=void 0,this.aesMode=void 0,this.subtle=e,this.aesIV=t,this.aesMode=i}decrypt(e,t){switch(this.aesMode){case 0:return this.subtle.decrypt({name:"AES-CBC",iv:this.aesIV},t,e);case 1:return this.subtle.decrypt({name:"AES-CTR",counter:this.aesIV,length:64},t,e);default:throw Error(`[AESCrypto] invalid aes mode ${this.aesMode}`)}}}class tK{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){let t=new DataView(e),i=new Uint32Array(4);for(let e=0;e<4;e++)i[e]=t.getUint32(4*e);return i}initTable(){let e=this.sBox,t=this.invSBox,i=this.subMix,r=i[0],s=i[1],a=i[2],n=i[3],l=this.invSubMix,o=l[0],h=l[1],d=l[2],c=l[3],f=new Uint32Array(256),g=0,m=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 i=m^m<<1^m<<2^m<<3^m<<4;i=i>>>8^255&i^99,e[g]=i,t[i]=g;let l=f[g],p=f[l],y=f[p],v=257*f[i]^0x1010100*i;r[g]=v<<24|v>>>8,s[g]=v<<16|v>>>16,a[g]=v<<8|v>>>24,n[g]=v,v=0x1010101*y^65537*p^257*l^0x1010100*g,o[i]=v<<24|v>>>8,h[i]=v<<16|v>>>16,d[i]=v<<8|v>>>24,c[i]=v,g?(g=l^f[f[f[y^l]]],m^=f[f[m]]):g=m=1}}expandKey(e){let t,i,r,s,a=this.uint8ArrayToUint32Array_(e),n=!0,l=0;for(;l<a.length&&n;)n=a[l]===this.key[l],l++;if(n)return;this.key=a;let o=this.keySize=a.length;if(4!==o&&6!==o&&8!==o)throw Error("Invalid aes key size="+o);let h=this.ksRows=(o+6+1)*4,d=this.keySchedule=new Uint32Array(h),c=this.invKeySchedule=new Uint32Array(h),f=this.sBox,g=this.rcon,m=this.invSubMix,p=m[0],y=m[1],v=m[2],E=m[3];for(t=0;t<h;t++){if(t<o){r=d[t]=a[t];continue}s=r,t%o==0?s=(f[(s=s<<8|s>>>24)>>>24]<<24|f[s>>>16&255]<<16|f[s>>>8&255]<<8|f[255&s])^g[t/o|0]<<24:o>6&&t%o==4&&(s=f[s>>>24]<<24|f[s>>>16&255]<<16|f[s>>>8&255]<<8|f[255&s]),d[t]=r=(d[t-o]^s)>>>0}for(i=0;i<h;i++)t=h-i,s=3&i?d[t]:d[t-4],i<4||t<=4?c[i]=s:c[i]=p[f[s>>>24]]^y[f[s>>>16&255]]^v[f[s>>>8&255]]^E[f[255&s]],c[i]=c[i]>>>0}networkToHostOrderSwap(e){return e<<24|(65280&e)<<8|(0xff0000&e)>>8|e>>>24}decrypt(e,t,i){let r,s,a,n,l,o,h,d,c,f,g,m,p,y,v=this.keySize+6,E=this.invKeySchedule,T=this.invSBox,S=this.invSubMix,L=S[0],A=S[1],R=S[2],b=S[3],k=this.uint8ArrayToUint32Array_(i),I=k[0],D=k[1],_=k[2],P=k[3],C=new Int32Array(e),w=new Int32Array(C.length),x=this.networkToHostOrderSwap;for(;t<C.length;){for(c=x(C[t]),f=x(C[t+1]),g=x(C[t+2]),m=x(C[t+3]),l=c^E[0],o=m^E[1],h=g^E[2],d=f^E[3],p=4,y=1;y<v;y++)r=L[l>>>24]^A[o>>16&255]^R[h>>8&255]^b[255&d]^E[p],s=L[o>>>24]^A[h>>16&255]^R[d>>8&255]^b[255&l]^E[p+1],a=L[h>>>24]^A[d>>16&255]^R[l>>8&255]^b[255&o]^E[p+2],n=L[d>>>24]^A[l>>16&255]^R[o>>8&255]^b[255&h]^E[p+3],l=r,o=s,h=a,d=n,p+=4;r=T[l>>>24]<<24^T[o>>16&255]<<16^T[h>>8&255]<<8^T[255&d]^E[p],s=T[o>>>24]<<24^T[h>>16&255]<<16^T[d>>8&255]<<8^T[255&l]^E[p+1],a=T[h>>>24]<<24^T[d>>16&255]<<16^T[l>>8&255]<<8^T[255&o]^E[p+2],n=T[d>>>24]<<24^T[l>>16&255]<<16^T[o>>8&255]<<8^T[255&h]^E[p+3],w[t]=x(r^I),w[t+1]=x(n^D),w[t+2]=x(a^_),w[t+3]=x(s^P),I=c,D=f,_=g,P=m,t+=4}return w.buffer}}class tH{constructor(e,t,i){this.subtle=void 0,this.key=void 0,this.aesMode=void 0,this.subtle=e,this.key=t,this.aesMode=i}expandKey(){let e=function(e){switch(e){case 0:return"AES-CBC";case 1:return"AES-CTR";default:throw Error(`[FastAESKey] invalid aes mode ${e}`)}}(this.aesMode);return this.subtle.importKey("raw",this.key,{name:e},!1,["encrypt","decrypt"])}}class tV{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.enableSoftw
44areAES=void 0,this.enableSoftwareAES=e.enableSoftwareAES,this.removePKCS7Padding=t,t)try{const e=self.crypto;e&&(this.subtle=e.subtle||e.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(){let e,t,{currentResult:i,remainderData:r}=this;if(!i||r)return this.reset(),null;let s=new Uint8Array(i);return this.reset(),this.removePKCS7Padding&&(t=(e=s.byteLength)&&new DataView(s.buffer).getUint8(e-1))?s.slice(0,e-t):s}reset(){this.currentResult=null,this.currentIV=null,this.remainderData=null,this.softwareDecrypter&&(this.softwareDecrypter=null)}decrypt(e,t,i,r){return this.useSoftware?new Promise((s,a)=>{let n=ArrayBuffer.isView(e)?e:new Uint8Array(e);this.softwareDecrypt(n,t,i,r);let l=this.flush();l?s(l.buffer):a(Error("[softwareDecrypt] Failed to decrypt data"))}):this.webCryptoDecrypt(new Uint8Array(e),t,i,r)}softwareDecrypt(e,t,i,r){let{currentIV:s,currentResult:a,remainderData:n}=this;if(0!==r||16!==t.byteLength)return en.warn("SoftwareDecrypt: can only handle AES-128-CBC"),null;this.logOnce("JS AES decrypt"),n&&(e=eW(n,e),this.remainderData=null);let l=this.getValidChunk(e);if(!l.length)return null;s&&(i=s);let o=this.softwareDecrypter;return o||(o=this.softwareDecrypter=new tK),o.expandKey(t),this.currentResult=o.decrypt(l.buffer,0,i),this.currentIV=l.slice(-16).buffer,a||null}webCryptoDecrypt(e,t,i,r){if(this.key!==t||!this.fastAesKey){if(!this.subtle)return Promise.resolve(this.onWebCryptoError(e,t,i,r));this.key=t,this.fastAesKey=new tH(this.subtle,t,r)}return this.fastAesKey.expandKey().then(t=>this.subtle?(this.logOnce("WebCrypto AES decrypt"),new tG(this.subtle,new Uint8Array(i),r).decrypt(e.buffer,t)):Promise.reject(Error("web crypto not initialized"))).catch(s=>(en.warn(`[decrypter]: WebCrypto Error, disable WebCrypto API, ${s.name}: ${s.message}`),this.onWebCryptoError(e,t,i,r)))}onWebCryptoError(e,t,i,r){let s=this.enableSoftwareAES;if(s){this.useSoftware=!0,this.logEnabled=!0,this.softwareDecrypt(e,t,i,r);let s=this.flush();if(s)return s.buffer}throw Error("WebCrypto"+(s?" and softwareDecrypt":"")+": failed to decrypt data")}getValidChunk(e){let t=e,i=e.length-e.length%16;return i!==e.length&&(t=e.slice(0,i),this.remainderData=e.slice(i)),t}logOnce(e){this.logEnabled&&(en.log(`[decrypter]: ${e}`),this.logEnabled=!1)}}class tj{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){let i=e.url;if(!i)return Promise.reject(new tY({type:N.NETWORK_ERROR,details:G.FRAG_LOAD_ERROR,fatal:!1,frag:e,error:Error(`Fragment does not have a ${i?"part list":"url"}`),networkDetails:null}));this.abort();let r=this.config,s=r.fLoader,a=r.loader;return new Promise((n,l)=>{if(this.loader&&this.loader.destroy(),e.gap)if(e.tagList.some(e=>"GAP"===e[0]))return void l(tq(e));else e.gap=!1;let o=this.loader=s?new s(r):new a(r),h=tW(e);e.loader=o;let d=tP(r.fragLoadPolicy.default),c={loadPolicy:d,timeout:d.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:"initSegment"===e.sn?1/0:131072};e.stats=o.stats;let f={onSuccess:(t,i,r,s)=>{this.resetLoader(e,o);let a=t.data;r.resetIV&&e.decryptdata&&(e.decryptdata.iv=new Uint8Array(a.slice(0,16)),a=a.slice(16)),n({frag:e,part:null,payload:a,networkDetails:s})},onError:(t,r,s,a)=>{this.resetLoader(e,o),l(new tY({type:N.NETWORK_ERROR,details:G.FRAG_LOAD_ERROR,fatal:!1,frag:e,response:ee({url:i,data:void 0},t),error:Error(`HTTP Error ${t.code} ${t.text}`),networkDetails:s,stats:a}))},onAbort:(t,i,r)=>{this.resetLoader(e,o),l(new tY({type:N.NETWORK_ERROR,details:G.INTERNAL_ABORTED,fatal:!1,frag:e,error:Error("Aborted"),networkDetails:r,stats:t}))},onTimeout:(t,i,r)=>{this.resetLoader(e,o),l(new tY({type:N.NETWORK_ERROR,details:G.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,error:Error(`Timeout after ${c.timeout}ms`),networkDetails:r,stats:t}))}};t&&(f.onProgress=(i,r,s,a)=>t({frag:e,part:null,payload:s,networkDetails:a})),o.load(h,c,f)})}loadPart(e,t,i){this.abort();
44let r=this.config,s=r.fLoader,a=r.loader;return new Promise((n,l)=>{if(this.loader&&this.loader.destroy(),e.gap||t.gap)return void l(tq(e,t));let o=this.loader=s?new s(r):new a(r),h=tW(e,t);e.loader=o;let d=tP(r.fragLoadPolicy.default),c={loadPolicy:d,timeout:d.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:131072};t.stats=o.stats,o.load(h,c,{onSuccess:(r,s,a,l)=>{this.resetLoader(e,o),this.updateStatsFromPart(e,t);let h={frag:e,part:t,payload:r.data,networkDetails:l};i(h),n(h)},onError:(i,r,s,a)=>{this.resetLoader(e,o),l(new tY({type:N.NETWORK_ERROR,details:G.FRAG_LOAD_ERROR,fatal:!1,frag:e,part:t,response:ee({url:h.url,data:void 0},i),error:Error(`HTTP Error ${i.code} ${i.text}`),networkDetails:s,stats:a}))},onAbort:(i,r,s)=>{e.stats.aborted=t.stats.aborted,this.resetLoader(e,o),l(new tY({type:N.NETWORK_ERROR,details:G.INTERNAL_ABORTED,fatal:!1,frag:e,part:t,error:Error("Aborted"),networkDetails:s,stats:i}))},onTimeout:(i,r,s)=>{this.resetLoader(e,o),l(new tY({type:N.NETWORK_ERROR,details:G.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,part:t,error:Error(`Timeout after ${c.timeout}ms`),networkDetails:s,stats:i}))}})})}updateStatsFromPart(e,t){let i=e.stats,r=t.stats,s=r.total;if(i.loaded+=r.loaded,s){let r=Math.round(e.duration/t.duration),a=Math.min(Math.round(i.loaded/s),r),n=(r-a)*Math.round(i.loaded/a);i.total=i.loaded+n}else i.total=Math.max(i.loaded,i.total);let a=i.loading,n=r.loading;a.start?a.first+=n.first-n.start:(a.start=n.start,a.first=n.first),a.end=n.end}resetLoader(e,t){e.loader=null,this.loader===t&&(self.clearTimeout(this.partLoadTimeout),this.loader=null),t.destroy()}}function tW(e,t=null){let i=t||e,r={frag:e,part:t,responseType:"arraybuffer",url:i.url,headers:{},rangeStart:0,rangeEnd:0},s=i.byteRangeStartOffset,a=i.byteRangeEndOffset;if($(s)&&$(a)){var n,l;let t=s,i=a;if("initSegment"===e.sn&&("AES-128"===(l=null==(n=e.decryptdata)?void 0:n.method)||"AES-256"===l)){let e=a-s;e%16&&(i=a+(16-e%16)),0!==s&&(r.resetIV=!0,t=s-16)}r.rangeStart=t,r.rangeEnd=i}return r}function tq(e,t){let i=Error(`GAP ${e.gap?"tag":"attribute"} found`),r={type:N.MEDIA_ERROR,details:G.FRAG_GAP,fatal:!1,frag:e,error:i,networkDetails:null};return t&&(r.part=t),(t||e).stats.aborted=!0,new tY(r)}class tY extends Error{constructor(e){super(e.error.message),this.data=void 0,this.data=e}}class tX extends et{constructor(e,t){super(e,t),this._boundTick=void 0,this._tickTimer=null,this._tickInterval=null,this._tickCallCount=0,this._boundTick=this.tick.bind(this)}destroy(){this.onHandlerDestroying(),this.onHandlerDestroyed()}onHandlerDestroying(){this.clearNextTick(),this.clearInterval()}onHandlerDestroyed(){}hasInterval(){return!!this._tickInterval}hasNextTick(){return!!this._tickTimer}setInterval(e){return!this._tickInterval&&(this._tickCallCount=0,this._tickInterval=self.setInterval(this._boundTick,e),!0)}clearInterval(){return!!this._tickInterval&&(self.clearInterval(this._tickInterval),this._tickInterval=null,!0)}clearNextTick(){return!!this._tickTimer&&(self.clearTimeout(this._tickTimer),this._tickTimer=null,!0)}tick(){this._tickCallCount++,1===this._tickCallCount&&(this.doTick(),this._tickCallCount>1&&this.tickImmediate(),this._tickCallCount=0)}tickImmediate(){this.clearNextTick(),this._tickTimer=self.setTimeout(this._boundTick,0)}doTick(){}}class tz{constructor(e,t,i,r=0,s=-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=tQ(),this.buffering={audio:tQ(),video:tQ(),audiovideo:tQ()},this.level=e,this.sn=t,this.id=i,this.size=r,this.part=s,this.partial=a}}function tQ(){return{start:0,executeStart:0,executeEnd:0,end:0}}let tZ={length:0,start:()=>0,end:()=>0};class tJ{static isBuffered(e,t){if(e){let i=tJ.getBuffered(e);for(let e=i.length;e--;)if(t>=i.start(e)&&t<=i.end(e))return!0}return!1}static bufferedRanges(e){if(e){let t=tJ.getBuffered(e);return tJ.timeRangesToArray(t)}return[]}static timeRangesToArray(e){let t=[];for(let i=0;i<e.length;i++)t.push({start:e.start(i),end:e.end(i)});return t}static bufferInfo(e,t,i){if(e){let r=tJ.bufferedRanges(e);if(r.length)return tJ.bufferedInfo(r,t,i)}return{len:0,start:t,end:t,bufferedIndex:-1}}static bufferedInfo(e,t,i){t=Math.max(0,t),e.length>1&&e.sort((e,t)=>
44e.start-t.start||t.end-e.end);let r=-1,s=[];if(i)for(let a=0;a<e.length;a++){t>=e[a].start&&t<=e[a].end&&(r=a);let n=s.length;if(n){let t=s[n-1].end;e[a].start-t<i?e[a].end>t&&(s[n-1].end=e[a].end):s.push(e[a])}else s.push(e[a])}else s=e;let a=0,n,l=t,o=t;for(let e=0;e<s.length;e++){let h=s[e].start,d=s[e].end;if(-1===r&&t>=h&&t<=d&&(r=e),t+i>=h&&t<d)l=h,a=(o=d)-t;else if(t+i<h){n=h;break}}return{len:a,start:l||0,end:o||0,nextStart:n,buffered:e,bufferedIndex:r}}static getBuffered(e){try{return e.buffered||tZ}catch(e){return en.log("failed to get media.buffered",e),tZ}}}let t0=/\{\$([a-zA-Z0-9-_]+)\}/g;function t1(e,t){if(null!==e.variableList||e.hasVariableRefs){let i=e.variableList;return t.replace(t0,t=>{let r=t.substring(2,t.length-1),s=i?.[r];return void 0===s?(e.playlistParsingError||(e.playlistParsingError=Error(`Missing preceding EXT-X-DEFINE tag for Variable Reference: "${r}"`)),t):s})}return t}function t2(e,t,i){let r,s,a=e.variableList;if(a||(e.variableList=a={}),"QUERYPARAM"in t){r=t.QUERYPARAM;try{let e=new self.URL(i).searchParams;if(e.has(r))s=e.get(r);else throw Error(`"${r}" does not match any query parameter in URI: "${i}"`)}catch(t){e.playlistParsingError||(e.playlistParsingError=Error(`EXT-X-DEFINE QUERYPARAM: ${t.message}`))}}else r=t.NAME,s=t.VALUE;r in a?e.playlistParsingError||(e.playlistParsingError=Error(`EXT-X-DEFINE duplicate Variable Name declarations: "${r}"`)):a[r]=s||""}let t3=/^(\d+)x(\d+)$/,t4=/(.+?)=(".*?"|.*?)(?:,|$)/g;class t5{constructor(e,t){"string"==typeof e&&(e=t5.parseAttrList(e,t)),Z(this,e)}get clientAttrs(){return Object.keys(this).filter(e=>"X-"===e.substring(0,2))}decimalInteger(e){let 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),i=new Uint8Array((t=(1&t.length?"0":"")+t).length/2);for(let e=0;e<t.length/2;e++)i[e]=parseInt(t.slice(2*e,2*e+2),16);return i}return null}hexadecimalIntegerAsNumber(e){let t=parseInt(this[e],16);return t>Number.MAX_SAFE_INTEGER?1/0:t}decimalFloatingPoint(e){return parseFloat(this[e])}optionalFloat(e,t){let i=this[e];return i?parseFloat(i):t}enumeratedString(e){return this[e]}enumeratedStringList(e,t){let i=this[e];return(i?i.split(/[ ,]+/):[]).reduce((e,t)=>(e[t.toLowerCase()]=!0,e),t)}bool(e){return"YES"===this[e]}decimalResolution(e){let t=t3.exec(this[e]);if(null!==t)return{width:parseInt(t[1],10),height:parseInt(t[2],10)}}static parseAttrList(e,t){let i,r={};for(t4.lastIndex=0;null!==(i=t4.exec(e));){let s=i[1].trim(),a=i[2],n=0===a.indexOf('"')&&a.lastIndexOf('"')===a.length-1,l=!1;if(n)a=a.slice(1,-1);else switch(s){case"IV":case"SCTE35-CMD":case"SCTE35-IN":case"SCTE35-OUT":l=!0}if(t&&(n||l))a=t1(t,a);else if(!l&&!n)switch(s){case"CLOSED-CAPTIONS":if("NONE"===a)break;case"ALLOWED-CPC":case"CLASS":case"ASSOC-LANGUAGE":case"AUDIO":case"BYTERANGE":case"CHANNELS":case"CHARACTERISTICS":case"CODECS":case"DATA-ID":case"END-DATE":case"GROUP-ID":case"ID":case"IMPORT":case"INSTREAM-ID":case"KEYFORMAT":case"KEYFORMATVERSIONS":case"LANGUAGE":case"NAME":case"PATHWAY-ID":case"QUERYPARAM":case"RECENTLY-REMOVED-DATERANGES":case"SERVER-URI":case"STABLE-RENDITION-ID":case"STABLE-VARIANT-ID":case"START-DATE":case"SUBTITLES":case"SUPPLEMENTAL-CODECS":case"URI":case"VALUE":case"VIDEO":case"X-ASSET-LIST":case"X-ASSET-URI":en.warn(`${e}: attribute ${s} is missing quotes`)}r[s]=a}return r}}class t8{constructor(e,t,i=0){var r;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?.tagAnchor||null,this.tagOrder=null!=(r=t?.tagOrder)?r:i,t){const i=t.attr;for(const t in i)if(Object.prototype.hasOwnProperty.call(e,t)&&e[t]!==i[t]){en.warn(`DATERANGE tag attribute: "${t}" does not match for tags with ID: "${e.ID}"`),this._badValueForSameId=t;break}e=Z(new t5({}),i,e)}if(this.attr=e,t?(this._startDate=t._startDate,this._cue=t._cue,this._endDate=t._endDate,this._dateAtEnd=t._dateAtEnd):this._startDate=new Date(e["START-DATE"]),"END-DATE"in this.attr){const e=t?.endDate||new Date(this.attr["END-DATE"]);$(e.getTime())&&(this._endDate=e)}}get id(){return this.attr.ID}get class(){return this.attr.CLASS}get cue(){let e=this._cue;return void 0===e?this._cue=this.attr.enumeratedStringList(this.attr.CUE?"CUE":"X-CUE",{pre:!1,post:!1,once:!1}):e}get startTime(){let{tagAnchor:e}=this;return null===e||null===e.programDateTime?(en.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(){let e=this._endDate||this._dateAtEnd;if(e)return e;let t=this.duration;return null!==t?this._dateAtEnd=new Date(this._startDate.getTime()+1e3*t):null}get duration(){if("DURATION"in this.attr){let e=this.attr.decimalFloatingPoint("DURATION");if($(e))return e}else if(this._endDate)return(this._endDate.getTime()-this._startDate.getTime())/1e3;return null}get plannedDuration(){return"PLANNED-DURATION"in this.attr?this.attr.decimalFloatingPoint("PLANNED-DURATION"):null}get endOnNext(){return this.attr.bool("END-ON-NEXT")}get isInterstitial(){return"com.apple.hls.interstitial"===this.class}get isValid(){return!!this.id&&!this._badValueForSameId&&$(this.startDate.getTime())&&(null===this.duration||this.duration>=0)&&(!this.endOnNext||!!this.class)&&(!this.attr.CUE||!this.cue.pre&&!this.cue.post||this.cue.pre!==this.cue.post)&&(!this.isInterstitial||"X-ASSET-URI"in this.attr||"X-ASSET-LIST"in this.attr)}}class t6{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.drift
44StartTime=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}let t=this.lastPartSn-e.lastPartSn,i=this.lastPartIndex-e.lastPartIndex;this.updated=this.endSN!==e.endSN||!!i||!!t||!this.live,this.advanced=this.endSN>e.endSN||t>0||0===t&&i>0,this.updated||this.advanced?this.misses=Math.floor(.6*e.misses):this.misses=e.misses+1}hasKey(e){return this.encryptedFragments.some(t=>{let i=t.decryptdata;return i||(t.setKeyFormat(e.keyFormat),i=t.decryptdata),!!i&&e.matches(i)})}get hasProgramDateTime(){return!!this.fragments.length&&$(this.fragments[this.fragments.length-1].programDateTime)}get levelTargetDuration(){return this.averagetargetduration||this.targetduration||10}get drift(){let 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 null!=(e=this.partList)&&e.length?this.partList[this.partList.length-1].end:this.fragmentEnd}get fragmentEnd(){return this.fragments.length?this.fragments[this.fragments.length-1].end:0}get fragmentStart(){return this.fragments.length?this.fragments[0].start:0}get age(){return this.advancedDateTime?Math.max(Date.now()-this.advancedDateTime,0)/1e3:0}get lastPartIndex(){var e;return null!=(e=this.partList)&&e.length?this.partList[this.partList.length-1].index:-1}get maxPartIndex(){let e=this.partList;if(e){let t=this.lastPartIndex;if(-1!==t){for(let i=e.length;i--;)if(e[i].index>t)return e[i].index;return t}}return 0}get lastPartSn(){var e;return null!=(e=this.partList)&&e.length?this.partList[this.partList.length-1].fragment.sn:this.endSN}get expired(){if(this.live&&this.age&&this.misses<3){let e=this.partEnd-this.fragmentStart;return this.age>Math.max(e,this.totalduration)+this.levelTargetDuration}return!1}}function t9(e,t){return e.length===t.length&&!e.some((e,i)=>e!==t[i])}function t7(e,t){return!e&&!t||!!e&&!!t&&t9(e,t)}function ie(e){return"AES-128"===e||"AES-256"===e||"AES-256-CTR"===e}function it(e){switch(e){case"AES-128":case"AES-256":return 0;case"AES-256-CTR":return 1;default:throw Error(`invalid full segment method ${e}`)}}function ii(e){return Uint8Array.from(atob(e),e=>e.charCodeAt(0))}function ir(e){return Uint8Array.from(unescape(encodeURIComponent(e)),e=>e.charCodeAt(0))}function is(e){let t=function(e,t,i){let r=e[t];e[t]=e[i],e[i]=r};t(e,0,3),t(e,1,2),t(e,4,5),t(e,6,7)}function ia(e){let t=e.split(":"),i=null;if("data"===t[0]&&2===t.length){let e=t[1].split(";"),r=e[e.length-1].split(",");if(2===r.length){let t,s,a="base64"===r[0],n=r[1];a?(e.splice(-1,1),i=ii(n)):(t=ir(n).subarray(0,16),(s=new Uint8Array(16)).set(t,16-t.length),i=s)}}return i}let il="u">typeof self?self:void 0;var io="org.w3.clearkey",ih="com.apple.fps",id="com.microsoft.playready",iu="com.widevine.alpha",ic="org.w3.clearkey",ig="com.apple.streamingkeydelivery",im="com.microsoft.playready",ip="urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed";function iy(e){switch(e){case ig:return ih;case im:return id;case ip:return iu;case ic:return io}}function iv(e){switch(e){case ih:return ig;case id:return im;case iu:return ip;case io:return ic}}function iE(e){let{drmSystems:t,widevineLicenseUrl:i}=e,r=t?[ih,iu,id,io].filter(e=>!!t[e]):[];return!r[iu]&&i&&r.push(iu),r}let iT=null!=il&&null!=(ru=il.navigator)&&ru.requestMediaKeySystemAccess?self.navigator.requestMediaKeySystemAccess.bind(self.navigator):null;function iS(e){let t=new Uint16Array(e.buffer,e.byteOffset,e.byteLength/2),i=String.fromCharCode.apply(null,Array.from(t)),r=i.substring(i.indexOf("<"),i.length),s=new DOMParser().parseFromString(r,"text/xml").getElementsByTagName("KID")[0];if(s){let e=s.childNodes[0]?s.childNodes[0].nodeValue:s.getAttribute("VALUE");if(e){let t=ii(e).subarray(0,16);return is(t),t}}return null}let iL={};class iA{static clearKeyUriToKeyIdMap(){iL={}}static setKeyIdForUri(e,t){iL[e]=t}static addKeyIdForUri(e){let t=Object.keys(iL).length%Number.MAX_SAFE_INTEGER,i=new Uint8Array(16);return new DataView(i.buffer,12,4).setUint32(0,t),iL[e]=i,i}constructor(e,t,i,r=[1],s=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.pss
44h=null,this.method=e,this.uri=t,this.keyFormat=i,this.keyFormatVersions=r,this.iv=s,this.encrypted=!!e&&"NONE"!==e,this.isCommonEncryption=this.encrypted&&!ie(e),null!=a&&a.startsWith("0x")&&(this.keyId=new Uint8Array(eu(a)))}matches(e){return e.uri===this.uri&&e.method===this.method&&e.encrypted===this.encrypted&&e.keyFormat===this.keyFormat&&t9(e.keyFormatVersions,this.keyFormatVersions)&&t7(e.iv,this.iv)&&t7(e.keyId,this.keyId)}isSupported(){if(this.method){if(ie(this.method)||"NONE"===this.method)return!0;if("identity"===this.keyFormat)return"SAMPLE-AES"===this.method;switch(this.keyFormat){case ig:case ip:case im:case ic:return -1!==["SAMPLE-AES","SAMPLE-AES-CENC","SAMPLE-AES-CTR"].indexOf(this.method)}}return!1}getDecryptData(e,t){var i,r;if(!this.encrypted||!this.uri)return null;if(ie(this.method)){let t=this.iv;return t||("number"!=typeof e&&(en.warn(`missing IV for initialization segment with method="${this.method}" - compliance issue`),e=0),t=function(e){let t=new Uint8Array(16);for(let i=12;i<16;i++)t[i]=e>>8*(15-i)&255;return t}(e)),new iA(this.method,this.uri,"identity",this.keyFormatVersions,t)}if(this.keyId){let e=iL[this.uri];if(e&&!t9(this.keyId,e)&&iA.setKeyIdForUri(this.uri,this.keyId),this.pssh)return this}let s=ia(this.uri);if(s)switch(this.keyFormat){case ip:if(this.pssh=s,!this.keyId){let e=function(e){let t=[];if(e instanceof ArrayBuffer){let i=e.byteLength,r=0;for(;r+32<i;){let i=function(e){let t=e.getUint32(0),i=e.byteOffset,r=e.byteLength;if(r<t)return{offset:i,size:r};if(0x70737368!==e.getUint32(4))return{offset:i,size:t};let s=e.getUint32(8)>>>24;if(0!==s&&1!==s)return{offset:i,size:t};let a=e.buffer,n=ed(new Uint8Array(a,i+12,16)),l=null,o=0;if(0===s)o=28;else{let s=e.getUint32(28);if(!s||r<32+16*s)return{offset:i,size:t};l=[];for(let e=0;e<s;e++)l.push(new Uint8Array(a,i+32+16*e,16));o=32+16*s}if(!o)return{offset:i,size:t};let h=e.getUint32(o);return t-32<h?{offset:i,size:t}:{version:s,systemId:n,kids:l,data:new Uint8Array(a,i+o+4,h),offset:i,size:t}}(new DataView(e,r));t.push(i),r+=i.size}}return t}(s.buffer);if(e.length){let t=e[0];this.keyId=null!=(i=t.kids)&&i.length?t.kids[0]:null}}this.keyId||(this.keyId=iR(t));break;case im:{let e=new Uint8Array([154,4,240,121,152,64,66,134,171,146,230,91,224,136,95,149]);this.pssh=function(e,t){let i,r;if(16!==e.byteLength)throw RangeError("Invalid system id");i=new Uint8Array,r=new Uint8Array;let s=new Uint8Array(4);return t.byteLength>0&&new DataView(s.buffer).setUint32(0,t.byteLength,!1),function(e,...t){let i=t.length,r=8,s=i;for(;s--;)r+=t[s].byteLength;let a=new Uint8Array(r);for(a[0]=r>>24&255,a[1]=r>>16&255,a[2]=r>>8&255,a[3]=255&r,a.set(e,4),s=0,r=8;s<i;s++)a.set(t[s],r),r+=t[s].byteLength;return a}([112,115,115,104],new Uint8Array([0,0,0,0]),e,r,i,s,t)}(e,s),this.keyId=iS(s);break}default:{let e=s.subarray(0,16);if(16!==e.length){let t=new Uint8Array(16);t.set(e,16-e.length),e=t}this.keyId=e}}if(!this.keyId||16!==this.keyId.byteLength){let e,i;r=t,(e=(i=r?.[ip])?i.keyId:null)||(e=iR(t))||(e=iL[this.uri]),e&&(this.keyId=e,iA.setKeyIdForUri(this.uri,e))}return this}}function iR(e){let t=e?.[im];if(t){let e=ia(t.uri);if(e)return iS(e)}return null}let ib=/#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,ik=/#EXT-X-MEDIA:(.*)/g,iI=/^#EXT(?:INF|-X-TARGETDURATION):/m,iD=RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,/(?!#) *(\S[^\r\n]*)/.source,/#.*/.source].join("|"),"g"),i_=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 iP{static findGroup(e,t){for(let i=0;i<e.length;i++){let r=e[i];if(r.id===t)return r}}static resolve(e,t){return eL.buildAbsoluteURL(t,e,{alwaysNormalize:!0})}static isMediaPlaylist(e){return iI.test(e)}static parseMasterPlaylist(e,t){var i;let r,s={contentSteering:null,levels:[],playlistParsingError:null,sessionData:null,sessionKeys:null,startTimeOffset:null,variableList:null,hasVariableRefs:t0.test(e)},a=[];if(ib.lastIndex=0,!e.startsWith("#EXTM3U"))return s.playlistParsingError=Error("no EXTM3U delimiter"),s;for(;null!=(r=ib.exec(e));)if(r[1]){let e=new t5(r[1],s),n=t1(s,r[2]),l={attrs:e,bitrate:e.decimalInteger("BANDWIDTH")||e.decimalInteger("AVERAGE-BANDWIDTH"),name:e.NAME,url:iP.resolve(n,t)},o=e.decimalResolution("RESOLUTION");o&&(l.width=o.width,l.height=o.height),iM(e.CODECS,l);let h=e["SUPPLEMENTAL-CODECS"];h&&(l.supplemental={}
44,iM(h,l.supplemental)),null!=(i=l.unknownCodecs)&&i.length||a.push(l),s.levels.push(l)}else if(r[3]){let e=r[3],i=r[4];switch(e){case"SESSION-DATA":{let e=new t5(i,s),t=e["DATA-ID"];t&&(null===s.sessionData&&(s.sessionData={}),s.sessionData[t]=e);break}case"SESSION-KEY":{let e=iw(i,t,s);e.encrypted&&e.isSupported()?(null===s.sessionKeys&&(s.sessionKeys=[]),s.sessionKeys.push(e)):en.warn(`[Keys] Ignoring invalid EXT-X-SESSION-KEY tag: "${i}"`);break}case"DEFINE":{let e=new t5(i,s);t2(s,e,t)}break;case"CONTENT-STEERING":{let e=new t5(i,s);s.contentSteering={uri:iP.resolve(e["SERVER-URI"],t),pathwayId:e["PATHWAY-ID"]||"."};break}case"START":s.startTimeOffset=ix(i)}}let n=a.length>0&&a.length<s.levels.length;return s.levels=n?a:s.levels,0===s.levels.length&&(s.playlistParsingError=Error("no levels found in manifest")),s}static parseMasterPlaylistMedia(e,t,i){let r,s={},a=i.levels,n={AUDIO:a.map(e=>({id:e.attrs.AUDIO,audioCodec:e.audioCodec})),SUBTITLES:a.map(e=>({id:e.attrs.SUBTITLES,textCodec:e.textCodec})),"CLOSED-CAPTIONS":[]},l=0;for(ik.lastIndex=0;null!==(r=ik.exec(e));){let e=new t5(r[1],i),a=e.TYPE;if(a){let i=n[a],r=s[a]||[];s[a]=r;let o=e.LANGUAGE,h=e["ASSOC-LANGUAGE"],d=e.CHANNELS,c=e.CHARACTERISTICS,f=e["INSTREAM-ID"],g={attrs:e,bitrate:0,id:l++,groupId:e["GROUP-ID"]||"",name:e.NAME||o||"",type:a,default:e.bool("DEFAULT"),autoselect:e.bool("AUTOSELECT"),forced:e.bool("FORCED"),lang:o,url:e.URI?iP.resolve(e.URI,t):""};if(h&&(g.assocLang=h),d&&(g.channels=d),c&&(g.characteristics=c),f&&(g.instreamId=f),null!=i&&i.length){let e=iP.findGroup(i,g.groupId)||i[0];iO(g,e,"audioCodec"),iO(g,e,"textCodec")}r.push(g)}}return s}static parseLevelPlaylist(e,t,i,r,s,a){var n;let l={url:t},o=new t6(t),h=o.fragments,d=[],c=null,f=0,g=0,m=0,p=0,y=0,v=null,E=new e_(r,l),T,S,L,A=-1,R=!1,b=null,k;if(iD.lastIndex=0,o.m3u8=e,o.hasVariableRefs=t0.test(e),(null==(n=iD.exec(e))?void 0:n[0])!=="#EXTM3U")return o.playlistParsingError=Error("Missing format identifier #EXTM3U"),o;for(;null!==(T=iD.exec(e));){R&&(R=!1,(E=new e_(r,l)).playlistOffset=m,E.setStart(m),E.sn=f,E.cc=p,y&&(E.bitrate=y),E.level=i,c&&(E.initSegment=c,c.rawProgramDateTime&&(E.rawProgramDateTime=c.rawProgramDateTime,c.rawProgramDateTime=null),b&&(E.setByteRange(b),b=null)));let e=T[1];if(e){E.duration=parseFloat(e);let t=(" "+T[2]).slice(1);E.title=t||null,E.tagList.push(t?["INF",e,t]:["INF",e])}else if(T[3]){if($(E.duration)){E.playlistOffset=m,E.setStart(m),L&&iB(E,L,o),E.sn=f,E.level=i,E.cc=p,h.push(E);let e=(" "+T[3]).slice(1);E.relurl=t1(o,e),iF(E,v,d),v=E,m+=E.duration,f++,g=0,R=!0}}else{if(!(T=T[0].match(i_))){en.warn("No matches on slow regex match for level playlist!");continue}for(S=1;S<T.length&&void 0===T[S];S++);let e=(" "+T[S]).slice(1),s=(" "+T[S+1]).slice(1),n=T[S+2]?(" "+T[S+2]).slice(1):null;switch(e){case"BYTERANGE":v?E.setByteRange(s,v):E.setByteRange(s);break;case"PROGRAM-DATE-TIME":E.rawProgramDateTime=s,E.tagList.push(["PROGRAM-DATE-TIME",s]),-1===A&&(A=h.length);break;case"PLAYLIST-TYPE":o.type&&iU(o,e,T),o.type=s.toUpperCase();break;case"MEDIA-SEQUENCE":0!==o.startSN?iU(o,e,T):h.length>0&&iN(o,e,T),f=o.startSN=parseInt(s);break;case"SKIP":{o.skippedSegments&&iU(o,e,T);let t=new t5(s,o),i=t.decimalInteger("SKIPPED-SEGMENTS");if($(i)){o.skippedSegments+=i;for(let e=i;e--;)h.push(null);f+=i}let r=t.enumeratedString("RECENTLY-REMOVED-DATERANGES");r&&(o.recentlyRemovedDateranges=(o.recentlyRemovedDateranges||[]).concat(r.split("	")));break}case"TARGETDURATION":0!==o.targetduration&&iU(o,e,T),o.targetduration=Math.max(parseInt(s),1);break;case"VERSION":null!==o.version&&iU(o,e,T),o.version=parseInt(s);break;case"INDEPENDENT-SEGMENTS":break;case"ENDLIST":o.live||iU(o,e,T),o.live=!1;break;case"#":(s||n)&&E.tagList.push(n?[s,n]:[s]);break;case"DISCONTINUITY":p++,E.tagList.push(["DIS"]);break;case"GAP":E.gap=!0,E.tagList.push([e]);break;case"BITRATE":E.tagList.push([e,s]),$(y=1e3*parseInt(s))?E.bitrate=y:y=0;break;case"DATERANGE":{let e=new t5(s,o),t=new t8(e,o.dateRanges[e.ID],o.dateRangeTagCount);o.dateRangeTagCount++,t.isValid||o.skippedSegments?o.dateRanges[t.id]=t:en.warn(`Ignoring invalid DATERANGE tag: "${s}"`),E.tagList.push(["EXT-X-DATERANGE",s]);break}case"DEFINE":{let e=new t5(s,o);"IMPORT"in e?function(e,t,i){let r=t.IMPORT;if(i&&r in i){let t=e.variableList;t||(e.variableList=t={}),t[r]=i[r]}else e.playlistParsingError||(e.playlistParsingError=Error(`EXT-X-DEFINE IMPORT attribute not found in Multivariant Playlist: "${r}"`))}(o,e,a):t2(o,e,t)}break;case"DISCONTINUITY-SEQUENCE":0!==o.startCC?iU(o,e,T):h.length>0&&iN(o,e,T),o.startCC=p=parseInt(s);break;case"KEY":{let e=iw(s,t,o);
44if(e.isSupported()){if("NONE"===e.method){L=void 0;break}L||(L={});let t=L[e.keyFormat];null!=t&&t.matches(e)||(t&&(L=Z({},L)),L[e.keyFormat]=e)}else en.warn(`[Keys] Ignoring unsupported EXT-X-KEY tag: "${s}"`);break}case"START":o.startTimeOffset=ix(s);break;case"MAP":{let e=new t5(s,o);if(E.duration){let t=new e_(r,l);i$(t,e,i,L),c=t,E.initSegment=c,c.rawProgramDateTime&&!E.rawProgramDateTime&&(E.rawProgramDateTime=c.rawProgramDateTime)}else{let t=E.byteRangeEndOffset;if(t){let e=E.byteRangeStartOffset;b=`${t-e}@${e}`}else b=null;i$(E,e,i,L),c=E,R=!0}c.cc=p;break}case"SERVER-CONTROL":k&&iU(o,e,T),o.canBlockReload=(k=new t5(s)).bool("CAN-BLOCK-RELOAD"),o.canSkipUntil=k.optionalFloat("CAN-SKIP-UNTIL",0),o.canSkipDateRanges=o.canSkipUntil>0&&k.bool("CAN-SKIP-DATERANGES"),o.partHoldBack=k.optionalFloat("PART-HOLD-BACK",0),o.holdBack=k.optionalFloat("HOLD-BACK",0);break;case"PART-INF":o.partTarget&&iU(o,e,T),o.partTarget=new t5(s).decimalFloatingPoint("PART-TARGET");break;case"PART":{let e=o.partList;e||(e=o.partList=[]);let t=g>0?e[e.length-1]:void 0,i=g++,r=new eP(new t5(s,o),E,l,i,t);e.push(r),E.duration+=r.duration;break}case"PRELOAD-HINT":{let e=new t5(s,o);o.preloadHint=e;break}case"RENDITION-REPORT":{let e=new t5(s,o);o.renditionReports=o.renditionReports||[],o.renditionReports.push(e);break}default:en.warn(`line parsed but not handled: ${T}`)}}}v&&!v.relurl?(h.pop(),m-=v.duration,o.partList&&(o.fragmentHint=v)):o.partList&&(iF(E,v,d),E.cc=p,o.fragmentHint=E,L&&iB(E,L,o)),o.targetduration||(o.playlistParsingError=Error("Missing Target Duration"));let I=h.length,D=h[0],_=h[I-1];if((m+=o.skippedSegments*o.targetduration)>0&&I&&_){o.averagetargetduration=m/I;let e=_.sn;o.endSN="initSegment"!==e?e:0,o.live||(_.endList=!0),A>0&&(function(e,t){let i=e[t];for(let r=t;r--;){let t=e[r];if(!t)return;t.programDateTime=i.programDateTime-1e3*t.duration,i=t}}(h,A),D&&d.unshift(D))}return o.fragmentHint&&(m+=o.fragmentHint.duration),o.totalduration=m,d.length&&o.dateRangeTagCount&&D&&iC(d,o),o.endCC=p,o}}function iC(e,t){let i=e.length;if(!i)if(!t.hasProgramDateTime)return;else{let r=t.fragments[t.fragments.length-1];e.push(r),i++}let r=e[i-1],s=t.live?1/0:t.totalduration,a=Object.keys(t.dateRanges);for(let l=a.length;l--;){let o=t.dateRanges[a[l]],h=o.startDate.getTime();o.tagAnchor=r.ref;for(let r=i;r--;){var n;if((null==(n=e[r])?void 0:n.sn)<t.startSN)break;let i=function(e,t,i,r,s){let a=i[r];if(a){let l=a.programDateTime;if(t>=l||0===r){var n;if(t<=l+1e3*(((null==(n=i[r+1])?void 0:n.start)||s)-a.start)){let s=i[r].sn-e.startSN;if(s<0)return -1;let a=e.fragments;if(a.length>i.length){let n=(i[r+1]||a[a.length-1]).sn-e.startSN;for(let e=n;e>s;e--){let i=a[e].programDateTime;if(t>=i&&t<i+1e3*a[e].duration)return e}}return s}}}return -1}(t,h,e,r,s);if(-1!==i){o.tagAnchor=t.fragments[i].ref;break}}}}function iw(e,t,i){var r,s;let a=new t5(e,i),n=null!=(r=a.METHOD)?r:"",l=a.URI,o=a.hexadecimalInteger("IV"),h=a.KEYFORMATVERSIONS,d=null!=(s=a.KEYFORMAT)?s:"identity";return l&&a.IV&&!o&&en.error(`Invalid IV: ${a.IV}`),new iA(n,l?iP.resolve(l,t):"",d,(h||"1").split("/").map(Number).filter(Number.isFinite),o,a.KEYID)}function ix(e){let t=new t5(e).decimalFloatingPoint("TIME-OFFSET");return $(t)?t:null}function iM(e,t){let i=(e||"").split(/[ ,]+/).filter(e=>e);["video","audio","text"].forEach(e=>{let r=i.filter(t=>eZ(t,e));r.length&&(t[`${e}Codec`]=r.map(e=>e.split("/")[0]).join(","),i=i.filter(e=>-1===r.indexOf(e)))}),t.unknownCodecs=i}function iO(e,t,i){let r=t[i];r&&(e[i]=r)}function iF(e,t,i){e.rawProgramDateTime?i.push(e):null!=t&&t.programDateTime&&(e.programDateTime=t.endProgramDateTime)}function i$(e,t,i,r){e.relurl=t.URI,t.BYTERANGE&&e.setByteRange(t.BYTERANGE),e.level=i,e.sn="initSegment",r&&(e.levelkeys=r),e.initSegment=null}function iB(e,t,i){e.levelkeys=t;let{encryptedFragments:r}=i;(!r.length||r[r.length-1].levelkeys!==t)&&Object.keys(t).some(e=>t[e].isCommonEncryption)&&r.push(e)}function iU(e,t,i){e.playlistParsingError=Error(`#EXT-X-${t} must not appear more than once (${i[0]})`)}function iN(e,t,i){e.playlistParsingError=Error(`#EXT-X-${t} must appear before the first Media Segment (${i[0]})`)}function iG(e,t){let i=t.startPTS;if($(i)){let r=0,s;t.sn>e.sn?(r=i-e.start,s=e):(r=e.start-i,s=t),s.duration!==r&&s.setDuration(r)}else t.sn>e.sn?e.cc===t.cc&&e.minEndPTS?t.setStart(e.start+(e.minEndPTS-e.start)):t.setStart(e.start+e.duration):t.setStart(Math.max(e.start-t.duration,0))}function iK(e,t,i,r,s,a,n){let l;r-i<=0&&(n.warn("Fragment should have a positive duration",t),r=i+t.duration,a=s+t.duration);let o=i,h=r,d=t.startPTS,c=t.endPTS;if($(d)){let l=Math.abs(d-i);e&&l>e.totalduration?n.warn(`media timestamps and playlist times differ by ${l}s for level ${t.level} ${e.url}`):$(t.deltaPTS)?t.deltaPTS=Math.max(l,t.deltaPTS):t.deltaPTS=l,o=Math.max(i,d),i=Math.min(i,d),s=void 0!==t.startDTS?Math.min(s,t.startDTS):s,h=Math.min(r,c),r=Math.max(r,c),a=void 0!==t.endDTS?Math.max(a,t.endDTS):a}let f=i-t.start;0!==t.start&&t.setStart(i),t.setDuration(r-t.start),t.startPTS=i,t.maxStartPTS=o,t.startDTS=s,t.endPTS=r,t.minEndPTS=h,t.endDTS=a;let g=t.sn;if(!e||g<e.startSN||g>e.endSN)return 0;let m=g-e.startSN,p=e.fragments;for(p[m]=t,l=m;l>0;l--)iG(p[l],p[l-1]);for(l=m;l<p.length-1;l++)iG(p[l],p[l+1]);return e.fragmentHint&&iG(p[p.length-1],e.fragmentHint),e.PTSKnown=e.alignedSliding=!0,f}function iH(e,t,i,r,s){return Error(`${e} ${s.url}
45Playlist starting @${t.startSN}
46${t.m3u8}
47
48Playlist starting @${i.startSN}
49${i.m3u8}`)}function iV(e,t,i=!0){let r=t.startSN+t.skippedSegments-e.startSN,s=e.fragments,a=r>=0,n=0;if(a&&r<s.length)n=s[r].start;else if(a&&t.startSN===e.endSN+1)n=e.fragmentEnd;else if(a&&i)n=e.fragmentStart+r*t.levelTargetDuration;else{if(t.skippedSegments||0!==t.fragmentStart)return;n=e.fragmentStart}ij(t,n)}function ij(e,t){if(t){let i=e.fragments;for(let r=e.skippedSegments;r<i.length;r++)i[r].addStart(t);e.fragmentHint&&e.fragmentHint.addStart(t)}}
49function iW(e,t=1/0){let i=1e3*e.targetduration;if(e.updated){let r=e.fragments;if(r.length&&4*i>t){let e=1e3*r[r.length-1].duration;e<i&&(i=e)}}else i/=2;return Math.round(i)}function iq(e,t,i){if(!e)return null;let r=e.fragments[t-e.startSN];return r||(r=e.fragmentHint)&&r.sn===t?r:t<e.startSN&&i&&i.sn===t?i:null}function iY(e,t,i){return e?iX(e.partList,t,i):null}function iX(e,t,i){if(e)for(let r=e.length;r--;){let s=e[r];if(s.index===i&&s.fragment.sn===t)return s}return null}function iz(e){e.forEach((e,t)=>{var i;null==(i=e.details)||i.fragments.forEach(e=>{e.level=t,e.initSegment&&(e.initSegment.level=t)})})}function iQ(e){return e.replace(/\?[^?]*$/,"")}function iZ(e,t){for(let r=0,s=e.length;r<s;r++){var i;if((null==(i=e[r])?void 0:i.cc)===t)return e[r]}return null}function iJ(e,t){let i=e.start+t;e.startPTS=i,e.setStart(i),e.endPTS=i+e.duration}function i0(e,t){let i=t.fragments;for(let t=0,r=i.length;t<r;t++)iJ(i[t],e);t.fragmentHint&&iJ(t.fragmentHint,e),t.alignedSliding=!0}function i1(e,t){if(!t||!(e.startCC<t.endCC)||!(e.endCC>t.startCC))return;let i=Math.min(t.endCC,e.endCC),r=iZ(t.fragments,i),s=iZ(e.fragments,i);r&&s&&(en.log(`Aligning playlist at start of dicontinuity sequence ${i}`),i0(r.start-s.start,e))}function i2(e,t){let i,r;if(!e.hasProgramDateTime||!t.hasProgramDateTime)return;let s=e.fragments,a=t.fragments;if(!s.length||!a.length)return;let n=Math.min(t.endCC,e.endCC);t.startCC<n&&e.startCC<n&&(i=iZ(a,n),r=iZ(s,n)),i&&r||(r=iZ(s,(i=a[Math.floor(a.length/2)]).cc)||s[Math.floor(s.length/2)]);let l=i.programDateTime,o=r.programDateTime;l&&o&&i0((o-l)/1e3-(r.start-i.start),e)}function i3(e,t,i){i4(e,t,i),e.addEventListener(t,i)}function i4(e,t,i){e.removeEventListener(t,i)}let i5=function(e){let t="",i=e.length;for(let r=0;r<i;r++)t+=`[${e.start(r).toFixed(3)}-${e.end(r).toFixed(3)}]`;return t},i8="STOPPED",i6="IDLE",i9="KEY_LOADING",i7="FRAG_LOADING",re="FRAG_LOADING_WAITING_RETRY",rt="WAITING_TRACK",ri="PARSING",rr="PARSED",rs="ENDED",ra="ERROR",rn="WAITING_INIT_PTS",rl="WAITING_LEVEL";class ro extends tX{constructor(e,t,i,r,s){super(r,e.logger),this.hls=void 0,this.fragPrevious=null,this.fragCurrent=null,this.fragmentTracker=void 0,this.transmuxer=null,this._state=i8,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=()=>{let{config:e,fragCurrent:t,media:i,mediaBuffer:r,state:s}=this,a=i?i.currentTime:0,n=tJ.bufferInfo(r||i,a,e.maxBufferHole),l=!n.len;if(this.log(`Media seeking to ${$(a)?a.toFixed(3):a}, state: ${s}, ${l?"out of":"in"} buffer`),this.state===rs)this.resetLoadingState();else if(t){let i=e.maxFragLookUpTolerance,r=t.start-i,s=t.start+t.duration+i;if(l||s<n.start||r>n.end){let e=a>s;(a<r||e)&&(e&&t.loader&&(this.log(`Cancelling fragment load for seek (sn: ${t.sn})`),t.abortRequests(),this.resetLoadingState()),this.fragPrevious=null)}}if(i&&(this.fragmentTracker.removeFragmentsInRange(a,1/0,this.playlistType,!0),a>this.lastCurrentTime&&(this.lastCurrentTime=a),!this.loadingParts)){let e=Math.max(n.end,a),t=this.shouldLoadParts(this.getLevelDetails(),e);t&&(this.log(`LL-Part loading ON after seeking to ${a.toFixed(2)} with buffer @${e.toFixed(2)}`),this.loadingParts=t)}this.hls.hasEnoughToStart||(this.log(`Setting ${l?"startPosition":"nextLoadPosition"} to ${a} for seek without enough to start`),this.nextLoadPosition=a,l&&(this.startPosition=a)),l&&this.state===i6&&this.tickImmediate()},this.onMediaEnded=()=>{this.log("setting startPosition to 0 because media ended"),this.startPosition=this.lastCurrentTime=0},this.playlistType=s,this.hls=e,this.fragmentLoader=new tj(e.config),this.keyLoader=i,this.fragmentTracker=t,this.config=e.config,this.decrypter=new tV(e.config)}registerListeners(){let{hls:e}=this;
49e.on(K.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(K.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(K.MANIFEST_LOADING,this.onManifestLoading,this),e.on(K.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(K.ERROR,this.onError,this)}unregisterListeners(){let{hls:e}=this;e.off(K.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(K.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(K.MANIFEST_LOADING,this.onManifestLoading,this),e.off(K.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(K.ERROR,this.onError,this)}doTick(){this.onTickEnd()}onTickEnd(){}startLoad(e){}stopLoad(){if(this.state===i8)return;this.fragmentLoader.abort(),this.keyLoader.abort(this.playlistType);let e=this.fragCurrent;null!=e&&e.loader&&(e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.resetTransmuxer(),this.fragCurrent=null,this.fragPrevious=null,this.clearInterval(),this.clearNextTick(),this.state=i8}get startPositionValue(){let{nextLoadPosition:e,startPosition:t}=this;return -1===t&&e?e:t}get bufferingEnabled(){return this.buffering}pauseBuffering(){this.buffering=!1}resumeBuffering(){this.buffering=!0}get inFlightFrag(){return{frag:this.fragCurrent,state:this.state}}_streamEnded(e,t){if(t.live||!this.media)return!1;let i=e.end||0,r=this.config.timelineOffset||0;if(i<=r)return!1;let s=e.buffered;this.config.maxBufferHole&&s&&s.length>1&&(e=tJ.bufferedInfo(s,e.start,0));let a=e.nextStart;if(a&&a>r&&a<t.edge||this.media.currentTime<e.start)return!1;let n=t.partList;if(null!=n&&n.length){let e=n[n.length-1];return tJ.isBuffered(this.media,e.start+e.duration/2)}let l=t.fragments[t.fragments.length-1].type;return this.fragmentTracker.isEndListAppended(l)}getLevelDetails(){if(this.levels&&null!==this.levelLastLoaded)return this.levelLastLoaded.details}get timelineOffset(){let e=this.config.timelineOffset;if(e){var t;return(null==(t=this.getLevelDetails())?void 0:t.appliedTimelineOffset)||e}return 0}onMediaAttached(e,t){let i=this.media=this.mediaBuffer=t.media;i3(i,"seeking",this.onMediaSeeking),i3(i,"ended",this.onMediaEnded);let r=this.config;this.levels&&r.autoStartLoad&&this.state===i8&&this.startLoad(r.startPosition)}onMediaDetaching(e,t){let i=!!t.transferMedia,r=this.media;if(null!==r){if(r.ended&&(this.log("MSE detaching and video ended, reset startPosition"),this.startPosition=this.lastCurrentTime=0),i4(r,"seeking",this.onMediaSeeking),i4(r,"ended",this.onMediaEnded),this.keyLoader&&!i&&this.keyLoader.detach(),this.media=this.mediaBuffer=null,this.loopSn=void 0,i){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=i8,this.fragmentLoader&&this.fragmentLoader.destroy(),this.keyLoader&&this.keyLoader.destroy(),this.decrypter&&this.decrypter.destroy(),this.hls=this.log=this.warn=this.decrypter=this.keyLoader=this.fragmentLoader=this.fragmentTracker=null,super.onHandlerDestroyed()}loadFragment(e,t,i){this.startFragRequested=!0,this._loadFragForPlayback(e,t,i)}_loadFragForPlayback(e,t,i){let r=e=>{let t=e.frag;if(this.fragContextChanged(t)){this.warn(`${t.type} sn: ${t.sn}${e.part?" part: "+e.part.index:""} of ${this.fragInfo(t,!1,e.part)}) was dropped during download.`),this.fragmentTracker.removeFragment(t);return}t.stats.chunkCount++,this._handleFragmentLoadProgress(e)};this._doFragLoad(e,t,i,r).then(e=>{if(!e)return;let t=this.state,i=e.frag;if(this.fragContextChanged(i)){t!==i7&&(this.fragCurrent||t!==ri)||(this.fragmentTracker.removeFragment(i),this.state=i6);return}"payload"in e&&(this.log(`Loaded ${i.type} sn: ${i.sn} of ${this.playlistLabel()} ${i.level}`),this.hls.trigger(K.FRAG_LOADED,e)),this._handleFragmentLoadComplete(e)}).catch(t=>{this.state===i8||this.state===ra||(this.warn(`Frag error: ${t?.message||t}`),this.resetFragmentLoading(e))})}clearTrackerIfNeeded(e){var t;let{fragmentTracker:i}=this;if(i.getState(e)===tO){let t=e.type,r=this.getFwdBufferInfo(this.mediaBuffer,t),s=Math.max(e.duration,r?r.len:this.config.maxBufferLength),a=this.backtrackFragment;((a?e.sn-a.sn:0)==1||this.reduceMaxBufferLength(s,e.duration))&&i.removeFragment(e)}else(null==(t=this.mediaBuffer)?void 0:t.buffered.length)===0?i.removeAllFragments():i.hasParts(e.type)&&(i.detectPartialFragments({frag:e,part:null,stats:e.stats,id:e.type}),i.getState(e)===tF&&i.removeFragment(e))}checkLiveUpdate(e){if(e.updated&&!e.live){let 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){let t=e.details;return t?.live&&"EVENT"!==t.type&&(this.levelLastLoaded!==e||t.expired)}flushMainBuffer(e,t,i=null){e-t&&this.hls.trigger(K.BUFFER_FLUSHING,{startOffset:e,endOffset:t,type:i})}_loadInitSegment(e,t){this._doFragLoad(e,t).then(e=>{let t=e?.frag;if(!t||this.fragContextChanged(t)||!this.levels)throw Error("init load aborted");return e}).then(e=>{let{hls:t}=this,{frag:i,payload:r}=e,s=i.decryptdata;if(r&&r.byteLength>0&&null!=s&&s.key&&s.iv&&ie(s.method)){let a=self.performance.now();
49return this.decrypter.decrypt(new Uint8Array(r),s.key.buffer,s.iv.buffer,it(s.method)).catch(e=>{throw t.trigger(K.ERROR,{type:N.MEDIA_ERROR,details:G.FRAG_DECRYPT_ERROR,fatal:!1,error:e,reason:e.message,frag:i}),e}).then(r=>{let s=self.performance.now();return t.trigger(K.FRAG_DECRYPTED,{frag:i,payload:r,stats:{tstart:a,tdecrypt:s}}),e.payload=r,this.completeInitSegmentLoad(e)})}return this.completeInitSegmentLoad(e)}).catch(t=>{this.state===i8||this.state===ra||(this.warn(t),this.resetFragmentLoading(e))})}completeInitSegmentLoad(e){let{levels:t}=this;if(!t)throw Error("init load aborted, missing levels");let i=e.frag.stats;this.state!==i8&&(this.state=i6),e.frag.data=new Uint8Array(e.payload),i.parsing.start=i.buffering.start=self.performance.now(),i.parsing.end=i.buffering.end=self.performance.now(),this.tick()}unhandledEncryptionError(e,t){var i,r;let s=e.tracks;if(s&&!t.encrypted&&(null!=(i=s.audio)&&i.encrypted||null!=(r=s.video)&&r.encrypted)&&(!this.config.emeEnabled||!this.keyLoader.emeController)){let e=this.media,i=Error(`Encrypted track with no key in ${this.fragInfo(t)} (media ${e?"attached mediaKeys: "+e.mediaKeys:"detached"})`);return this.warn(i.message),!!e&&!e.mediaKeys&&(this.hls.trigger(K.ERROR,{type:N.KEY_SYSTEM_ERROR,details:G.KEY_SYSTEM_NO_KEYS,fatal:!1,error:i,frag:t}),this.resetTransmuxer(),!0)}return!1}fragContextChanged(e){let{fragCurrent:t}=this;return!e||!t||e.sn!==t.sn||e.level!==t.level}fragBufferedComplete(e,t){let i=this.mediaBuffer?this.mediaBuffer:this.media;if(this.log(`Buffered ${e.type} sn: ${e.sn}${t?" part: "+t.index:""} of ${this.fragInfo(e,!1,t)} > buffer:${i?i5(tJ.getBuffered(i)):"(detached)"})`),eD(e)){var r;if(e.type!==X){let t=e.elementaryStreams;if(!Object.keys(t).some(e=>!!t[e])){this.state=i6;return}}let t=null==(r=this.levels)?void 0:r[e.level];null!=t&&t.fragmentError&&(this.log(`Resetting level fragment error count of ${t.fragmentError} on frag buffered`),t.fragmentError=0)}this.state=i6}_handleFragmentLoadComplete(e){let{transmuxer:t}=this;if(!t)return;let{frag:i,part:r,partsLoaded:s}=e,a=!s||0===s.length||s.some(e=>!e),n=new tz(i.level,i.sn,i.stats.chunkCount+1,0,r?r.index:-1,!a);t.flush(n)}_handleFragmentLoadProgress(e){}_doFragLoad(e,t,i=null,r){var s,a;let n;this.fragCurrent=e;let l=t.details;if(!this.levels||!l)throw Error(`frag load aborted, missing level${l?"":" detail"}s`);let o=null;if(e.encrypted&&!(null!=(s=e.decryptdata)&&s.key)){if(this.log(`Loading key for ${e.sn} of [${l.startSN}-${l.endSN}], ${this.playlistLabel()} ${e.level}`),this.state=i9,this.fragCurrent=e,o=this.keyLoader.load(e).then(e=>{if(!this.fragContextChanged(e.frag))return this.hls.trigger(K.KEY_LOADED,e),this.state===i9&&(this.state=i6),e}),this.hls.trigger(K.KEY_LOADING,{frag:e}),null===this.fragCurrent)return this.log("context changed in KEY_LOADING"),Promise.resolve(null)}else e.encrypted||(o=this.keyLoader.loadClear(e,l.encryptedFragments,this.startFragRequested))&&this.log("[eme] blocking frag load until media-keys acquired");let h=this.fragPrevious;if(eD(e)&&(!h||e.sn!==h.sn)){let i=this.shouldLoadParts(t.details,e.end);i!==this.loadingParts&&(this.log(`LL-Part loading ${i?"ON":"OFF"} loading sn ${h?.sn}->${e.sn}`),this.loadingParts=i)}if(i=Math.max(e.start,i||0),this.loadingParts&&eD(e)){let s=l.partList;if(s&&r){i>l.fragmentEnd&&l.fragmentHint&&(e=l.fragmentHint);let a=this.getNextPart(s,e,i);if(a>-1){let n,h=s[a];return e=this.fragCurrent=h.fragment,this.log(`Loading ${e.type} sn: ${e.sn} part: ${h.index} (${a}/${s.length-1}) of ${this.fragInfo(e,!1,h)}) cc: ${e.cc} [${l.startSN}-${l.endSN}], target: ${parseFloat(i.toFixed(3))}`),this.nextLoadPosition=h.start+h.duration,this.state=i7,n=o?o.then(i=>!i||this.fragContextChanged(i.frag)?null:this.doFragPartsLoad(e,h,t,r)).catch(e=>this.handleFragLoadError(e)):this.doFragPartsLoad(e,h,t,r).catch(e=>this.handleFragLoadError(e)),this.hls.trigger(K.FRAG_LOADING,{frag:e,part:h,targetBufferTime:i}),null===this.fragCurrent?Promise.reject(Error("frag load aborted, context changed in FRAG_LOADING parts")):n}if(!e.url||this.loadedEndOfParts(s,i))return Promise.resolve(null)}}if(eD(e)&&this.loadingParts)this.log(`LL-Part loading OFF after next part miss @${i.toFixed(2)} Check buffer at sn: ${e.sn} loaded parts: ${null==(a=l.partList)?void 0:a.filter(e=>e.loaded).map(e=>`[${e.start}-${e.end}]`)}`),this.loadingParts=!1;else if(!e.url)return Promise.resolve(null);this.log(`Loading ${e.type} sn: ${e.sn} of ${this.fragInfo(e,!1)}) cc: ${e.cc} ${"["+l.startSN+"-"+l.endSN+"]"}, target: ${parseFloat(i.toFixed(3))}`),$(e.sn)&&!this.bitrateTest&&(this.nextLoadPosition=e.start+e.duration),this.state=i7;let d=this.config.progressive&&e.type!==X;return n=d&&o?o.then(t=>!t||this.fragContextChanged(t.frag)?null:this.fragmentLoader.load(e,r)).catch(e=>this.handleFragLoadError(e)):Promise.all([this.fragmentLoader.load(e,d?r:void 0),o]).then(([e])=>(!d&&r&&r(e),e)).catch(e=>this.handleFragLoadError(e)),this.hls.trigger(K.FRAG_LOADING,{frag:e,targetBufferTime:i}),null===this.fragCurrent?Promise.reject(Error("frag load aborted, context changed in FRAG_LOADING")):n}doFragPartsLoad(e,t,i,r){return new Promise((s,a)=>{var n;let l=[],o=null==(n=i.details)?void 0:n.partList,h=t=>{this.fragmentLoader.loadPart(e,t,r).then(r=>{l[t.index]=r;let a=r.part;this.hls.trigger(K.FRAG_LOADED,r);let n=iY(i.details,e.sn,t.index+1)||iX(o,e.sn,t.index+1);if(!n)return s({frag:e,part:a,partsLoaded:l});h(n)}).catch(a)};h(t)})}handleFragLoadError(e){if("data"in e){let t=e.data;t.frag&&t.details===G.INTERNAL_ABORTED?this.handleFragLoadAborted(t.frag,t.part):t.frag&&t.type===N.KEY_SYSTEM_ERROR?(t.frag.abortRequests(),this.resetStartWhenNotLoaded(),this.resetFragmentLoading(t.frag)):this.hls.trigger(K.ERROR,t)}else this.hls.trigger(K.ERROR,{type:N.OTHER_ERROR,details:G.INTERNAL_EXCEPTION,err:e,error:e,fatal:!0});return null}_handleTransmuxerFlush(e){let t=this.getCurrentContext(e);if(!t||this.state!==ri){this.fragCurrent||this.state===i8||this.state===ra||(this.state=i6);return}let{frag:i,part:r,level:s}=t,a=self.performance.now();i.stats.parsing.end=a,r&&(r.stats.parsing.end=a);let n=this.getLevelDetails(),l=n&&i.sn>n.endSN||this.shouldLoadParts(n,i.end);l!==this.loadingParts&&(this.log(`LL-Part loading ${l?"ON":"OFF"} after parsing segment ending @${i.end.toFixed(2)}`),this.loadingParts=l),this.updateLevelTiming(i,r,s,e.partial)}shouldLoadParts(e,t){if(this.config.lowLatencyMode){if(!e)return this.loadingParts;if(e.partList){var i,r;let s=e.partList[0];if(s.fragment.type===X)return!1;if(t>=s.end+((null==(i=e.fragmentHint)?void 0:i.duration)||0)&&(this.hls.hasEnoughToStart?(null==(r=this.media)?void 0:r.currentTime)||this.lastCurrentTime:this.getLoadPosition())>s.start-s.fragment.duration)return!0}}return!1}getCurrentContext(e){let{levels:t,fragCurrent:i}=this,{level:r,sn:s,part:a}=e;if(!(null!=t&&t[r]))return this.warn(`Levels object was unset while buffering fragment ${s} of ${this.playlistLabel()} ${r}. The current chunk will not be buffered.`),null;let n=t[r],l=n.details,o=a>-1?iY(l,s,a):null,h=o?o.fragment:iq(l,s,i);return h?(i&&i!==h&&(h.stats=i.stats),{frag:h,part:o,level:n}):null}bufferFragmentData(e,t,i,r,s){if(this.state!==ri)return;let{data1:a,data2:n}=e,l=a;if(n&&(l=eW(a,n)),!l.length)return;let o=this.initPTS[t.cc],h=o?-o.baseTime/o.timescale:void 0,d={type:e.type,frag:t,part:i,chunkMeta:r,offset:h,parent:t.type,data:l};if(this.hls.trigger(K.BUFFER_APPENDING,d),e.dropped&&e.independent&&!i){if(s)return;this.flushBufferGap(t)}}flushBufferGap(e){let t=this.media;if(!t)return;if(!tJ.isBuffered(t,t.currentTime))return void this.flushMainBuffer(0,e.start);let i=t.currentTime,r=tJ.bufferInfo(t,i,0),s=e.duration,a=Math.min(2*this.config.maxFragLookUpTolerance,.25*s),n=Math.max(Math.min(e.start-a,r.end-a),i+a);e.start-n>a&&this.flushMainBuffer(n,e.start)}getFwdBufferInfo(e,t){var i;let r=this.getLoadPosition();if(!$(r))return null;let s=this.lastCurrentTime>r||null!=(i=this.media)&&i.paused?0:this.config.maxBufferHole;return this.getFwdBufferInfoAtPos(e,r,t,s)}getFwdBufferInfoAtPos(e,t,i,r){let s=tJ.bufferInfo(e,t,r);if(0===s.len&&void 0!==s.nextStart){let a=this.fragmentTracker.getBufferedFrag(t,i);if(a&&(s.nextStart<=a.end||a.gap)){let i=Math.max(Math.min(s.nextStart,a.end)-t,r);return tJ.bufferInfo(e,t,i)}}return s}
49getMaxBufferLength(e){let{config:t}=this;return Math.min(e?Math.max(8*t.maxBufferSize/e,t.maxBufferLength):t.maxBufferLength,t.maxMaxBufferLength)}exceedsMaxBuffer(e,t,i){let r=e.nextStart;if(r&&i.start>r){let r=e.buffered;if(r){let s=e.len,a=e.bufferedIndex;for(let e=r.length-1;e>a;e--)r[e].start<i.start&&(s+=r[e].end-r[e].start);return s>=t}}return!1}reduceMaxBufferLength(e,t){let i=this.config,r=Math.max(Math.min(e-t,i.maxBufferLength),t),s=Math.max(e-3*t,i.maxMaxBufferLength/2,r);return s>=r&&(i.maxMaxBufferLength=s,this.warn(`Reduce max buffer length to ${s}s`),!0)}getAppendedFrag(e,t=q){let i=this.fragmentTracker?this.fragmentTracker.getAppendedFrag(e,t):null;return i&&"fragment"in i?i.fragment:i}getNextFragment(e,t){let i=t.fragments,r=i.length;if(!r)return null;let{config:s}=this,a=t.fragmentStart,n=s.lowLatencyMode&&!!t.partList,l=null;if(t.live){let i=s.initialLiveManifestSize;if(r<i)return this.warn(`Not enough fragments to start playback (have: ${r}, need: ${i})`),null;if(!t.PTSKnown&&!this.startFragRequested&&-1===this.startPosition||e<a){var o;let i,r;n&&!this.loadingParts&&(this.log("LL-Part loading ON for initial live fragment"),this.loadingParts=!0),l=this.getInitialLiveFragment(t);let s=this.config.startPosition,h=this.hls.startPosition,d=this.hls.liveSyncPosition,c=(null==(o=l)?void 0:o.start)||0;-1!==h&&h>=a?(i=h,r=h===s?"config":"next load start"):null!==d?(i=d,r="live edge"):(i=e,r="buffer pos"),i<c&&(i=c,r="live frag start"),i<a&&(i=a,r="playlist start"),(this.startPosition!=i||this.nextLoadPosition!=i)&&(this.log(`Setting startPosition to ${i.toFixed(3)} ${-1===h?"":`(from ${s}) `}based on ${r}. live edge: ${d} live frag start: ${c.toFixed(3)} playlist start: ${a.toFixed(3)} buffer pos: ${e}`),this.startPosition=this.nextLoadPosition=i)}}else e<=a&&(l=i[0]);if(!l){let i=this.loadingParts?t.partEnd:t.fragmentEnd;l=this.getFragmentAtPosition(e,i,t)}let h=this.filterReplacedPrimary(l,t);if(!h&&l){let e=l.sn-t.startSN;h=this.filterReplacedPrimary(i[e+1]||null,t)}return this.mapToInitFragWhenRequired(h)}isLoopLoading(e,t){if(this.nextLoadPosition<=t)return!1;let i=this.fragmentTracker.getState(e);return"OK"===i||i===tF&&!!e.gap}getNextFragmentLoopLoading(e,t,i,r,s){let a=null;if(e.gap&&(a=this.getNextFragment(this.nextLoadPosition,t))&&!a.gap&&i.nextStart){let e=this.getFwdBufferInfoAtPos(this.mediaBuffer?this.mediaBuffer:this.media,i.nextStart,r,0);if(null!==e&&i.len+e.len>=s){let e=a.sn;return this.loopSn!==e&&(this.log(`buffer full after gaps in "${r}" playlist starting at sn: ${e}`),this.loopSn=e),null}}return this.loopSn=void 0,a}get primaryPrefetch(){if(rh(this.config)){var e;if(null==(e=this.hls.interstitialsManager)||null==(e=e.playingItem)?void 0:e.event)return!0}return!1}filterReplacedPrimary(e,t){if(!e)return e;if(rh(this.config)&&e.type!==X){let i=this.hls.interstitialsManager,r=i?.bufferingItem;if(r){let i=r.event;if(i){if(i.appendInPlace||Math.abs(e.start-r.start)>1||0===r.start)return null}else if(e.end<=r.start&&t?.live===!1||e.start>r.end&&r.nextEvent&&(r.nextEvent.appendInPlace||e.start-r.end>1))return null}let s=i?.playerQueue;if(s)for(let t=s.length;t--;){let i=s[t].interstitial;if(i.appendInPlace&&e.start>=i.startTime&&e.end<=i.resumeTime)return null}}return e}mapToInitFragWhenRequired(e){return null==e||!e.initSegment||e.initSegment.data||this.bitrateTest?e:e.initSegment}getNextPart(e,t,i){let r=-1,s=!1,a=!0;for(let n=0,l=e.length;n<l;n++){let l=e[n];if(a=a&&!l.independent,r>-1&&i<l.start)break;let o=l.loaded;o?r=-1:(s||(l.independent||a)&&l.fragment===t)&&(l.fragment!==t&&this.warn(`Need buffer at ${i} but next unloaded part starts at ${l.start}`),r=n),s=o}return r}loadedEndOfParts(e,t){let i;for(let r=e.length;r--&&(i=e[r]).loaded;)if(t>i.start)return!0;return!1}getInitialLiveFragment(e){let t=e.fragments,i=this.fragPrevious,r=null;if(i){if(e.hasProgramDateTime&&(r=function(e,t,i){if(null===t||!Array.isArray(e)||!e.length||!$(t)||t<(e[0].programDateTime||0)||t>=(e[e.length-1].endProgramDateTime||0))return null;for(let r=0;r<e.length;++r){let s=e[r];if(function(e,t,i){let r=1e3*Math.min(t,i.duration+(i.deltaPTS?i.deltaPTS:0));return(i.endProgramDateTime||0)-r>e}(t,i,s))return s}return null}(t,i.endProgramDateTime,this.config.maxFragLookUpTolerance))&&this.log(`Live playlist, switching playlist, load frag with same PDT: ${i.programDateTime}`),!r){let s=i.sn+1;if(s>=e.startSN&&s<=e.endSN){let a=t[s-e.startSN];i.cc===a.cc&&(r=a,this.log(`Live playlist, switching playlist, load frag with next SN: ${r.sn}`))}r||(r=tR(e,i.cc,i.end))&&this.log(`Live playlist, switching playlist, load frag with same CC: ${r.sn}`)}}else{let t=this.hls.liveSyncPosition;null!==t&&(r=this.getFragmentAtPosition(t,this.bitrateTest?e.fragmentEnd:e.edge,e))}return r}getFragmentAtPosition(e,t,i){let r,{config:s}=this,{fragPrevious:a}=this,{fragments:n,endSN:l}=i,{fragmentHint:o}=i,{maxFragLookUpTolerance:h}=s,d=i.partList,c=!!(this.loadingParts&&null!=d&&d.length&&o);if(c&&!this.bitrateTest&&d[d.length-1].fragment.sn===o.sn&&(n=n.concat(o),l=o.sn),e<t){var f;let i=e<this.lastCurrentTime||e>t-h||null!=(f=this.media)&&f.paused||!this.startFragRequested?0:h;r=tL(a,n,e,i)}else r=n[n.length-1];if(r){let e=r.sn-i.startSN,t=this.fragmentTracker.getState(r);
49if(("OK"===t||t===tF&&r.gap)&&(a=r),a&&r.sn===a.sn&&(!c||d[0].fragment.sn>r.sn||!i.live)&&r.level===a.level){let t=n[e+1];r=r.sn<l&&"OK"!==this.fragmentTracker.getState(t)?t:null}}return r}alignPlaylists(e,t,i){let r=e.fragments.length;if(!r)return this.warn("No fragments in live playlist"),0;let s=e.fragmentStart,a=!t,n=e.alignedSliding&&$(s);if(a||!n&&!s){i&&(i1(e,i),e.alignedSliding||i2(e,i),e.alignedSliding||e.skippedSegments||iV(i,e,!1));let s=e.fragmentStart;return this.log(`Live playlist sliding: ${s.toFixed(2)} start-sn: ${t?t.startSN:"na"}->${e.startSN} fragments: ${r}`),s}return s}waitForCdnTuneIn(e){return e.live&&e.canBlockReload&&e.partTarget&&e.tuneInGoal>Math.max(e.partHoldBack,3*e.partTarget)}setStartPosition(e,t){let i=this.startPosition;i<t&&(i=-1);let r=this.timelineOffset;if(-1===i){let s=null!==this.startTimeOffset,a=s?this.startTimeOffset:e.startTimeOffset;null!==a&&$(a)?(i=t+a,a<0&&(i+=e.edge),i=Math.min(Math.max(t,i),t+e.totalduration),this.log(`Setting startPosition to ${i} for start time offset ${a} found in ${s?"multivariant":"media"} playlist`),this.startPosition=i):e.live?(i=this.hls.liveSyncPosition||t,this.log(`Setting startPosition to -1 to start at live edge ${i}`),this.startPosition=-1):(this.log("setting startPosition to 0 by default"),this.startPosition=i=0),this.lastCurrentTime=i+r}this.nextLoadPosition=i+r}getLoadPosition(){var e;let{media:t}=this,i=0;return null!=(e=this.hls)&&e.hasEnoughToStart&&t?i=t.currentTime:this.nextLoadPosition>=0&&(i=this.nextLoadPosition),i}handleFragLoadAborted(e,t){this.transmuxer&&e.type===this.playlistType&&eD(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===re)||(this.state=i6)}onFragmentOrKeyLoadError(e,t){var i,r,s;if(t.chunkMeta&&!t.frag){let e=this.getCurrentContext(t.chunkMeta);e&&(t.frag=e.frag)}let a=t.frag;if(!a||a.type!==e||!this.levels)return;if(this.fragContextChanged(a))return void this.warn(`Frag load error must match current frag to retry ${a.url} > ${null==(r=this.fragCurrent)?void 0:r.url}`);let n=t.details===G.FRAG_GAP;n&&this.fragmentTracker.fragBuffered(a,!0);let l=t.errorAction;if(!l){this.state=ra;return}let{action:o,flags:h,retryCount:d=0,retryConfig:c}=l,f=!!c,g=f&&5===o,m=f&&!l.resolved&&1===h,p=null==(i=this.hls.latestLevelDetails)?void 0:i.live;if(!g&&m&&eD(a)&&!a.endList&&p&&!tI(t))this.resetFragmentErrors(e),this.treatAsGap(a),l.resolved=!0;else if((g||m)&&d<c.maxNumRetry){let i=tw(null==(s=t.response)?void 0:s.code),r=t_(c,d);if(this.resetStartWhenNotLoaded(),this.retryDate=self.performance.now()+r,this.state=re,l.resolved=!0,i){this.log("Waiting for connection (offline)"),this.retryDate=1/0,t.reason="offline";return}this.warn(`Fragment ${a.sn} of ${e} ${a.level} errored with ${t.details}, retrying loading ${d+1}/${c.maxNumRetry} in ${r}ms`)}else if(c)if(this.resetFragmentErrors(e),!(d<c.maxNumRetry))return void this.warn(`${t.details} reached or exceeded max retry (${d})`);else n||3===o||(l.resolved=!0);else 2===o?this.state=rl:this.state=ra;this.tickImmediate()}checkRetryDate(){let e=self.performance.now(),t=this.retryDate,i=t===1/0;(!t||e>=t||i&&!tw(0))&&(i&&this.log("Connection restored (online)"),this.resetStartWhenNotLoaded(),this.state=i6)}reduceLengthAndFlushBuffer(e){if(this.state===ri||this.state===rr){let t=e.frag,i=e.parent,r=this.getFwdBufferInfo(this.mediaBuffer,i),s=r&&r.len>.5;s&&this.reduceMaxBufferLength(r.len,t?.duration||10);let a=!s;return a&&this.warn(`Buffer full error while media.currentTime (${this.getLoadPosition()}) is not buffered, flush ${i} buffer`),t&&(this.fragmentTracker.removeFragment(t),this.nextLoadPosition=t.start),this.resetLoadingState(),a}return!1}resetFragmentErrors(e){e===Y&&(this.fragCurrent=null),this.hls.hasEnoughToStart||(this.startFragRequested=!1),this.state!==i8&&(this.state=i6)}afterBufferFlushed(e,t,i){if(!e)return;let r=tJ.getBuffered(e);this.fragmentTracker.detectEvictedFragments(t,r,i),this.state===rs&&this.resetLoadingState()}
49resetLoadingState(){this.log("Reset loading state"),this.fragCurrent=null,this.fragPrevious=null,this.state!==i8&&(this.state=i6)}resetStartWhenNotLoaded(){if(!this.hls.hasEnoughToStart){this.startFragRequested=!1;let e=this.levelLastLoaded,t=e?e.details:null;null!=t&&t.live?(this.log("resetting startPosition for live start"),this.startPosition=-1,this.setStartPosition(t,t.fragmentStart),this.resetLoadingState()):this.nextLoadPosition=this.startPosition}}resetWhenMissingContext(e){this.log(`Loading context changed while buffering sn ${e.sn} of ${this.playlistLabel()} ${-1===e.level?"<removed>":e.level}. This chunk will not be buffered.`),this.removeUnbufferedFrags(),this.resetStartWhenNotLoaded(),this.resetLoadingState()}removeUnbufferedFrags(e=0){this.fragmentTracker.removeFragmentsInRange(e,1/0,this.playlistType,!1,!0)}updateLevelTiming(e,t,i,r){let s=i.details;if(!s)return void this.warn("level.details undefined");if(!Object.keys(e.elementaryStreams).reduce((t,a)=>{let n=e.elementaryStreams[a];if(n){let l=n.endPTS-n.startPTS;if(l<=0)return this.warn(`Could not parse fragment ${e.sn} ${a} duration reliably (${l})`),t||!1;let o=r?0:iK(s,e,n.startPTS,n.endPTS,n.startDTS,n.endDTS,this);return this.hls.trigger(K.LEVEL_PTS_UPDATED,{details:s,level:i,drift:
49o,type:a,frag:e,start:n.startPTS,end:n.endPTS}),!0}return t},!1)){var a;let t=(null==(a=this.transmuxer)?void 0:a.error)===null;if((0===i.fragmentError||t&&(i.fragmentError<2||e.endList))&&this.treatAsGap(e,i),t){let t=Error(`Found no media in fragment ${e.sn} of ${this.playlistLabel()} ${e.level} resetting transmuxer to fallback to playlist timing`);if(this.warn(t.message),this.hls.trigger(K.ERROR,{type:N.MEDIA_ERROR,details:G.FRAG_PARSING_ERROR,fatal:!1,error:t,frag:e,reason:`Found no media in msn ${e.sn} of ${this.playlistLabel()} "${i.url}"`}),!this.hls)return;this.resetTransmuxer()}}this.state=rr,this.log(`Parsed ${e.type} sn: ${e.sn}${t?" part: "+t.index:""} of ${this.fragInfo(e,!1,t)})`),this.hls.trigger(K.FRAG_PARSED,{frag:e,part:t})}playlistLabel(){return this.playlistType===q?"level":"track"}fragInfo(e,t=!0,i){var r,s;return`${this.playlistLabel()} ${e.level} (${i?"part":"frag"}:[${(null!=(r=t&&!i?e.startPTS:(i||e).start)?r:NaN).toFixed(3)}-${(null!=(s=t&&!i?e.endPTS:(i||e).end)?s:NaN).toFixed(3)}]${i&&"main"===e.type?"INDEPENDENT="+(i.independent?"YES":"NO"):""}`}treatAsGap(e,t){t&&t.fragmentError++,e.gap=!0,this.fragmentTracker.removeFragment(e),this.fragmentTracker.fragBuffered(e,!0)}resetTransmuxer(){var e;null==(e=this.transmuxer)||e.reset()}recoverWorkerError(e){"demuxerWorker"===e.event&&(this.fragmentTracker.removeAllFragments(),this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null),this.resetStartWhenNotLoaded(),this.resetLoadingState())}set state(e){let t=this._state;t!==e&&(this._state=e,this.log(`${t}->${e}`))}get state(){return this._state}}function rh(e){return!!e.interstitialsController&&!1!==e.enableInterstitialPlayback}class rd{constructor(){this.chunks=[],this.dataLength=0}push(e){this.chunks.push(e),this.dataLength+=e.length}flush(){let e,{chunks:t,dataLength:i}=this;return t.length?(e=1===t.length?t[0]:function(e,t){let i=new Uint8Array(t),r=0;for(let t=0;t<e.length;t++){let s=e[t];i.set(s,r),r+=s.length}return i}(t,i),this.reset(),e):new Uint8Array(0)}reset(){this.chunks.length=0,this.dataLength=0}}var ru,rc,rf={exports:{}},rg=(rc||(rc=1,function(e){var t=Object.prototype.hasOwnProperty,i="~";function r(){}function s(e,t,i){this.fn=e,this.context=t,this.once=i||!1}function a(e,t,r,a,n){if("function"!=typeof r)throw TypeError("The listener must be a function");
49var l=new s(r,a||e,n),o=i?i+t:t;return e._events[o]?e._events[o].fn?e._events[o]=[e._events[o],l]:e._events[o].push(l):(e._events[o]=l,e._eventsCount++),e}function n(e,t){0==--e._eventsCount?e._events=new r:delete e._events[t]}function l(){this._events=new r,this._eventsCount=0}Object.create&&(r.prototype=Object.create(null),new r().__proto__||(i=!1)),l.prototype.eventNames=function(){var e,r,s=[];if(0===this._eventsCount)return s;for(r in e=this._events)t.call(e,r)&&s.push(i?r.slice(1):r);return Object.getOwnPropertySymbols?s.concat(Object.getOwnPropertySymbols(e)):s},l.prototype.listeners=function(e){var t=i?i+e:e,r=this._events[t];if(!r)return[];if(r.fn)return[r.fn];for(var s=0,a=r.length,n=Array(a);s<a;s++)n[s]=r[s].fn;return n},l.prototype.listenerCount=function(e){var t=i?i+e:e,r=this._events[t];return r?r.fn?1:r.length:0},l.prototype.emit=function(e,t,r,s,a,n){var l=i?i+e:e;if(!this._events[l])return!1;var o,h,d=this._events[l],c=arguments.length;if(d.fn){switch(d.once&&this.removeListener(e,d.fn,void 0,!0),c){case 1:return d.fn.call(d.context),!0;case 2:return d.fn.call(d.context,t),!0;case 3:return d.fn.call(d.context,t,r),!0;case 4:return d.fn.call(d.context,t,r,s),!0;case 5:return d.fn.call(d.context,t,r,s,a),!0;case 6:return d.fn.call(d.context,t,r,s,a,n),!0}for(h=1,o=Array(c-1);h<c;h++)o[h-1]=arguments[h];d.fn.apply(d.context,o)}else{var f,g=d.length;for(h=0;h<g;h++)switch(d[h].once&&this.removeListener(e,d[h].fn,void 0,!0),c){case 1:d[h].fn.call(d[h].context);break;case 2:d[h].fn.call(d[h].context,t);break;case 3:d[h].fn.call(d[h].context,t,r);break;case 4:d[h].fn.call(d[h].context,t,r,s);break;default:if(!o)for(f=1,o=Array(c-1);f<c;f++)o[f-1]=arguments[f];d[h].fn.apply(d[h].context,o)}}return!0},l.prototype.on=function(e,t,i){return a(this,e,t,i,!1)},l.prototype.once=function(e,t,i){return a(this,e,t,i,!0)},l.prototype.removeListener=function(e,t,r,s){var a=i?i+e:e;if(!this._events[a])return this;if(!t)return n(this,a),this;var l=this._events[a];if(l.fn)l.fn!==t||s&&!l.once||r&&l.context!==r||n(this,a);else{for(var o=0,h=[],d=l.length;o<d;o++)(l[o].fn!==t||s&&!l[o].once||r&&l[o].context!==r)&&h.push(l[o]);h.length?this._events[a]=1===h.length?h[0]:h:n(this,a)}return this},l.prototype.removeAllListeners=function(e){var t;return e?(t=i?i+e:e,this._events[t]&&n(this,t)):(this._events=new r,this._eventsCount=0),this},l.prototype.off=l.prototype.removeListener,l.prototype.addListener=l.prototype.on,l.prefixed=i,l.EventEmitter=l,e.exports=l}(rf)),(r=rf.exports)&&r.__esModule&&Object.prototype.hasOwnProperty.call(r,"default"))?r.default:r;let rm="1.6.16",rp={};function ry(e,t){return t+10<=e.length&&51===e[t]&&68===e[t+1]&&73===e[t+2]&&e[t+3]<255&&e[t+4]<255&&e[t+6]<128&&e[t+7]<128&&e[t+8]<128&&e[t+9]<128}function rv(e,t){return t+10<=e.length&&73===e[t]&&68===e[t+1]&&51===e[t+2]&&e[t+3]<255&&e[t+4]<255&&e[t+6]<128&&e[t+7]<128&&e[t+8]<128&&e[t+9]<128}function rE(e,t){return(127&e[t])<<21|(127&e[t+1])<<14|(127&e[t+2])<<7|127&e[t+3]}function rT(e,t){let i=t,r=0;for(;rv(e,t);)r+=10,r+=rE(e,t+6),ry(e,t+10)&&(r+=10),t+=r;if(r>0)return e.subarray(i,i+r)}function rS(e,t){return 255===e[t]&&(246&e[t+1])==240}function rL(e,t){return 1&e[t+1]?7:9}function rA(e,t){return(3&e[t+3])<<11|e[t+4]<<3|(224&e[t+5])>>>5}function rR(e,t){return t+1<e.length&&rS(e,t)}function rb(e,t,i,r,s){if(!e.samplerate){let a=function(e,t,i,r){let s=t[i+2],a=s>>2&15;if(a>12){let t=Error(`invalid ADTS sampling index:${a}`);e.emit(K.ERROR,K.ERROR,{type:N.MEDIA_ERROR,details:G.FRAG_PARSING_ERROR,fatal:!0,error:t,reason:t.message});return}let n=(s>>6&3)+1,l=t[i+3]>>6&3|(1&s)<<2,o="mp4a.40."+n,h=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350][a],d=a;(5===n||29===n)&&(d-=3);let c=[n<<3|(14&d)>>1,(1&d)<<7|l<<3];return en.log(`manifest codec:${r}, parsed codec:${o}, channels:${l}, rate:${h} (ADTS object type:${n} sampling index:${a})`),{config:c,samplerate:h,channelCount:l,codec:o,parsedCodec:o,manifestCodec:r}}(t,i,r,s);a&&Z(e,a)}}function rk(e,t,i,r,s){let a,n=r+s*(9216e4/e.samplerate),l=function(e,t){let i=rL(e,t);if(t+i<=e.length){let r=rA(e,t)-i;if(r>0)return{headerLength:i,frameLength:r}}}(t,i);if(l){let{frameLength:r,headerLength:s}=l,o=s+r,h=Math.max(0,i+o-t.length);h?(a=new Uint8Array(o-s)).set(t.subarray(i+s,t.length),0):a=t.subarray(i+s,i+o);let d={unit:a,pts:n};return h||e.samples.push(d),{sample:d,length:o,missing:h}}let o=t.length-i;return(a=new Uint8Array(o)).set(t.subarray(i,t.length),0),{sample:{unit:a,pts:n},length:o,missing:-1}}function rI(e,t=0,i=1/0){var r,s,a,n,l,o;let h,d,c,f,g,m;return r=e,s=t,a=i,n=Uint8Array,h=(l=r)instanceof ArrayBuffer?l:l.buffer,d=1,"BYTES_PER_ELEMENT"in n&&(d=n.BYTES_PER_ELEMENT),f=((c=(o=r)&&o.buffer instanceof ArrayBuffer&&void 0!==o.byteLength&&void 0!==o.byteOffset?r.byteOffset:0)+r.byteLength)/d,m=Math.floor(Math.min((g=Math.floor(Math.max(0,Math.min((c+s)/d,f))))+Math.max(a,0),f)),new n(h,g,m-g)}
49function rD(e){let t=0,i=[];for(;rv(e,t);){let r=rE(e,t+6);e[t+5]>>6&1&&(t+=10);let s=(t+=10)+r;for(;t+10<s;){let r=function(e){let t=String.fromCharCode(e[0],e[1],e[2],e[3]),i=rE(e,4);return{type:t,size:i,data:e.subarray(10,10+i)}}(e.subarray(t)),s="PRIV"===r.type?function(e){if(e.size<2)return;let t=eh(e.data,!0),i=new Uint8Array(e.data.subarray(t.length+1));return{key:e.type,info:t,data:i.buffer}}(r):"W"===r.type[0]?function(e){if("WXXX"===e.type){if(e.size<2)return;let t=1,i=eh(e.data.subarray(t),!0);t+=i.length+1;let r=eh(e.data.subarray(t));return{key:e.type,info:i,data:r}}let t=eh(e.data);return{key:e.type,info:"",data:t}}(r):"APIC"===r.type?function(e){var t;let i,r={key:e.type,description:"",data:"",mimeType:null,pictureType:null};if(e.size<2)return;if(3!==e.data[0])return void console.log("Ignore frame with unrecognized character encoding");let s=e.data.subarray(1).indexOf(0);if(-1===s)return;let a=eh(rI(e.data,1,s)),n=e.data[2+s],l=e.data.subarray(3+s).indexOf(0);if(-1===l)return;let o=eh(rI(e.data,3+s,l));return i="-->"===a?eh(rI(e.data,4+s+l)):(t=e.data.subarray(4+s+l))instanceof ArrayBuffer?t:0==t.byteOffset&&t.byteLength==t.buffer.byteLength?t.buffer:new Uint8Array(t).buffer,r.mimeType=a,r.pictureType=n,r.description=o,r.data=i,r}(r):function(e){if(e.size<2)return;if("TXXX"===e.type){let t=1,i=eh(e.data.subarray(t),!0);t+=i.length+1;let r=eh(e.data.subarray(t));return{key:e.type,info:i,data:r}}let t=eh(e.data.subarray(1));return{key:e.type,info:"",data:t}}(r);s&&i.push(s),t+=r.size+10}ry(e,t)&&(t+=10)}return i}function r_(e){return e&&"PRIV"===e.key&&"com.apple.streaming.transportStreamTimestamp"===e.info}function rP(e){let t=rD(e);for(let e=0;e<t.length;e++){let i=t[e];if(r_(i))return function(e){if(8===e.data.byteLength){let t=new Uint8Array(e.data),i=1&t[3],r=(t[4]<<23)+(t[5]<<15)+(t[6]<<7)+t[7];return r/=45,i&&(r+=47721858.84),Math.round(r)}}(i)}}let rC=((s={}).audioId3="org.id3",s.dateRange="com.apple.quicktime.HLS",s.emsg="https://aomedia.org/emsg/ID3",s.misbklv="urn:misb:KLV:bin:1910.1",s);function rw(e="",t=9e4){return{type:e,id:-1,pid:-1,inputTimeScale:t,sequenceNumber:-1,samples:[],dropped:0}}class rx{constructor(){this._audioTrack=void 0,this._id3Track=void 0,this.frameIndex=0,this.cachedData=null,this.basePTS=null,this.initPTS=null,this.lastPTS=null}resetInitSegment(e,t,i,r){this._id3Track={type:"id3",id:3,pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0}}resetTimeStamp(e){this.initPTS=e,this.resetContiguity()}resetContiguity(){this.basePTS=null,this.lastPTS=null,this.frameIndex=0}canParse(e,t){return!1}appendFrame(e,t,i){}demux(e,t){this.cachedData&&(e=eW(this.cachedData,e),this.cachedData=null);let i=rT(e,0),r=i?i.length:0,s,a=this._audioTrack,n=this._id3Track,l=i?rP(i):void 0,o=e.length;for((null===this.basePTS||0===this.frameIndex&&$(l))&&(this.basePTS=rM(l,t,this.initPTS),this.lastPTS=this.basePTS),null===this.lastPTS&&(this.lastPTS=this.basePTS),i&&i.length>0&&n.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:i,type:rC.audioId3,duration:1/0});r<o;){if(this.canParse(e,r)){let t=this.appendFrame(a,e,r);t?(this.frameIndex++,this.lastPTS=t.sample.pts,r+=t.length,s=r):r=o}else{var h,d;rv(h=e,d=r)&&rE(h,d+6)+10<=h.length-d?(i=rT(e,r),n.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:i,type:rC.audioId3,duration:1/0}),r+=i.length,s=r):r++}if(r===o&&s!==o){let t=e.slice(s);this.cachedData?this.cachedData=eW(this.cachedData,t):this.cachedData=t}}return{audioTrack:a,videoTrack:rw(),id3Track:n,textTrack:rw()}}demuxSampleAes(e,t,i){return Promise.reject(Error(`[${this}] This demuxer does not support Sample-AES decryption`))}flush(e){let t=this.cachedData;return t&&(this.cachedData=null,this.demux(t,0)),{audioTrack:this._audioTrack,videoTrack:rw(),id3Track:this._id3Track,textTrack:rw()}}destroy(){this.cachedData=null,this._audioTrack=this._id3Track=void 0}}let rM=(e,t,i)=>$(e)?90*e:9e4*t+(i?9e4*i.baseTime/i.timescale:0),rO=null,rF=[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],r$=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],rB=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],rU=[0,1,1,4];function rN(e,t,i,r,s){if(i+24>t.length)return;let a=rG(t,i);if(a&&i+a.frameLength<=t.length){let n=r+s*(9e4*a.samplesPerFrame/a.sampleRate),l={unit:t.subarray(i,i+a.frameLength),pts:n,dts:n};return e.config=[],e.channelCount=a.channelCount,e.samplerate=a.sampleRate,e.samples.push(l),{sample:l,length:a.frameLength,missing:0}}}function rG(e,t){let i=e[t+1]>>3&3,r=e[t+1]>>1&3,s=e[t+2]>>4&15,a=e[t+2]>>2&3;if(1!==i&&0!==s&&15!==s&&3!==a){let n=e[t+2]>>1&1,l=e[t+3]>>6,o=1e3*rF[14*(3===i?3-r:3===r?3:4)+s-1],h=r$[(3===i?0:2===i?1:2)*3+a],d=rB[i][r],c=rU[r],f=Math.floor(d*o/h+n)*c;if(null===rO){let e=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);rO=e?parseInt(e[1]):0}return rO&&rO<=87&&2===r&&o>=224e3&&0===l&&(e[t+3]=128|e[t+3]),{sampleRate:h,channelCount:3===l?1:2,frameLength:f,samplesPerFrame:8*d*c}}}
49function rK(e,t){return 255===e[t]&&(224&e[t+1])==224&&(6&e[t+1])!=0}function rH(e,t){return t+1<e.length&&rK(e,t)}function rV(e,t){if(t+1<e.length&&rK(e,t)){let i=rG(e,t),r=4;null!=i&&i.frameLength&&(r=i.frameLength);let s=t+r;return s===e.length||rH(e,s)}return!1}let rj=(e,t)=>{let i=0,r=5;t+=5;let s=new Uint32Array(1),a=new Uint32Array(1),n=new Uint8Array(1);for(;r>0;){n[0]=e[t];let l=Math.min(r,8),o=8-l;a[0]=0xff000000>>>24+o<<o,s[0]=(n[0]&a[0])>>o,i=i?i<<l|s[0]:s[0],t+=1,r-=l}return i};function rW(e,t,i,r,s){if(i+8>t.length||11!==t[i]||119!==t[i+1])return -1;let a=t[i+4]>>6;if(a>=3)return -1;let n=[48e3,44100,32e3][a],l=63&t[i+4],o=2*[64,69,96,64,70,96,80,87,120,80,88,120,96,104,144,96,105,144,112,121,168,112,122,168,128,139,192,128,140,192,160,174,240,160,175,240,192,208,288,192,209,288,224,243,336,224,244,336,256,278,384,256,279,384,320,348,480,320,349,480,384,417,576,384,418,576,448,487,672,448,488,672,512,557,768,512,558,768,640,696,960,640,697,960,768,835,1152,768,836,1152,896,975,1344,896,976,1344,1024,1114,1536,1024,1115,1536,1152,1253,1728,1152,1254,1728,1280,1393,1920,1280,1394,1920][3*l+a];if(i+o>t.length)return -1;let h=t[i+6]>>5,d=0;2===h?d+=2:(1&h&&1!==h&&(d+=2),4&h&&(d+=2));let c=(t[i+6]<<8|t[i+7])>>12-d&1,f=[2,1,2,3,3,4,4,5][h]+c,g=t[i+5]>>3,m=7&t[i+5],p=new Uint8Array([a<<6|g<<1|m>>2,(3&m)<<6|h<<3|c<<2|l>>4,l<<4&224]),y=t.subarray(i,i+o);return e.config=p,e.channelCount=f,e.samplerate=n,e.samples.push({unit:y,pts:r+1536/n*9e4*s}),o}let rq=/\/emsg[-/]ID3/i;function rY(e,t){return $(e.presentationTime)?e.presentationTime/e.timeScale:t+e.presentationTimeDelta/e.timeScale}class rX{constructor(e,t,i){this.keyData=void 0,this.decrypter=void 0,this.keyData=i,this.decrypter=new tV(t,{removePKCS7Padding:!1})}decryptBuffer(e){return this.decrypter.decrypt(e,this.keyData.key.buffer,this.keyData.iv.buffer,0)}decryptAacSample(e,t,i){let r=e[t].unit;if(r.length<=16)return;let s=r.subarray(16,r.length-r.length%16),a=s.buffer.slice(s.byteOffset,s.byteOffset+s.length);this.decryptBuffer(a).then(s=>{let a=new Uint8Array(s);r.set(a,16),this.decrypter.isSync()||this.decryptAacSamples(e,t+1,i)}).catch(i)}decryptAacSamples(e,t,i){for(;;t++){if(t>=e.length)return void i();if(!(e[t].unit.length<32)&&(this.decryptAacSample(e,t,i),!this.decrypter.isSync()))return}}getAvcEncryptedData(e){let t=new Int8Array(16*Math.floor((e.length-48)/160)+16),i=0;for(let r=32;r<e.length-16;r+=160,i+=16)t.set(e.subarray(r,r+16),i);return t}getAvcDecryptedUnit(e,t){let i=new Uint8Array(t),r=0;for(let t=32;t<e.length-16;t+=160,r+=16)e.set(i.subarray(r,r+16),t);return e}decryptAvcSample(e,t,i,r,s){let a=ez(s.data),n=this.getAvcEncryptedData(a);this.decryptBuffer(n.buffer).then(n=>{s.data=this.getAvcDecryptedUnit(a,n),this.decrypter.isSync()||this.decryptAvcSamples(e,t,i+1,r)}).catch(r)}decryptAvcSamples(e,t,i,r){if(e instanceof Uint8Array)throw Error("Cannot decrypt samples of type Uint8Array");for(;;t++,i=0){if(t>=e.length)return void r();let s=e[t].units;for(;!(i>=s.length);i++){let a=s[i];if(!(a.data.length<=48||1!==a.type&&5!==a.type)&&(this.decryptAvcSample(e,t,i,r,a),!this.decrypter.isSync()))return}}}}class rz{constructor(){this.VideoSample=null}createVideoSample(e,t,i){return{key:e,frame:!1,pts:t,dts:i,units:[],length:0}}getLastNalUnit(e){var t;let i=this.VideoSample,r;if(i&&0!==i.units.length||(i=e[e.length-1]),null!=(t=i)&&t.units){let e=i.units;r=e[e.length-1]}return r}pushAccessUnit(e,t){if(e.units.length&&e.frame){if(void 0===e.pts){let i=t.samples,r=i.length;if(!r)return void t.dropped++;{let t=i[r-1];e.pts=t.pts,e.dts=t.dts}}t.samples.push(e)}}parseNALu(e,t,i){let r=t.byteLength,s=e.naluState||0,a=s,n=[],l=0,o,h,d,c=-1,f=0;for(-1===s&&(c=0,f=this.getNALuType(t,0),s=0,l=1);l<r;){if(o=t[l++],!s){s=+!o;continue}if(1===s){s=2*!o;continue}if(o)if(1===o){if(h=l-s-1,c>=0){let e={data:t.subarray(c,h),type:f};n.push(e)}else{let i=this.getLastNalUnit(e.samples);i&&(a&&l<=4-a&&i.state&&(i.data=i.data.subarray(0,i.data.byteLength-a)),h>0&&(i.data=eW(i.data,t.subarray(0,h)),i.state=0))}l<r?(d=this.getNALuType(t,l),c=l,f=d,s=0):s=-1}else s=0;else s=3}if(c>=0&&s>=0){let e={data:t.subarray(c,r),type:f,state:s};n.push(e)}if(0===n.length){let i=this.getLastNalUnit(e.samples);i&&(i.data=eW(i.data,t))}return e.naluState=s,n}}class rQ{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(){let e=this.data,t=this.bytesAvailable,i=e.byteLength-t,r=new Uint8Array(4),s=Math.min(4,t);if(0===s)throw Error("no bytes available");r.set(e.subarray(i,i+s)),this.word=new DataView(r.buffer).getUint32(0),this.bitsAvailable=8*s,this.bytesAvailable-=s}skipBits(e){let t;e=Math.min(e,8*this.bytesAvailable+this.bitsAvailable),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),i=this.word>>>32-t;if(e>32&&en.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 Error("no bits available");return(t=e-t)>0&&this.bitsAvailable?i<<t|this.readBits(t):i}skipLZ(){let e;for(e=0;e<this.bitsAvailable;++e)if((this.word&0x80000000>>>e)!=0)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(){let e=this.skipLZ();return this.readBits(e+1)-1}readEG(){let e=this.readUEG();return 1&e?1+e>>>1:-1*(e>>>1)}readBoolean(){return 1===this.readBits(1)}readUByte(){return this.readBits(8)}readUShort(){return this.readBits(16)}readUInt(){return this.readBits(32)}}class rZ extends rz{parsePES(e,t,i,r){let s=this.parseNALu(e,i.data,r),a=this.VideoSample,n,l=!1;i.data=null,a&&s.length&&!e.audFound&&(this.pushAccessUnit(a,e),a=this.VideoSample=this.createVideoSample(!1,i.pts,i.dts)),s.forEac
49h(r=>{var s,o,h,d,c;switch(r.type){case 1:{let t=!1;n=!0;let s=r.data;if(l&&s.length>4){let e=this.readSliceType(s);(2===e||4===e||7===e||9===e)&&(t=!0)}t&&null!=(h=a)&&h.frame&&!a.key&&(this.pushAccessUnit(a,e),a=this.VideoSample=null),a||(a=this.VideoSample=this.createVideoSample(!0,i.pts,i.dts)),a.frame=!0,a.key=t;break}case 5:n=!0,null!=(s=a)&&s.frame&&!a.key&&(this.pushAccessUnit(a,e),a=this.VideoSample=null),a||(a=this.VideoSample=this.createVideoSample(!0,i.pts,i.dts)),a.key=!0,a.frame=!0;break;case 6:n=!0,eX(r.data,1,i.pts,t.samples);break;case 7:{n=!0,l=!0;let t=r.data,i=this.readSPS(t);if(!e.sps||e.width!==i.width||e.height!==i.height||(null==(d=e.pixelRatio)?void 0:d[0])!==i.pixelRatio[0]||(null==(c=e.pixelRatio)?void 0:c[1])!==i.pixelRatio[1]){e.width=i.width,e.height=i.height,e.pixelRatio=i.pixelRatio,e.sps=[t];let r=t.subarray(1,4),s="avc1.";for(let e=0;e<3;e++){let t=r[e].toString(16);t.length<2&&(t="0"+t),s+=t}e.codec=s}break}case 8:n=!0,e.pps=[r.data];break;case 9:n=!0,e.audFound=!0,null!=(o=a)&&o.frame&&(this.pushAccessUnit(a,e),a=null),a||(a=this.VideoSample=this.createVideoSample(!1,i.pts,i.dts));break;case 12:n=!0;break;default:n=!1}a&&n&&a.units.push(r)}),r&&a&&(this.pushAccessUnit(a,e),this.VideoSample=null)}getNALuType(e,t){return 31&e[t]}readSliceType(e){let t=new rQ(e);return t.readUByte(),t.readUEG(),t.readUEG()}skipScalingList(e,t){let i=8,r=8;for(let s=0;s<e;s++)0!==r&&(r=(i+t.readEG()+256)%256),i=0===r?i:r}readSPS(e){let t=new rQ(e),i=0,r=0,s=0,a=0,n,l,o,h=t.readUByte.bind(t),d=t.readBits.bind(t),c=t.readUEG.bind(t),f=t.readBoolean.bind(t),g=t.skipBits.bind(t),m=t.skipEG.bind(t),p=t.skipUEG.bind(t),y=this.skipScalingList.bind(this);h();let v=h();if(d(5),g(3),h(),p(),100===v||110===v||122===v||244===v||44===v||83===v||86===v||118===v||128===v){let e=c();if(3===e&&g(1),p(),p(),g(1),f())for(l=3!==e?8:12,o=0;o<l;o++)f()&&y(o<6?16:64,t)}p();let E=c();if(0===E)c();else if(1===E)for(g(1),m(),m(),n=c(),o=0;o<n;o++)m();p(),g(1);let T=c(),S=c(),L=d(1);0===L&&g(1),g(1),f()&&(i=c(),r=c(),s=c(),a=c());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()]}return{width:Math.ceil((T+1)*16-2*i-2*r),height:(2-L)*(S+1)*16-(L?2:4)*(s+a),pixelRatio:A}}}class rJ extends rz{constructor(...e){super(...e),this.initVPS=null}parsePES(e,t,i,r){let s=this.parseNALu(e,i.data,r),a=this.VideoSample,n,l=!1;i.data=null,a&&s.length&&!e.audFound&&(this.pushAccessUnit(a,e),a=this.VideoSample=this.createVideoSample(!1,i.pts,i.dts)),s.forEach(r=>{var s,o,h;switch(r.type){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:case 8:case 9:a||(a=this.VideoSample=this.createVideoSample(!1,i.pts,i.dts)),a.frame=!0,n=!0;break;case 16:case 17:case 18:case 21:n=!0,l&&null!=(h=a)&&h.frame&&!a.key&&(this.pushAccessUnit(a,e),a=this.VideoSample=null),a||(a=this.VideoSample=this.createVideoSample(!0,i.pts,i.dts)),a.key=!0,a.frame=!0;break;case 19:case 20:n=!0,null!=(s=a)&&s.frame&&!a.key&&(this.pushAccessUnit(a,e),a=this.VideoSample=null),a||(a=this.VideoSample=this.createVideoSample(!0,i.pts,i.dts)),a.key=!0,a.frame=!0;break;case 39:n=!0,eX(r.data,2,i.pts,t.samples);break;case 32:n=!0,e.vps||("object"!=typeof e.params&&(e.params={}),e.params=Z(e.params,this.readVPS(r.data)),this.initVPS=r.data),e.vps=[r.data];break;case 33:if(n=!0,l=!0,void 0===e.vps||e.vps[0]===this.initVPS||void 0===e.sps||this.matchSPS(e.sps[0],r.data)||(this.initVPS=e.vps[0],e.sps=e.pps=void 0),!e.sps){let t=this.readSPS(r.data);for(let i in e.width=t.width,e.height=t.height,e.pixelRatio=t.pixelRatio,e.codec=t.codecString,e.sps=[],"object"!=typeof e.params&&(e.params={}),t.params)e.params[i]=t.params[i]}this.pushParameterSet(e.sps,r.data,e.vps),a||(a=this.VideoSample=this.createVideoSample(!0,i.pts,i.dts)),a.key=!0;break;case 34:if(n=!0,"object"==typeof e.params){if(!e.pps){e.pps=[];let t=this.readPPS(r.data);for(let i in t)e.params[i]=t[i]}this.pushParameterSet(e.pps,r.data,e.vps)}break;case 35:n=!0,e.audFound=!0,null!=(o=a)&&o.frame&&(this.pushAccessUnit(a,e),a=null),a||(a=this.VideoSample=this.createVideoSample(!1,i.pts,i.dts));break;default:n=!1}a&&n&&a.units.push(r)}),r&&a&&(this.pushAccessUnit(a,e),this.VideoSample=null)}pushParameterSet(e,t,i){(!i||i[0]!==this.initVPS)&&(i||e.length)||e.push(t)}getNALuType(e,t){return(126&e[t])>>>1}ebsp2rbsp(e){let t=new Uint8Array(e.byteLength),i=0;for(let r=0;r<e.byteLength;r++)r>=2&&3===e[r]&&0===e[r-1]&&0===e[r-2]||(t[i]=e[r],i++);return new Uint8Array(t.buffer,0,i)}pushAccessUnit(e,t){super.pushAccessUnit(e,t),this.initVPS&&(this.initVPS=null)}readVPS(e){let t=new rQ(e);return t.readUByte(),t.readUByte(),t.readBits(4),t.skipBits(2),t.readBits(6),{numTemporalLayers:t.readBits(3)+1,temporalIdNested:t.readBoolean()}}readSPS(e){let t=new rQ(this.ebsp2rbsp(e));t.readUByte(),t.readUByte(),t.readBits(4);let i=t.readBits(3);t.readBoolean();let r=t.readBits(2),s=t.readBoolean(),a=t.readBits(5),n=t.readUByte(),l=t.readUByte(),o=t.readUByte(),h=t.readUByte(),d=t.readUByte(),c=t.readUByte(),f=t.readUByte(),g=t.readUByte(),m=t.readUByte(),p=t.readUByte(),y=t.readUByte(),v=[],E=[];for(let e=0;e<i;e++)v.push(t.readBoolean()),E.push(t.readBoolean());if(i>0)for(let e=i;e<8;e++)t.readBits(2);for(let e=0;e<i;e++)v[e]&&(t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte()),E[e]&&t.readUByte();t.readUEG();let T=t.readUEG();3==T&&t.skipBits(1);let S=t.readUEG(),L=t.readUEG(),A=t.readBoolean(),R=0,b=0,k=0,I=0;A&&(R+=t.readUEG(),b+=t.readUEG(),k+=t.readUEG(),I+=t.readUEG());let D=t.readUEG(),_=t.readUEG(),P=t.readUEG(),C=t.readBoolean();for(let e=C?0:i;e<=i;e++)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 e=0;e<4;e++)for(let i=0;i<(3===e?2:6);i++)if(t.readBoolean()){let i=Math.min(64,1<<4+(e<<1));e>1&&t.readEG();for(let e=0;e<i;e++)t.readEG()}else t.readUEG();t.readBoolean(),t.readBoolean(),t.readBoolean()&&(t.readUByte(),t.skipUEG(),t.skipUEG(),t.readBoolean());let w=t.readUEG(),x=0;for(let e=0;e<w;e++){let i=!1;if(0!==e&&(i=t.readBoolean()),i){e===w&&t.readUEG(),t.readBoolean(),t.readUEG();let i=0;for(let e=0;e<=x;e++){let e=t.readBoolean(),r=!1;e||(r=t.readBoolean()),(e||r)&&i++}x=i}else{let e=t.readUEG(),i=t.readUEG();x=e+i;for(let i=0;i<e;i++)t.readUEG(),t.readBoolean();for(let e=0;e<i;e++)t.readUEG(),t.readBoolean()}}if(t.readBoolean()){let e=t.readUEG();for(let i=0;i<e;i++){for(let e=0;e<P+4;e++)t.readBits(1);t.readBits(1)}}let M=0,O=1,F=1,$=!0,B=1,U=0;t.readBoolean(),t.readBoolean();if(t.readBoolean()){if(t.readBoolean()){let e=t.readUByte();e>0&&e<16?(O=[1,12,10,16,40,24,20,32,80,18,15,64,160,4,3,2][e-1],F=[1,11,11,11,33,11,11,11,33,11,11,33,99,3,2,1][e-1]):255===e&&(O=t.readBits(16),F=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(),t.readBoolean()&&(t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG()),t.readBoolean()&&(B=t.readBits(32),U=t.readBits(32),t.readBoolean()&&t.readUEG(),t.readBoolean())){let e=t.readBoolean(),r=t.readBoolean(),s=!1;(e||r)&&((s=t.readBoolean())&&(t.readUByte(),t.readBits(5),t.readBoolean(),t.readBits(5)),t.readBits(4),t.readBits(4),s&&t.readBits(4),t.readBits(5),t.readBits(5),t.readBits(5));for(let a=0;a<=i;a++){let i=($=t.readBoolean())||t.readBoolean(),a=!1;i?t.readEG():a=t.readBoolean();let n=a?1:t.readUEG()+1;if(e)for(let e=0;e<n;e++)t.readUEG(),t.readUEG(),s&&(t.readUEG(),t.readUEG()),t.skipBits(1);if(r)for(let e=0;e<n;e++)t.readUEG(),t.readUEG(),s&&(t.readUEG(),t.readUEG()),t.skipBits(1)}}t.readBoolean()&&(t.readBoolean(),t.readBoolean(),t.readBoolean(),M=t.readUEG())}let N=S,G=L;if(A){let e=1,t=1;1===T?e=t=2:2==T&&(e=2),N=S-e*b-e*R,G=L-t*I-t*k}let K=r?["A","B","C"][r]:"",H=n<<24|l<<16|o<<8|h,V=0;for(let e=0;e<32;e++)V=(V|(H>>e&1)<<31-e)>>>0;let j=V.toString(16);return 1===a&&"2"===j&&(j="6"),{codecString:`hvc1.${K}${a}.${j}.${s?"H":"L"}${y}.B0`,params:{general_tier_flag:s,general_profile_idc:a,general_profile_space:r,general_profile_compatibility_flags:[n,l,o,h],general_constraint_indicator_flags:[d,c,f,g,m,p],general_level_idc:y,bit_depth:D+8,bit_depth_luma_minus8:D,bit_depth_chroma_minus8:_,min_spatial_segmentation_idc:M,chroma_format_idc:T,frame_rate:{fixed:$,fps:U/B}},width:N,height:G,pixelRatio:[O,F]}}readPPS(e){let t=new rQ(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);let i=t.readBoolean(),r=t.readBoolean(),s=1;return r&&i?s=0:r?s=3:i&&(s=2),{parallelismType:s}}matchSPS(e,t){return String.fromCharCode.apply(null,e).substr(3)===String.fromCharCode.apply(null,t).substr(3)}}class r0{constructor(e,t,i,r){this.logger=void 0,this.observer=void 0,this.config=void 0,this.typeSupp
49orted=void 0,this.sampleAes=null,this.pmtParsed=!1,this.audioCodec=void 0,this.videoCodec=void 0,this._pmtId=-1,this._videoTrack=void 0,this._audioTrack=void 0,this._id3Track=void 0,this._txtTrack=void 0,this.aacOverFlow=null,this.remainderData=null,this.videoParser=void 0,this.observer=e,this.config=t,this.typeSupported=i,this.logger=r,this.videoParser=null}static probe(e,t){let i=r0.syncOffset(e);return i>0&&t.warn(`MPEG2-TS detected but first sync word found @ offset ${i}`),-1!==i}static syncOffset(e){let t=e.length,i=Math.min(940,t-188)+1,r=0;for(;r<i;){let s=!1,a=-1,n=0;for(let l=r;l<t;l+=188)if(71===e[l]&&(t-l==188||71===e[l+188])){if(n++,-1===a&&0!==(a=l)&&(i=Math.min(a+18612,e.length-188)+1),s||(s=0===r1(e,l)),s&&n>1&&(0===a&&n>2||l+188>i))return a}else{if(n)return -1;break}r++}return -1}static createTrack(e,t){return{container:"video"===e||"audio"===e?"video/mp2t":void 0,type:e,id:ew[e],pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0,duration:"audio"===e?t:void 0}}resetInitSegment(e,t,i,r){this.pmtParsed=!1,this._pmtId=-1,this._videoTrack=r0.createTrack("video"),this._videoTrack.duration=r,this._audioTrack=r0.createTrack("audio",r),this._id3Track=r0.createTrack("id3"),this._txtTrack=r0.createTrack("text"),this._audioTrack.segmentCodec="aac",this.videoParser=null,this.aacOverFlow=null,this.remainderData=null,this.audioCodec=t,this.videoCodec=i}resetTimeStamp(){}resetContiguity(){let{_audioTrack:e,_videoTrack:t,_id3Track:i}=this;e&&(e.pesData=null),t&&(t.pesData=null),i&&(i.pesData=null),this.aacOverFlow=null,this.remainderData=null}demux(e,t,i=!1,r=!1){let s;i||(this.sampleAes=null);let a=this._videoTrack,n=this._audioTrack,l=this._id3Track,o=this._txtTrack,h=a.pid,d=a.pesData,c=n.pid,f=l.pid,g=n.pesData,m=l.pesData,p=null,y=this.pmtParsed,v=this._pmtId,E=e.length;if(this.remainderData&&(E=(e=eW(this.remainderData,e)).length,this.remainderData=null),E<188&&!r)return this.remainderData=e,{audioTrack:n,videoTrack:a,id3Track:l,textTrack:o};let T=Math.max(0,r0.syncOffset(e));(E-=(E-T)%188)<e.byteLength&&!r&&(this.remainderData=new Uint8Array(e.buffer,E,e.buffer.byteLength-E));let S=0;for(let t=T;t<E;t+=188)if(71===e[t]){let r,E=!!(64&e[t+1]),S=r1(e,t);if((48&e[t+3])>>4>1){if((r=t+5+e[t+4])===t+188)continue}else r=t+4;switch(S){case h:E&&(d&&(s=r4(d,this.logger))&&(this.readyVideoParser(a.segmentCodec),null!==this.videoParser&&this.videoParser.parsePES(a,o,s,!1)),d={data:[],size:0}),d&&(d.data.push(e.subarray(r,t+188)),d.size+=t+188-r);break;case c:if(E){if(g&&(s=r4(g,this.logger)))switch(n.segmentCodec){case"aac":this.parseAACPES(n,s);break;case"mp3":this.parseMPEGPES(n,s);break;case"ac3":this.parseAC3PES(n,s)}g={data:[],size:0}}g&&(g.data.push(e.subarray(r,t+188)),g.size+=t+188-r);break;case f:E&&(m&&(s=r4(m,this.logger))&&this.parseID3PES(l,s),m={data:[],size:0}),m&&(m.data.push(e.subarray(r,t+188)),m.size+=t+188-r);break;case 0:var L,A;E&&(r+=e[r]+1),v=this._pmtId=(31&(L=e)[(A=r)+10])<<8|L[A+11];break;case v:{E&&(r+=e[r]+1);let s=function(e,t,i,r,s,a){let n={audioPid:-1,videoPid:-1,id3Pid:-1,segmentVideoCodec:"avc",segmentAudioCodec:"aac"},l=(15&e[t+1])<<8|e[t+2],o=t+3+l-4,h=(15&e[t+10])<<8|e[t+11];for(t+=12+h;t<o;){let l=r1(e,t),o=(15&e[t+3])<<8|e[t+4];switch(e[t]){case 207:if(!r){r3("ADTS AAC",a);break}case 15:-1===n.audioPid&&(n.audioPid=l);break;case 21:-1===n.id3Pid&&(n.id3Pid=l);break;case 219:if(!r){r3("H.264",a);break}case 27:-1===n.videoPid&&(n.videoPid=l);break;case 3:case 4:i.mpeg||i.mp3?-1===n.audioPid&&(n.audioPid=l,n.segmentAudioCodec="mp3"):a.log("MPEG audio found, not supported in this browser");break;case 193:if(!r){r3("AC-3",a);break}case 129:i.ac3?-1===n.audioPid&&(n.audioPid=l,n.segmentAudioCodec="ac3"):a.log("AC-3 audio found, not supported in this browser");break;case 6:if(-1===n.audioPid&&o>0){let r=t+5,s=o;for(;s>2;){106===e[r]&&(!0!==i.ac3?a.log("AC-3 audio found, not supported in this browser for now"):(n.audioPid=l,n.segmentAudioCodec="ac3"));let t=e[r+1]+2;r+=t,s-=t}}break;case 194:case 135:return r2(s,Error("Unsupported EC-3 in M2TS found"),void 0,a),n;case 36:-1===n.videoPid&&(n.videoPid=l,n.segmentVideoCodec="hevc",a.log("HEVC in M2TS found"))}t+=o+5}return n}
49(e,r,this.typeSupported,i,this.observer,this.logger);(h=s.videoPid)>0&&(a.pid=h,a.segmentCodec=s.segmentVideoCodec),(c=s.audioPid)>0&&(n.pid=c,n.segmentCodec=s.segmentAudioCodec),(f=s.id3Pid)>0&&(l.pid=f),null===p||y||(this.logger.warn(`MPEG-TS PMT found at ${t} after unknown PID '${p}'. Backtracking to sync byte @${T} to parse all TS packets.`),p=null,t=T-188),y=this.pmtParsed=!0;break}case 17:case 8191:break;default:p=S}}else S++;S>0&&r2(this.observer,Error(`Found ${S} TS packet/s that do not start with 0x47`),void 0,this.logger),a.pesData=d,n.pesData=g,l.pesData=m;let R={audioTrack:n,videoTrack:a,id3Track:l,textTrack:o};return r&&this.extractRemainingSamples(R),R}flush(){let e,{remainderData:t}=this;return this.remainderData=null,e=t?this.demux(t,-1,!1,!0):{videoTrack:this._videoTrack,audioTrack:this._audioTrack,id3Track:this._id3Track,textTrack:this._txtTrack},this.extractRemainingSamples(e),this.sampleAes?this.decrypt(e,this.sampleAes):e}extractRemainingSamples(e){let t,{audioTrack:i,videoTrack:r,id3Track:s,textTrack:a}=e,n=r.pesData,l=i.pesData,o=s.pesData;if(n&&(t=r4(n,this.logger))?(this.readyVideoParser(r.segmentCodec),null!==this.videoParser&&(this.videoParser.parsePES(r,a,t,!0),r.pesData=null)):r.pesData=n,l&&(t=r4(l,this.logger))){switch(i.segmentCodec){case"aac":this.parseAACPES(i,t);break;case"mp3":this.parseMPEGPES(i,t);break;case"ac3":this.parseAC3PES(i,t)}i.pesData=null}else null!=l&&l.size&&this.logger.log("last AAC PES packet truncated,might overlap between fragments"),i.pesData=l;o&&(t=r4(o,this.logger))?(this.parseID3PES(s,t),s.pesData=null):s.pesData=o}demuxSampleAes(e,t,i){let r=this.demux(e,i,!0,!this.config.progressive),s=this.sampleAes=new rX(this.observer,this.config,t);return this.decrypt(r,s)}readyVideoParser(e){null===this.videoParser&&("avc"===e?this.videoParser=new rZ:"hevc"===e&&(this.videoParser=new rJ))}decrypt(e,t){return new Promise(i=>{let{audioTrack:r,videoTrack:s}=e;r.samples&&"aac"===r.segmentCodec?t.decryptAacSamples(r.samples,0,()=>{s.samples?t.decryptAvcSamples(s.samples,0,0,()=>{i(e)}):i(e)}):s.samples&&t.decryptAvcSamples(s.samples,0,0,()=>{i(e)})})}destroy(){this.observer&&this.observer.removeAllListeners(),this.config=this.logger=this.observer=null,this.aacOverFlow=this.videoParser=this.remainderData=this.sampleAes=null,this._videoTrack=this._audioTrack=this._id3Track=this._txtTrack=void 0}parseAACPES(e,t){let i,r,s,a=0,n=this.aacOverFlow,l=t.data;if(n){this.aacOverFlow=null;let t=n.missing,i=n.sample.unit.byteLength;-1===t?l=eW(n.sample.unit,l):(n.sample.unit.set(l.subarray(0,t),i-t),e.samples.push(n.sample),a=n.missing)}for(i=a,r=l.length;i<r-1&&!rR(l,i);i++);if(i!==a){let e,t=i<r-1;if(e=t?`AAC PES did not start with ADTS header,offset:${i}`:"No ADTS header found in AAC PES",r2(this.observer,Error(e),t,this.logger),!t)return}if(rb(e,this.observer,l,i,this.audioCodec),void 0!==t.pts)s=t.pts;else{if(!n)return void this.logger.warn("[tsdemuxer]: AAC PES unknown PTS");let t=9216e4/e.samplerate;s=n.sample.pts+t}let o=0,h;for(;i<r;)if(h=rk(e,l,i,s,o),i+=h.length,h.missing){this.aacOverFlow=h;break}else for(o++;i<r-1&&!rR(l,i);i++);}parseMPEGPES(e,t){let i=t.data,r=i.length,s=0,a=0,n=t.pts;if(void 0===n)return void this.logger.warn("[tsdemuxer]: MPEG PES unknown PTS");for(;a<r;)if(rH(i,a)){let t=rN(e,i,a,n,s);if(t)a+=t.length,s++;else break}else a++}parseAC3PES(e,t){{let i=t.data,r=t.pts;if(void 0===r)return void this.logger.warn("[tsdemuxer]: AC3 PES unknown PTS");let s=i.length,a=0,n=0,l;for(;n<s&&(l=rW(e,i,n,r,a++))>0;)n+=l}}parseID3PES(e,t){if(void 0===t.pts)return void this.logger.warn("[tsdemuxer]: ID3 PES unknown PTS");let i=Z({},t,{type:this._videoTrack?rC.emsg:rC.audioId3,duration:1/0});e.samples.push(i)}}function r1(e,t){return((31&e[t+1])<<8)+e[t+2]}function r2(e,t,i,r){r.warn(`parsing error: ${t.message}`),e.emit(K.ERROR,K.ERROR,{type:N.MEDIA_ERROR,details:G.FRAG_PARSING_ERROR,fatal:!1,levelRetry:i,error:t,reason:t.message})}function r3(e,t){t.log(`${e} with AES-128-CBC encryption found in unencrypted stream`)}function r4(e,t){let i=0,r,s,a,n,l,o=e.data;if(!e||0===e.size)return null;for(;o[0].length<19&&o.length>1;)o[0]=eW(o[0],o[1]),o.splice(1,1);if(((r=o[0])[0]<<16)+(r[1]<<8)+r[2]===1){if((s=(r[4]<<8)+r[5])&&s>e.size-6)return null;let h=r[7];192&h&&(n=(14&r[9])*0x20000000+(255&r[10])*4194304+(254&r[11])*16384+(255&r[12])*128+(254&r[13])/2,64&h?n-(l=(14&r[14])*0x20000000+(255&r[15])*4194304+(254&r[16])*16384+(255&r[17])*128+(254&r[18])/2)>60*9e4&&(t.warn(`${Math.round((n-l)/9e4)}s delta between PTS and DTS, align them`),n=l):l=n);let d=(a=r[8])+9;if(e.size<=d)return null;e.size-=d;let c=new Uint8Array(e.size);for(let e=0,t=o.length;e<t;e++){let t=(r=o[e]).byteLength;if(d)if(d>t){d-=t;continue}else r=r.subarray(d),t-=d,d=0;c.set(r,i),i+=t}return s&&(s-=a+3),{data:c,pts:n,dts:l,len:s}}return null}class r5{static getSilentFrame(e,t){if("mp4a.40.2"===e){if(1===t)return new Uint8Array([0,200,0,128,35,128]);if(2===t)return new Uint8Array([33,0,73,144,2,25,0,35,128]);if(3===t)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,142]);if(4===t)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,128,44,128,8,2,56]);if(5===t)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,56]);if(6===t)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,0,178,0,32,8,224])}else{if(1===t)return new Uint8Array([1,64,34,128,163,78,230,128,186,8,0,0,0,28,6,241,193,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);if(2===t||3===t)return new Uint8Array([1,64,34,128,163,94,230,128,186,8,0,0,0,0,149,0,6,241,161,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94])}}}class r8{static init(){let e;for(e in r8.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:[]},r8.types)r8.types.hasOwnProperty(e)&&(r8.types[e]=[e.charCodeAt(0),e.charCodeAt(1),e.charCodeAt(2),e.charCodeAt(3)]);r8.HDLR_TYPES={video:new Uint8Array([0,0,0,0,0,0,0,0,118,105,100,101,0,0,0,0,0,0,0,0,0,0,0,0,86,105,100,101,111,72,97,110,100,108,101,114,0]),audio:new Uint8Array([0,0,0,0,0,0,0,0,115,111,117,110,0,0,0,0,0,0,0,0,0,0,0,0,83,111,117,110,100,72,97,110,100,108,101,114,0])};let t=new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,12,117,114,108,32,0,0,0,1]);r8.STTS=r8.STSC=r8.STCO=new Uint8Array([0,0,0,0,0,0,0,0]),r8.STSZ=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),r8.VMHD=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0]),r8.SMHD=new Uint8Array([0,0,0,0,0,0,0,0]),r8.STSD=new Uint8Array([0,0,0,0,0,0,0,1]);
49let i=new Uint8Array([105,115,111,109]),r=new Uint8Array([97,118,99,49]),s=new Uint8Array([0,0,0,1]);r8.FTYP=r8.box(r8.types.ftyp,i,s,i,r),r8.DINF=r8.box(r8.types.dinf,r8.box(r8.types.dref,t))}static box(e,...t){let i=8,r=t.length,s=r;for(;r--;)i+=t[r].byteLength;let a=new Uint8Array(i);for(a[0]=i>>24&255,a[1]=i>>16&255,a[2]=i>>8&255,a[3]=255&i,a.set(e,4),r=0,i=8;r<s;r++)a.set(t[r],i),i+=t[r].byteLength;return a}static hdlr(e){return r8.box(r8.types.hdlr,r8.HDLR_TYPES[e])}static mdat(e){return r8.box(r8.types.mdat,e)}static mdhd(e,t){let i=Math.floor((t*=e)/0x100000000),r=Math.floor(t%0x100000000);return r8.box(r8.types.mdhd,new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,e>>24&255,e>>16&255,e>>8&255,255&e,i>>24,i>>16&255,i>>8&255,255&i,r>>24,r>>16&255,r>>8&255,255&r,85,196,0,0]))}static mdia(e){return r8.box(r8.types.mdia,r8.mdhd(e.timescale||0,e.duration||0),r8.hdlr(e.type),r8.minf(e))}static mfhd(e){return r8.box(r8.types.mfhd,new Uint8Array([0,0,0,0,e>>24,e>>16&255,e>>8&255,255&e]))}static minf(e){return"audio"===e.type?r8.box(r8.types.minf,r8.box(r8.types.smhd,r8.SMHD),r8.DINF,r8.stbl(e)):r8.box(r8.types.minf,r8.box(r8.types.vmhd,r8.VMHD),r8.DINF,r8.stbl(e))}static moof(e,t,i){return r8.box(r8.types.moof,r8.mfhd(e),r8.traf(i,t))}static moov(e){let t=e.length,i=[];for(;t--;)i[t]=r8.trak(e[t]);return r8.box.apply(null,[r8.types.moov,r8.mvhd(e[0].timescale||0,e[0].duration||0)].concat(i).concat(r8.mvex(e)))}static mvex(e){let t=e.length,i=[];for(;t--;)i[t]=r8.trex(e[t]);return r8.box.apply(null,[r8.types.mvex,...i])}static mvhd(e,t){let i=Math.floor((t*=e)/0x100000000),r=Math.floor(t%0x100000000),s=new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,e>>24&255,e>>16&255,e>>8&255,255&e,i>>24,i>>16&255,i>>8&255,255&i,r>>24,r>>16&255,r>>8&255,255&r,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,255,255,255,255]);return r8.box(r8.types.mvhd,s)}static sdtp(e){let t,i,r=e.samples||[],s=new Uint8Array(4+r.length);for(t=0;t<r.length;t++)i=r[t].flags,s[t+4]=i.dependsOn<<4|i.isDependedOn<<2|i.hasRedundancy;return r8.box(r8.types.sdtp,s)}static stbl(e){return r8.box(r8.types.stbl,r8.stsd(e),r8.box(r8.types.stts,r8.STTS),r8.box(r8.types.stsc,r8.STSC),r8.box(r8.types.stsz,r8.STSZ),r8.box(r8.types.stco,r8.STCO))}static avc1(e){let t=[],i=[],r,s,a;for(r=0;r<e.sps.length;r++)a=(s=e.sps[r]).byteLength,t.push(a>>>8&255),t.push(255&a),t=t.concat(Array.prototype.slice.call(s));for(r=0;r<e.pps.length;r++)a=(s=e.pps[r]).byteLength,i.push(a>>>8&255),i.push(255&a),i=i.concat(Array.prototype.slice.call(s));let n=r8.box(r8.types.avcC,new Uint8Array([1,t[3],t[4],t[5],255,224|e.sps.length].concat(t).concat([e.pps.length]).concat(i))),l=e.width,o=e.height,h=e.pixelRatio[0],d=e.pixelRatio[1];return r8.box(r8.types.avc1,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,l>>8&255,255&l,o>>8&255,255&o,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]),n,r8.box(r8.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),r8.box(r8.types.pasp,new Uint8Array([h>>24,h>>16&255,h>>8&255,255&h,d>>24,d>>16&255,d>>8&255,255&d])))}static esds(e){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,...e.config,6,1,2])}static audioStsd(e){let t=e.samplerate||0;return new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,e.channelCount||0,0,16,0,0,0,0,t>>8&255,255&t,0,0])}static mp4a(e){return r8.box(r8.types.mp4a,r8.audioStsd(e),r8.box(r8.types.esds,r8.esds(e)))}static mp3(e){return r8.box(r8.types[".mp3"],r8.audioStsd(e))}static ac3(e){return r8.box(r8.types["ac-3"],r8.audioStsd(e),r8.box(r8.types.dac3,e.config))}static stsd(e){let{segmentCodec:t}=e;if("audio"===e.type){if("aac"===t)return r8.box(r8.types.stsd,r8.STSD,r8.mp4a(e));if("ac3"===t&&e.config)return r8.box(r8.types.stsd,r8.STSD,r8.ac3(e));if("mp3"===t&&"mp3"===e.codec)return r8.box(r8.types.stsd,r8.STSD,r8.mp3(e))}else if(e.pps&&e.sps){if("avc"===t)return r8.box(r8.types.stsd,r8.STSD,r8.avc1(e));if("hevc"===t&&e.vps)return r8.box(r8.types.stsd,r8.STSD,r8.hvc1(e))}
49else throw Error("video track missing pps or sps");throw Error(`unsupported ${e.type} segment codec (${t}/${e.codec})`)}static tkhd(e){let t=e.id,i=(e.duration||0)*(e.timescale||0),r=e.width||0,s=e.height||0,a=Math.floor(i/0x100000000),n=Math.floor(i%0x100000000);return r8.box(r8.types.tkhd,new Uint8Array([1,0,0,7,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,t>>24&255,t>>16&255,t>>8&255,255&t,0,0,0,0,a>>24,a>>16&255,a>>8&255,255&a,n>>24,n>>16&255,n>>8&255,255&n,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,r>>8&255,255&r,0,0,s>>8&255,255&s,0,0]))}static traf(e,t){let i=r8.sdtp(e),r=e.id,s=Math.floor(t/0x100000000),a=Math.floor(t%0x100000000);return r8.box(r8.types.traf,r8.box(r8.types.tfhd,new Uint8Array([0,0,0,0,r>>24,r>>16&255,r>>8&255,255&r])),r8.box(r8.types.tfdt,new Uint8Array([1,0,0,0,s>>24,s>>16&255,s>>8&255,255&s,a>>24,a>>16&255,a>>8&255,255&a])),r8.trun(e,i.length+16+20+8+16+8+8),i)}static trak(e){return e.duration=e.duration||0xffffffff,r8.box(r8.types.trak,r8.tkhd(e),r8.mdia(e))}static trex(e){let t=e.id;return r8.box(r8.types.trex,new Uint8Array([0,0,0,0,t>>24,t>>16&255,t>>8&255,255&t,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,1]))}static trun(e,t){let i,r,s,a,n,l,o=e.samples||[],h=o.length,d=12+16*h,c=new Uint8Array(d);for(t+=8+d,c.set([+("video"===e.type),0,15,1,h>>>24&255,h>>>16&255,h>>>8&255,255&h,t>>>24&255,t>>>16&255,t>>>8&255,255&t],0),i=0;i<h;i++)s=(r=o[i]).duration,a=r.size,n=r.flags,l=r.cts,c.set([s>>>24&255,s>>>16&255,s>>>8&255,255&s,a>>>24&255,a>>>16&255,a>>>8&255,255&a,n.isLeading<<2|n.dependsOn,n.isDependedOn<<6|n.hasRedundancy<<4|n.paddingValue<<1|n.isNonSync,61440&n.degradPrio,15&n.degradPrio,l>>>24&255,l>>>16&255,l>>>8&255,255&l],12+16*i);return r8.box(r8.types.trun,c)}static initSegment(e){r8.types||r8.init();let t=r8.moov(e);return eW(r8.FTYP,t)}static hvc1(e){let t=e.params,i=[e.vps,e.sps,e.pps],r=new Uint8Array([1,t.general_profile_space<<6|32*!!t.general_tier_flag|t.general_profile_idc,t.general_profile_compatibility_flags[0],t.general_profile_compatibility_flags[1],t.general_profile_compatibility_flags[2],t.general_profile_compatibility_flags[3],t.general_constraint_indicator_flags[0],t.general_constraint_indicator_flags[1],t.general_constraint_indicator_flags[2],t.general_constraint_indicator_flags[3],t.general_constraint_indicator_flags[4],t.general_constraint_indicator_flags[5],t.general_level_idc,240|t.min_spatial_segmentation_idc>>8,255&t.min_spatial_segmentation_idc,252|t.parallelismType,252|t.chroma_format_idc,248|t.bit_depth_luma_minus8,248|t.bit_depth_chroma_minus8,0,parseInt(t.frame_rate.fps),3|t.temporal_id_nested<<2|t.num_temporal_layers<<3|64*!!t.frame_rate.fixed,i.length]),s=r.length;for(let e=0;e<i.length;e+=1){s+=3;for(let t=0;t<i[e].length;t+=1)s+=2+i[e][t].length}let a=new Uint8Array(s);a.set(r,0),s=r.length;let n=i.length-1;for(let e=0;e<i.length;e+=1){a.set(new Uint8Array([32+e|128*(e===n),0,i[e].length]),s),s+=3;for(let t=0;t<i[e].length;t+=1)a.set(new Uint8Array([i[e][t].length>>8,255&i[e][t].length]),s),s+=2,a.set(i[e][t],s),s+=i[e][t].length}let l=r8.box(r8.types.hvcC,a),o=e.width,h=e.height,d=e.pixelRatio[0],c=e.pixelRatio[1];return r8.box(r8.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,o>>8&255,255&o,h>>8&255,255&h,0,72,0,0,0,72,0,0,0,0,0,0,0,1,18,100,97,105,108,121,109,111,116,105,111,110,47,104,108,115,46,106,115,0,0,0,0,0,0,0,0,0,0,0,0,0,0,24,17,17]),l,r8.box(r8.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),r8.box(r8.types.pasp,new Uint8Array([d>>24,d>>16&255,d>>8&255,255&d,c>>24,c>>16&255,c>>8&255,255&c])))}}function r6(e,t,i=1,r=!1){let s=e*t*i;return r?Math.round(s):s}function r9(e,t=!1){return r6(e,1e3,11111111111111112e-21,t)}function r7(e){let{baseTime:t,timescale:i,trackId:r}=e;return`${t/i} (${t}/${i}) trackId: ${r}`}r8.types=void 0,r8.HDLR_TYPES=void 0,r8.STTS=void 0,r8.STSC=void 0,r8.STCO=void 0,r8.STSZ=void 0,r8.VMHD=void 0,r8.SMHD=void 0,r8.STSD=void 0,r8.FTYP=void 0,r8.DINF=void 0;let se=null,st=null;function si(e,t,i,r){return{duration:t,size:i,cts:r,flags:{isLeading:0,isDependedOn:0,hasRedundancy:0,degradPrio:0,dependsOn:e?2:1,isNonSync:+!e}}}class sr extends et{constructor(e,t,i,r){if(super("mp4-remuxer",r),this.observer=void 0,this.config=void 0,this.typeSupp
49orted=void 0,this.ISGenerated=!1,this._initPTS=null,this._initDTS=null,this.nextVideoTs=null,this.nextAudioTs=null,this.videoSampleDuration=null,this.isAudioContiguous=!1,this.isVideoContiguous=!1,this.videoTrackConfig=void 0,this.observer=e,this.config=t,this.typeSupported=i,this.ISGenerated=!1,null===se){const e=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);se=e?parseInt(e[1]):0}if(null===st){const e=navigator.userAgent.match(/Safari\/(\d+)/i);st=e?parseInt(e[1]):0}}destroy(){this.config=this.videoTrackConfig=this._initPTS=this._initDTS=null}resetTimeStamp(e){let t=this._initPTS;t&&e&&e.trackId===t.trackId&&e.baseTime===t.baseTime&&e.timescale===t.timescale||this.log(`Reset initPTS: ${t&&r7(t)} > ${e&&r7(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,i=e[0].pts,r=e.reduce((e,r)=>{let s=r.pts,a=s-e;return a<-0x100000000&&(t=!0,a=(s=ss(s,i))-e),a>0?e:s},i);return t&&this.debug("PTS rollover detected"),r}remux(e,t,i,r,s,a,n,l){let o,h,d,c,f,g,m=s,p=s,y=e.pid>-1,v=t.pid>-1,E=t.samples.length,T=e.samples.length>0,S=n&&E>0||E>1;if((!y||T)&&(!v||S)||this.ISGenerated||n){if(this.ISGenerated){var L,A,R,b;let e=this.videoTrackConfig;(e&&(t.width!==e.width||t.height!==e.height||(null==(L=t.pixelRatio)?void 0:L[0])!==(null==(A=e.pixelRatio)?void 0:A[0])||(null==(R=t.pixelRatio)?void 0:R[1])!==(null==(b=e.pixelRatio)?void 0:b[1]))||!e&&S||null===this.nextAudioTs&&T)&&this.resetInitSegment()}this.ISGenerated||(d=this.generateIS(e,t,s,a));let i=this.isVideoContiguous,r=-1,n;if(S&&(r=function(e){for(let t=0;t<e.length;t++)if(e[t].key)return t;return -1}(t.samples),!i&&this.config.forceKeyFrameOnDiscontinuity))if(g=!0,r>0){this.warn(`Dropped ${r} out of ${E} video samples due to a missing keyframe`);let e=this.getVideoStartPts(t.samples);t.samples=t.samples.slice(r),t.dropped+=r,p+=(t.samples[0].pts-e)/t.inputTimeScale,n=p}else -1===r&&(this.warn(`No keyframe found out of ${E} video samples`),g=!1);if(this.ISGenerated){if(T&&S){let i=this.getVideoStartPts(t.samples),r=(ss(e.samples[0].pts,i)-i)/t.inputTimeScale;m+=Math.max(0,r),p+=Math.max(0,-r)}if(T){if(e.samplerate||(this.warn("regenerate InitSegment as audio detected"),d=this.generateIS(e,t,s,a)),h=this.remuxAudio(e,m,this.isAudioContiguous,a,v||S||l===Y?p:void 0),S){let r=h?h.endPTS-h.startPTS:0;t.inputTimeScale||(this.warn("regenerate InitSegment as video detected"),d=this.generateIS(e,t,s,a)),o=this.remuxVideo(t,p,i,r)}}else S&&(o=this.remuxVideo(t,p,i,0));o&&(o.firstKeyFrame=r,o.independent=-1!==r,o.firstKeyFramePTS=n)}}return this.ISGenerated&&this._initPTS&&this._initDTS&&(i.samples.length&&(f=sa(i,s,this._initPTS,this._initDTS)),r.samples.length&&(c=sn(r,s,this._initPTS))),{audio:h,video:o,initSegment:d,independent:g,text:c,id3:f}}computeInitPts(e,t,i,r){let s=Math.round(i*t),a=ss(e,s);if(a<s+t)for(this.log(`Adjusting PTS for rollover in timeline near ${(s-a)/t} ${r}`);a<s+t;)a+=0x200000000;return a-s}generateIS(e,t,i,r){let s=e.samples,a=t.samples,n=this.typeSupported,l={},o=this._initPTS,h=!o||r,d="audio/mp4",c,f,g,m=-1;if(h&&(c=f=1/0),e.config&&s.length){switch(e.timescale=e.samplerate,e.segmentCodec){case"mp3":n.mpeg?(d="audio/mpeg",e.codec=""):n.mp3&&(e.codec="mp3");break;case"ac3":e.codec="ac-3"}l.audio={id:"audio",container:d,codec:e.codec,initSegment:"mp3"===e.segmentCodec&&n.mpeg?new Uint8Array(0):r8.initSegment([e]),metadata:{channelCount:e.channelCount}},h&&(m=e.id,g=e.inputTimeScale,o&&g===o.timescale?h=!1:c=f=this.computeInitPts(s[0].pts,g,i,"audio"))}if(t.sps&&t.pps&&a.length){if(t.timescale=t.inputTimeScale,l.video={id:"main",container:"video/mp4",codec:t.codec,initSegment:r8.initSegment([t]),metadata:{width:t.width,height:t.height}},h)if(m=t.id,g=t.inputTimeScale,o&&g===o.timescale)h=!1;else{let e=this.getVideoStartPts(a),t=ss(a[0].dts,e),r=this.computeInitPts(t,g,i,"video"),s=this.computeInitPts(e,g,i,"video");f=Math.min(f,r),c=Math.min(c,s)}this.videoTrackConfig={width:t.width,height:t.height,pixelRatio:t.pixelRatio}}if(Object.keys(l).length)return this.ISGenerated=!0,h?(o&&this.warn(`Timestamps at playlist time: ${r?"":"~"}${i} ${c/g} != initPTS: ${o.baseTime/o.timescale} (${o.baseTime}/${o.timescale}) trackId: ${o.trackId}`),this.log(`Found initPTS at playlist time: ${i} offset: ${c/g} (${c}/${g}) trackId: ${m}`),this._initPTS={baseTime:c,timescale:g,trackId:m},this._initDTS={baseTime:f,timescale:g,trackId:m}):c=g=void 0,{tracks:l,initPTS:c,timescale:g,trackId:m}}remuxVideo(e,t,i,r){let s,a=e.inputTimeScale,n=e.samples,l=[],o=n.length,h=this._initPTS,d=h.baseTime*a/h.timescale,c=this.nextVideoTs,f=8,g=this.videoSampleDuration,m,p,y=1/0,v=-1/0,E=!1;if(!i||null===c){let e=d+t*a,r=n[0].pts-ss(n[0].dts,n[0].pts);se&&null!==c&&15e3>Math.abs(e-r-(c+d))?i=!0:c=e-r-d}let T=c+d;for(let e=0;e<o;e++){let t=n[e];t.pts=ss(t.pts,T),t.dts=ss(t.dts,T),t.dts<n[e>0?e-1:e].dts&&(E=!0)}E&&n.sort(function(e,t){let i=e.dts-t.dts,r=e.pts-t.pts;return i||r}),m=n[0].dts;let S=(p=n[n.length-1].dts)-m,L=S?Math.round(S/(o-1)):g||e.inputTimeScale/30;if(i){let i=m-T,r=i>L,s=i<-1;if((r||s)&&(r?this.warn(`${(e.segmentCodec||"").toUpperCase()}: ${r9(i,!0)} ms (${i}dts) hole between fragments detected at ${t.toFixed(3)}`):this.warn(`${(e.segmentCodec||"").toUpperCase()}: ${r9(-i,!0)} ms (${i}dts) overlapping between fragments detected at ${t.toFixed(3)}`),!s||T>=n[0].pts||se)){m=T;let e=n[0].pts-i;
49if(r)n[0].dts=m,n[0].pts=e;else{let t=!0;for(let r=0;r<n.length&&!(n[r].dts>e&&t);r++){let e=n[r].pts;if(n[r].dts-=i,n[r].pts-=i,r<n.length-1){let i=n[r+1].pts;t=i<=n[r].pts==i<=e}}}this.log(`Video: Initial PTS/DTS adjusted: ${r9(e,!0)}/${r9(m,!0)}, delta: ${r9(i,!0)} ms`)}}let A=0,R=0,b=m=Math.max(0,m);for(let e=0;e<o;e++){let t=n[e],i=t.units,r=i.length,s=0;for(let e=0;e<r;e++)s+=i[e].data.length;R+=s,A+=r,t.length=s,t.dts<b?(t.dts=b,b+=L/4|0||1):b=t.dts,y=Math.min(t.pts,y),v=Math.max(t.pts,v)}p=n[o-1].dts;let k=R+4*A+8;try{s=new Uint8Array(k)}catch(e){this.observer.emit(K.ERROR,K.ERROR,{type:N.MUX_ERROR,details:G.REMUX_ALLOC_ERROR,fatal:!1,error:e,bytes:k,reason:`fail allocating video mdat ${k}`});return}let I=new DataView(s.buffer);I.setUint32(0,k),s.set(r8.types.mdat,4);let D=!1,_=1/0,P=1/0,C=-1/0,w=-1/0;for(let e=0;e<o;e++){let t,i=n[e],h=i.units,c=0;for(let e=0,t=h.length;e<t;e++){let t=h[e],i=t.data,r=t.data.byteLength;I.setUint32(f,r),f+=4,s.set(i,f),f+=r,c+=4+r}if(e<o-1)g=n[e+1].dts-i.dts,t=n[e+1].pts-i.pts;else{let s=this.config,l=e>0?i.dts-n[e-1].dts:L;if(t=e>0?i.pts-n[e-1].pts:L,s.stretchShortVideoTrack&&null!==this.nextAudioTs){let e=Math.floor(s.maxBufferHole*a),t=(r?y+r*a:this.nextAudioTs+d)-i.pts;t>e?((g=t-l)<0?g=l:D=!0,this.log(`It is approximately ${t/90} ms to the next segment; using duration ${g/90} ms for the last video frame.`)):g=l}else g=l}let m=Math.round(i.pts-i.dts);_=Math.min(_,g),C=Math.max(C,g),P=Math.min(P,t),w=Math.max(w,t),l.push(si(i.key,g,c,m))}if(l.length){if(se){if(se<70){let e=l[0].flags;e.dependsOn=2,e.isNonSync=0}}else if(st&&w-P<C-_&&L/C<.025&&0===l[0].cts){this.warn("Found irregular gaps in sample duration. Using PTS instead of DTS to determine MP4 sample duration.");let e=m;for(let t=0,i=l.length;t<i;t++){let r=e+l[t].duration,s=e+l[t].cts;if(t<i-1){let e=r+l[t+1].cts;l[t].duration=e-s}else l[t].duration=t?l[t-1].duration:L;l[t].cts=0,e=r}}}let x=p+(g=D||!g?L:g);this.nextVideoTs=c=x-d,this.videoSampleDuration=g,this.isVideoContiguous=!0;let M={data1:r8.moof(e.sequenceNumber++,m,Z(e,{samples:l})),data2:s,startPTS:(y-d)/a,endPTS:(v+g-d)/a,startDTS:(m-d)/a,endDTS:c/a,type:"video",hasAudio:!1,hasVideo:!0,nb:l.length,dropped:e.dropped};return e.samples=[],e.dropped=0,M}getSamplesPerFrame(e){switch(e.segmentCodec){case"mp3":return 1152;case"ac3":return 1536;default:return 1024}}remuxAudio(e,t,i,r,s){let a=e.inputTimeScale,n=e.samplerate?e.samplerate:a,l=a/n,o=this.getSamplesPerFrame(e),h=o*l,d=this._initPTS,c="mp3"===e.segmentCodec&&this.typeSupported.mpeg,f=[],g=void 0!==s,m=e.samples,p=8*!c,y=this.nextAudioTs||-1,v=d.baseTime*a/d.timescale,E=v+t*a;if(this.isAudioContiguous=i=i||m.length&&y>0&&(r&&9e3>Math.abs(E-(y+v))||Math.abs(ss(m[0].pts,E)-(y+v))<20*h),m.forEach(function(e){e.pts=ss(e.pts,E)}),!i||y<0){let e=m.length;if(e!==(m=m.filter(e=>e.pts>=0)).length&&this.warn(`Removed ${m.length-e} of ${e} samples (initPTS ${v} / ${a})`),!m.length)return;y=0===s?0:r&&!g?Math.max(0,E-v):m[0].pts-v}if("aac"===e.segmentCodec){let t=this.config.maxAudioFramesDrift;for(let i=0,r=y+v;i<m.length;i++){let s=m[i],n=s.pts,l=n-r,o=Math.abs(1e3*l/a);if(l<=-t*h&&g)0===i&&(this.warn(`Audio frame @ ${(n/a).toFixed(3)}s overlaps marker by ${Math.round(1e3*l/a)} ms.`),this.nextAudioTs=y=n-v,r=n);else if(l>=t*h&&o<1e4&&g){let t=Math.round(l/h);for(r=n-t*h;r<0&&t&&h;)t--,r+=h;0===i&&(this.nextAudioTs=y=r-v),this.warn(`Injecting ${t} audio frames @ ${((r-v)/a).toFixed(3)}s due to ${Math.round(1e3*l/a)} ms gap.`);for(let a=0;a<t;a++){let t=r5.getSilentFrame(e.parsedCodec||e.manifestCodec||e.codec,e.channelCount);t||(this.log("Unable to get silent frame for given audio codec; duplicating last frame instead."),t=s.unit.subarray()),m.splice(i,0,{unit:t,pts:r}),r+=h,i++}}s.pts=r,r+=h}}let T=null,S=null,L,A=0,R=m.length;for(;R--;)A+=m[R].unit.byteLength;for(let t=0,r=m.length;t<r;t++){let r=m[t],s=r.unit,a=r.pts;if(null!==S)f[t-1].duration=Math.round((a-S)/l);else{if(i&&"aac"===e.segmentCodec&&(a=y+v),T=a,!(A>0))return;A+=p;try{L=new Uint8Array(A)}catch(e){this.observer.emit(K.ERROR,K.ERROR,{type:N.MUX_ERROR,details:G.REMUX_ALLOC_ER
49ROR,fatal:!1,error:e,bytes:A,reason:`fail allocating audio mdat ${A}`});return}c||(new DataView(L.buffer).setUint32(0,A),L.set(r8.types.mdat,4))}L.set(s,p);let n=s.byteLength;p+=n,f.push(si(!0,o,n,0)),S=a}let b=f.length;if(!b)return;let k=f[f.length-1];y=S-v,this.nextAudioTs=y+l*k.duration;let I=c?new Uint8Array(0):r8.moof(e.sequenceNumber++,T/l,Z({},e,{samples:f}));e.samples=[];let D=(T-v)/a,_=this.nextAudioTs/a,P={data1:I,data2:L,startPTS:D,endPTS:_,startDTS:D,endDTS:_,type:"audio",hasAudio:!0,hasVideo:!1,nb:b};return this.isAudioContiguous=!0,P}}function ss(e,t){let i;if(null===t)return e;for(i=t<e?-0x200000000:0x200000000;Math.abs(e-t)>0x100000000;)e+=i;return e}function sa(e,t,i,r){let s=e.samples.length;if(!s)return;let a=e.inputTimeScale;for(let n=0;n<s;n++){let s=e.samples[n];s.pts=ss(s.pts-i.baseTime*a/i.timescale,t*a)/a,s.dts=ss(s.dts-r.baseTime*a/r.timescale,t*a)/a}let n=e.samples;return e.samples=[],{samples:n}}function sn(e,t,i){let r=e.samples.length;if(!r)return;let s=e.inputTimeScale;for(let a=0;a<r;a++){let r=e.samples[a];r.pts=ss(r.pts-i.baseTime*s/i.timescale,t*s)/s}e.samples.sort((e,t)=>e.pts-t.pts);let a=e.samples;return e.samples=[],{samples:a}}function sl(e,t,i=!1){return e?.start!==void 0?(e.start+(i?e.duration:0))/e.timescale:t}function so(e,t,i){let r=e.codec;return r&&r.length>4?r:t===eR?"ec-3"===r||"ac-3"===r||"alac"===r?r:"fLaC"===r||"Opus"===r?e8(r,!1):(i.warn(`Unhandled audio codec "${r}" in mp4 MAP`),r||"mp4a"):(i.warn(`Unhandled video codec "${r}" in mp4 MAP`),r||"avc1")}try{t=self.performance.now.bind(self.performance)}catch{t=Date.now}let sh=[{demux:class{constructor(e,t){this.remainderData=null,this.timeOffset=0,this.config=void 0,this.videoTrack=void 0,this.audioTrack=void 0,this.id3Track=void 0,this.txtTrack=void 0,this.config=t}resetTimeStamp(){}resetInitSegment(e,t,i,r){let s=this.videoTrack=rw("video",1),a=this.audioTrack=rw("audio",1),n=this.txtTrack=rw("text",1);if(this.id3Track=rw("id3",1),this.timeOffset=0,!(null!=e&&e.byteLength))return;let l=eU(e);if(l.video){let{id:e,timescale:t,codec:i,supplemental:r}=l.video;s.id=e,s.timescale=n.timescale=t,s.codec=i,s.supplemental=r}if(l.audio){let{id:e,timescale:t,codec:i}=l.audio;a.id=e,a.timescale=t,a.codec=i}n.id=ew.text,s.sampleDuration=0,s.duration=a.duration=r}resetContiguity(){this.remainderData=null}static probe(e){let t=e.byteLength;for(let i=0;i<t;){let r=eO(e,i);if(r>8&&109===e[i+4]&&111===e[i+5]&&111===e[i+6]&&102===e[i+7])return!0;i=r>1?i+r:t}return!1}demux(e,t){this.timeOffset=t;let i=e,r=this.videoTrack,s=this.txtTrack;if(this.config.progressive){this.remainderData&&(i=eW(this.remainderData,e));let t=function(e){let t={valid:null,remainder:null},i=eB(e,["moof"]);if(i.length<2)return t.remainder=e,t;let r=i[i.length-1];return t.valid=e.slice(0,r.byteOffset-8),t.remainder=e.slice(r.byteOffset-8),t}(i);this.remainderData=t.remainder,r.samples=t.valid||new Uint8Array}else r.samples=i;let a=this.extractID3Track(r,t);return s.samples=eq(t,r),{videoTrack:r,audioTrack:this.audioTrack,id3Track:a,textTrack:this.txtTrack}}flush(){let e=this.timeOffset,t=this.videoTrack,i=this.txtTrack;t.samples=this.remainderData||new Uint8Array,this.remainderData=null;let r=this.extractID3Track(t,this.timeOffset);return i.samples=eq(e,t),{videoTrack:t,audioTrack:rw(),id3Track:r,textTrack:rw()}}extractID3Track(e,t){let i=this.id3Track;if(e.samples.length){let r=eB(e.samples,["emsg"]);r&&r.forEach(e=>{let r=function(e){let t=e[0],i="",r="",s=0,a=0,n=0,l=0,o=0,h=0;if(0===t){for(;"\0"!==ex(e.subarray(h,h+1));)i+=ex(e.subarray(h,h+1)),h+=1;for(i+=ex(e.subarray(h,h+1)),h+=1;"\0"!==ex(e.subarray(h,h+1));)r+=ex(e.subarray(h,h+1)),h+=1;r+=ex(e.subarray(h,h+1)),h+=1,s=eO(e,12),a=eO(e,16),l=eO(e,20),o=eO(e,24),h=28}else if(1===t){h+=4,s=eO(e,h);let t=eO(e,h+=4),a=eO(e,h+=4);for(h+=4,B(n=0x100000000*t+a)||(n=Number.MAX_SAFE_INTEGER,en.warn("Presentation time exceeds safe integer limit and wrapped to max safe integer in parsing emsg box")),l=eO(e,h),h+=4,o=eO(e,h),h+=4;"\0"!==ex(e.subarray(h,h+1));)i+=ex(e.subarray(h,h+1)),h+=1;for(i+=ex(e.subarray(h,h+1)),h+=1;"\0"!==ex(e.subarray(h,h+1));)r+=ex(e.subarray(h,h+1)),h+=1;r+=ex(e.subarray(h,h+1)),h+=1}return{schemeIdUri:i,value:r,timeScale:s,presentationTime:n,presentationTimeDelta:a,eventDuration:l,id:o,payload:e.subarray(h,e.byteLength)}}(e);if(rq.test(r.schemeIdUri)){let e=rY(r,t),s=0xffffffff===r.eventDuration?1/0:r.eventDuration/r.timeScale;s<=.001&&(s=1/0);let a=r.payload;i.samples.push({data:a,len:a.byteLength,dts:e,pts:e,type:rC.emsg,duration:s})}else if(this.config.enableEmsgKLVMetadata&&r.schemeIdUri.startsWith("urn:misb:KLV:bin:1910.1")){let e=rY(r,t);i.samples.push({data:r.payload,len:r.payload.byteLength,dts:e,pts:e,type:rC.misbklv,duration:1/0})}})}return i}demuxSampleAes(e,t,i){return Promise.reject(Error("The MP4 demuxer does not support SAMPLE-AES decryption"))}destroy(){this.config=null,this.remainderData=null,this.videoTrack=this.audioTrack=this.id3Track=this.txtTrack=void 0}},remux:class extends et{constructor(e,t,i,r){super("passthrough-remuxer",r),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;let t=this.initPTS;t&&e&&t.baseTime===e.baseTime&&t.timescale===e.timescale||(this.initPTS=e)}resetNextTimestamp(){this.isVideoContiguous=!1,this.lastEndTime=null}resetInitSegment(e,t,i,r){this.audioCodec=t,this.videoCodec=i,this.generateInitSegment(e,r),this.emitInitSegment=!0}generateInitSegment(e,t){let{audioCodec:i,videoCodec:r}=this;if(!(null!=e&&e.byteLength)){this.initTracks=void 0,this.initData=void 0;return}let{audio:s,video:a}=this.initData=eU(e);if(t)!function(e,t){if(!e||!t)return;let i=t.keyId;i&&t.isCommonEncryption&&eV(e,(e,t)=>{let r=e.subarray(8,24);r.some(e=>0!==e)||(en.log(`[eme] Patching keyId in 'enc${t?"a":"v"}>sinf>>tenc' box: ${ed(r)} -> ${ed(i)}`),e.set(i,8))})}(e,t);else{let e=s||a;null!=e&&e.encrypted&&this.warn(`Init segment with encrypted track with has no key ("${e.codec}")!`)}s&&(i=so(s,eR,this)),a&&(r=so(a,eb,this));let n={};s&&a?n.audiovideo={container:"video/mp4",codec:i+","+r,supplemental:a.supplemental,encrypted:a.encrypted,initSegment:e,id:"main"}:s?n.audio={container:"audio/mp4",codec:i,encrypted:s.encrypted,initSegment:e,id:"audio"}:a?n.video={container:"video/mp4",codec:r,supplemental:a.supplemental,encrypted:a.encrypted,initSegment:e,id:"main"}:this.warn("initSegment does not contain moov or trak boxes."),this.initTracks=n}remux(e,t,i,r,s,a){var n,l;let{initPTS:o,lastEndTime:h}=this,d={audio:void 0,video:void 0,text:r,id3:i,initSegment:void 0};$(h)||(h=this.lastEndTime=s||0);let c=t.samples;if(!c.length)return d;let f={initPTS:void 0,timescale:void 0,trackId:void 0},g=this.initData;if(null!=(n=g)&&n.length||(this.generateInitSegment(c),g=this.initData),!(null!=(l=g)&&l.length))return this.warn("Failed to generate initSegment."),d;this.emitInitSegment&&(f.tracks=this.initTracks,this.emitInitSegment=!1);let m=function(e,t,i){let r={},s=eB(e,["moof","traf"]);for(let e=0;e<s.length;e++){let a=s[e],n=eB(a,["tfhd"])[0],l=eO(n,4),o=t[l];if(!o)continue;r[l]||(r[l]={start:NaN,duration:0,sampleCount:0,timescale:o.timescale,type:o.type});let h=r[l],d=eB(a,["tfdt"])[0];if(d){let e=d[0],t=eO(d,4);1===e&&(0xffffffff===t?i.warn("[mp4-demuxer]: Ignoring assumed invali
49d signed 64-bit track fragment decode time"):(t*=0x100000000,t+=eO(d,8))),$(t)&&(!$(h.start)||t<h.start)&&(h.start=t)}let c=o.default,f=eO(n,0)|c?.flags,g=c?.duration||0;8&f&&(g=2&f?eO(n,12):eO(n,8));let m=eB(a,["trun"]),p=h.start||0,y=0,v=g;for(let e=0;e<m.length;e++){let t=m[e],i=eO(t,4),r=h.sampleCount;h.sampleCount+=i;let s=1&t[3],a=4&t[3],n=1&t[2],l=2&t[2],o=4&t[2],d=8&t[2],c=8,f=i;for(s&&(c+=4),a&&i&&(1&t[c+1]||void 0!==h.keyFrameIndex||(h.keyFrameIndex=r),c+=4,n?(v=eO(t,c),c+=4):v=g,l&&(c+=4),d&&(c+=4),p+=v,y+=v,f--);f--;)n?(v=eO(t,c),c+=4):v=g,l&&(c+=4),o&&(1&t[c+1]||void 0===h.keyFrameIndex&&(h.keyFrameIndex=h.sampleCount-(f+1),h.keyFrameStart=p),c+=4),d&&(c+=4),p+=v,y+=v;!y&&g&&(y+=g*i)}h.duration+=y}if(!Object.keys(r).some(e=>r[e].duration)){let t=1/0,i=0,s=eB(e,["sidx"]);for(let e=0;e<s.length;e++){let r=function(e){let t=[],i=e[0],r=8,s=eO(e,8);r+=4;let a=0,n=0;0===i?(a=eO(e,r),n=eO(e,r+4),r+=8):(a=eF(e,r),n=eF(e,r+8),r+=16),r+=2;let l=e.length+n,o=eM(e,r);r+=2;for(let i=0;i<o;i++){let i=r,a=eO(e,i);i+=4;let n=0x7fffffff&a;if((0x80000000&a)>>>31==1)return en.warn("SIDX has hierarchical references (not supported)"),null;let o=eO(e,i);i+=4,t.push({referenceSize:n,subsegmentDuration:o,info:{duration:o/s,start:l,end:l+n-1}}),l+=n,i+=4,r=i}return{earliestPresentationTime:a,timescale:s,version:i,referencesCount:o,references:t}}(s[e]);if(null!=r&&r.references){t=Math.min(t,r.earliestPresentationTime/r.timescale);let e=r.references.reduce((e,t)=>e+t.info.duration||0,0);i=Math.max(i,e+r.earliestPresentationTime/r.timescale)}}i&&$(i)&&Object.keys(r).forEach(e=>{r[e].duration||(r[e].duration=i*r[e].timescale-r[e].start)})}return r}(c,g,this),p=g.audio?m[g.audio.id]:null,y=g.video?m[g.video.id]:null,v=sl(y,1/0),E=sl(p,1/0),T=sl(y,0,!0),S=sl(p,0,!0),L=s,A=0,R=p&&(!y||!o&&E<v||o&&o.trackId===g.audio.id),b=R?p:y;if(b){let e=b.timescale,t=b.start-s*e,i=R?g.audio.id:g.video.id;L=b.start/e,A=R?S-E:T-v,(a||!o)&&(function(e,t,i,r){if(null===e)return!0;let s=Math.max(r,1);return Math.abs(t-e.baseTime/e.timescale-i)>s}(o,L,s,A)||e!==o.timescale)&&(o&&this.warn(`Timestamps at playlist time: ${a?"":"~"}${s} ${t/e} != initPTS: ${o.baseTime/o.timescale} (${o.baseTime}/${o.timescale}) trackId: ${o.trackId}`),this.log(`Found initPTS at playlist time: ${s} offset: ${L-s} (${t}/${e}) trackId: ${i}`),o=null,f.initPTS=t,f.timescale=e,f.trackId=i)}else this.warn(`No audio or video samples found for initPTS at playlist time: ${s}`);o?(f.initPTS=o.baseTime,f.timescale=o.timescale,f.trackId=o.trackId):(f.timescale&&void 0!==f.trackId&&void 0!==f.initPTS||(this.warn("Could not set initPTS"),f.initPTS=L,f.timescale=1,f.trackId=-1),this.initPTS=o={baseTime:f.initPTS,timescale:f.timescale,trackId:f.trackId});let k=L-o.baseTime/o.timescale,I=k+A;A>0?this.lastEndTime=I:(this.warn("Duration parsed from mp4 should be greater than zero"),this.resetNextTimestamp());let D=!!g.audio,_=!!g.video,P="";D&&(P+="audio"),_&&(P+="video");let C={data1:c,startPTS:k,startDTS:k,endPTS:I,endDTS:I,type:P,hasAudio:D,hasVideo:_,nb:1,dropped:0,encrypted:!!g.audio&&g.audio.encrypted||!!g.video&&g.video.encrypted};d.audio=D&&!_?C:void 0,d.video=_?C:void 0;let w=y?.sampleCount;if(w){let e=y.keyFrameIndex,t=-1!==e;C.nb=w,C.dropped=0===e||this.isVideoContiguous?0:t?e:w,C.independent=t,C.firstKeyFrame=e,t&&y.keyFrameStart&&(C.firstKeyFramePTS=(y.keyFrameStart-o.baseTime)/o.timescale),this.isVideoContiguous||(d.independent=t),this.isVideoContiguous||(this.isVideoContiguous=t),C.dropped&&this.warn(`fmp4 does not start with IDR: firstIDR ${e}/${w} dropped: ${C.dropped} start: ${C.firstKeyFramePTS||"NA"}`)}return d.initSegment=f,d.id3=sa(i,s,o,o),r.samples.length&&(d.text=sn(r,s,o)),d}}},{demux:r0,remux:sr},{demux:class extends rx{constructor(e,t){super(),this.observer=void 0,this.config=void 0,this.observer=e,this.config=t}resetInitSegment(e,t,i,r){super.resetInitSegment(e,t,i,r),this._audioTrack={container:"audio/adts",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"aac",samples:[],manifestCodec:t,duration:r,inputTimeScale:9e4,dropped:0}}static probe(e,t){if(!e)return!1;let i=rT(e,0),r=i?.length||0;if(rV(e,r))return!1;for(let i=e.length;r<i;r++)if(function(e,t){if(rR(e,t)){let i=rL(e,t);if(t+i>=e.length)return!1;let r=rA(e,t);if(r<=i)return!1;let s=t+r;return s===e.length||rR(e,s)}return!1}(e,r))return t.log("ADTS sync word found !"),!0;return!1}canParse(e,t){return t+5<e.length&&rS(e,t)&&rA(e,t)<=e.length-t}appendFrame(e,t,i){rb(e,this.observer,t,i,e.manifestCodec);let r=rk(e,t,i,this.basePTS,this.frameIndex);if(r&&0===r.missing)return r}},remux:sr},{demux:class extends rx{resetInitSegment(e,t,i,r){super.resetInitSegment(e,t,i,r),this._audioTrack={container:"audio/mpeg",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"mp3",samples:[],manifestCodec:t,duration:r,inputTimeScale:9e4,dropped:0}}static probe(e){if(!e)return!1;let t=rT(e,0),i=t?.length||0;
49if(t&&11===e[i]&&119===e[i+1]&&void 0!==rP(t)&&16>=rj(e,i))return!1;for(let t=e.length;i<t;i++)if(rV(e,i))return en.log("MPEG Audio sync word found !"),!0;return!1}canParse(e,t){return rK(e,t)&&4<=e.length-t}appendFrame(e,t,i){if(null!==this.basePTS)return rN(e,t,i,this.basePTS,this.frameIndex)}},remux:sr}];sh.splice(2,0,{demux:class extends rx{constructor(e){super(),this.observer=void 0,this.observer=e}resetInitSegment(e,t,i,r){super.resetInitSegment(e,t,i,r),this._audioTrack={container:"audio/ac-3",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"ac3",samples:[],manifestCodec:t,duration:r,inputTimeScale:9e4,dropped:0}}canParse(e,t){return t+64<e.length}appendFrame(e,t,i){let r=rW(e,t,i,this.basePTS,this.frameIndex);if(-1!==r)return{sample:e.samples[e.samples.length-1],length:r,missing:0}}static probe(e){if(!e)return!1;let t=rT(e,0);if(!t)return!1;let i=t.length;return 11===e[i]&&119===e[i+1]&&void 0!==rP(t)&&16>rj(e,i)}},remux:sr});class sd{constructor(e,t,i,r,s,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=i,this.id=s,this.logger=a}configure(e){this.transmuxConfig=e,this.decrypter&&this.decrypter.reset()}push(e,i,r,s){var a,n;let l,o=r.transmuxing;o.executeStart=t();let h=new Uint8Array(e),{currentTransmuxState:d,transmuxConfig:c}=this;s&&(this.currentTransmuxState=s);let{contiguous:f,discontinuity:g,trackSwitch:m,accurateTimeOffset:p,timeOffset:y,initSegmentChange:v}=s||d,{audioCodec:E,videoCodec:T,defaultInitPts:S,duration:L,initSegmentData:A}=c,R=(a=h,n=i,l=null,a.byteLength>0&&n?.key!=null&&null!==n.iv&&null!=n.method&&(l=n),l);if(R&&ie(R.method)){let e=this.getDecrypter(),i=it(R.method);if(!e.isSync())return this.asyncResult=!0,this.decryptionPromise=e.webCryptoDecrypt(h,R.key.buffer,R.iv.buffer,i).then(e=>{let t=this.push(e,null,r);return this.decryptionPromise=null,t}),this.decryptionPromise;{let s=e.softwareDecrypt(h,R.key.buffer,R.iv.buffer,i);if(r.part>-1){let t=e.flush();s=t&&t.buffer}if(!s)return o.executeEnd=t(),su(r);h=new Uint8Array(s)}}let b=this.needsProbing(g,m);if(b){let e=this.configureTransmuxer(h);if(e)return this.logger.warn(`[transmuxer] ${e.message}`),this.observer.emit(K.ERROR,K.ERROR,{type:N.MEDIA_ERROR,details:G.FRAG_PARSING_ERROR,fatal:!1,error:e,reason:e.message}),o.executeEnd=t(),su(r)}(g||m||v||b)&&this.resetInitSegment(A,E,T,L,i),(g||v||b)&&this.resetInitialTimestamp(S),f||this.resetContiguity();let k=this.transmux(h,R,y,p,r);this.asyncResult=sc(k);let I=this.currentTransmuxState;return I.contiguous=!0,I.discontinuity=!1,I.trackSwitch=!1,o.executeEnd=t(),k}flush(e){let i=e.transmuxing;i.executeStart=t();let{decrypter:r,currentTransmuxState:s,decryptionPromise:a}=this;if(a)return this.asyncResult=!0,a.then(()=>this.flush(e));let n=[],{timeOffset:l}=s;if(r){let t=r.flush();t&&n.push(this.push(t.buffer,null,e))}let{demuxer:o,remuxer:h}=this;if(!o||!h){i.executeEnd=t();let r=[su(e)];return this.asyncResult?Promise.resolve(r):r}let d=o.flush(l);return sc(d)?(this.asyncResult=!0,d.then(t=>(this.flushRemux(n,t,e),n))):(this.flushRemux(n,d,e),this.asyncResult?Promise.resolve(n):n)}flushRemux(e,i,r){let{audioTrack:s,videoTrack:a,id3Track:n,textTrack:l}=i,{accurateTimeOffset:o,timeOffset:h}=this.currentTransmuxState;this.logger.log(`[transmuxer.ts]: Flushed ${this.id} sn: ${r.sn}${r.part>-1?" part: "+r.part:""} of ${this.id===q?"level":"track"} ${r.level}`);let d=this.remuxer.remux(s,a,n,l,h,o,!0,this.id);e.push({remuxResult:d,chunkMeta:r}),r.transmuxing.executeEnd=t()}resetInitialTimestamp(e){let{demuxer:t,remuxer:i}=this;t&&i&&(t.resetTimeStamp(e),i.resetTimeStamp(e))}resetContiguity(){let{demuxer:e,remuxer:t}=this;e&&t&&(e.resetContiguity(),t.resetNextTimestamp())}resetInitSegment(e,t,i,r,s){let{demuxer:a,remuxer:n}=this;a&&n&&(a.resetInitSegment(e,t,i,r),n.resetInitSegment(e,t,i,s))}destroy(){this.demuxer&&(this.demuxer.destroy(),this.demuxer=void 0),this.remuxer&&(this.remuxer.destroy(),this.remuxer=void 0)}transmux(e,t,i,r,s){return t&&"SAMPLE-AES"===t.method?this.transmuxSampleAes(e,t,i,r,s):this.transmuxUnencrypted(e,i,r,s)}transmuxUnencrypted(e,t,i,r){let{audioTrack:s,videoTrack:a,id3Track:n,textTrack:l}=this.demuxer.demux(e,t,!1,!this.config.progressive);return{remuxResult:this.remuxer.remux(s,a,n,l,t,i,!1,this.id),chunkMeta:r}}transmuxSampleAes(e,t,i,r,s){return this.demuxer.demuxSampleAes(e,t,i).then(e=>({remuxResult:this.remuxer.remux(e.audioTrack,e.videoTrack,e.id3Track,e.textTrack,i,r,!1,this.id),chunkMeta:s}))}
49configureTransmuxer(e){let t,{config:i,observer:r,typeSupported:s}=this;for(let i=0,r=sh.length;i<r;i++){var a;if(null!=(a=sh[i].demux)&&a.probe(e,this.logger)){t=sh[i];break}}if(!t)return Error("Failed to find demuxer by probing fragment data");let n=this.demuxer,l=this.remuxer,o=t.remux,h=t.demux;l&&l instanceof o||(this.remuxer=new o(r,i,s,this.logger)),n&&n instanceof h||(this.demuxer=new h(r,i,s,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 tV(this.config)),e}}let su=e=>({remuxResult:{},chunkMeta:e});function sc(e){return"then"in e&&e.then instanceof Function}class sf{constructor(e,t,i,r,s){this.audioCodec=void 0,this.videoCodec=void 0,this.initSegmentData=void 0,this.duration=void 0,this.defaultInitPts=void 0,this.audioCodec=e,this.videoCodec=t,this.initSegmentData=i,this.duration=r,this.defaultInitPts=s||null}}class sg{constructor(e,t,i,r,s,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=i,this.trackSwitch=r,this.timeOffset=s,this.initSegmentChange=a}}let sm=0;class sp{constructor(e,t,i,r){this.error=null,this.hls=void 0,this.id=void 0,this.instanceNo=sm++,this.observer=void 0,this.frag=null,this.part=null,this.useWorker=void 0,this.workerContext=null,this.transmuxer=null,this.onTransmuxComplete=void 0,this.onFlush=void 0,this.onWorkerMessage=e=>{let t=e.data,i=this.hls;if(!(!i||!(null!=t&&t.event)||t.instanceNo!==this.instanceNo))switch(t.event){case"init":{var r;let e=null==(r=this.workerContext)?void 0:r.objectURL;e&&self.URL.revokeObjectURL(e);break}case"transmuxComplete":this.handleTransmuxComplete(t.data);break;case"flush":this.onFlush(t.data);break;case"workerLog":i.logger[t.data.logType]&&i.logger[t.data.logType](t.data.message);break;default:t.data=t.data||{},t.data.frag=this.frag,t.data.part=this.part,t.data.id=this.id,i.trigger(t.event,t.data)}},this.onWorkerError=e=>{if(!this.hls)return;let t=Error(`${e.message}  (${e.filename}:${e.lineno})`);this.hls.config.enableWorker=!1,this.hls.logger.warn(`Error in "${this.id}" Web Worker, fallback to inline`),this.hls.trigger(K.ERROR,{type:N.OTHER_ERROR,details:G.INTERNAL_EXCEPTION,fatal:!1,event:"demuxerWorker",error:t})};const s=e.config;this.hls=e,this.id=t,this.useWorker=!!s.enableWorker,this.onTransmuxComplete=i,this.onFlush=r;const a=(e,t)=>{(t=t||{}).frag=this.frag||void 0,e===K.ERROR&&(t.parent=this.id,t.part=this.part,this.error=t.error),this.hls.trigger(e,t)};this.observer=new rg,this.observer.on(K.FRAG_DECRYPTED,a),this.observer.on(K.ERROR,a);const n=e7(s.preferManagedMediaSource);if(this.useWorker&&"u">typeof Worker){const i=this.hls.logger;if(s.workerPath||"function"==typeof __HLS_WORKER_BUNDLE__){try{s.workerPath?(i.log(`loading Web Worker ${s.workerPath} for "${t}"`),this.workerContext=function(e){let t=rp[e];if(t)return t.clientCount++,t;let i=new self.URL(e,self.location.href).href,r={worker:new self.Worker(i),scriptURL:i,clientCount:1};return rp[e]=r,r}(s.workerPath)):(i.log(`injecting Web Worker for "${t}"`),this.workerContext=function(){let e=rp[rm];if(e)return e.clientCount++,e;let t=new self.Blob([`var exports={};var module={exports:exports};function define(f){f()};define.amd=true;(${__HLS_WORKER_BUNDLE__.toString()})(true);`],{type:"text/javascript"}),i=self.URL.createObjectURL(t),r={worker:new self.Worker(i),objectURL:i,clientCount:1};return rp[rm]=r,r}());const{worker:e}=this.workerContext;e.addEventListener("message",this.onWorkerMessage),e.addEventListener("error",this.onWorkerError),e.postMessage({instanceNo:this.instanceNo,cmd:"init",typeSupported:n,id:t,config:tc(s)})}catch(r){i.warn(`Error setting up "${t}" Web Worker, fallback to inline`,r),this.terminateWorker(),this.error=null,this.transmuxer=new sd(this.observer,n,s,"",t,e.logger)}return}}this.transmuxer=new sd(this.observer,n,s,"",t,e.logger)}reset(){if(this.frag=null,this.part=null,this.workerContext){let e=this.instanceNo;this.instanceNo=sm++;let t=this.hls.config,i=e7(t.preferManagedMediaSource);this.workerContext.worker.postMessage({instanceNo:this.instanceNo,cmd:"reset",resetNo:e,typeSupp
49orted:i,id:this.id,config:tc(t)})}}terminateWorker(){if(this.workerContext){let{worker:e}=this.workerContext;this.workerContext=null,e.removeEventListener("message",this.onWorkerMessage),e.removeEventListener("error",this.onWorkerError),function(e){let t=rp[e||rm];if(t&&1==t.clientCount--){let{worker:i,objectURL:r}=t;delete rp[e||rm],r&&self.URL.revokeObjectURL(r),i.terminate()}}(this.hls.config.workerPath)}}destroy(){if(this.workerContext)this.terminateWorker(),this.onWorkerMessage=this.onWorkerError=null;else{let e=this.transmuxer;e&&(e.destroy(),this.transmuxer=null)}let e=this.observer;e&&e.removeAllListeners(),this.frag=null,this.part=null,this.observer=null,this.hls=null}push(e,t,i,r,s,a,n,l,o,h){var d,c;o.transmuxing.start=self.performance.now();let{instanceNo:f,transmuxer:g}=this,m=a?a.start:s.start,p=s.decryptdata,y=this.frag,v=!(y&&s.cc===y.cc),E=!(y&&o.level===y.level),T=y?o.sn-y.sn:-1,S=this.part?o.part-this.part.index:-1,L=0===T&&o.id>1&&o.id===y?.stats.chunkCount,A=!E&&(1===T||0===T&&(1===S||L&&S<=0)),R=self.performance.now();(E||T||0===s.stats.parsing.start)&&(s.stats.parsing.start=R),a&&(S||!A)&&(a.stats.parsing.start=R);let b=!(y&&(null==(d=s.initSegment)?void 0:d.url)===(null==(c=y.initSegment)?void 0:c.url)),k=new sg(v,A,l,E,m,b);if(!A||v||b){this.hls.logger.log(`[transmuxer-interface]: Starting new transmux session for ${s.type} sn: ${o.sn}${o.part>-1?" part: "+o.part:""} ${this.id===q?"level":"track"}: ${o.level} id: ${o.id}
50        discontinuity: ${v}
51        trackSwitch: ${E}
52        contiguous: ${A}
53        accurateTimeOffset: ${l}
54        timeOffset: ${m}
55        initSegmentChange: ${b}`);let e=new sf(i,r,t,n,h);this.configureTransmuxer(e)}if(this.frag=s,this.part=a,this.workerContext)this.workerContext.worker.postMessage({instanceNo:f,cmd:"demux",data:e,decryptdata:p,chunkMeta:o,state:k},e instanceof ArrayBuffer?[e]:[]);else if(g){let t=g.push(e,p,o,k);sc(t)?t.then(e=>{this.handleTransmuxComplete(e)}).catch(e=>{this.transmuxerError(e,o,"transmuxer-interface push error")}):this.handleTransmuxComplete(t)}}flush(e){e.transmuxing.start=self.performance.now();let{instanceNo:t,transmuxer:i}=this;if(this.workerContext)this.workerContext.worker.postMessage({instanceNo:t,cmd:"flush",chunkMeta:e});else if(i){let t=i.flush(e);sc(t)?t.then(t=>{this.handleFlushResult(t,e)}).catch(t=>{this.transmuxerError(t,e,"transmuxer-interface flush error")}):this.handleFlushResult(t,e)}}transmuxerError(e,t,i){this.hls&&(this.error=e,this.hls.trigger(K.ERROR,{type:N.MEDIA_ERROR,details:G.FRAG_PARSING_ERROR,chunkMeta:t,frag:this.frag||void 0,part:this.part||void 0,fatal:!1,error:e,err:e,reason:i}))}handleFlushResult(e,t){e.forEach(e=>{this.handleTransmuxComplete(e)}),this.onFlush(t)}configureTransmuxer(e){let{instanceNo:t,transmuxer:i}=this;this.workerContext?this.workerContext.worker.postMessage({instanceNo:t,cmd:"configure",config:e}):i&&i.configure(e)}handleTransmuxComplete(e){e.chunkMeta.transmuxing.end=self.performance.now(),this.onTransmuxComplete(e)}}class sy extends et{constructor(e,t){super(t,e.logger),this.hls=void 0,this.canLoad=!1,this.timer=-1,this.hls=e}destroy(){this.clearTimer(),this.hls=this.log=this.warn=null}clearTimer(){-1!==this.timer&&(self.clearTimeout(this.timer),this.timer=-1)}startLoad(){this.canLoad=!0,this.loadPlaylist()}stopLoad(){this.canLoad=!1,this.clearTimer()}switchParams(e,t,i){let r=t?.renditionReports;if(r){let s=-1;for(let i=0;i<r.length;i++){let a,n=r[i];try{a=new self.URL(n.URI,t.url).href}catch(e){this.warn(`Could not construct new URL for Rendition Report: ${e}`),a=n.URI||""}if(a===e){s=i;break}a===e.substring(0,a.length)&&(s=i)}if(-1!==s){let e=r[s],a=parseInt(e["LAST-MSN"])||t.lastPartSn,n=parseInt(e["LAST-PART"])||t.lastPartIndex;if(this.hls.config.lowLatencyMode){let e=Math.min(t.age-t.partTarget,t.targetduration);n>=0&&e>t.partTarget&&(n+=1)}return new th(a,n>=0?n:void 0,i&&to(i))}}}loadPlaylist(e){this.clearTimer()}loadingPlaylist(e,t){this.clearTimer()}shouldLoadPlaylist(e){return this.canLoad&&!!e&&!!e.url&&(!e.details||e.details.live)}getUrlWithDirectives(e,t){if(t)try{return t.addDirectives(e)}catch(e){this.warn(`Could not construct new URL with HLS Delivery Directives: ${e}`)}return e}playlistLoaded(e,t,i){let{details:r,stats:s}=t,a=self.performance.now(),n=s.loading.first?Math.max(0,a-s.loading.first):0;r.advancedDateTime=Date.now()-n;let l=this.hls.config.timelineOffset;
55if(l!==r.appliedTimelineOffset){let e=Math.max(l||0,0);r.appliedTimelineOffset=e,r.fragments.forEach(t=>{t.setStart(t.playlistOffset+e)})}if(r.live||null!=i&&i.live){let l,h,d,c="levelInfo"in t?t.levelInfo:t.track;if(r.reloaded(i),i&&r.fragments.length>0){!function(e,t,i){let r;if(e===t)return;let s=null,a=e.fragments;for(let e=a.length-1;e>=0;e--){let t=a[e].initSegment;if(t){s=t;break}}e.fragmentHint&&delete e.fragmentHint.endPTS,function(e,t,i){let r=t.skippedSegments,s=Math.max(e.startSN,t.startSN)-t.startSN,a=+!!e.fragmentHint+(r?t.endSN:Math.min(e.endSN,t.endSN))-t.startSN,n=t.startSN-e.startSN,l=t.fragmentHint?t.fragments.concat(t.fragmentHint):t.fragments,o=e.fragmentHint?e.fragments.concat(e.fragmentHint):e.fragments;for(let c=s;c<=a;c++){let s=o[n+c],a=l[c];if(r&&!a&&s&&(a=t.fragments[c]=s),s&&a){var h,d;i(s,a,c,l);let r=s.relurl,n=a.relurl;if(r&&(h=r)!==(d=n)&&d&&iQ(h)!==iQ(d)){t.playlistParsingError=iH(`media sequence mismatch ${a.sn}:`,e,t,s,a);return}if(s.cc!==a.cc){t.playlistParsingError=iH(`discontinuity sequence mismatch (${s.cc}!=${a.cc})`,e,t,s,a);return}}}}(e,t,(e,i,a,n)=>{if((!t.startCC||t.skippedSegments)&&i.cc!==e.cc){let r=e.cc-i.cc;for(let e=a;e<n.length;e++)n[e].cc+=r;t.endCC=n[n.length-1].cc}$(e.startPTS)&&$(e.endPTS)&&(i.setStart(i.startPTS=e.startPTS),i.startDTS=e.startDTS,i.maxStartPTS=e.maxStartPTS,i.endPTS=e.endPTS,i.endDTS=e.endDTS,i.minEndPTS=e.minEndPTS,i.setDuration(e.endPTS-e.startPTS),i.duration&&(r=i),t.PTSKnown=t.alignedSliding=!0),e.hasStream
55s&&(i.elementaryStreams=e.elementaryStreams),i.loader=e.loader,e.hasStats&&(i.stats=e.stats),e.initSegment&&(i.initSegment=e.initSegment,s=e.initSegment)});let n=t.fragments,l=t.fragmentHint?n.concat(t.fragmentHint):n;if(s&&l.forEach(e=>{var t;e&&(!e.initSegment||e.initSegment.relurl===(null==(t=s)?void 0:t.relurl))&&(e.initSegment=s)}),t.skippedSegments){if(t.deltaUpdateFailed=n.some(e=>!e),t.deltaUpdateFailed){i.warn("[level-helper] Previous playlist missing segments skipped in delta playlist");for(let e=t.skippedSegments;e--;)n.shift();t.startSN=n[0].sn}else{t.canSkipDateRanges&&(t.dateRanges=function(e,t,i){let{dateRanges:r,recentlyRemovedDateranges:s}=t,a=Z({},e);s&&s.forEach(e=>{delete a[e]});let n=Object.keys(a).length;return n?(Object.keys(r).forEach(e=>{let t=a[e],s=new t8(r[e].attr,t);s.isValid?(a[e]=s,t||(s.tagOrder+=n)):i.warn(`Ignoring invalid Playlist Delta Update DATERANGE tag: "${tc(r[e].attr)}"`)}),a):r}(e.dateRanges,t,i));let r=e.fragments.filter(e=>e.rawProgramDateTime);if(e.hasProgramDateTime&&!t.hasProgramDateTime)for(let e=1;e<l.length;e++)null===l[e].programDateTime&&iF(l[e],l[e-1],r);iC(r,t)}t.endCC=n[n.length-1].cc}if(!t.startCC){var o;let i=iq(e,t.startSN-1);t.startCC=null!=(o=i?.cc)?o:n[0].cc}(function(e,t,i){if(e&&t){let r=0;for(let s=0,a=e.length;s<=a;s++){let a=e[s],n=t[s+r];a&&n&&a.index===n.index&&a.fragment.sn===n.fragment.sn?i(a,n):r--}}})(e.partList,t.partList,(e,t)=>{t.elementaryStreams=e.elementaryStreams,t.stats=e.stats}),r?iK(t,r,r.startPTS,r.endPTS,r.startDTS,r.endDTS,i):iV(e,t),n.length&&(t.totalduration=t.edge-n[0].start),t.driftStartTime=e.driftStartTime,t.driftStart=e.driftStart;let h=t.advancedDateTime;if(t.advanced&&h){let e=t.edge;t.driftStart||(t.driftStartTime=h,t.driftStart=e),t.driftEndTime=h,t.driftEnd=e}else t.driftEndTime=e.driftEndTime,t.driftEnd=e.driftEnd,t.advancedDateTime=e.advancedDateTime;-1===t.requestScheduled&&(t.requestScheduled=e.requestScheduled)}(i,r,this);let e=r.playlistParsingError;if(e){this.warn(e);let i=this.hls;if(!i.config.ignorePlaylistParsingErrors){var o;let{networkDetails:a}=t;i.trigger(K.ERROR,{type:N.NETWORK_ERROR,details:G.LEVEL_PARSING_ERROR,fatal:!1,url:r.url,error:e,reason:e.message,level:t.level||void 0,parent:null==(o=r.fragments[0])?void 0:o.type,networkDetails:a,stats:s});return}r.playlistParsingError=null}}-1===r.requestScheduled&&(r.requestScheduled=s.loading.start);let f=this.hls.mainForwardBufferInfo,g=f?f.end-f.len:0,m=(r.edge-g)*1e3,p=iW(r,m);if(r.requestScheduled+p<a?r.requestScheduled=a:r.requestScheduled+=p,this.log(`live playlist ${e} ${r.advanced?"REFRESHED "+r.lastPartSn+"-"+r.lastPartIndex:r.updated?"UPDATED":"MISSED"}`),!this.canLoad||!r.live)return;if(r.canBlockReload&&r.endSN&&r.advanced){let e=this.hls.config.lowLatencyMode,s=r.lastPartSn,n=r.endSN,o=r.lastPartIndex,f=s===n;-1!==o?f?(h=n+1,d=e?0:o):(h=s,d=e?o+1:r.maxPartIndex):h=n+1;let g=r.age,m=g+r.ageHeader,p=Math.min(m-r.partTarget,1.5*r.targetduration);if(p>0){if(m>3*r.targetduration)this.log(`Playlist last advanced ${g.toFixed(2)}s ago. Omitting segment and part directives.`),h=void 0,d=void 0;else if(null!=i&&i.tuneInGoal&&m-r.partTarget>i.tuneInGoal)this.warn(`CDN Tune-in goal increased from: ${i.tuneInGoal} to: ${p} with playlist age: ${r.age}`),p=0;else{let e=Math.floor(p/r.targetduration);h+=e,void 0!==d&&(d+=Math.round(p%r.targetduration/r.partTarget)),this.log(`CDN Tune-in age: ${r.ageHeader}s last advanced ${g.toFixed(2)}s goal: ${p} skip sn ${e} to part ${d}`)}r.tuneInGoal=p}if(l=this.getDeliveryDirectives(r,t.deliveryDirectives,h,d),e||!f){r.requestScheduled=a,this.loadingPlaylist(c,l);return}}else(r.canBlockReload||r.canSkipUntil)&&(l=this.getDeliveryDirectives(r,t.deliveryDirectives,h,d));l&&void 0!==h&&r.canBlockReload&&(r.requestScheduled=s.loading.first+Math.max(p-2*n,p/2)),this.scheduleLoading(c,l,r)}else this.clearTimer()}scheduleLoading(e,t,i){let r=i||e.details;if(!r)return void this.loadingPlaylist(e,t);let s=self.performance.now(),a=r.requestScheduled;if(s>=a)return void this.loadingPlaylist(e,t);let n=a-s;this.log(`reload live playlist ${e.name||e.bitrate+"bps"} in ${Math.round(n)} ms`),this.clearTimer(),this.timer=self.setTimeout(()=>this.loadingPlaylist(e,t),n)}getDeliveryDirectives(e,t,i,r){let s=to(e);return null!=t&&t.skip&&e.deltaUpdateFailed&&(i=t.msn,r=t.part,s=""),new th(i,r,s)}checkRetry(e){let t=e.details,i=tb(e),r=e.errorAction,{action:s,retryCount:a=0,retryConfig:n}=r||{},l=!!r&&!!n&&(5===s||!r.resolved&&2===s);if(l){var o;if(a>=n.maxNumRetry)return!1;if(i&&null!=(o=e.context)&&o.deliveryDirectives)this.warn(`Retrying playlist loading ${a+1}/${n.maxNumRetry} after "${t}" without delivery-directives`),this.loadPlaylist();else{let e=t_(n,a);this.clearTimer(),this.timer=self.setTimeout(()=>this.loadPlaylist(),e),this.warn(`Retrying playlist loading ${a+1}/${n.maxNumRetry} after "${t}" in ${e}ms`)}e.levelRetry=!0,r.resolved=!0}return l}}function sv(e,t){if(e.length!==t.length)return!1;for(let i=0;i<e.length;i++)if(!sE(e[i].attrs,t[i].attrs))return!1;return!0}function sE(e,t,i){let r=e["STABLE-RENDITION-ID"];return r&&!i?r===t["STABLE-RENDITION-ID"]:!(i||["LANGUAGE","NAME","CHARACTERISTICS","AUTOSELECT","DEFAULT","FORCED","ASSOC-LANGUAGE"]).some(i=>e[i]!==t[i])}function sT(e,t){return t.label.toLowerCase()===e.name.toLowerCase()&&(!t.language||t.language.toLowerCase()===(e.lang||"").toLowerCase())}class sS{constructor(e){this.tracks=void 0,this.queues={video:[],audio:[],audiovideo:[]},this.tracks=e}destroy(){this.tracks=this.queues=null}append(e,t,i){if(null===this.queues||null===this.tracks)return;let r=this.queues[t];r.push(e),1!==r.length||i||this.executeNext(t)}appendBlocker(e){return new Promise(t=>{this.append({label:"async-blocker",execute:t,onStart:()=>{},onComplete:()=>{},onError:()=>{}},e)})}prependBlocker(e){return new Promise(t=>{this.queues&&this.queues[e].unshift({label:"async-blocker-prepend",execute:t,onStart:()=>{},onComplete:()=>{},onError:()=>{}})})}removeBlockers(){null!==this.queues&&[this.queues.video,this.queues.audio,this.queues.audiovideo].forEac
55h(e=>{var t;let i=null==(t=e[0])?void 0:t.label;("async-blocker"===i||"async-blocker-prepend"===i)&&(e[0].execute(),e.splice(0,1))})}unblockAudio(e){null!==this.queues&&this.queues.audio[0]===e&&this.shiftAndExecuteNext("audio")}executeNext(e){if(null===this.queues||null===this.tracks)return;let t=this.queues[e];if(t.length){let r=t[0];try{r.execute()}catch(s){var i;if(r.onError(s),null===this.queues||null===this.tracks)return;let t=null==(i=this.tracks[e])?void 0:i.buffer;null!=t&&t.updating||this.shiftAndExecuteNext(e)}}}shiftAndExecuteNext(e){null!==this.queues&&(this.queues[e].shift(),this.executeNext(e))}current(e){var t;return(null==(t=this.queues)?void 0:t[e][0])||null}toString(){let{queues:e,tracks:t}=this;return null===e||null===t?"<destroyed>":`
56${this.list("video")}
57${this.list("audio")}
58${this.list("audiovideo")}}`}list(e){var t,i;return null!=(t=this.queues)&&t[e]||null!=(i=this.tracks)&&i[e]?`${e}: (${this.listSbInfo(e)}) ${this.listOps(e)}`:""}listSbInfo(e){var t;let i=null==(t=this.tracks)?void 0:t[e],r=i?.buffer;return r?`SourceBuffer${r.updating?" updating":""}${i.ended?" ended":""}${i.ending?" ending":""}`:"none"}listOps(e){var t;return(null==(t=this.queues)?void 0:t[e].map(e=>e.label).join(", "))||""}}let sL=/(avc[1234]|hvc1|hev1|dvh[1e]|vp09|av01)(?:\.[^.,]+)+/,sA="HlsJsTrackRemovedError";class sR extends Error{constructor(e){super(e),this.name=sA}}function sb(e){let t=e.querySelectorAll("source");[].slice.call(t).forEach(t=>{e.removeChild(t)})}function sk(e){return+("audio"===e)}class sI{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=1/0,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(){let{hls:e}=this;e.on(K.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.on(K.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(K.MANIFEST_PARSED,this.onManifestParsed,this),e.on(K.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(K.BUFFER_CODECS,this.onBufferCodecs,this),e.on(K.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListener(){let{hls:e}=this;e.off(K.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.off(K.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(K.MANIFEST_PARSED,this.onManifestParsed,this),e.off(K.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(K.BUFFER_CODECS,this.onBufferCodecs,this),e.off(K.MEDIA_DETACHING,this.onMediaDetaching,this)}onFpsDropLevelCapping(e,t){let i=this.hls.levels[t.droppedLevel];this.isLevelAllowed(i)&&this.restrictedLevels.push({bitrate:i.bitrate,height:i.height,width:i.width})}onMediaAttaching(e,t){this.media=t.media instanceof HTMLVideoElement?t.media:null,this.clientRect=null,this.timer&&this.hls.levels.length&&this.detectPlayerSize()}onManifestParsed(e,t){let i=this.hls;this.restrictedLevels=[],this.firstLevel=t.firstLevel,i.config.capLevelToPlayerSize&&t.video&&this.startCapping()}onLevelsUpdated(e,t){this.timer&&$(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}let e=this.hls.levels;if(e.length){let t=this.hls,i=this.getMaxLevel(e.length-1);i!==this.autoLevelCapping&&t.logger.log(`Setting autoLevelCapping to ${i}: ${e[i].height}p@${e[i].bitrate} for media ${this.mediaWidth}x${this.mediaHeight}`),t.autoLevelCapping=i,t.autoLevelEnabled&&t.autoLevelCapping>this.autoLevelCapping&&this.streamController&&this.streamController.nextLevelSwitch(),this.autoLevelCapping=t.autoLevelCapping}}}getMaxLevel(e){let t=this.hls.levels;if(!t.length)return -1;let i=t.filter((t,i)=>this.isLevelAllowed(t)&&i<=e);return this.clientRect=null,sI.getMaxLevelByMediaSize(i,this.mediaWidth,this.mediaHeight)}startCapping(){this.timer||(this.autoLevelCapping=1/0,self.clearInterval(this.timer),this.timer=self.setInterval(this.detectPlayerSize.bind(this),1e3),this.detectPlayerSize())}stopCapping(){this.restrictedLevels=[],this.firstLevel=-1,this.autoLevelCapping=1/0,this.timer&&(self.clearInterval(this.timer),this.timer=void 0)}getDimensions(){if(this.clientRect)return this.clientRect;let e=this.media,t={width:0,height:0};if(e){let i=e.getBoundingClientRect();t.width=i.width,t.height=i.height,t.width||t.height||(t.width=i.right-i.left||e.
58width||0,t.height=i.bottom-i.top||e.height||0)}return this.clientRect=t,t}get mediaWidth(){return this.getDimensions().width*this.contentScaleFactor}get mediaHeight(){return this.getDimensions().height*this.contentScaleFactor}get contentScaleFactor(){let e=1;if(!this.hls.config.ignoreDevicePixelRatio)try{e=self.devicePixelRatio}catch{}return Math.min(e,this.hls.config.maxDevicePixelRatio)}isLevelAllowed(e){return!this.restrictedLevels.some(t=>e.bitrate===t.bitrate&&e.width===t.width&&e.height===t.height)}static getMaxLevelByMediaSize(e,t,i){if(!(null!=e&&e.length))return -1;let r=(e,t)=>!t||e.width!==t.width||e.height!==t.height,s=e.length-1,a=Math.max(t,i);for(let t=0;t<e.length;t+=1){let i=e[t];if((i.width>=a||i.height>=a)&&r(i,e[t+1])){s=t;break}}return s}}class sD{constructor(e,t){Array.isArray(e)&&(e=e.map(e=>e instanceof sD?e:new sD(e))),this.value=e,this.params=t}}function s_(e,t,i){return Error(`failed to serialize "${Array.isArray(e)?JSON.stringify(e):e instanceof Map?"Map{}":e instanceof Set?"Set{}":"object"==typeof e?JSON.stringify(e):String(e)}" as ${t}`,{cause:i})}class sP{constructor(e){this.description=e}}let sC="Bare Item";function sw(e){if(e<-0x38d7ea4c67fff||0x38d7ea4c67fff<e)throw s_(e,"Integer");return e.toString()}let sx=/[\x00-\x1f\x7f]+/;function sM(e){let t=e.description||e.toString().slice(7,-1);if(!1===/^([a-zA-Z*])([!#$%&'*+\-.^_`|~\w:/]*)$/.test(t))throw s_(t,"Token");return t}function sO(e){switch(typeof e){case"number":if(!$(e))throw s_(e,sC);return Number.isInteger(e)?sw(e):function(e){let t=function e(t,i){if(t<0)return-e(-t,i);let r=Math.pow(10,i);if(!(Math.abs(t*r%1-.5)<Number.EPSILON))return Math.round(t*r)/r;{let e=Math.floor(t*r);return(e%2==0?e:e+1)/r}}(e,3);if(Math.floor(Math.abs(t)).toString().length>12)throw s_(e,"Decimal");let i=t.toString();return i.includes(".")?i:`${i}.0`}(e);case"string":if(sx.test(e))throw s_(e,"String");return`"${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`;case"symbol":return sM(e);case"boolean":if("boolean"!=typeof e)throw s_(e,"Boolean");return e?"?1":"?0";case"object":if(e instanceof Date)return`@${sw(e.getTime()/1e3)}`;if(e instanceof Uint8Array){if(!1===ArrayBuffer.isView(e))throw s_(e,"Byte Sequence");return`:${btoa(String.fromCharCode(...e))}:`}if(e instanceof sP)return sM(e);default:throw s_(e,sC)}}function sF(e){if(!1===/^[a-z*][a-z0-9\-_.*]*$/.test(e))throw s_(e,"Key");return e}function s$(e){return null==e?"":Object.entries(e).map(([e,t])=>!0===t?`;${sF(e)}`:`;${sF(e)}=${sO(t)}`).join("")}function sB(e){return e instanceof sD?`${sO(e.value)}${s$(e.params)}`:sO(e)}function sU(e,t){return function(e,t={whitespace:!0}){if("object"!=typeof e||null==e)throw s_(e,"Dict");let i=e instanceof Map?e.entries():Object.entries(e),r=t?.whitespace?" ":"";return Array.from(i).map(([e,t])=>{var i;t instanceof sD||(t=new sD(t));let r=sF(e);return!0===t.value?r+=s$(t.params):(r+="=",Array.isArray(t.value)?r+=(i=t,`(${i.value.map(sB).join(" ")})${s$(i.params)}`):r+=sB(t)),r}).join(`,${r}`)}(e,t)}let sN="CMCD-Object",sG="CMCD-Request",sK="CMCD-Session",sH="CMCD-Status",sV={br:sN,ab:sN,d:sN,ot:sN,tb:sN,tpb:sN,lb:sN,tab:sN,lab:sN,url:sN,pb:sG,bl:sG,tbl:sG,dl:sG,ltc:sG,mtp:sG,nor:sG,nrr:sG,rc:sG,sn:sG,sta:sG,su:sG,ttfb:sG,ttfbb:sG,ttlb:sG,cmsdd:sG,cmsds:sG,smrt:sG,df:sG,cs:sG,ts:sG,cid:sK,pr:sK,sf:sK,sid:sK,st:sK,v:sK,msd:sK,bs:sH,bsd:sH,cdn:sH,rtp:sH,bg:sH,pt:sH,ec:sH,e:sH},sj="event",sW=e=>Math.round(e),sq=(e,t)=>Array.isArray(e)?e.map(e=>sq(e,t)):e instanceof sD&&"string"==typeof e.value?new sD(sq(e.value,t),e.params):(t.baseUrl&&(e=function(e,t){let i=new URL(e),r=new URL(t);if(i.origin!==r.origin)return e;let s=i.pathname.split("/").slice(1),a=r.pathname.split("/").slice(1,-1);for(;s[0]===a[0];)s.shift(),a.shift();for(;a.length;)a.shift(),s.unshift("..");return s.join("/")+i.search+i.hash}(e,t.baseUrl)),1===t.version?encodeURIComponent(e):e),sY=e=>100*sW(e/100),sX={br:sW,d:sW,bl:sY,dl:sY,mtp:sY,nor:(e,t)=>{let i=e;return t.version>=2&&(e instanceof sD&&"string"==typeof e.value?i=new sD([e]):"string"==typeof e&&(i=[e])),sq(i,t)},rtp:sY,tb:sW}
58,sz="request",sQ="response",sZ=["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"],sJ=["e"],s0=/^[a-zA-Z0-9-.]+-[a-zA-Z0-9-.]+$/;function s1(e){return s0.test(e)}let s2=["d","dl","nor","ot","rtp","su"],s3=["cmsdd","cmsds","rc","smrt","ttfb","ttfbb","ttlb","url"],s4=["bl","br","bs","cid","d","dl","mtp","nor","nrr","ot","pr","rtp","sf","sid","st","su","tb","v"];function s5(e){return s4.includes(e)||s1(e)}let s8={[sQ]:function(e){return sZ.includes(e)||s2.includes(e)||s3.includes(e)||s1(e)},[sj]:function(e){return sZ.includes(e)||sJ.includes(e)||s1(e)},[sz]:function(e){return sZ.includes(e)||s2.includes(e)||s1(e)}};function s6(e,t={}){let i={};if(null==e||"object"!=typeof e)return i;let r=t.version||e.v||1,s=t.reportingMode||sz,a=1===r?s5:s8[s],n=Object.keys(e).filter(a),l=t.filter;"function"==typeof l&&(n=n.filter(l));let o=s===sQ||s===sj;o&&!n.includes("ts")&&n.push("ts"),r>1&&!n.includes("v")&&n.push("v");let h=Z({},sX,t.formatters),d={version:r,reportingMode:s,baseUrl:t.baseUrl};return n.sort().forEach(t=>{var s;let a=e[t],n=h[t];if("function"==typeof n&&(a=n(a,d)),"v"===t){if(1===r)return;a=r}"pr"==t&&1===a||(o&&"ts"===t&&!$(a)&&(a=Date.now()),("number"==typeof(s=a)?$(s):null!=s&&""!==s&&!1!==s)&&(["ot","sf","st","e","sta"].includes(t)&&"string"==typeof a&&(a=new sP(a)),i[t]=a))}),i}let s9=/CMCD=[^&#]+/;function s7(e,t,i,r){e&&Object.keys(t).forEach(s=>{let a=e.filter(e=>e.groupId===s).map(e=>{let a=Z({},e);return a.details=void 0,a.attrs=new t5(a.attrs),a.url=a.attrs.URI=ae(e.url,e.attrs["STABLE-RENDITION-ID"],"PER-RENDITION-URIS",i),a.groupId=a.attrs["GROUP-ID"]=t[s],a.attrs["PATHWAY-ID"]=r,a});e.push(...a)})}function ae(e,t,i,r){let s,{HOST:a,PARAMS:n,[i]:l}=r;t&&(s=l?.[t])&&(e=s);let o=new self.URL(e);return a&&!s&&(o.host=a),n&&Object.keys(n).sort().forEach(e=>{e&&o.searchParams.set(e,n[e])}),o.href}class at extends et{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=at.CDMCleanupPromise?[at.CDMCleanupPromise]:[],this.bannedKeyIds={},this.onMediaEncrypted=e=>{let{initDataType:t,initData:i}=e,r=`"${e.type}" event: init data type: "${t}"`;if(this.debug(r),null!==i){if(!this.keyFormatPromise){let e=Object.keys(this.keySystemAccessPromises);e.length||(e=iE(this.config));let t=e.map(iv).filter(e=>!!e);this.keyFormatPromise=this.getKeyFormatPromise(t)}this.keyFormatPromise.then(s=>{let a,n=iy(s);if("sinf"!==t||n!==ih)return void this.log(`Ignoring "${e.type}" event with init data type: "${t}" for selected key-system ${n}`);try{let e=ex(new Uint8Array(i)),t=ii(JSON.parse(e).sinf),r=ej(t);if(!r)throw Error("'schm' box missing or not cbcs/cenc with schi > tenc");a=new Uint8Array(r.subarray(8,24))}catch(e){this.warn(`${r} Failed to parse sinf: ${e}`);return}let l=ed(a),{keyIdToKeySessionPromise:o,mediaKeySessions:h}=this,d=o[l];for(let e=0;e<h.length;e++){let r=h[e],s=r.decryptdata;if(!s.keyId)continue;let n=ed(s.keyId);if(t9(a,s.keyId)||-1!==s.uri.replace(/-/g,"").indexOf(l)){if(!(d=o[n]))continue;if(s.pssh)break;delete o[n],s.pssh=new Uint8Array(i),s.keyId=a,(d=o[l]=d.then(()=>this.generateRequestWithPreferredKeySession(r,t,i,"encrypted-event-key-match"))).catch(e=>this.handleError(e));break}}d||this.handleError(Error(`Key ID ${l} not encountered in playlist. Key-system sessions ${h.length}.`))}).catch(e=>this.handleError(e))}},this.onWaitingForKey=e=>{this.log(`"${e.type}" event`)},this.hls=e,this.config=e.config,this.registerListeners()}destroy(){this.onDestroying(),this.onMediaDetached();let 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}
58registerListeners(){this.hls.on(K.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.on(K.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.on(K.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.on(K.MANIFEST_LOADED,this.onManifestLoaded,this),this.hls.on(K.DESTROYING,this.onDestroying,this)}unregisterListeners(){this.hls.off(K.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.off(K.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.off(K.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.off(K.MANIFEST_LOADED,this.onManifestLoaded,this),this.hls.off(K.DESTROYING,this.onDestroying,this)}getLicenseServerUrl(e){let{drmSystems:t,widevineLicenseUrl:i}=this.config,r=t?.[e];return r?r.licenseUrl:e===iu&&i?i:void 0}getLicenseServerUrlOrThrow(e){let t=this.getLicenseServerUrl(e);if(void 0===t)throw Error(`no license server URL configured for key-system "${e}"`);return t}getServerCertificateUrl(e){let{drmSystems:t}=this.config,i=t?.[e];if(i)return i.serverCertificateUrl;this.log(`No Server Certificate in config.drmSystems["${e}"]`)}attemptKeySystemAccess(e){let t=this.hls.levels,i=(e,t,i)=>!!e&&i.indexOf(e)===t,r=t.map(e=>e.audioCodec).filter(i),s=t.map(e=>e.videoCodec).filter(i);return r.length+s.length===0&&s.push("avc1.42e01e"),new Promise((t,i)=>{let a=e=>{let n=e.shift();this.getMediaKeysPromise(n,r,s).then(e=>t({keySystem:n,mediaKeys:e})).catch(t=>{e.length?a(e):t instanceof ar?i(t):i(new ar({type:N.KEY_SYSTEM_ERROR,details:G.KEY_SYSTEM_NO_ACCESS,error:t,fatal:!0},t.message))})};a(e)})}requestMediaKeySystemAccess(e,t){let{requestMediaKeySystemAccessFunc:i}=this.config;if("function"!=typeof i){let e=`Configured requestMediaKeySystemAccess is not a function ${i}`;return null===iT&&"http:"===self.location.protocol&&(e=`navigator.requestMediaKeySystemAccess is not available over insecure protocol ${location.protocol}`),Promise.reject(Error(e))}return i(e,t)}getMediaKeysPromise(e,t,i){var r;let s=function(e,t,i,r){var s,a,n,l;let o;switch(e){case ih:o=["cenc","sinf"];break;case iu:case id:o=["cenc"];break;case io:o=["cenc","keyids"];break;default:throw Error(`Unknown key-system: ${e}`)}return s=o,a=t,n=i,[{initDataTypes:s,persistentState:(l=r).persistentState||"optional",distinctiveIdentifier:l.distinctiveIdentifier||"optional",sessionTypes:l.sessionTypes||[l.sessionType||"temporary"],audioCapabilities:a.map(e=>({contentType:`audio/mp4; codecs=${e}`,robustness:l.audioRobustness||"",encryptionScheme:l.audioEncryptionScheme||null})),videoCapabilities:n.map(e=>({contentType:`video/mp4; codecs=${e}`,robustness:l.videoRobustness||"",encryptionScheme:l.videoEncryptionScheme||null}))}]}(e,t,i,this.config.drmSystemOptions||{}),a=this.keySystemAccessPromises[e],n=null==(r=a)?void 0:r.keySystemAccess;if(!n){this.log(`Requesting encrypted media "${e}" key-system access with config: ${tc(s)}`),n=this.requestMediaKeySystemAccess(e,s);let t=a=this.keySystemAccessPromises[e]={keySystemAccess:n};return n.catch(t=>{this.log(`Failed to obtain access to key-system "${e}": ${t}`)}),n.then(i=>{this.log(`Access for key-system "${i.keySystem}" obtained`);let r=this.fetchServerCertificate(e);this.log(`Create media-keys for "${e}"`);let s=t.mediaKeys=i.createMediaKeys().then(i=>(this.log(`Media-keys created for "${e}"`),t.hasMediaKeys=!0,r.then(t=>t?this.setMediaKeysServerCertificate(i,e,t):i)));return s.catch(t=>{this.error(`Failed to create media-keys for "${e}"}: ${t}`)}),s})}return n.then(()=>a.mediaKeys)}createMediaKeySessionContext({decryptdata:e,keySystem:t,mediaKeys:i}){this.log(`Creating key-system session "${t}" keyId: ${ed(e.keyId||[])} keyUri: ${e.uri}`);let r=i.createSession(),s={decryptdata:e,keySystem:t,mediaKeys:i,mediaKeysSession:r,keyStatus:"status-pending"};return this.mediaKeySessions.push(s),s}renewKeySession(e){let t=e.decryptdata;if(t.pssh){let i=this.createMediaKeySessionContext(e),r=ai(t);this.keyIdToKeySessionPromise[r]=this.generateRequestWithPreferredKeySession(i,"cenc",t.pssh.buffer,"expired")}else this.warn("Could not renew expired session. Missing pssh initData.");this.removeSession(e)}updateKeySession(e,t){let i=e.mediaKeysSession;return this.log(`Updating key-session "${i.sessionId}" for keyId ${ed(e.decryptdata.keyId||[])}
59      } (data length: ${t.byteLength})`),i.update(t)}getSelectedKeySystemFormats(){return Object.keys(this.keySystemAccessPromises).map(e=>({keySystem:e,hasMediaKeys:this.keySystemAccessPromises[e].hasMediaKeys})).filter(({hasMediaKeys:e})=>!!e).map(({keySystem:e})=>iv(e)).filter(e=>!!e)}getKeySystemAccess(e){return this.getKeySystemSelectionPromise(e).then(({keySystem:e,mediaKeys:t})=>this.attemptSetMediaKeys(e,t))}selectKeySystem(e){return new Promise((t,i)=>{this.getKeySystemSelectionPromise(e).then(({keySystem:e})=>{let r=iv(e);r?t(r):i(Error(`Unable to find format for key-system "${e}"`))}).catch(i)})}selectKeySystemFormat(e){let 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){let t=iE(this.config),i=e.map(iy).filter(e=>!!e&&-1!==t.indexOf(e));return this.selectKeySystem(i)}getKeyStatus(e){let{mediaKeySessions:t}=this;for(let s=0;s<t.length;s++){var i,r;let a=(i=e,r=t[s],i.keyId&&r.mediaKeysSession.keyStatuses.has(i.keyId)?r.mediaKeysSession.keyStatuses.get(i.keyId):i.matches(r.decryptdata)?r.keyStatus:void 0);if(a)return a}}loadKey(e){let t=e.keyInfo.decryptdata,i=ai(t),r=this.bannedKeyIds[i];if(r||"internal-error"===this.getKeyStatus(t)){let i=as(r||"internal-error",t);return this.handleError(i,e.frag),Promise.reject(i)}let s=`(keyId: ${i} format: "${t.keyFormat}" method: ${t.method} uri: ${t.uri})`;this.log(`Starting session for key ${s}`);let a=this.keyIdToKeySessionPromise[i];if(!a){let r=this.getKeySystemForKeyPromise(t).then(({keySystem:i,mediaKeys:r})=>(this.throwIfDestroyed(),this.log(`Handle encrypted media sn: ${e.frag.sn} ${e.frag.type}: ${e.frag.level} using key ${s}`),this.attemptSetMediaKeys(i,r).then(()=>(this.throwIfDestroyed(),this.createMediaKeySessionContext({keySystem:i,mediaKeys:r,decryptdata:t}))))).then(e=>{let i=t.pssh?t.pssh.buffer:null;return this.generateRequestWithPreferredKeySession(e,"cenc",i,"playlist-key")});return r.catch(t=>this.handleError(t,e.frag)),this.keyIdToKeySessionPromise[i]=r,r}return a.catch(i=>{if(i instanceof ar){let r=ee({},i.data);"internal-error"===this.getKeyStatus(t)&&(r.decryptdata=t);let s=new ar(r,i.message);this.handleError(s,e.frag)}}),a}throwIfDestroyed(e="Invalid state"){if(!this.hls)throw Error("invalid state")}handleError(e,t){if(this.hls)if(e instanceof ar){t&&(e.data.frag=t);let i=e.data.decryptdata;this.error(`${e.message}${i?` (${ed(i.keyId||[])})`:""}`),this.hls.trigger(K.ERROR,e.data)}else this.error(e.message),this.hls.trigger(K.ERROR,{type:N.KEY_SYSTEM_ERROR,details:G.KEY_SYSTEM_NO_KEYS,error:e,fatal:!0})}
59getKeySystemForKeyPromise(e){let t=ai(e),i=this.keyIdToKeySessionPromise[t];if(!i){let t=iy(e.keyFormat),i=t?[t]:iE(this.config);return this.attemptKeySystemAccess(i)}return i}getKeySystemSelectionPromise(e){if(e.length||(e=iE(this.config)),0===e.length)throw new ar({type:N.KEY_SYSTEM_ERROR,details:G.KEY_SYSTEM_NO_CONFIGURED_LICENSE,fatal:!0},`Missing key-system license configuration options ${tc({drmSystems:this.config.drmSystems})}`);return this.attemptKeySystemAccess(e)}attemptSetMediaKeys(e,t){if(this.mediaResolved=void 0,this.mediaKeys===t)return Promise.resolve();let i=this.setMediaKeysQueue.slice();this.log(`Setting media-keys for "${e}"`);let r=Promise.all(i).then(()=>this.media?this.media.setMediaKeys(t):new Promise((e,i)=>{this.mediaResolved=()=>{if(this.mediaResolved=void 0,!this.media)return i(Error("Attempted to set mediaKeys without media element attached"));this.mediaKeys=t,this.media.setMediaKeys(t).then(e).catch(i)}}));return this.mediaKeys=t,this.setMediaKeysQueue.push(r),r.then(()=>{this.log(`Media-keys set for "${e}"`),i.push(r),this.setMediaKeysQueue=this.setMediaKeysQueue.filter(e=>-1===i.indexOf(e))})}generateRequestWithPreferredKeySession(e,t,i,r){var s;let a=null==(s=this.config.drmSystems)||null==(s=s[e.keySystem])?void 0:s.generateRequest;if(a)try{let r=a.call(this.hls,t,i,e);if(!r)throw Error("Invalid response from configured generateRequest filter");t=r.initDataType,i=r.initData?r.initData:null,e.decryptdata.pssh=i?new Uint8Array(i):null}catch(e){if(this.warn(e.message),this.hls&&this.hls.config.debug)throw e}if(null===i)return this.log(`Skipping key-session request for "${r}" (no initData)`),Promise.resolve(e);let n=ai(e.decryptdata),l=e.decryptdata.uri;this.log(`Generating key-session request for "${r}" keyId: ${n} URI: ${l} (init data type: ${t} length: ${i.byteLength})`);let o=new rg,h=e._onmessage=t=>{let i=e.mediaKeysSession;if(!i)return void o.emit("error",Error("invalid state"));let{messageType:r,message:s}=t;this.log(`"${r}" message event for session "${i.sessionId}" message size: ${s.byteLength}`),"license-request"===r||"license-renewal"===r?this.renewLicense(e,s).catch(e=>
59{o.eventNames().length?o.emit("error",e):this.handleError(e)}):"license-release"===r?e.keySystem===ih&&this.updateKeySession(e,ir("acknowledged")).then(()=>this.removeSession(e)).catch(e=>this.handleError(e)):this.warn(`unhandled media key message type "${r}"`)},d=(e,t)=>{let i;t.keyStatus=e,e.startsWith("usable")?o.emit("resolved"):"internal-error"===e||"output-restricted"===e||"output-downscaled"===e?i=as(e,t.decryptdata):"expired"===e?i=Error(`key expired (keyId: ${n})`):"released"===e?i=Error("key released"):"status-pending"===e||this.warn(`unhandled key status change "${e}" (keyId: ${n})`),i&&(o.eventNames().length?o.emit("error",i):this.handleError(i))},c=e._onkeystatuseschange=t=>{if(!e.mediaKeysSession)return void o.emit("error",Error("invalid state"));let i=this.getKeyStatuses(e);if(!Object.keys(i).some(e=>"status-pending"!==i[e]))return;if("expired"===i[n]){this.log(`Expired key ${tc(i)} in key-session "${e.mediaKeysSession.sessionId}"`),this.renewKeySession(e);return}let r=i[n];if(r)d(r,e);else{var s;e.keyStatusTimeouts||(e.keyStatusTimeouts={}),(s=e.keyStatusTimeouts)[n]||(s[n]=self.setTimeout(()=>{if(!e.mediaKeysSession||!this.mediaKeys)return;let t=this.getKeyStatus(e.decryptdata);if(t&&"status-pending"!==t)return this.log(`No status for keyId ${n} in key-session "${e.mediaKeysSession.sessionId}". Using session key-status ${t} from other session.`),d(t,e);this.log(`key status for ${n} in key-session "${e.mediaKeysSession.sessionId}" timed out after 1000ms`),d(r="internal-error",e)},1e3)),this.log(`No status for keyId ${n} (${tc(i)}).`)}};i3(e.mediaKeysSession,"message",h),i3(e.mediaKeysSession,"keystatuseschange",c);let f=new Promise((e,t)=>{o.on("error",t),o.on("resolved",e)});return e.mediaKeysSession.generateRequest(t,i).then(()=>{this.log(`Request generated for key-session "${e.mediaKeysSession.sessionId}" keyId: ${n} URI: ${l}`)}).catch(t=>{throw new ar({type:N.KEY_SYSTEM_ERROR,details:G.KEY_SYSTEM_NO_SESSION,error:t,decryptdata:e.decryptdata,fatal:!1},`Error generating key-session request: ${t}`)}).then(()=>f).catch(t=>(o.removeAllListeners(),this.removeSession(e).then(()=>{throw t}))).then(()=>(o.removeAllListeners(),e))}getKeyStatuses(e){let t={};return e.mediaKeysSession.keyStatuses.forEach((i,r)=>{if("string"==typeof r&&"object"==typeof i){let e=r;r=i,i=e}let s="buffer"in r?new Uint8Array(r.buffer,r.byteOffset,r.byteLength):new Uint8Array(r);e.keySystem===id&&16===s.length&&(t[ed(s)]=i,is(s));let a=ed(s);"internal-error"===i&&(this.bannedKeyIds[a]=i),this.log(`key status change "${i}" for keyStatuses keyId: ${a} key-session "${e.mediaKeysSession.sessionId}"`),t[a]=i}),t}fetchServerCertificate(e){let t=this.config,i=new t.loader(t),r=this.getServerCertificateUrl(e);return r?(this.log(`Fetching server certificate for "${e}"`),new Promise((s,a)=>{let n={responseType:"arraybuffer",url:r},l=t.certLoadPolicy.default,o={loadPolicy:l,timeout:l.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0};i.load(n,o,{onSuccess:(e,t,i,r)=>{s(e.data)},onError:(t,i,s,l)=>{a(new ar({type:N.KEY_SYSTEM_ERROR,details:G.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:s,response:ee({url:n.url,data:void 0},t)},`"${e}" certificate request failed (${r}). Status: ${t.code} (${t.text})`))},onTimeout:(t,i,s)=>{a(new ar({type:N.KEY_SYSTEM_ERROR,details:G.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:s,response:{url:n.url,data:void 0}},`"${e}" certificate request timed out (${r})`))},onAbort:(e,t,i)=>{a(Error("aborted"))}})})):Promise.resolve()}setMediaKeysServerCertificate(e,t,i){return new Promise((r,s)=>{e.setServerCertificate(i).then(s=>{this.log(`setServerCertificate ${s?"success":"not supported by CDM"} (${i.byteLength}) on "${t}"`),r(e)}).catch(e=>{s(new ar({type:N.KEY_SYSTEM_ERROR,details:G.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED,error:e,fatal:!0},e.message))})})}renewLicense(e,t){return this.requestLicense(e,new Uint8Array(t)).then(t=>this.updateKeySession(e,new Uint8Array(t)).catch(t=>{throw new ar({type:N.KEY_SYSTEM_ERROR,details:G.KEY_SYSTEM_SESSION_UPDATE_FAILED,decryptdata:e.decryptdata,error:t,fatal:!1},t.message)}))}unpackPlayReadyKeyMessage(e,t){let i=String.fromCharCode.apply(null,new Uint16Array(t.buffer));if(!i.includes("PlayReadyKeyMessage"))return e.setRequestHeader("Content-Type","text/xml; charset=utf-8"),t;let r=new DOMParser().parseFromString(i,"application/xml"),s=r.querySelectorAll("HttpHeader");if(s.length>0){let t;for(let i=0,r=s.length;i<r;i++){var a,n;let r=null==(a=(t=s[i]).querySelector("name"))?void 0:a.textContent,l=null==(n=t.querySelector("value"))?void 0:n.textContent;r&&l&&e.setRequestHeader(r,l)}}let l=r.querySelector("Challenge"),o=l?.textContent;
59if(!o)throw Error("Cannot find <Challenge> in key message");return ir(atob(o))}setupLicenseXHR(e,t,i,r){let s=this.config.licenseXhrSetup;return s?Promise.resolve().then(()=>{if(!i.decryptdata)throw Error("Key removed");return s.call(this.hls,e,t,i,r)}).catch(a=>{if(!i.decryptdata)throw a;return e.open("POST",t,!0),s.call(this.hls,e,t,i,r)}).then(i=>(e.readyState||e.open("POST",t,!0),{xhr:e,licenseChallenge:i||r})):(e.open("POST",t,!0),Promise.resolve({xhr:e,licenseChallenge:r}))}requestLicense(e,t){let i=this.config.keyLoadPolicy.default;return new Promise((r,s)=>{let a=this.getLicenseServerUrlOrThrow(e.keySystem);this.log(`Sending license request to URL: ${a}`);let n=new XMLHttpRequest;n.responseType="arraybuffer",n.onreadystatechange=()=>{if(!this.hls||!e.mediaKeysSession)return s(Error("invalid state"));if(4===n.readyState)if(200===n.status){this._requestLicenseFailureCount=0;let t=n.response;this.log(`License received ${t instanceof ArrayBuffer?t.byteLength:t}`);let i=this.config.licenseResponseCallback;if(i)try{t=i.call(this.hls,n,a,e)}catch(e){this.error(e)}r(t)}else{let l=i.errorRetry,o=l?l.maxNumRetry:0;if(this._requestLicenseFailureCount++,this._requestLicenseFailureCount>o||n.status>=400&&n.status<500)s(new ar({type:N.KEY_SYSTEM_ERROR,details:G.KEY_SYSTEM_LICENSE_REQUEST_FAILED,decryptdata:e.decryptdata,fatal:!0,networkDetails:n,response:{url:a,data:void 0,code:n.status,text:n.statusText}},`License Request XHR failed (${a}). Status: ${n.status} (${n.statusText})`));else{let i=o-this._requestLicenseFailureCount+1;this.warn(`Retrying license request, ${i} attempts left`),this.requestLicense(e,t).then(r,s)}}},e.licenseXhr&&e.licenseXhr.readyState!==XMLHttpRequest.DONE&&e.licenseXhr.abort(),e.licenseXhr=n,this.setupLicenseXHR(n,a,e,t).then(({xhr:t,licenseChallenge:i})=>{e.keySystem==id&&(i=this.unpackPlayReadyKeyMessage(t,i)),t.send(i)}).catch(s)})}onDestroying(){this.unregisterListeners(),this._clear()}onMediaAttached(e,t){if(!this.config.emeEnabled)return;let i=t.media;this.media=i,i3(i,"encrypted",this.onMediaEncrypted),i3(i,"waitingforkey",this.onWaitingForKey);let r=this.mediaResolved;r?r():this.mediaKeys=i.mediaKeys}onMediaDetached(){let e=this.media;e&&(i4(e,"encrypted",this.onMediaEncrypted),i4(e,"waitingforkey",this.onWaitingForKey),this.media=null,this.mediaKeys=null)}_clear(){var e;this._requestLicenseFailureCount=0,this.keyIdToKeySessionPromise={},this.bannedKeyIds={};let t=this.mediaResolved;if(t&&t(),!this.mediaKeys&&!this.mediaKeySessions.length)return;let i=this.media,r=this.mediaKeySessions.slice();this.mediaKeySessions=[],this.mediaKeys=null,iA.clearKeyUriToKeyIdMap();let s=r.length;at.CDMCleanupPromise=Promise.all(r.map(e=>this.removeSession(e)).concat((null==i||null==(e=i.setMediaKeys(null))?void 0:e.catch(e=>{this.log(`Could not clear media keys: ${e}`),this.hls&&this.hls.trigger(K.ERROR,{type:N.OTHER_ERROR,details:G.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR,fatal:!1,error:Error(`Could not clear media keys: ${e}`)})}))||Promise.resolve())).catch(e=>{this.log(`Could not close sessions and clear media keys: ${e}`),this.hls&&this.hls.trigger(K.ERROR,{type:N.OTHER_ERROR,details:G.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:Error(`Could not close sessions and clear media keys: ${e}`)})}).then(()=>{s&&this.log("finished closing key sessions and clearing media keys")})}onManifestLoading(){this._clear()}onManifestLoaded(e,{sessionKeys:t}){if(!(!t||!this.config.emeEnabled)&&!this.keyFormatPromise){let e=t.reduce((e,t)=>(-1===e.indexOf(t.keyFormat)&&e.push(t.keyFormat),e),[]);this.log(`Selecting key-system from session-keys ${e.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(e)}}removeSession(e){let{mediaKeysSession:t,licenseXhr:i,decryptdata:r}=e;if(t){var s;this.log(`Remove licenses and keys and close session "${t.sessionId}" keyId: ${ed(r?.keyId||[])}`),e._onmessage&&(t.removeEventListener("message",e._onmessage),e._onmessage=void 0),e._onkeystatuseschange&&(t.removeEventListener("keystatuseschange",e._onkeystatuseschange),e._onkeystatuseschange=void 0),i&&i.readyState!==XMLHttpRequest.DONE&&i.abort(),e.mediaKeysSession=e.decryptdata=e.licenseXhr=void 0;let a=this.mediaKeySessions.indexOf(e);a>-1&&this.mediaKeySessions.splice(a,1);let{keyStatusTimeouts:n}=e;
59n&&Object.keys(n).forEach(e=>self.clearTimeout(n[e]));let{drmSystemOptions:l}=this.config;return(l&&("persistent-license"===l.sessionType||null!=(s=l.sessionTypes)&&s.some(e=>"persistent-license"===e))?new Promise((e,i)=>{self.setTimeout(()=>i(Error("MediaKeySession.remove() timeout")),8e3),t.remove().then(e).catch(i)}):Promise.resolve()).catch(e=>{this.log(`Could not remove session: ${e}`),this.hls&&this.hls.trigger(K.ERROR,{type:N.OTHER_ERROR,details:G.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR,fatal:!1,error:Error(`Could not remove session: ${e}`)})}).then(()=>t.close()).catch(e=>{this.log(`Could not close session: ${e}`),this.hls&&this.hls.trigger(K.ERROR,{type:N.OTHER_ERROR,details:G.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:Error(`Could not close session: ${e}`)})})}return Promise.resolve()}}function ai(e){if(!e)throw Error("Could not read keyId of undefined decryptdata");if(null===e.keyId)throw Error("keyId is null");return ed(e.keyId)}at.CDMCleanupPromise=void 0;class ar extends Error{constructor(e,t){super(t),this.data=void 0,e.error||(e.error=Error(t)),this.data=e,e.err=e.error}}function as(e,t){let i="output-restricted"===e,r=i?G.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:G.KEY_SYSTEM_STATUS_INTERNAL_ERROR;return new ar({type:N.KEY_SYSTEM_ERROR,details:r,fatal:!1,decryptdata:t},i?"HDCP level output restricted":`key status changed to "${e}"`)}function aa(e,t){let i;try{i=new Event("addtrack")}catch{(i=document.createEvent("Event")).initEvent("addtrack",!1,!1)}i.track=e,t.dispatchEvent(i)}function an(e,t){let i=e.mode;if("disabled"===i&&(e.mode="hidden"),e.cues&&!e.cues.getCueById(t.id))try{if(e.addCue(t),!e.cues.getCueById(t.id))throw Error(`addCue is failed for: ${t}`)}catch(i){en.debug(`[texttrack-utils]: ${i}`);try{let i=new self.TextTrackCue(t.startTime,t.endTime,t.text);i.id=t.id,e.addCue(i)}catch(e){en.debug(`[texttrack-utils]: Legacy TextTrackCue fallback failed: ${e}`)}}"disabled"===i&&(e.mode=i)}function al(e,t){let i=e.mode;if("disabled"===i&&(e.mode="hidden"),e.cues)for(let i=e.cues.length;i--;)t&&e.cues[i].removeEventListener("enter",t),e.removeCue(e.cues[i]);"disabled"===i&&(e.mode=i)}function ao(e,t,i,r){let s=e.mode;if("disabled"===s&&(e.mode="hidden"),e.cues&&e.cues.length>0){let s=function(e,t,i){let r=[],s=function(e,t){if(t<=e[0].startTime)return 0;let i=e.length-1;if(t>e[i].endTime)return -1;let r=0,s=i,a;for(;r<=s;)if(t<e[a=Math.floor((s+r)/2)].startTime)s=a-1;else{if(!(t>e[a].startTime)||!(r<i))return a;r=a+1}return e[r].startTime-t<t-e[s].startTime?r:s}(e,t);if(s>-1)for(let a=s,n=e.length;a<n;a++){let s=e[a];if(s.startTime>=t&&s.endTime<=i)r.push(s);else if(s.startTime>i)break}return r}(e.cues,t,i);for(let t=0;t<s.length;t++)(!r||r(s[t]))&&e.removeCue(s[t])}"disabled"===s&&(e.mode=s)}function ah(e){let t=[];for(let i=0;i<e.length;i++){let r=e[i];("subtitles"===r.kind||"captions"===r.kind)&&r.label&&t.push(e[i])}return t}function ad(e){let t=5381,i=e.length;for(;i;)t=33*t^e.charCodeAt(--i);return(t>>>0).toString()}let au=((a={})[a.Point=0]="Point",a[a.Range=1]="Range",a);class ac{constructor(e,t){this.base=void 0,this._duration=null,this._timelineStart=null,this.appendInPlaceDisabled=void 0,this.appendInPlaceStarted=void 0,this.dateRange=void 0,this.hasPlayed=!1,this.cumulativeDuration=0,this.resumeOffset=NaN,this.playoutLimit=NaN,this.restrictions={skip:!1,jump:!1},this.snapOptions={out:!1,in:!1},this.assetList=[],this.assetListLoader=void 0,this.assetListResponse=null,this.resumeAnchor=void 0,this.error=void 0,this.resetOnResume=void 0,this.base=t,this.dateRange=e,this.setDateRange(e)}setDateRange(e){this.dateRange=e,this.resumeOffset=e.attr.optionalFloat("X-RESUME-OFFSET",this.resumeOffset),this.playoutLimit=e.attr.optionalFloat("X-PLAYOUT-LIMIT",this.playoutLimit),this.restrictions=e.attr.enumeratedStringList("X-RESTRICT",this.restrictions),this.snapOptions=e.attr.enumeratedStringList("X-SNAP",this.snapOptions)}reset(){var e;this.appendInPlaceStarted=!1,null==(e=this.assetListLoader)||e.destroy(),this.assetListLoader=void 0,this.supplementsPrimary||(this.assetListResponse=null,this.assetList=[],this._duration=null)}isAssetPastPlayoutLimit(e){var t;if(e>0&&e>=this.assetList.length)return!0;let i=this.playoutLimit;return!(e<=0||isNaN(i))&&(0===i||((null==(t=this.assetList[e])?void 0:t.startOffset)||0)>i)}findAssetIndex(e){return this.assetList.indexOf(e)}get identifier(){return this.dateRange.id}get startDate(){return this.dateRange.startDate}get startTime(){let e=this.dateRange.startTime;if(this.snapOptions.out){let t=this.dateRange.tagAnchor;if(t)return af(e,t)}return e}get startOffset(){return this.cue.pre?0:this.startTime}get startIsAligned(){if(0===this.startTime||this.snapOptions.out)return!0;let e=this.dateRange.tagAnchor;if(e){let t=this.dateRange.startTime,i=af(t,e);return t-i<.1}return!1}get resumptionOffset(){let e=this.resumeOffset,t=$(e)?e:this.duration;return this.cumulativeDuration+t}get resumeTime(){let e=this.startOffset+this.resumptionOffset;if(this.snapOptions.in){let t=this.resumeAnchor;if(t)return af(e,t)}return e}get appendInPlace(){return!!this.appendInPlaceStarted||!this.appendInPlaceDisabled&&!!(!this.cue.once&&!this.cue.pre&&this.startIsAligned&&(isNaN(this.playoutLimit)&&isNaN(this.resumeOffset)||this.resumeOffset&&this.duration&&.025>Math.abs(this.resumeOffset-this.duration)))}set appendInPlace(e){if(this.appendInPlaceStarted){this.resetOnResume=!e;return}this.appendInPlaceDisabled=!e}get timelineStart(){return null!==this._timelineStart?this._timelineStart:this.startTime}set timelineStart(e){this._timelineStart=e}get duration(){let e,t=this.playoutLimit;return e=null!==this._duration?this._duration:this.dateRange.duration?this.dateRange.duration:this.dateRange.plannedDuration||0,!isNaN(t)&&t<e&&(e=t),e}set duration(e){this._duration=e}get cue(){return this.dateRange.cue}get timelineOccupancy(){return"RANGE"===this.dateRange.attr["X-TIMELINE-OCCUPIES"]?au.Range:au.Point}get supplementsPrimary(){return"PRIMARY"===this.dateRange.attr["X-TIMELINE-STYLE"]}get contentMayVary(){return"NO"!==this.dateRange.attr["X-CONTENT-MAY-VARY"]}get assetUrl(){return this.dateRange.attr["X-ASSET-URI"]}get assetListUrl(){return this.dateRange.attr["X-ASSET-LIST"]}get baseUrl(){return this.base.url}get assetListLoaded(){return this.assetList.length>0||null!==this.assetListResponse}toString(){var e;return e=this,`["${e.identifier}" ${e.cue.pre?"<pre>":e.cue.post?"<post>":""}${e.timelineStart.toFixed(2)}-${e.resumeTime.toFixed(2)}]`}}function af(e,t){return e-t.start<t.duration/2&&!(.025>Math.abs(e-(t.start+t.duration)))?t.start:t.start+t.duration}function ag(e,t,i){let r=new self.URL(e,i);return"data:"!==r.protocol&&r.searchParams.set("_HLS_primary_id",t),r}function am(e,t){for(;null!=(i=e.assetList[++t])&&i.error;)var i;return t}function ap(e){let t=e.timelineStart,i=e.duration||0;return`["${e.identifier}" ${t.toFixed(2)}-${(t+i).toFixed(2)}]`}class ay{constructor(e,t,i,r){this.hls=void 0,this.interstitial=void 0,this.assetItem=void 0,this.tracks=null,this.hasDetail
59s=!1,this.mediaAttached=null,this._currentTime=void 0,this._bufferedEosTime=void 0,this.checkPlayout=()=>{this.reachedPlayout(this.currentTime)&&this.hls&&this.hls.trigger(K.PLAYOUT_LIMIT_REACHED,{})};const s=this.hls=new e(t);this.interstitial=i,this.assetItem=r;const a=()=>{this.hasDetails=!0};s.once(K.LEVEL_LOADED,a),s.once(K.AUDIO_TRACK_LOADED,a),s.once(K.SUBTITLE_TRACK_LOADED,a),s.on(K.MEDIA_ATTACHING,(e,{media:t})=>{this.removeMediaListeners(),this.mediaAttached=t,this.interstitial.playoutLimit&&(t.addEventListener("timeupdate",this.checkPlayout),this.appendInPlace&&s.on(K.BUFFER_APPENDED,()=>{let e=this.bufferedEnd;this.reachedPlayout(e)&&(this._bufferedEosTime=e,s.trigger(K.BUFFERED_TO_END,void 0))}))})}get appendInPlace(){return this.interstitial.appendInPlace}loadSource(){let 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=ag(t,e.config.primarySessionId||"").href}catch{}e.loadSource(t)}}bufferedInPlaceToEnd(e){var t;if(!this.appendInPlace)return!1;if(null!=(t=this.hls)&&t.bufferedToEnd)return!0;if(!e)return!1;let i=Math.min(this._bufferedEosTime||1/0,this.duration),r=this.timelineOffset,s=tJ.bufferInfo(e,r,0);return this.getAssetTime(s.end)>=i-.02}reachedPlayout(e){let t=this.interstitial.playoutLimit;return this.startOffset+e>=t}get destroyed(){var e;return!(null!=(e=this.hls)&&e.userConfig)}get assetId(){return this.assetItem.identifier}get interstitialId(){return this.assetItem.parentIdentifier}get media(){var e;return(null==(e=this.hls)?void 0:e.media)||null}get bufferedEnd(){let e=this.media||this.mediaAttached;if(!e)return this._bufferedEosTime?this._bufferedEosTime:this.currentTime;let t=tJ.bufferInfo(e,e.currentTime,.001);return this.getAssetTime(t.end)}get currentTime(){let e=this.media||this.mediaAttached;return e?this.getAssetTime(e.currentTime):this._currentTime||0}get duration(){let e=this.assetItem.duration;if(!e)return 0;let t=this.interstitial.playoutLimit;if(t){let i=t-this.startOffset;if(i>0&&i<e)return i}return e}get remaining(){let e=this.duration;return e?Math.max(0,e-this.currentTime):0}get startOffset(){return this.assetItem.startOffset}get timelineOffset(){var e;return(null==(e=this.hls)?void 0:e.config.timelineOffset)||0}set timelineOffset(e){let t=this.timelineOffset;if(e!==t&&Math.abs(e-t)>1/9e4&&this.hls){if(this.hasDetails)throw Error("Cannot set timelineOffset after playlists are loaded");this.hls.config.timelineOffset=e}}getAssetTime(e){return Math.min(Math.max(0,e-this.timelineOffset),this.duration)}removeMediaListeners(){let e=this.mediaAttached;e&&(this._currentTime=e.currentTime,this.bufferSnapShot(),e.removeEventListener("timeupdate",this.checkPlayout))}bufferSnapShot(){if(this.mediaAttached){var e;null!=(e=this.hls)&&e.bufferedToEnd&&(this._bufferedEosTime=this.bufferedEnd)}}destroy(){this.removeMediaListeners(),this.hls&&this.hls.destroy(),this.hls=null,this.tracks=this.mediaAttached=this.checkPlayout=null}attachMedia(e){var t;this.loadSource(),null==(t=this.hls)||t.attachMedia(e)}detachMedia(){var e;this.removeMediaListeners(),this.mediaAttached=null,null==(e=this.hls)||e.detachMedia()}resumeBuffering(){var e;null==(e=this.hls)||e.resumeBuffering()}pauseBuffering(){var e;null==(e=this.hls)||e.pauseBuffering()}transferMedia(){var e;return this.bufferSnapShot(),(null==(e=this.hls)?void 0:e.transferMedia())||null}resetDetails(){let e=this.hls;if(e&&this.hasDetails){e.stopLoad();let t=e=>delete e.details;e.levels.forEach(t),e.allAudioTracks.forEach(t),e.allSubtitleTracks.forEach(t),this.hasDetails=!1}}on(e,t,i){var r;null==(r=this.hls)||r.on(e,t)}once(e,t,i){var r;null==(r=this.hls)||r.once(e,t)}off(e,t,i){var r;null==(r=this.hls)||r.off(e,t)}toString(){var e;return`HlsAssetPlayer: ${ap(this.assetItem)} ${null==(e=this.hls)?void 0:e.sessionId} ${this.appendInPlace?"append-in-place":""}`}}class av extends et{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={}
59,this.setDurations(0,0,0),this.events&&this.events.forEach(e=>e.reset()),this.events=this.items=null}resetErrorsInRange(e,t){return this.events?this.events.reduce((i,r)=>e<=r.startOffset&&t>r.startOffset?(delete r.error,i+1):i,0):0}get duration(){let e=this.items;return e?e[e.length-1].end:0}get length(){return this.items?this.items.length:0}getEvent(e){return e&&this.eventMap[e]||null}hasEvent(e){return e in this.eventMap}findItemIndex(e,t){if(e.event)return this.findEventIndex(e.event.identifier);let i=-1;e.nextEvent?i=this.findEventIndex(e.nextEvent.identifier)-1:e.previousEvent&&(i=this.findEventIndex(e.previousEvent.identifier)+1);let r=this.items;if(r)for(r[i]||(void 0===t&&(t=e.start),i=this.findItemIndexAtTime(t));i>=0&&null!=(s=r[i])&&s.event;){var s;i--}return i}findItemIndexAtTime(e,t){let i=this.items;if(i)for(let r=0;r<i.length;r++){let s=i[r];if(t&&"primary"!==t&&(s=s[t]),e===s.start||e>s.start&&e<s.end)return r}return -1}findJumpRestrictedIndex(e,t){let i=this.items;if(i)for(let r=e;r<=t&&i[r];r++){let e=i[r].event;if(null!=e&&e.restrictions.jump&&!e.appendInPlace)return r}return -1}findEventIndex(e){let t=this.items;if(t)for(let r=t.length;r--;){var i;if((null==(i=t[r].event)?void 0:i.identifier)===e)return r}return -1}findAssetIndex(e,t){let i=e.assetList,r=i.length;if(r>1)for(let e=0;e<r;e++){let s=i[e];if(!s.error){let i=s.timelineStart;if(t===i||t>i&&(t<i+(s.duration||0)||e===r-1))return e}}return 0}get assetIdAtEnd(){var e;let t=null==(e=this.items)||null==(e=e[this.length-1])?void 0:e.event;if(t){let e=t.assetList,i=e[e.length-1];if(i)return i.identifier}return null}parseInterstitialDateRanges(e,t){let i=e.main.details,{dateRanges:r}=i,s=this.events,a=this.parseDateRanges(r,{url:i.url},t),n=Object.keys(r),l=s?s.filter(e=>!n.includes(e.identifier)):[];a.length&&a.sort((e,t)=>{let i=e.cue.pre,r=e.cue.post,s=t.cue.pre,a=t.cue.post;if(i&&!s)return -1;if(s&&!i||r&&!a)return 1;if(a&&!r)return -1;if(!i&&!s&&!r&&!a){let i=e.startTime,r=t.startTime;if(i!==r)return i-r}return e.dateRange.tagOrder-t.dateRange.tagOrder}),this.events=a,l.forEach(e=>{this.removeEvent(e)}),this.updateSchedule(e,l)}updateSchedule(e,t=[],i=!1){let r=this.events||[];
59if(r.length||t.length||this.length<2){let s=this.items,a=this.parseSchedule(r,e);(i||t.length||s?.length!==a.length||a.some((e,t)=>Math.abs(e.playout.start-s[t].playout.start)>.005||Math.abs(e.playout.end-s[t].playout.end)>.005))&&(this.items=a,this.onScheduleUpdate(t,s))}}parseDateRanges(e,t,i){let r=[],s=Object.keys(e);for(let a=0;a<s.length;a++){let n=s[a],l=e[n];if(l.isInterstitial){let e=this.eventMap[n];e?e.setDateRange(l):(e=new ac(l,t),this.eventMap[n]=e,!1===i&&(e.appendInPlace=i)),r.push(e)}}return r}parseSchedule(e,t){let i=[],r=t.main.details,s=r.live?1/0:r.edge,a=0;if((e=e.filter(e=>!e.error&&!(e.cue.once&&e.hasPlayed))).length){this.resolveOffsets(e,t);let r=0,l=0;if(e.forEach((t,n)=>{let o=t.cue.pre,h=t.cue.post,d=e[n-1]||null,c=t.appendInPlace,f=h?s:t.startOffset,g=t.duration,m=t.timelineOccupancy===au.Range?g:0,p=t.resumptionOffset,y=d?.startTime===f,v=f+t.cumulativeDuration,E=c?v+g:f+p;if(o||!h&&f<=0){let e=l;l+=m,t.timelineStart=v;let r=a;a+=g,i.push({event:t,start:v,end:E,playout:{start:r,end:a},integrated:{start:e,end:l}})}else{if(!(f<=s))return;if(!y){let s=f-r;if(s>.033){let o=r,h=l;l+=s;let d=a;a+=s;let c={previousEvent:e[n-1]||null,nextEvent:t,start:o,end:o+s,playout:{start:d,end:a},integrated:{start:h,end:l}};i.push(c)}else s>0&&d&&(d.cumulativeDuration+=s,i[i.length-1].end=f)}h&&(E=v),t.timelineStart=v;let o=l;l+=m;let c=a;a+=g,i.push({event:t,start:v,end:E,playout:{start:c,end:a},integrated:{start:o,end:l}})}let T=t.resumeTime;r=h||T>s?s:T}),r<s){var n;let e=r,t=l,o=s-r;l+=o;let h=a;a+=o,i.push({previousEvent:(null==(n=i[i.length-1])?void 0:n.event)||null,nextEvent:null,start:r,end:e+o,playout:{start:h,end:a},integrated:{start:t,end:l}})}this.setDurations(s,a,l)}else i.push({previousEvent:null,nextEvent:null,start:0,end:s,playout:{start:0,end:s},integrated:{start:0,end:s}}),this.setDurations(s,s,s);return i}setDurations(e,t,i){this.durations={primary:e,playout:t,integrated:i}}resolveOffsets(e,t){let i=t.main.details,r=i.live?1/0:i.edge,s=0,a=-1;e.forEach((n,l)=>{let o=n.cue.pre,h=n.cue.post,d=o?0:h?r:n.startTime;this.updateAssetDurations(n),a===d?n.cumulativeDuration=s:(s=0,a=d),!h&&n.snapOptions.in&&(n.resumeAnchor=tL(null,i.fragments,n.startOffset+n.resumptionOffset,0,0)||void 0),n.appendInPlace&&!n.appendInPlaceStarted&&(this.primaryCanResumeInPlaceAt(n,t)||(n.appendInPlace=!1)),!n.appendInPlace&&l+1<e.length&&e[l+1].startTime-e[l].resumeTime<.033&&(e[l+1].appendInPlace=!1,e[l+1].appendInPlace&&this.warn(`Could not change append strategy for abutting event ${n}`));let c=$(n.resumeOffset)?n.resumeOffset:n.duration;s+=c})}primaryCanResumeInPlaceAt(e,t){let i=e.resumeTime,r=e.startTime+e.resumptionOffset;return Math.abs(i-r)>.025?(this.log(`"${e.identifier}" resumption ${i} not aligned with estimated timeline end ${r}`),!1):!Object.keys(t).some(r=>{let s=t[r].details,a=s.edge;if(i>=a)return this.log(`"${e.identifier}" resumption ${i} past ${r} playlist end ${a}`),!1;let n=tL(null,s.fragments,i);if(!n)return this.log(`"${e.identifier}" resumption ${i} does not align with any fragments in ${r} playlist (${s.fragStart}-${s.fragmentEnd})`),!0;let l=.175*("audio"===r);return!(Math.abs(n.start-i)<.025+l||Math.abs(n.end-i)<.025+l)&&(this.log(`"${e.identifier}" resumption ${i} not aligned with ${r} fragment bounds (${n.start}-${n.end} sn: ${n.sn} cc: ${n.cc})`),!0)})}updateAssetDurations(e){if(!e.assetListLoaded)return;let t=e.timelineStart,i=0,r=!1,s=!1;for(let a=0;a<e.assetList.length;a++){let n=e.assetList[a],l=t+i;n.startOffset=i,n.timelineStart=l,r||(r=null===n.duration),s||(s=!!n.error),i+=n.error?0:n.duration||0}r&&!s?e.duration=Math.max(i,e.duration):e.duration=i}removeEvent(e){e.reset(),delete this.eventMap[e.identifier]}}function aE(e){return`[${e.event?'"'+e.event.identifier+'"':"primary"}: ${e.start.toFixed(2)}-${e.end.toFixed(2)}]`}class aT{constructor(e){this.hls=void 0,this.hls=e}destroy(){this.hls=null}loadAssetList(e,t){let i,r=e.assetListUrl;try{i=ag(r,this.hls.sessionId,e.baseUrl)}catch(i){let t=this.assignAssetListError(e,G.ASSET_LIST_LOAD_ERROR,i,r);this.hls.trigger(K.ERROR,t);return}t&&"data:"!==i.protocol&&i.searchParams.set("_HLS_start_offset",""+t);let s=this.hls.config,a=new s.loader(s),n={responseType:"json",url:i.href},l=s.interstitialAssetListLoadPolicy.default,o={loadPolicy:l,timeout:l.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0};return a.load(n,o,{onSuccess:(t,i,r,s)=>{let a=t.data;if(!Array.isArray(a?.ASSETS)){let t=this.assignAssetListError(e,G.ASSET_LIST_PARSING_ERROR,Error("Invalid interstitial asset list"),r.url,i,s);this.hls.trigger(K.ERROR,t);return}e.assetListResponse=a,this.hls.trigger(K.ASSET_LIST_LOADED,{event:e,assetListResponse:a,networkDetails:s})},onError:(t,i,r,s)=>{let a=this.assignAssetListError(e,G.ASSET_LIST_LOAD_ERROR,Error(`Error loading X-ASSET-LIST: HTTP status ${t.code} ${t.text} (${i.url})`),i.url,s,r);this.hls.trigger(K.ERROR,a)},onTimeout:(t,i,r)=>{let s=this.assignAssetListError(e,G.ASSET_LIST_LOAD_TIMEOUT,Error(`Timeout loading X-ASSET-LIST (${i.url})`),i.url,t,r);this.hls.trigger(K.ERROR,s)}}),this.hls.trigger(K.ASSET_LIST_LOADING,{event:e}),a}assignAssetListError(e,t,i,r,s,a){return e.error=i,{type:N.NETWORK_E
59RROR,details:t,fatal:!1,interstitial:e,url:r,error:i,networkDetails:a,stats:s}}}function aS(e){var t;null==e||null==(t=e.play())||t.catch(()=>{})}function aL(e,t){return`[${e}] Advancing timeline position to ${t}`}class aA{constructor(e){this.buffered=void 0;const t=(t,i,r)=>{if((i>>>=0)>r-1)throw new DOMException(`Failed to execute '${t}' on 'TimeRanges': The index provided (${i}) is greater than the maximum bound (${r})`);return e[i][t]};this.buffered={get length(){return e.length},end:i=>t("end",i,e.length),start:i=>t("start",i,e.length)}}}let aR={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},ab=e=>String.fromCharCode(aR[e]||e),ak={17:1,18:3,21:5,22:7,23:9,16:11,19:12,20:14},aI={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},a_={25:2,26:4,29:6,30:8,31:10,27:13,28:15},aP=["white","green","blue","cyan","red","yellow","magenta","black","transparent"];class aC{constructor(){this.time=null,this.verboseLevel=0}log(e,t){if(this.verboseLevel>=e){let i="function"==typeof t?t():t;en.log(`${this.time} [${e}] ${i}`)}}}let aw=function(e){let t=[];for(let i=0;i<e.length;i++)t.push(e[i].toString(16));return t};class ax{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){let t=["foreground","underline","italics","background","flash"];for(let i=0;i<t.length;i++){let r=t[i];e.hasOwnProperty(r)&&(this[r]=e[r])}}isDefault(){return"white"===this.foreground&&!this.underline&&!this.italics&&"black"===this.background&&!this.flash}equals(e){return this.foreground===e.foreground&&this.underline===e.underline&&this.italics===e.italics&&this.background===e.background&&this.flash===e.flash}copy(e){this.foreground=e.foreground,this.underline=e.underline,this.italics=e.italics,this.background=e.background,this.flash=e.flash}toString(){return"color="+this.foreground+", underline="+this.underline+", italics="+this.italics+", background="+this.background+", flash="+this.flash}}class aM{constructor(){this.uchar=" ",this.penState=new ax}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 aO{constructor(e){this.chars=[],this.pos=0,this.currPenState=new ax,this.cueStartTime=null,this.logger=void 0;for(let e=0;e<100;e++)this.chars.push(new aM);this.logger=e}equals(e){for(let t=0;t<100;t++)if(!this.chars[t].equals(e.chars[t]))return!1;return!0}copy(e){for(let t=0;t<100;t++)this.chars[t].copy(e.chars[t])}isEmpty(){let e=!0;for(let t=0;t<100;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>100&&(this.logger.log(3,"Too large cursor position "+this.pos),this.pos=100)}moveCursor(e){let t=this.pos+e;if(e>1)for(let e=this.pos+1;e<t+1;e++)this.chars[e].setPenState(this.currPenState);this.setCursor(t)}backSpace(){this.moveCursor(-1),this.chars[this.pos].setChar(" ",this.currPenState)}insertChar(e){e>=144&&this.backSpace();let t=ab(e);this.pos>=100?this.logger.log(0,()=>"Cannot insert "+e.toString(16)+" ("+t+") at position "+this.pos+". Skipping it!"):(this.chars[this.pos].setChar(t,this.currPenState),this.moveCursor(1))}clearFromPos(e){let t;for(t=e;t<100;t++)this.chars[t].reset()}clear(){this.clearFromPos(0),this.pos=0,this.currPenState.reset()}clearToEndOfRow(){this.clearFromPos(this.pos)}getTextString(){let e=[],t=!0;for(let i=0;i<100;i++){let r=this.chars[i].uchar;" "!==r&&(t=!1),e.push(r)}return t?"":e.join("")}setPenStyles(e){this.currPenState.setStyles(e),this.chars[this.pos].setPenState(this.currPenState)}}class aF{constructor(e){this.rows=[],this.currRow=14,this.nrRollUpRows=null,this.lastOutputScreen=null,this.logger=void 0;for(let t=0;t<15;t++)this.rows.push(new aO(e));this.logger=e}reset(){for(let e=0;e<15;e++)this.rows[e].clear();this.currRow=14}equals(e){let t=!0;for(let i=0;i<15;i++)if(!this.rows[i].equals(e.rows[i])){t=!1;break}return t}copy(e){for(let t=0;t<15;t++)this.rows[t].copy(e.rows[t])}isEmpty(){let e=!0;for(let t=0;t<15;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 = "+tc(e));let t=e.row-1;if(this.nrRollUpRows&&t<this.nrRollUpRows-1&&(t=this.nrRollUpRows-1),this.nrRollUpRows&&this.currRow!==t){for(let e=0;e<15;e++)this.rows[e].clear();let e=this.currRow+1-this.nrRollUpRows,i=this.lastOutputScreen;if(i){let r=i.rows[e].cueStartTime,s=this.logger.time;if(null!==r&&null!==s&&r<s)for(let r=0;r<this.nrRollUpRows;r++)this.rows[t-this.nrRollUpRows+r+1].copy(i.rows[e+r])}}this.currRow=t;let i=this.rows[this.currRow];if(null!==e.indent){let t=Math.max(e.indent-1,0);i.setCursor(e.indent),e.color=i.chars[t].penState.foreground}let r={foreground:e.color,underline:e.underline,italics:e.italics,background:"black",flash:!1};this.setPen(r)}setBkgData(e){this.logger.log(2,()=>"bkgData = "+tc(e)),this.backSpace(),this.setPen(e),this.insertChar(32)}setRollUpRows(e){this.nrRollUpRows=e}rollUp(){if(null===this.nrRollUpRows)return void this.logger.log(3,"roll_up but nrRollUpRows not set yet");this.logger.log(1,()=>this.getDisplayText());let 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;let t=[],i="",r=-1;for(let i=0;i<15;i++){let s=this.rows[i].getTextString();s&&(r=i+1,e?t.push("Row "+r+": '"+s+"'"):t.push(s.trim()))}return t.length>0&&(i=e?"["+t.join(" | ")+"]":t.join(`
60`)),i}getTextAndFormat(){return this.rows}}class a${constructor(e,t,i){this.chNr=void 0,this.outputFilter=void 0,this.mode=void 0,this.verbose=void 0,this.displayedMemory=void 0,this.nonDisplayedMemory=void 0,this.lastOutputScreen=void 0,this.currRollUpRow=void 0,this.writeScreen=void 0,this.cueStartTime=void 0,this.logger=void 0,this.chNr=e,this.outputFilter=t,this.mode=null,this.verbose=0,this.displayedMemory=new aF(i),this.nonDisplayedMemory=new aF(i),this.lastOutputScreen=new aF(i),this.currRollUpRow=this.displayedMemory.rows[14],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null,this.logger=i}reset(){this.mode=null,this.displayedMemory.reset(),this.nonDisplayedMemory.reset(),this.lastOutputScreen.reset(),this.outputFilter.reset(),this.currRollUpRow=this.displayedMemory.rows[14],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null}getHandler(){return this.outputFilter}setHandler(e){this.outputFilter=e}setPAC(e){this.writeScreen.setPAC(e)}setBkgData(e){this.writeScreen.setBkgData(e)}setMode(e){e!==this.mode&&(this.mode=e,this.logger.log(2,()=>"MODE="+e),"MODE_POP-ON"===this.mode?this.writeScreen=this.nonDisplayedMemory:(this.writeScreen=this.displayedMemory,this.writeScreen.reset()),"MODE_ROLL-UP"!==this.mode&&(this.displayedMemory.nrRollUpRows=null,this.nonDisplayedMemory.nrRollUpRows=null),this.mode=e)}insertChars(e){for(let t=0;t<e.length;t++)this.writeScreen.insertChar(e[t]);let t=this.writeScreen===this.displayedMemory?"DISP":"NON_DISP";this.logger.log(2,()=>t+": "+this.writeScreen.getDisplayText(!0)),("MODE_PAINT-ON"===this.mode||"MODE_ROLL-UP"===this.mode)&&(this.logger.log(1,()=>"DISPLAYED: "+this.displayedMemory.getDisplayText(!0)),this.outputDataUpdate())}ccRCL(){this.logger.log(2,"RCL - Resume Caption Loading"),this.setMode("MODE_POP-ON")}ccBS(){this.logger.log(2,"BS - BackSpace"),"MODE_TEXT"!==this.mode&&(this.writeScreen.backSpace(),this.writeScreen===this.displayedMemory&&this.outputDataUpdate())}ccAOF(){}ccAON(){}ccDER(){this.logger.log(2,"DER- Delete to End of Row"),this.writeScreen.clearToEndOfRow(),this.outputDataUpdate()}ccRU(e){this.logger.log(2,"RU("+e+") - Roll Up"),this.writeScreen=this.displayedMemory,this.setMode("MODE_ROLL-UP"),this.writeScreen.setRollUpRows(e)}ccFON(){this.logger.log(2,"FON - Flash On"),this.writeScreen.setPen({flash:!0})}
60ccRDC(){this.logger.log(2,"RDC - Resume Direct Captioning"),this.setMode("MODE_PAINT-ON")}ccTR(){this.logger.log(2,"TR"),this.setMode("MODE_TEXT")}ccRTD(){this.logger.log(2,"RTD"),this.setMode("MODE_TEXT")}ccEDM(){this.logger.log(2,"EDM - Erase Displayed Memory"),this.displayedMemory.reset(),this.outputDataUpdate(!0)}ccCR(){this.logger.log(2,"CR - Carriage Return"),this.writeScreen.rollUp(),this.outputDataUpdate(!0)}ccENM(){this.logger.log(2,"ENM - Erase Non-displayed Memory"),this.nonDisplayedMemory.reset()}ccEOC(){if(this.logger.log(2,"EOC - End Of Caption"),"MODE_POP-ON"===this.mode){let 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){let t={flash:!1};(t.underline=e%2==1,t.italics=e>=46,t.italics)?t.foreground="white":t.foreground=["white","green","blue","cyan","red","yellow","magenta"][Math.floor(e/2)-16],this.logger.log(2,"MIDROW: "+tc(t)),this.writeScreen.setPen(t)}outputDataUpdate(e=!1){let t=this.logger.time;null!==t&&this.outputFilter&&(null!==this.cueStartTime||this.displayedMemory.isEmpty()?this.displayedMemory.equals(this.lastOutputScreen)||(this.outputFilter.newCue(this.cueStartTime,t,this.lastOutputScreen),e&&this.outputFilter.dispatchCue&&this.outputFilter.dispatchCue(),this.cueStartTime=this.displayedMemory.isEmpty()?null:t):this.cueStartTime=t,this.lastOutputScreen.copy(this.displayedMemory))}cueSplitAtTime(e){this.outputFilter&&(this.displayedMemory.isEmpty()||(this.outputFilter.newCue&&this.outputFilter.newCue(this.cueStartTime,e,this.displayedMemory),this.cueStartTime=e))}}class aB{constructor(e,t,i){this.channels=void 0,this.currentChannel=0,this.cmdHistory={a:null,b:null},this.logger=void 0;const r=this.logger=new aC;this.channels=[null,new a$(e,t,r),new a$(e+1,i,r)]}getHandler(e){return this.channels[e].getHandler()}setHandler(e,t){this.channels[e].setHandler(t)}addData(e,t){this.logger.time=e;for(let e=0;e<t.length;e+=2){var i,r,s,a,n,l,o,h;let d=127&t[e],c=127&t[e+1],f=!1,g=null;if(0===d&&0===c)continue;this.logger.log(3,()=>"["+aw([t[e],t[e+1]])+"] -> ("+aw([d,c])+")");let m=this.cmdHistory;if(d>=16&&d<=31){if(i=d,r=c,(s=m).a===i&&s.b===r){(a=m).a=null,a.b=null,this.logger.log(3,()=>"Repeated command ("+aw([d,c])+") is dropped");continue}n=d,l=c,(o=this.cmdHistory).a=n,o.b=l,(f=this.parseCmd(d,c))||(f=this.parseMidrow(d,c)),f||(f=this.parsePAC(d,c)),f||(f=this.parseBackgroundAttributes(d,c))}else{(h=m).a=null,h.b=null}if(!f&&(g=this.parseChars(d,c))){let e=this.currentChannel;e&&e>0?this.channels[e].insertChars(g):this.logger.log(2,"No channel found yet. TEXT-MODE?")}f||g||this.logger.log(2,()=>"Couldn't parse cleaned data "+aw([d,c])+" orig: "+aw([t[e],t[e+1]]))}}parseCmd(e,t){if(!((20===e||28===e||21===e||29===e)&&t>=32&&t<=47||(23===e||31===e)&&t>=33&&t<=35))return!1;let i=20===e||21===e||23===e?1:2,r=this.channels[i];return 20===e||21===e||28===e||29===e?32===t?r.ccRCL():33===t?r.ccBS():34===t?r.ccAOF():35===t?r.ccAON():36===t?r.ccDER():37===t?r.ccRU(2):38===t?r.ccRU(3):39===t?r.ccRU(4):40===t?r.ccFON():41===t?r.ccRDC():42===t?r.ccTR():43===t?r.ccRTD():44===t?r.ccEDM():45===t?r.ccCR():46===t?r.ccENM():47===t&&r.ccEOC():r.ccTO(t-32),this.currentChannel=i,!0}parseMidrow(e,t){let i=0;if((17===e||25===e)&&t>=32&&t<=47){if((i=17===e?1:2)!==this.currentChannel)return this.logger.log(0,"Mismatch channel in midrow parsing"),!1;let r=this.channels[i];return!!r&&(r.ccMIDROW(t),this.logger.log(3,()=>"MIDROW ("+aw([e,t])+")"),!0)}return!1}parsePAC(e,t){let i,r=(e>=17&&e<=23||e>=25&&e<=31)&&t>=64&&t<=127,s=(16===e||24===e)&&t>=64&&t<=95;if(!(r||s))return!1;let a=e<=23?1:2;i=t>=64&&t<=95?1===a?ak[e]:aD[e]:1===a?aI[e]:a_[e];let n=this.channels[a];return!!n&&(n.setPAC(this.interpretPAC(i,t)),this.currentChannel=a,!0)}interpretPAC(e,t){let i,r={color:null,italics:!1,indent:null,underline:!1,row:e};return r.underline=(1&(i=t>95?t-96:t-64))==1,i<=13?r.color=["white","green","blue","cyan","red","yellow","magenta","white"][Math.floor(i/2)]:i<=15?(r.italics=!0,r.color="white"):r.indent=4*Math.floor((i-16)/2),r}parseChars(e,t){let i,r=null,s=null;if(e>=25?(i=2,s=e-8):(i=1,s=e),s>=17&&s<=19){let e;e=17===s?t+80:18===s?t+112:t+144,this.logger.log(2,()=>"Special char '"+ab(e)+"' in channel "+i),r=[e]}else e>=32&&e<=127&&(r=0===t?[e]:[e,t]);return r&&this.logger.log(3,()=>"Char codes =  "+aw(r).join(",")),r}
60parseBackgroundAttributes(e,t){if(!((16===e||24===e)&&t>=32&&t<=47||(23===e||31===e)&&t>=45&&t<=47))return!1;let i={};return 16===e||24===e?(i.background=aP[Math.floor((t-32)/2)],t%2==1&&(i.background=i.background+"_semi")):45===t?i.background="transparent":(i.foreground="black",47===t&&(i.underline=!0)),this.channels[e<=23?1:2].setBkgData(i),!0}reset(){var e;for(let e=0;e<Object.keys(this.channels).length;e++){let t=this.channels[e];t&&t.reset()}(e=this.cmdHistory).a=null,e.b=null}cueSplitAtTime(e){for(let t=0;t<this.channels.length;t++){let i=this.channels[t];i&&i.cueSplitAtTime(e)}}}var aU=function(){if(null!=il&&il.VTTCue)return self.VTTCue;let e=["","lr","rl"],t=["start","middle","end","left","right"];function i(e,t){if("string"!=typeof t||!Array.isArray(e))return!1;let i=t.toLowerCase();return!!~e.indexOf(i)&&i}function r(e){let t=1;for(;t<arguments.length;t++){let i=arguments[t];for(let t in i)e[t]=i[t]}return e}function s(s,a,n){let l={enumerable:!0};this.hasBeenReset=!1;let o="",h=!1,d=s,c=a,f=n,g=null,m="",p=!0,y="auto",v="start",E=50,T="middle",S=50,L="middle";Object.defineProperty(this,"id",r({},l,{get:function(){return o},set:function(e){o=""+e}})),Object.defineProperty(this,"pauseOnExit",r({},l,{get:function(){return h},set:function(e){h=!!e}})),Object.defineProperty(this,"startTime",r({},l,{get:function(){return d},set:function(e){if("number"!=typeof e)throw TypeError("Start time must be set to a number.");d=e,this.hasBeenReset=!0}})),Object.defineProperty(this,"endTime",r({},l,{get:function(){return c},set:function(e){if("number"!=typeof e)throw TypeError("End time must be set to a number.");c=e,this.hasBeenReset=!0}})),Object.defineProperty(this,"text",r({},l,{get:function(){return f},set:function(e){f=""+e,this.hasBeenReset=!0}})),Object.defineProperty(this,"region",r({},l,{get:function(){return g},set:function(e){g=e,this.hasBeenReset=!0}})),Object.defineProperty(this,"vertical",r({},l,{get:function(){return m},set:function(t){let r=i(e,t);if(!1===r)throw SyntaxError("An invalid or illegal string was specified.");m=r,this.hasBeenReset=!0}})),Object.defineProperty(this,"snapToLines",r({},l,{get:function(){return p},set:function(e){p=!!e,this.hasBeenReset=!0}})),Object.defineProperty(this,"line",r({},l,{get:function(){return y},set:function(e){if("number"!=typeof e&&"auto"!==e)throw SyntaxError("An invalid number or illegal string was specified.");y=e,this.hasBeenReset=!0}})),Object.defineProperty(this,"lineAlign",r({},l,{get:function(){return v},set:function(e){let r=i(t,e);if(!r)throw SyntaxError("An invalid or illegal string was specified.");v=r,this.hasBeenReset=!0}})),Object.defineProperty(this,"position",r({},l,{get:function(){return E},set:function(e){if(e<0||e>100)throw Error("Position must be between 0 and 100.");E=e,this.hasBeenReset=!0}})),Object.defineProperty(this,"positionAlign",r({},l,{get:function(){return T},set:function(e){let r=i(t,e);if(!r)throw SyntaxError("An invalid or illegal string was specified.");T=r,this.hasBeenReset=!0}})),Object.defineProperty(this,"size",r({},l,{get:function(){return S},set:function(e){if(e<0||e>100)throw Error("Size must be between 0 and 100.");S=e,this.hasBeenReset=!0}})),Object.defineProperty(this,"align",r({},l,{get:function(){return L},set:function(e){let r=i(t,e);if(!r)throw SyntaxError("An invalid or illegal string was specified.");L=r,this.hasBeenReset=!0}})),this.displayState=void 0}return s.prototype.getCueAsHTML=function(){return self.WebVTT.convertCueToDOMTree(self,this.text)},s}();class aN{decode(e,t){if(!e)return"";if("string"!=typeof e)throw Error("Error - expected string data.");return decodeURIComponent(encodeURIComponent(e))}}function aG(e){function t(e,t,i,r){return(0|e)*3600+(0|t)*60+(0|i)+parseFloat(r||0)}let i=e.match(/^(?:(\d+):)?(\d{2}):(\d{2})(\.\d+)?/);return i?parseFloat(i[2])>59?t(i[2],i[3],0,i[4]):t(i[1],i[2],i[3],i[4]):null}class aK{constructor(){this.values=Object.create(null)}set(e,t){this.get(e)||""===t||(this.values[e]=t)}get(e,t,i){return i?this.has(e)?this.values[e]:t[i]:this.has(e)?this.values[e]:t}has(e){return e in this.values}alt(e,t,i){for(let r=0;r<i.length;++r)if(t===i[r]){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)){let i=parseFloat(t);if(i>=0&&i<=100)return this.set(e,i),!0}return!1}}function aH(e,t,i,r){let s=r?e.split(r):[e];for(let e in s){if("string"!=typeof s[e])continue;let r=s[e].split(i);if(2===r.length)t(r[0],r[1])}}let aV=new aU(0,0,""),aj="middle"===aV.align?"middle":"center";function aW(e){return e.replace(/<br(?: \/)?>/gi,`
61`)}class aq{constructor(){this.state="INITIAL",this.buffer="",this.decoder=new aN,this.regionList=[],this.cue=null,this.oncue=void 0,this.onparsingerror=void 0,this.onflush=void 0}parse(e){let t=this;function i(){let e=t.buffer,i=0;for(e=aW(e);i<e.length&&"\r"!==e[i]&&e[i]!==`
62`;)++i;let r=e.slice(0,i);return"\r"===e[i]&&++i,e[i]===`
63`&&++i,t.buffer=e.slice(i),r}e&&(t.buffer+=t.decoder.decode(e,{stream:!0}));try{let e="";if("INITIAL"===t.state){if(!/\r\n|\n/.test(t.buffer))return this;let r=(e=i()).match(/^()?WEBVTT([ \t].*)?$/);if(!(null!=r&&r[0]))throw Error("Malformed WebVTT signature.");t.state="HEADER"}let s=!1;for(;t.buffer&&/\r\n|\n/.test(t.buffer);)switch(s?s=!1:e=i(),t.state){case"HEADER":var r;/:/.test(e)?(r=e,aH(r,function(e,t){},/:/)):e||(t.state="ID");continue;case"NOTE":e||(t.state="ID");continue;case"ID":if(/^NOTE($|[ \t])/.test(e)){t.state="NOTE";break}if(!e)continue;if(t.cue=new aU(0,0,""),t.state="CUE",-1===e.indexOf("-->")){t.cue.id=e;continue}case"CUE":if(!t.cue){t.state="BADCUE";continue}try{!function(e,t,i){var r;let s,a,n,l=e;function o(){let t=aG(e);
63if(null===t)throw Error("Malformed timestamp: "+l);return e=e.replace(/^[^\sa-zA-Z-]+/,""),t}function h(){e=e.replace(/^\s+/,"")}if(h(),t.startTime=o(),h(),"-->"!==e.slice(0,3))throw Error("Malformed time stamp (time stamps must be separated by '-->'): "+l);e=e.slice(3),h(),t.endTime=o(),h(),r=e,s=new aK,aH(r,function(e,t){let r;switch(e){case"region":for(let r=i.length-1;r>=0;r--)if(i[r].id===t){s.set(e,i[r].region);break}break;case"vertical":s.alt(e,t,["rl","lr"]);break;case"line":r=t.split(","),s.integer(e,r[0]),s.percent(e,r[0])&&s.set("snapToLines",!1),s.alt(e,r[0],["auto"]),2===r.length&&s.alt("lineAlign",r[1],["start",aj,"end"]);break;case"position":r=t.split(","),s.percent(e,r[0]),2===r.length&&s.alt("positionAlign",r[1],["start",aj,"end","line-left","line-right","auto"]);break;case"size":s.percent(e,t);break;case"align":s.alt(e,t,["start",aj,"end","left","right"])}},/:/,/\s/),t.region=s.get("region",null),t.vertical=s.get("vertical",""),"auto"===(a=s.get("line","auto"))&&-1===aV.line&&(a=-1),t.line=a,t.lineAlign=s.get("lineAlign","start"),t.snapToLines=s.get("snapToLines",!0),t.size=s.get("size",100),t.align=s.get("align",aj),"auto"===(n=s.get("position","auto"))&&50===aV.position&&(n="start"===t.align||"left"===t.align?0:"end"===t.align||"right"===t.align?100:50),t.position=n}(e,t.cue,t.regionList)}catch{t.cue=null,t.state="BADCUE";continue}t.state="CUETEXT";continue;case"CUETEXT":{let i=-1!==e.indexOf("-->");if(!e||i&&(s=!0)){t.oncue&&t.cue&&t.oncue(t.cue),t.cue=null,t.state="ID";continue}if(null===t.cue)continue;t.cue.text&&(t.cue.text+=`
64`),t.cue.text+=e}continue;case"BADCUE":e||(t.state="ID")}}catch{"CUETEXT"===t.state&&t.cue&&t.oncue&&t.oncue(t.cue),t.cue=null,t.state="INITIAL"===t.state?"BADWEBVTT":"BADCUE"}return this}flush(){try{if((this.cue||"HEADER"===this.state)&&(this.buffer+=`
65
66`,this.parse()),"INITIAL"===this.state||"BADWEBVTT"===this.state)throw Error("Malformed WebVTT signature.")}catch(e){this.onparsingerror&&this.onparsingerror(e)}return this.onflush&&this.onflush(),this}}let aY=/\r\n|\n\r|\n|\r/g,aX=function(e,t,i=0){return e.slice(i,i+t.length)===t},az=function(e){let t=parseInt(e.slice(-3)),i=parseInt(e.slice(-6,-4)),r=parseInt(e.slice(-9,-7)),s=e.length>9?parseInt(e.substring(0,e.indexOf(":"))):0;if(!$(t)||!$(i)||!$(r)||!$(s))throw Error(`Malformed X-TIMESTAMP-MAP: Local:${e}`);return t+=1e3*i,t+=6e4*r,t+=36e5*s};function aQ(e,t,i){return ad(e.toString())+ad(t.toString())+ad(i)}let aZ=function(e,t,i){let r=e[t],s=e[r.prevCC];if(!s||!s.new&&r.new){e.ccOffset=e.presentationOffset=r.start,r.new=!1;return}for(;null!=(a=s)&&a.new;){var a;e.ccOffset+=r.start-s.start,r.new=!1,s=e[(r=s).prevCC]}e.presentationOffset=i},aJ="stpp.ttml.im1t",a0=/^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/,a1=/^(\d*(?:\.\d*)?)(h|m|s|ms|f|t)$/,a2={left:"start",center:"center",right:"end",start:"start",end:"end"};function a3(e,t,i,r){let s=eB(new Uint8Array(e),["mdat"]);if(0===s.length)return void r(Error("Could not parse IMSC1 mdat"));let a=s.map(e=>eh(e)),n=function(e,t=1,i=!1){return r6(e,1,1/t,i)}(t.baseTime,t.timescale);try{a.forEach(e=>i(function(e,t){let i=new DOMParser().parseFromString(e,"text/xml").getElementsByTagName("tt")[0];if(!i)throw Error("Invalid ttml");let r={frameRate:30,subFrameRate:1,frameRateMultiplier:0,tickRate:0},s=Object.keys(r).reduce((e,t)=>(e[t]=i.getAttribute(`ttp:${t}`)||r[t],e),{}),a="preserve"!==i.getAttribute("xml:space"),n=a5(a4(i,"styling","style")),l=a5(a4(i,"layout","region")),o=a4(i,"body","[begin]");return[].map.call(o,e=>{var i,r,o;let h,d,c,f=function e(t,i){return[].slice.call(t.childNodes).reduce((t,r,s)=>{var a;return"br"===r.nodeName&&s?t+`
67`:null!=(a=r.childNodes)&&a.length?e(r,i):i?t+r.textContent.trim().replace(/\s+/g," "):t+r.textContent},"")}(e,a);if(!f||!e.hasAttribute("begin"))return null;let g=a9(e.getAttribute("begin"),s),m=a9(e.getAttribute("dur"),s),p=a9(e.getAttribute("end"),s);if(null===g)throw a6(e);if(null===p){if(null===m)throw a6(e);p=g+m}let y=new aU(g-t,p-t,f);y.id=aQ(y.startTime,y.endTime,y.text);let v=(i=l[e.getAttribute("region")],r=n[e.getAttribute("style")],o=n,h="http://www.w3.org/ns/ttml#styling",d=null,(c=null!=i&&i.hasAttribute("style")?i.getAttribute("style"):null)&&o.hasOwnProperty(c)&&(d=o[c]),["displayAlign","textAlign","color","backgroundColor","fontSize","fontFamily"].reduce((e,t)=>
67{let s=a8(r,h,t)||a8(i,h,t)||a8(d,h,t);return s&&(e[t]=s),e},{})),{textAlign:E}=v;if(E){let e=a2[E];e&&(y.lineAlign=e),y.align=E}return Z(y,v),y}).filter(e=>null!==e)}(e,n)))}catch(e){r(e)}}function a4(e,t,i){let r=e.getElementsByTagName(t)[0];return r?[].slice.call(r.querySelectorAll(i)):[]}function a5(e){return e.reduce((e,t)=>{let i=t.getAttribute("xml:id");return i&&(e[i]=t),e},{})}function a8(e,t,i){return e&&e.hasAttributeNS(t,i)?e.getAttributeNS(t,i):null}function a6(e){return Error(`Could not parse ttml timestamp ${e}`)}function a9(e,t){var i,r;let s,a;if(!e)return null;let n=aG(e);return null===n&&(a0.test(e)?(i=e,r=t,a=(0|(s=a0.exec(i))[4])+(0|s[5])/r.subFrameRate,n=(0|s[1])*3600+(0|s[2])*60+(0|s[3])+a/r.frameRate):a1.test(e)&&(n=function(e,t){let i=a1.exec(e),r=Number(i[1]);switch(i[2]){case"h":return 3600*r;case"m":return 60*r;case"ms":return 1e3*r;case"f":return r/t.frameRate;case"t":return r/t.tickRate}return r}(e,t))),n}class a7{constructor(e,t){this.timelineController=void 0,this.cueRanges=[],this.trackName=void 0,this.startTime=null,this.endTime=null,this.screen=null,this.timelineController=e,this.trackName=t}dispatchCue(){null!==this.startTime&&(this.timelineController.addCues(this.trackName,this.startTime,this.endTime,this.screen,this.cueRanges),this.startTime=null)}newCue(e,t,i){(null===this.startTime||this.startTime>e)&&(this.startTime=e),this.endTime=t,this.screen=i,this.timelineController.createCaptionsTrack(this.trackName)}reset(){this.cueRanges=[],this.startTime=null}}function ne(e){return e.characteristics&&/transcribes-spoken-dialog/gi.test(e.characteristics)&&/describes-music-and-sound/gi.test(e.characteristics)?"captions":"subtitles"}function nt(e,t){return!!e&&e.kind===ne(t)&&sT(t,e)}function ni(){return{ccOffset:0,presentationOffset:0,0:{start:0,prevCC:-1,new:!0}}}let nr=/\s/,ns={newCue(e,t,i,r){let s,a,n,l,o,h=[],d=self.VTTCue||self.TextTrackCue;for(let f=0;f<r.rows.length;f++)if(s=r.rows[f],n=!0,l=0,o="",!s.isEmpty()){var c;for(let e=0;e<s.chars.length;e++)nr.test(s.chars[e].uchar)&&n?l++:(o+=s.chars[e].uchar,n=!1);s.cueStartTime=t,t===i&&(i+=1e-4),l>=16?l--:l++;let r=aW(o.trim()),g=aQ(t,i,r);null!=e&&null!=(c=e.cues)&&c.getCueById(g)||((a=new d(t,i,r)).id=g,a.line=f+1,a.align="left",a.position=10+Math.min(80,10*Math.floor(8*l/32)),h.push(a))}return e&&h.length&&(h.sort((e,t)=>"auto"===e.line||"auto"===t.line?0:e.line>8&&t.line>8?t.line-e.line:e.line-t.line),h.forEach(t=>an(e,t))),h}},na=/(\d+)-(\d+)\/(\d+)/;class nn{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||nl,this.controller=new self.AbortController,this.stats=new eA}destroy(){this.loader=this.callbacks=this.context=this.config=this.request=null,this.abortInternal(),this.response=null,this.fetchSetup=this.controller=this.stats=null}abortInternal(){this.controller&&!this.stats.loading.end&&(this.stats.aborted=!0,this.controller.abort())}abort(){var e;this.abortInternal(),null!=(e=this.callbacks)&&e.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.response)}load(e,t,i){var r;let s,a=this.stats;if(a.loading.start)throw Error("Loader can only be used once.");a.loading.start=self.performance.now();let n=(r=e,s={method:"GET",mode:"cors",credentials:"same-origin",signal:this.controller.signal,headers:new self.Headers(Z({},r.headers))},r.rangeEnd&&s.headers.set("Range","bytes="+r.rangeStart+"-"+String(r.rangeEnd-1)),s),l="arraybuffer"===e.responseType,o=l?"byteLength":"length",{maxTimeToFirstByteMs:h,maxLoadTimeMs:d}=t.loadPolicy;this.context=e,this.config=t,this.callbacks=i,this.request=this.fetchSetup(e,n),self.clearTimeout(this.requestTimeout),t.timeout=h&&$(h)?h:d,this.requestTimeout=self.setTimeout(()=>{this.callbacks&&(this.abortInternal(),this.callbacks.onTimeout(a,e,this.response))},t.timeout),(sc(this.request)?this.request.then(self.fetch):self.fetch(this.request)).then(i=>{var r;this.response=this.loader=i;let s=Math.max(self.performance.now(),a.loading.start);
67if(self.clearTimeout(this.requestTimeout),t.timeout=d,this.requestTimeout=self.setTimeout(()=>{this.callbacks&&(this.abortInternal(),this.callbacks.onTimeout(a,e,this.response))},d-(s-a.loading.start)),!i.ok){let{status:e,statusText:t}=i;throw new no(t||"fetch, bad network response",e,i)}a.loading.first=s,a.total=function(e){let t=e.get("Content-Range");if(t){let e=function(e){let t=na.exec(e);if(t)return parseInt(t[2])-parseInt(t[1])+1}(t);if($(e))return e}let i=e.get("Content-Length");if(i)return parseInt(i)}(i.headers)||a.total;let n=null==(r=this.callbacks)?void 0:r.onProgress;return n&&$(t.highWaterMark)?this.loadProgressively(i,a,e,t.highWaterMark,n):l?i.arrayBuffer():"json"===e.responseType?i.json():i.text()}).then(i=>{var r,s;let n=this.response;if(!n)throw Error("loader destroyed");self.clearTimeout(this.requestTimeout),a.loading.end=Math.max(self.performance.now(),a.loading.first);let l=i[o];l&&(a.loaded=a.total=l);let h={url:n.url,data:i,code:n.status},d=null==(r=this.callbacks)?void 0:r.onProgress;d&&!$(t.highWaterMark)&&d(a,e,i,n),null==(s=this.callbacks)||s.onSuccess(h,a,e,n)}).catch(t=>{var i;if(self.clearTimeout(this.requestTimeout),a.aborted)return;let r=t&&t.code||0,s=t?t.message:null;null==(i=this.callbacks)||i.onError({code:r,text:s},e,t?t.details:null,a)})}getCacheAge(){let e=null;if(this.response){let t=this.response.headers.get("age");e=t?parseFloat(t):null}return e}getResponseHeader(e){return this.response?this.response.headers.get(e):null}loadProgressively(e,t,i,r=0,s){let a=new rd,n=e.body.getReader(),l=()=>n.read().then(n=>{if(n.done)return a.dataLength&&s(t,i,a.flush().buffer,e),Promise.resolve(new ArrayBuffer(0));let o=n.value,h=o.length;return t.loaded+=h,h<r||a.dataLength?(a.push(o),a.dataLength>=r&&s(t,i,a.flush().buffer,e)):s(t,i,o.buffer,e),l()}).catch(()=>Promise.reject());return l()}}function nl(e,t){return new self.Request(e.url,t)}class no extends Error{constructor(e,t,i){super(e),this.code=void 0,this.details=void 0,this.code=t,this.details=i}}let nh=/^age:\s*[\d.]+\s*$/im;class nd{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 eA,this.retryDelay=0}destroy(){this.callbacks=null,this.abortInternal(),this.loader=null,this.config=null,this.context=null,this.xhrSetup=null}abortInternal(){let e=this.loader;self.clearTimeout(this.requestTimeout),self.clearTimeout(this.retryTimeout),e&&(e.onreadystatechange=null,e.onprogress=null,4!==e.readyState&&(this.stats.aborted=!0,e.abort()))}abort(){var e;this.abortInternal(),null!=(e=this.callbacks)&&e.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.loader)}load(e,t,i){if(this.stats.loading.start)throw Error("Loader can only be used once.");this.stats.loading.start=self.performance.now(),this.context=e,this.config=t,this.callbacks=i,this.loadInternal()}loadInternal(){let{config:e,context:t}=this;if(!e||!t)return;let i=this.loader=new self.XMLHttpRequest,r=this.stats;r.loading.first=0,r.loaded=0,r.aborted=!1;let s=this.xhrSetup;s?Promise.resolve().then(()=>{if(!(this.loader!==i||this.stats.aborted))return s(i,t.url)}).catch(e=>{if(!(this.loader!==i||this.stats.aborted))return i.open("GET",t.url,!0),s(i,t.url)}).then(()=>{this.loader!==i||this.stats.aborted||this.openAndSendXhr(i,t,e)}).catch(e=>{var s;null==(s=this.callbacks)||s.onError({code:i.status,text:e.message},t,i,r)}):this.openAndSendXhr(i,t,e)}openAndSendXhr(e,t,i){e.readyState||e.open("GET",t.url,!0);let r=t.headers,{maxTimeToFirstByteMs:s,maxLoadTimeMs:a}=i.loadPolicy;if(r)for(let t in r)e.setRequestHeader(t,r[t]);t.rangeEnd&&e.setRequestHeader("Range","bytes="+t.rangeStart+"-"+(t.rangeEnd-1)),e.onreadystatechange=this.readystatechange.bind(this),e.onprogress=this.loadprogress.bind(this),e.responseType=t.responseType,self.clearTimeout(this.requestTimeout),i.timeout=s&&$(s)?s:a,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),i.timeout),e.send()}readystatechange(){let{context:e,loader:t,stats:i}=this;if(!e||!t)return;let r=t.readyState,s=this.config;if(!i.aborted&&r>=2&&(0===i.loading.first&&(i.loading.first=Math.max(self.performance.now(),i.loading.start),s.timeout!==s.loadPolicy.maxLoadTimeMs&&(self.clearTimeout(this.requestTimeout),s.timeout=s.loadPolicy.maxLoadTimeMs,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),s.loadPolicy.maxLoadTimeMs-(i.loading.first-i.loading.start)))),4===r)){var a,n,l;self.clearTimeout(this.requestTimeout),t.onreadystatechange=null,t.onprogress=null;let r=t.status,o="text"===t.responseType?t.responseText:null;if(r>=200&&r<300){let s=o??t.response;if(null!=s){i.loading.end=Math.max(self.performance.now(),i.loading.first),i.loaded=i.total="arraybuffer"===t.responseType?s.byteLength:s.length,i.bwEstimate=8e3*i.total/(i.loading.end-i.loading.first);let l=null==(a=this.callbacks)?void 0:a.onProgress;l&&l(i,e,s,t);let o={url:t.responseURL,data:s,code:r};null==(n=this.callbacks)||n.onSuccess(o,i,e,t);return}}let h=s.loadPolicy.errorRetry;tC(h,i.retry,!1,{url:e.url,data:void 0,code:r})?this.retry(h):(en.error(`${r} while loading ${e.url}`),null==(l=this.callbacks)||l.onError({code:r,text:t.statusText},e,t,i))}}loadtimeout(){if(!this.config)return;let e=this.config.loadPolicy.timeoutRetry;if(tC(e,this.stats.retry,!0))this.retry(e);else{var t;en.warn(`timeout while loading ${null==(t=this.context)?void 0:t.url}`);let e=this.callbacks;e&&(this.abortInternal(),e.onTimeout(this.stats,this.context,this.loader))}}
67retry(e){let{context:t,stats:i}=this;this.retryDelay=t_(e,i.retry),i.retry++,en.warn(`${status?"HTTP Status "+status:"Timeout"} while loading ${t?.url}, retrying ${i.retry}/${e.maxNumRetry} in ${this.retryDelay}ms`),this.abortInternal(),this.loader=null,self.clearTimeout(this.retryTimeout),this.retryTimeout=self.setTimeout(this.loadInternal.bind(this),this.retryDelay)}loadprogress(e){let t=this.stats;t.loaded=e.loaded,e.lengthComputable&&(t.total=e.total)}getCacheAge(){let e=null;if(this.loader&&nh.test(this.loader.getAllResponseHeaders())){let t=this.loader.getResponseHeader("age");e=t?parseFloat(t):null}return e}getResponseHeader(e){return this.loader&&RegExp(`^${e}:\\s*[\\d.]+\\s*$`,"im").test(this.loader.getAllResponseHeaders())?this.loader.getResponseHeader(e):null}}let nu=ee(ee({autoStartLoad:!0,startPosition:-1,defaultAudioCodec:void 0,debug:!1,capLevelOnFPSDrop:!1,capLevelToPlayerSize:!1,ignoreDevicePixelRatio:!1,maxDevicePixelRatio:1/0,preferManagedMediaSource:!0,initialLiveManifestSize:1,maxBufferLength:30,backBufferLength:1/0,frontBufferFlushThreshold:1/0,startOnSegmentBoundary:!1,maxBufferSize:6e7,maxFragLookUpTolerance:.25,maxBufferHole:.1,detectStallWithCurrentTimeMs:1250,highBufferWatchdogPeriod:2,nudgeOffset:.1,nudgeMaxRetry:3,nudgeOnVideoHole:!0,liveSyncMode:"edge",liveSyncDurationCount:3,liveSyncOnStallIncrease:1,liveMaxLatencyDurationCount:1/0,liveSyncDuration:void 0,liveMaxLatencyDuration:void 0,maxLiveSyncPlaybackRate:1,liveDurationInfinity:!1,liveBackBufferLength:null,maxMaxBufferLength:600,enableWorker:!0,workerPath:null,enableSoftwareAES:!0,startLevel:void 0,startFragPrefetch:!1,fpsDroppedMonitoringPeriod:5e3,fpsDroppedMonitoringThreshold:.2,appendErrorMaxRetry:3,ignorePlaylistParsingErrors:!1,loader:nd,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,licenseXhrSetup:void 0,licenseResponseCallback:void 0,abrController:class extends et{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.co
67decTiers=null,this.timer=-1,this.fragCurrent=null,this.partCurrent=null,this.bitrateTestDelay=0,this.rebufferNotice=-1,this.supportedCache={},this.bwEstimator=void 0,this._abandonRulesCheck=e=>{var t;let{fragCurrent:i,partCurrent:r,hls:s}=this,{autoLevelEnabled:a,media:n}=s;if(!i||!n)return;let l=performance.now(),o=r?r.stats:i.stats,h=r?r.duration:i.duration,d=l-o.loading.start,c=s.minAutoLevel,f=i.level,g=this._nextAutoLevel;if(o.aborted||o.loaded&&o.loaded===o.total||f<=c){this.clearTimer(),this._nextAutoLevel=-1;return}if(!a)return;let m=g>-1&&g!==f,p=!!e||m;if(!p&&(n.paused||!n.playbackRate||!n.readyState))return;let y=s.mainForwardBufferInfo;if(!p&&null===y)return;let v=this.bwEstimator.getEstimateTTFB(),E=Math.abs(n.playbackRate);if(d<=Math.max(v,h/(2*E)*1e3))return;let T=y?y.len/E:0,S=o.loading.first?o.loading.first-o.loading.start:-1,L=o.loaded&&S>-1,A=this.getBwEstimate(),R=s.levels,b=R[f],k=Math.max(o.loaded,Math.round(h*(i.bitrate||b.averageBitrate)/8)),I=L?d-S:d;I<1&&L&&(I=Math.min(d,8*o.loaded/A));let D=L?1e3*o.loaded/I:0,_=v/1e3,P=D?(k-o.loaded)/D:8*k/A+_;if(P<=T)return;let C=D?8*D:A,w=(null==(t=e?.details||this.hls.latestLevelDetails)?void 0:t.live)===!0,x=this.hls.config.abrBandWidthUpFactor,M=1/0,O;for(O=f-1;O>c;O--){let e=R[O].maxBitrate,t=!R[O].details||w;if((M=this.getTimeToLoadFrag(_,C,h*e,t))<Math.min(T,h+_))break}if(M>=P||M>10*h)return;L?this.bwEstimator.sample(d-Math.min(v,S),o.loaded):this.bwEstimator.sampleTTFB(d);let F=R[O].maxBitrate;this.getBwEstimate()*x>F&&this.resetEstimator(F);let B=this.findBestLevel(F,c,O,0,T,1,1);B>-1&&(O=B),this.warn(`Fragment ${i.sn}${r?" part "+r.index:""} of level ${f} is loading too slowly;
68      Fragment duration: ${i.duration.toFixed(3)}
69      Time to underbuffer: ${T.toFixed(3)} s
70      Estimated load time for current fragment: ${P.toFixed(3)} s
71      Estimated load time for down switch fragment: ${M.toFixed(3)} s
72      TTFB estimate: ${0|S} ms
73      Current BW estimate: ${$(A)?0|A:"Unknown"} bps
74      New BW estimate: ${0|this.getBwEstimate()} bps
75      Switching to level ${O} @ ${0|F} bps`),s.nextLoadLevel=s.nextAutoLevel=O,this.clearTimer();let U=()=>{if(this.clearTimer(),this.fragCurrent===i&&this.hls.loadLevel===O&&O>0){let e=this.getStarvationDelay();if(this.warn(`Aborting inflight request ${O>0?"and switching down":""}
76      Fragment duration: ${i.duration.toFixed(3)} s
77      Time to underbuffer: ${e.toFixed(3)} s`),i.abortRequests(),this.fragCurrent=this.partCurrent=null,O>c){let t=this.findBestLevel(this.hls.levels[c].bitrate,c,O,0,e,1,1);-1===t&&(t=c),this.hls.nextLoadLevel=this.hls.nextAutoLevel=t,this.resetEstimator(this.hls.levels[t].bitrate)}}};m||P>2*M?U():this.timer=self.setInterval(U,1e3*M),s.trigger(K.FRAG_LOAD_EMERGENCY_ABORTED,{frag:i,part:r,stats:o})},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(){let e=this.hls.config;return new Q(e.abrEwmaSlowVoD,e.abrEwmaFastVoD,e.abrEwmaDefaultEstimate)}registerListeners(){let{hls:e}=this;e.on(K.MANIFEST_LOADING,this.onManifestLoading,this),e.on(K.FRAG_LOADING,this.onFragLoading,this),e.on(K.FRAG_LOADED,this.onFragLoaded,this),e.on(K.FRAG_BUFFERED,this.onFragBuffered,this),e.on(K.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(K.LEVEL_LOADED,this.onLevelLoaded,this),e.on(K.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(K.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.on(K.ERROR,this.onError,this)}unregisterListeners(){let{hls:e}=this;e&&(e.off(K.MANIFEST_LOADING,this.onManifestLoading,this),e.off(K.FRAG_LOADING,this.onFragLoading,this),e.off(K.FRAG_LOADED,this.onFragLoaded,this),e.off(K.FRAG_BUFFERED,this.onFragBuffered,this),e.off(K.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(K.LEVEL_LOADED,this.onLevelLoaded,this),e.off(K.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(K.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.off(K.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){let i=t.frag;
77if(!this.ignoreFragment(i)){if(!i.bitrateTest){var r;this.fragCurrent=i,this.partCurrent=null!=(r=t.part)?r: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 G.BUFFER_ADD_CODEC_ERROR:case G.BUFFER_APPEND_ERROR:this.lastLoadedFragLevel=-1,this.firstSelection=-1;break;case G.FRAG_LOAD_TIMEOUT:{let e=t.frag,{fragCurrent:i,partCurrent:r}=this;if(e&&i&&e.sn===i.sn&&e.level===i.level){let t=performance.now(),i=r?r.stats:e.stats,s=t-i.loading.start,a=i.loading.first?i.loading.first-i.loading.start:-1;if(i.loaded&&a>-1){let e=this.bwEstimator.getEstimateTTFB();this.bwEstimator.sample(s-Math.min(e,a),i.loaded)}else this.bwEstimator.sampleTTFB(s)}}}}getTimeToLoadFrag(e,t,i,r){let s=r?e+this.lastLevelLoadSec:0;return e+i/t+s}onLevelLoaded(e,t){let i=this.hls.config,{loading:r}=t.stats,s=r.end-r.first;$(s)&&(this.lastLevelLoadSec=s/1e3),t.details.live?this.bwEstimator.update(i.abrEwmaSlowLive,i.abrEwmaFastLive):this.bwEstimator.update(i.abrEwmaSlowVoD,i.abrEwmaFastVoD),this.timer>-1&&this._abandonRulesCheck(t.levelInfo)}onFragLoaded(e,{frag:t,part:i}){let r=i?i.stats:t.stats;if(t.type===q&&this.bwEstimator.sampleTTFB(r.loading.first-r.loading.start),!this.ignoreFragment(t)){if(this.clearTimer(),t.level===this._nextAutoLevel&&(this._nextAutoLevel=-1),this.firstSelection=-1,this.hls.config.abrMaxWithRealBitrate){let e=i?i.duration:t.duration,s=this.hls.levels[t.level],a=(s.loaded?s.loaded.bytes:0)+r.loaded,n=(s.loaded?s.loaded.duration:0)+e;s.loaded={bytes:a,duration:n},s.realBitrate=Math.round(8*a/n)}if(t.bitrateTest){let e={stats:r,frag:t,part:i,id:t.type};this.onFragBuffered(K.FRAG_BUFFERED,e),t.bitrateTest=!1}else this.lastLoadedFragLevel=t.level}}onFragBuffered(e,t){let{frag:i,part:r}=t,s=null!=r&&r.stats.loaded?r.stats:i.stats;if(s.aborted||this.ignoreFragment(i))return;let a=s.parsing.end-s.loading.start-Math.min(s.loading.first-s.loading.start,this.bwEstimator.getEstimateTTFB());this.bwEstimator.sample(a,s.loaded),s.bwEstimate=this.getBwEstimate(),i.bitrateTest?this.bitrateTestDelay=a/1e3:this.bitrateTestDelay=0}ignoreFragment(e){return e.type!==q||"initSegment"===e.sn}clearTimer(){this.timer>-1&&(self.clearInterval(this.timer),this.timer=-1)}get firstAutoLevel(){let{maxAutoLevel:e,minAutoLevel:t}=this.hls,i=this.getBwEstimate(),r=this.hls.config.maxStarvationDelay,s=this.findBestLevel(i,t,e,0,r,1,1);if(s>-1)return s;let a=this.hls.firstLevel,n=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 ${n}`),n}get forcedAutoLevel(){return this.nextAutoLevelKey?-1:this._nextAutoLevel}get nextAutoLevel(){let e=this.forcedAutoLevel,t=this.bwEstimator.canEstimate(),i=this.lastLoadedFragLevel>-1;if(-1!==e&&(!t||!i||this.nextAutoLevelKey===this.getAutoLevelKey()))return e;let r=t&&i?this.getNextABRAutoLevel():this.firstAutoLevel;if(-1!==e){let t=this.hls.levels;if(t.length>Math.max(e,r)&&t[e].loadError<=t[r].loadError)return e}return this._nextAutoLevel=r,this.nextAutoLevelKey=this.getAutoLevelKey(),r}getAutoLevelKey(){return`${this.getBwEstimate()}
77_${this.getStarvationDelay().toFixed(2)}`}getNextABRAutoLevel(){let{fragCurrent:e,partCurrent:t,hls:i}=this;if(i.levels.length<=1)return i.loadLevel;let{maxAutoLevel:r,config:s,minAutoLevel:a}=i,n=t?t.duration:e?e.duration:0,l=this.getBwEstimate(),o=this.getStarvationDelay(),h=s.abrBandWidthFactor,d=s.abrBandWidthUpFactor;if(o){let e=this.findBestLevel(l,a,r,o,0,h,d);if(e>=0)return this.rebufferNotice=-1,e}let c=n?Math.min(n,s.maxStarvationDelay):s.maxStarvationDelay;if(!o){let e=this.bitrateTestDelay;e&&(c=(n?Math.min(n,s.maxLoadingDelay):s.maxLoadingDelay)-e,this.info(`bitrate test took ${Math.round(1e3*e)}ms, set first fragment max fetchDuration to ${Math.round(1e3*c)} ms`),h=d=1)}let f=this.findBestLevel(l,a,r,o,c,h,d);if(this.rebufferNotice!==f&&(this.rebufferNotice=f,this.info(`${o?"rebuffering expected":"buffer is empty"}, optimal quality level ${f}`)),f>-1)return f;let g=i.levels[a],m=i.loadLevelObj;return m&&g?.bitrate<m.bitrate?a:i.loadLevel}getStarvationDelay(){let e=this.hls,t=e.media;if(!t)return 1/0;let i=t&&0!==t.playbackRate?Math.abs(t.playbackRate):1,r=e.mainForwardBufferInfo;return(r?r.len:0)/i}getBwEstimate(){return this.bwEstimator.canEstimate()?this.bwEstimator.getEstimate():this.hls.config.abrEwmaDefaultEstimate}findBestLevel(e,t,i,r,s,a,n){var l,o;let h=r+s,d=this.lastLoadedFragLevel,c=-1===d?this.hls.firstLevel:d,{fragCurrent:f,partCurrent:g}=this,{levels:m,allAudioTracks:p,loadLevel:y,config:v}=this.hls;if(1===m.length)return 0;let E=m[c],T=!!(null!=(l=this.hls.latestLevelDetails)&&l.live),S=-1===y||-1===d,L,A="SDR",R=E?.frameRate||0,{audioPreference:b,videoPreference:k}=v,I=this.audioTracksByGroup||(this.audioTracksByGroup=tg(p)),D=-1;if(S){if(-1!==this.firstSelection)return this.firstSelection;let r=function(e,t,i,r,s){let a=Object.keys(e),n=r?.channels,l=r?.audioCodec,o=s?.videoCodec,h=n&&2===parseInt(n),d=!1,c=!1,f=1/0,g=1/0,m=1/0,p=1/0,y=0,v=[],{preferHDR:E,allowedVideoRanges:T}=function(e,t){let i=!1,r=[];if(e&&(i="SDR"!==e,r=[e]),t){let e="SDR"!==(r=t.allowedVideoRanges||tl.slice(0)).join("")&&!t.videoCodec;(i=void 0!==t.preferHDR?t.preferHDR:e&&function(){if("function"==typeof matchMedia){let e=matchMedia("(dynamic-range: high)"),t=matchMedia("bad query");if(e.media!==t.media)return!0===e.matches}return!1}())||(r=["SDR"])}return{preferHDR:i,allowedVideoRanges:r}}(t,s);for(let t=a.length;t--;){let i=e[a[t]];d||(d=i.channels[2]>0),f=Math.min(f,i.minHeight),g=Math.min(g,i.minFramerate),m=Math.min(m,i.minBitrate),T.filter(e=>i.videoRanges[e]>0).length>0&&(c=!0)}f=$(f)?f:0,g=$(g)?g:0;let S=Math.max(1080,f),L=Math.max(30,g);i=Math.max(m=$(m)?m:i,i),c||(t=void 0);let A=a.length>1;return{codecSet:a.reduce((t,r)=>{let s=e[r];if(r===t)return t;if(v=c?T.filter(e=>s.videoRanges[e]>0):[],A){if(s.minBitrate>i)return tf(r,`min bitrate of ${s.minBitrate} > current estimate of ${i}`),t;if(!s.hasDefaultAudio)return tf(r,"no renditions with default or auto-select sound found"),t;if(l&&r.indexOf(l.substring(0,4))%5!=0)return tf(r,`audio codec preference "${l}" not found`),t;if(n&&!h){if(!s.channels[n])return tf(r,`no renditions with ${n} channel sound found (channels options: ${Object.keys(s.channels)})`),t}else if((!l||h)&&d&&0===s.channels[2])return tf(r,"no renditions with stereo sound found"),t;if(s.minHeight>S)return tf(r,`min resolution of ${s.minHeight} > maximum of ${S}`),t;if(s.minFramerate>L)return tf(r,`min framerate of ${s.minFramerate} > maximum of ${L}`),t;if(!v.some(e=>s.videoRanges[e]>0))return tf(r,`no variants with VIDEO-RANGE of ${tc(v)} found`),t;if(o&&r.indexOf(o.substring(0,4))%5!=0)return tf(r,`video codec preference "${o}" not found`),t;if(s.maxScore<y)return tf(r,`max score of ${s.maxScore} < selected max of ${y}`),t}return t&&(e3(r)>=e3(t)||s.fragmentError>e[t].fragmentError)?t:(p=s.minIndex,y=s.maxScore,r)},void 0),videoRanges:v,preferHDR:E,minFramerate:g,minBitrate:m,minIndex:p}}(this.codecTiers||(this.codecTiers=m.slice(t,i+1).reduce((e,t,i)=>{if(!t.codecSet)return e;let r=t.audioGroups,s=e[t.codecSet];s||(e[t.codecSet]=s={minBitrate:1/0,minHeight:1/0,minFramerate:1/0,minIndex:i,maxScore:0,videoRanges:{SDR:0},channels:{2:0},hasDefaultAudio:!r,fragmentError:0}
77),s.minBitrate=Math.min(s.minBitrate,t.bitrate);let a=Math.min(t.height,t.width);return s.minHeight=Math.min(s.minHeight,a),s.minFramerate=Math.min(s.minFramerate,t.frameRate),s.minIndex=Math.min(s.minIndex,i),s.maxScore=Math.max(s.maxScore,t.score),s.fragmentError+=t.fragmentError,s.videoRanges[t.videoRange]=(s.videoRanges[t.videoRange]||0)+1,r&&r.forEach(e=>{if(!e)return;let t=I.groups[e];t&&(s.hasDefaultAudio=s.hasDefaultAudio||I.hasDefaultAudio?t.hasDefault:t.hasAutoSelect||!I.hasDefaultAudio&&!I.hasAutoSelectAudio,Object.keys(t.channels).forEach(e=>{s.channels[e]=(s.channels[e]||0)+t.channels[e]}))}),e},{})),A,e,b,k),{codecSet:s,videoRanges:a,minFramerate:n,minBitrate:l,minIndex:o,preferHDR:h}=r;D=o,L=s,A=h?a[a.length-1]:a[0],R=n,e=Math.max(e,l),this.log(`picked start tier ${tc(r)}`)}else L=E?.codecSet,A=E?.videoRange;let _=g?g.duration:f?f.duration:0,P=this.bwEstimator.getEstimateTTFB()/1e3,C=[];for(let l=i;l>=t;l--){let t,f=m[l],p=l>c;if(!f)continue;if(v.useMediaCapabilities&&!f.supportedResult&&!f.supportedPromise){let t=navigator.mediaCapabilities;"function"==typeof t?.decodingInfo&&function(e,t,i,r,s,a){let n=e.videoCodec,l=e.audioCodec?e.audioGroups:null,o=a?.audioCodec,h=a?.channels,d=h?parseInt(h):o?1/0:2,c=null;if(null!=l&&l.length)try{c=1===l.length&&l[0]?t.groups[l[0]].channels:l.reduce((e,i)=>{if(i){let r=t.groups[i];if(!r)throw Error(`Audio track group ${i} not found`);Object.keys(r.channels).forEach(t=>{e[t]=(e[t]||0)+r.channels[t]})}return e},{2:0})}catch{return!0}return void 0!==n&&(n.split(",").some(e=>eY(e))||e.width>1920&&e.height>1088||e.height>1920&&e.width>1088||e.frameRate>Math.max(r,30)||"SDR"!==e.videoRange&&e.videoRange!==i||e.bitrate>Math.max(s,8e6))||!!c&&$(d)&&Object.keys(c).some(e=>parseInt(e)>d)}(f,I,A,R,e,b)?(f.supportedPromise=ts(f,I,t,this.supportedCache),f.supportedPromise.then(e=>{if(!this.hls)return;f.supportedResult=e;let t=this.hls.levels,i=t.indexOf(f);e.error?this.warn(`MediaCapabilities decodingInfo error: "${e.error}" for level ${i} ${tc(e)}`):e.supported?e.decodingInfoResults.some(e=>!1===e.smooth||!1===e.powerEfficient)&&this.log(`MediaCapabilities decodingInfo for level ${i} not smooth or powerEfficient: ${tc(e)}`):(this.warn(`Unsupported MediaCapabilities decodingInfo result for level ${i} ${tc(e)}`),i>-1&&t.length>1&&(this.log(`Removing unsupported level ${i}`),this.hls.removeLevel(i),-1===this.hls.loadLevel&&(this.hls.nextLoadLevel=0)))}).catch(e=>{this.warn(`Error handling MediaCapabilities decodingInfo: ${e}`)})):f.supportedResult=ti}if((L&&f.codecSet!==L||A&&f.videoRange!==A||p&&R>f.frameRate||!p&&R>0&&R<f.frameRate||null!=(o=f.supportedResult)&&null!=(o=o.decodingInfoResults)&&o.some(e=>!1===e.smooth))&&(!S||l!==D)){C.push(l);continue}let E=f.details,k=(g?E?.partTarget:E?.averagetargetduration)||_;t=p?n*e:a*e;let w=_&&r>=2*_&&0===s?f.averageBitrate:f.maxBitrate,x=this.getTimeToLoadFrag(P,t,w*k,void 0===E);if(t>=w&&(l===d||0===f.loadError&&0===f.fragmentError)&&(x<=P||!$(x)||T&&!this.bitrateTestDelay||x<h)){let e=this.forcedAutoLevel;return l!==y&&(-1===e||e!==y)&&(C.length&&this.trace(`Skipped level(s) ${C.join(",")} of ${i} max with CODECS and VIDEO-RANGE:"${m[C[0]].codecs}" ${m[C[0]].videoRange}; not compatible with "${L}" ${A}`),this.info(`switch candidate:${c}->${l} adjustedbw(${Math.round(t)})-bitrate=${Math.round(t-w)} ttfb:${P.toFixed(1)} avgDuration:${k.toFixed(1)} maxFetchDuration:${h.toFixed(1)} fetchDuration:${x.toFixed(1)} firstSelection:${S} codecSet:${f.codecSet} videoRange:${f.videoRange} hls.loadLevel:${y}`)),S&&(this.firstSelection=l),l}}return -1}set nextAutoLevel(e){let t=this.deriveNextAutoLevel(e);this._nextAutoLevel!==t&&(this.nextAutoLevelKey="",this._nextAutoLevel=t)}deriveNextAutoLevel(e){let{maxAutoLevel:t,minAutoLevel:i}=this.hls;return Math.min(Math.max(e,i),t)}},bufferController:class extends et{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=e=>{var t;this.hls&&(null==(t=this.mediaSource)?void 0:t.readyState)==="open"&&this.hls.pauseBuffer
77ing()},this._onStartStreaming=e=>{this.hls&&this.hls.resumeBuffering()},this._onMediaSourceOpen=e=>{let{media:t,mediaSource:i}=this;e&&this.log("Media source opened"),t&&i&&(i.removeEventListener("sourceopen",this._onMediaSourceOpen),t.removeEventListener("emptied",this._onMediaEmptied),this.updateDuration(),this.hls.trigger(K.MEDIA_ATTACHED,{media:t,mediaSource:i}),null!==this.mediaSource&&this.checkPendingTracks())},this._onMediaSourceClose=()=>{this.log("Media source closed")},this._onMediaSourceEnded=()=>{this.log("Media source ended")},this._onMediaEmptied=()=>{let{mediaSrc:e,_objectUrl:t}=this;e!==t&&this.error(`Media element src was set while attaching MediaSource (${t} > ${e})`)},this.hls=e,this.fragmentTracker=t,this.appendSource=function(e){return"u">typeof self&&e===self.ManagedMediaSource}(el(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(){let{hls:e}=this;e.on(K.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(K.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(K.MANIFEST_LOADING,this.onManifestLoading,this),e.on(K.MANIFEST_PARSED,this.onManifestParsed,this),e.on(K.BUFFER_RESET,this.onBufferReset,this),e.on(K.BUFFER_APPENDING,this.onBufferAppending,this),e.on(K.BUFFER_CODECS,this.onBufferCodecs,this),e.on(K.BUFFER_EOS,this.onBufferEos,this),e.on(K.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(K.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(K.FRAG_PARSED,this.onFragParsed,this),e.on(K.FRAG_CHANGED,this.onFragChanged,this),e.on(K.ERROR,this.onError,this)}unregisterListeners(){let{hls:e}=this;e.off(K.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(K.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(K.MANIFEST_LOADING,this.onManifestLoading,this),e.off(K.MANIFEST_PARSED,this.onManifestParsed,this),e.off(K.BUFFER_RESET,this.onBufferReset,this),e.off(K.BUFFER_APPENDING,this.onBufferAppending,this),e.off(K.BUFFER_CODECS,this.onBufferCodecs,this),e.off(K.BUFFER_EOS,this.onBufferEos,this),e.off(K.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(K.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(K.FRAG_PARSED,this.onFragParsed,this),e.off(K.FRAG_CHANGED,this.onFragChanged,this),e.off(K.ERROR,this.onError,this)}transferMedia(){let{media:e,mediaSource:t}=this;if(!e)return null;let i={};if(this.operationQueue){let e=this.isUpdating();e||this.operationQueue.removeBlockers();let t=this.isQueued();(e||t)&&this.warn(`Transfering MediaSource with${t?" operations in queue":""}${e?" updating SourceBuffer(s)":""} ${this.operationQueue}`),this.operationQueue.destroy()}let r=this.transferData;return!this.sourceBufferCount&&r&&r.mediaSource===t?Z(i,r.tracks):this.sourceBuffers.forEach(e=>{let[t]=e;t&&(i[t]=Z({},this.tracks[t]),this.removeBuffer(t)),e[0]=e[1]=null}),{media:e,mediaSource:t,tracks:i}}initTracks(){this.sourceBuffers=[[null,null],[null,null]],this.tracks={},this.resetQueue(),this.resetAppendErrors(),this.lastMpegAudioChunk=this.blockedAudioAppend=null,this.lastVideoAppendEnd=0}onManifestLoading(){this.bufferCodecEventsTotal=0,this.details=null}onManifestParsed(e,t){var i;let r=2;(!t.audio||t.video)&&t.altAudio||(r=1),this.bufferCodecEventsTotal=r,this.log(`${r} bufferCodec event(s) expected.`),null!=(i=this.transferData)&&i.mediaSource&&this.sourceBufferCount&&r&&this.bufferCreated()}onMediaAttaching(e,t){let i=this.media=t.media;this.transferData=this.overrides=void 0;let r=el(this.appendSource);if(r){let e=!!t.mediaSource;(e||t.overrides)&&(this.transferData=t,this.overrides=t.overrides);let n=this.mediaSource=t.mediaSource||new r;if(this.assignMediaSource(n),e)this._objectUrl=i.src,this.attachTransferred();else{let e=this._objectUrl=self.URL.createObjectURL(n);if(this.appendSource)try{var s,a;let t;i.removeAttribute("src");let r=self.ManagedMediaSource;i.disableRemotePlayback=i.disableRemotePlayback||r&&n instanceof r,sb(i),s=i,a=e,(t=self.document.createElement("source")).type="video/mp4",t.src=a,s.appendChild(t),i.load()}catch{i.src=e}else i.src=e}i.addEventListener("emptied",this._onMediaEmptied)}}assignMediaSource(e){var t,i;this.log(`${(null==(t=this.transferData)?void 0:t.mediaSource)===e?"transferred":"created"}
77 media source: ${null==(i=e.constructor)?void 0:i.name}`),e.addEventListener("sourceopen",this._onMediaSourceOpen),e.addEventListener("sourceended",this._onMediaSourceEnded),e.addEventListener("sourceclose",this._onMediaSourceClose),this.appendSource&&(e.addEventListener("startstreaming",this._onStartStreaming),e.addEventListener("endstreaming",this._onEndStreaming))}attachTransferred(){let e=this.media,t=this.transferData;if(!t||!e)return;let i=this.tracks,r=t.tracks,s=r?Object.keys(r):null,a=s?s.length:0,n=()=>{Promise.resolve().then(()=>{this.media&&this.mediaSourceOpenOrEnded&&this._onMediaSourceOpen()})};if(r&&s&&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})
78required tracks: ${tc(i,(e,t)=>"initSegment"===e?void 0:t)};
79transfer tracks: ${tc(r,(e,t)=>"initSegment"===e?void 0:t)}}`),!eo(r,i)){t.mediaSource=null,t.tracks=void 0;let s=e.currentTime,a=this.details,n=Math.max(s,a?.fragments[0].start||0);return n-s>1?void this.log(`attachTransferred: waiting for playback to reach new tracks start time ${s} -> ${n}`):(this.warn(`attachTransferred: resetting MediaSource for incompatible tracks ("${Object.keys(r)}"->"${Object.keys(i)}") start time: ${n} currentTime: ${s}`),this.onMediaDetaching(K.MEDIA_DETACHING,{}),this.onMediaAttaching(K.MEDIA_ATTACHING,t),void(e.currentTime=n))}this.transferData=void 0,s.forEach(e=>{let t=r[e];if(t){let i=t.buffer;if(i){let r=this.fragmentTracker,s=t.id;if(r.hasFragments(s)||r.hasParts(s)){let t=tJ.getBuffered(i);r.detectEvictedFragments(e,t,s,null,!0)}let a=sk(e),n=[e,i];this.sourceBuffers[a]=n,i.updating&&this.operationQueue&&this.operationQueue.prependBlocker(e),this.trackSourceBuffer(e,t)}}}),n(),this.bufferCreated()}else this.log("attachTransferred: MediaSource w/o SourceBuffers"),n()}get mediaSourceOpenOrEnded(){var e;let t=null==(e=this.mediaSource)?void 0:e.readyState;return"open"===t||"ended"===t}onMediaDetaching(e,t){let i=!!t.transferMedia;this.transferData=this.overrides=void 0;let{media:r,mediaSource:s,_objectUrl:a}=this;if(s){if(this.log(`media source ${i?"transferring":"detaching"}`),i)this.sourceBuffers.forEach(([e])=>{e&&this.removeBuffer(e)}),this.resetQueue();else{if(this.mediaSourceOpenOrEnded){let e="open"===s.readyState;try{let t=s.sourceBuffers;for(let i=t.length;i--;)e&&t[i].abort(),s.removeSourceBuffer(t[i]);e&&s.endOfStream()}catch(e){this.warn(`onMediaDetaching: ${e.message} while calling endOfStream`)}}this.sourceBufferCount&&this.onBufferReset()}s.removeEventListener("sourceopen",this._onMediaSourceOpen),s.removeEventListener("sourceended",this._onMediaSourceEnded),s.removeEventListener("sourceclose",this._onMediaSourceClose),this.appendSource&&(s.removeEventListener("startstreaming",this._onStartStreaming),s.removeEventListener("endstreaming",this._onEndStreaming)),this.mediaSource=null,this._objectUrl=null}r&&(r.removeEventListener("emptied",this._onMediaEmptied),i||(a&&self.URL.revokeObjectURL(a),this.mediaSrc===a?(r.removeAttribute("src"),this.appendSource&&sb(r),r.load()):this.warn("media|source.src was changed by a third party - skip cleanup")),this.media=null),this.hls.trigger(K.MEDIA_DETACHED,t)}onBufferReset(){this.sourceBuffers.forEach(([e])=>{e&&this.resetBuffer(e)}),this.initTracks()}resetBuffer(e){var t,i;let r=null==(t=this.tracks[e])?void 0:t.buffer;if(this.removeBuffer(e),r)try{null!=(i=this.mediaSource)&&i.sourceBuffers.length&&this.mediaSource.removeSourceBuffer(r)}catch(t){this.warn(`onBufferReset ${e}`,t)}delete this.tracks[e]}removeBuffer(e){this.removeBufferListeners(e),this.sourceBuffers[sk(e)]=[null,null];let t=this.tracks[e];t&&(t.buffer=void 0)}resetQueue(){this.operationQueue&&this.operationQueue.destroy(),this.operationQueue=new sS(this.tracks)}onBufferCodecs(e,t){var i;let r=this.tracks,s=Object.keys(t);this.log(`BUFFER_CODECS: "${s}" (current SB count ${this.sourceBufferCount})`);let a="audiovideo"in t&&(r.audio||r.video)||r.audiovideo&&("audio"in t||"video"in t),n=!a&&this.sourceBufferCount&&this.media&&s.some(e=>!r[e]);
79a||n?this.warn(`Unsupported transition between "${Object.keys(r)}" and "${s}" SourceBuffers`):(s.forEach(e=>{var i,s;let{id:a,codec:n,levelCodec:l,container:o,metadata:h,supplemental:d}=t[e],c=r[e],f=null==(i=this.transferData)||null==(i=i.tracks)?void 0:i[e],g=null!=f&&f.buffer?f:c,m=g?.pendingCodec||g?.codec,p=g?.levelCodec;c||(c=r[e]={buffer:void 0,listeners:[],codec:n,supplemental:d,container:o,levelCodec:l,metadata:h,id:a});let y=e6(m,p),v=y?.replace(sL,"$1"),E=e6(n,l),T=null==(s=E)?void 0:s.replace(sL,"$1");E&&y&&v!==T&&("audio"===e.slice(0,5)&&(E=e8(E,this.appendSource)),this.log(`switching codec ${m} to ${E}`),E!==(c.pendingCodec||c.codec)&&(c.pendingCodec=E),c.container=o,this.appendChangeType(e,o,E))}),(this.tracksReady||this.sourceBufferCount)&&(t.tracks=this.sourceBufferTracks),!this.sourceBufferCount&&(!(this.bufferCodecEventsTotal>1)||this.tracks.video||t.video||(null==(i=t.audio)?void 0:i.id)!=="main"||(this.log("Main audio-only"),this.bufferCodecEventsTotal=1),this.mediaSourceOpenOrEnded&&this.checkPendingTracks()))}get sourceBufferTracks(){return Object.keys(this.tracks).reduce((e,t)=>{let i=this.tracks[t];return e[t]={id:i.id,container:i.container,codec:i.codec,levelCodec:i.levelCodec},e},{})}appendChangeType(e,t,i){let r=`${t};codecs=${i}`,s={label:`change-type=${r}`,execute:()=>{let s=this.tracks[e];if(s){let a=s.buffer;null!=a&&a.changeType&&(this.log(`changing ${e} sourceBuffer type to ${r}`),a.changeType(r),s.codec=i,s.container=t)}this.shiftAndExecuteNext(e)},onStart:()=>{},onComplete:()=>{},onError:t=>{this.warn(`Failed to change ${e} SourceBuffer type`,t)}};this.append(s,e,this.isPending(this.tracks[e]))}blockAudio(e){var t;let i=e.start,r=i+.05*e.duration;if((null==(t=this.fragmentTracker.getAppendedFrag(i,q))?void 0:t.gap)===!0)return;let s={label:"block-audio",execute:()=>{var e;let t=this.tracks.video;(this.lastVideoAppendEnd>r||null!=t&&t.buffer&&tJ.isBuffered(t.buffer,r)||(null==(e=this.fragmentTracker.getAppendedFrag(r,q))?void 0:e.gap)===!0)&&(this.blockedAudioAppend=null,this.shiftAndExecuteNext("audio"))},onStart:()=>{},onComplete:()=>{},onError:e=>{this.warn("Error executing block-audio operation",e)}};this.blockedAudioAppend={op:s,frag:e},this.append(s,"audio",!0)}unblockAudio(){let{blockedAudioAppend:e,operationQueue:t}=this;e&&t&&(this.blockedAudioAppend=null,t.unblockAudio(e.op))}onBufferAppending(e,t){let{tracks:i}=this,{data:r,type:s,parent:a,frag:n,part:l,chunkMeta:o,offset:h}=t,d=o.buffering[s],{sn:c,cc:f}=n,g=self.performance.now();d.start=g;let m=n.stats.buffering,p=l?l.stats.buffering:null;0===m.start&&(m.start=g),p&&0===p.start&&(p.start=g);let y=i.audio,v=!1;"audio"===s&&y?.container==="audio/mpeg"&&(v=!this.lastMpegAudioChunk||1===o.id||this.lastMpegAudioChunk.sn!==o.sn,this.lastMpegAudioChunk=o);let E=i.video,T=E?.buffer;if(T&&"initSegment"!==c){let e=l||n,t=this.blockedAudioAppend;if("audio"!==s||"main"===a||this.blockedAudioAppend||E.ending||E.ended){if("video"===s){let i=e.end;if(t){let e=t.frag.start;(i>e||i<this.lastVideoAppendEnd||tJ.isBuffered(T,e))&&this.unblockAudio()}this.lastVideoAppendEnd=i}}else{let t=e.start+.05*e.duration,i=T.buffered,r=this.currentOp("video");(i.length||r)&&(r||tJ.isBuffered(T,t)||!(this.lastVideoAppendEnd<t))||this.blockAudio(e)}}let S=(l||n).start,L={label:`append-${s}`,execute:()=>{var e;d.executeStart=self.performance.now();let t=null==(e=this.tracks[s])?void 0:e.buffer;t&&(v?this.updateTimestampOffset(t,S,.1,s,c,f):void 0!==h&&$(h)&&this.updateTimestampOffset(t,h,1e-6,s,c,f)),this.appendExecutor(r,s)},onStart:()=>{},onComplete:()=>{let e=self.performance.now();d.executeEnd=d.end=e,0===m.first&&(m.first=e),p&&0===p.first&&(p.first=e);let t={};this.sourceBuffers.forEach(([e,i])=>{e&&(t[e]=tJ.getBuffered(i))}),this.appendErrors[s]=0,"audio"===s||"video"===s?this.appendErrors.audiovideo=0:(this.appendErrors.audio=0,this.appendErrors.video=0),this.hls.trigger(K.BUFFER_APPENDED,{type:s,frag:n,part:l,chunkMeta:o,parent:n.type,timeRanges:t})},onError:e=>{var t;let i={type:N.MEDIA_ERROR,parent:n.type,details:G.BUFFER_APPEND_ERROR,sourceBufferName:s,frag:n,part:l,chunkMeta:o,error:e,err:e,fatal:!1},r=null==(t=this.media)?void 0:t.error;if(e.code===DOMException.QUOTA_EXCEEDED_ERR||"QuotaExceededError"==e.name||"quota"in e)i.details=G.BUFFER_FULL_ERROR;else if(e.code===DOMException.INVALID_STATE_ERR&&this.mediaSourceOpenOrEnded&&!r)i.errorAction=tx(!0);else if(e.name===sA&&0===this.sourceBufferCount)i.errorAction=tx(!0);else{let e=++this.appendErrors[s];this.warn(`Failed ${e}/${this.hls.config.appendErrorMaxRetry} times to append segment in "${s}
79" sourceBuffer (${r||"no media error"})`),(e>=this.hls.config.appendErrorMaxRetry||r)&&(i.fatal=!0)}this.hls.trigger(K.ERROR,i)}};this.log(`queuing "${s}" append sn: ${c}${l?" p: "+l.index:""} of ${n.type===q?"level":"track"} ${n.level} cc: ${f}`),this.append(L,s,this.isPending(this.tracks[s]))}getFlushOp(e,t,i){return this.log(`queuing "${e}" remove ${t}-${i}`),{label:"remove",execute:()=>{this.removeExecutor(e,t,i)},onStart:()=>{},onComplete:()=>{this.hls.trigger(K.BUFFER_FLUSHED,{type:e})},onError:r=>{this.warn(`Failed to remove ${t}-${i} from "${e}" SourceBuffer`,r)}}}onBufferFlushing(e,t){let{type:i,startOffset:r,endOffset:s}=t;i?this.append(this.getFlushOp(i,r,s),i):this.sourceBuffers.forEach(([e])=>{e&&this.append(this.getFlushOp(e,r,s),e)})}onFragParsed(e,t){let{frag:i,part:r}=t,s=[],a=r?r.elementaryStreams:i.elementaryStreams;a[ek]?s.push("audiovideo"):(a[eR]&&s.push("audio"),a[eb]&&s.push("video"));let n=()=>{let e=self.performance.now();i.stats.buffering.end=e,r&&(r.stats.buffering.end=e);let t=r?r.stats:i.stats;this.hls.trigger(K.FRAG_BUFFERED,{frag:i,part:r,stats:t,id:i.type})};0===s.length&&this.warn(`Fragments must have at least one ElementaryStreamType set. type: ${i.type} level: ${i.level} sn: ${i.sn}`),this.blockBuffers(n,s).catch(e=>{this.warn(`Fragment buffered callback ${e}`),this.stepOperationQueue(this.sourceBufferTypes)})}onFragChanged(e,t){this.trimBuffers()}get bufferedToEnd(){return this.sourceBufferCount>0&&!this.sourceBuffers.some(([e])=>{if(e){let t=this.tracks[e];if(t)return!t.ended||t.ending}return!1})}onBufferEos(e,t){var i;this.sourceBuffers.forEach(([e])=>{if(e){let i=this.tracks[e];(!t.type||t.type===e)&&(i.ending=!0,i.ended||(i.ended=!0,this.log(`${e} buffer reached EOS`)))}});let r=(null==(i=this.overrides)?void 0:i.endOfStream)!==!1;this.sourceBufferCount>0&&!this.sourceBuffers.some(([e])=>{var t;return e&&!(null!=(t=this.tracks[e])&&t.ended)})?r?(this.log("Queueing EOS"),this.blockUntilOpen(()=>{this.tracksEnded();let{mediaSource:e}=this;if(!e||"open"!==e.readyState){e&&this.log(`Could not call mediaSource.endOfStream(). mediaSource.readyState: ${e.readyState}`);return}this.log("Calling mediaSource.endOfStream()"),e.endOfStream(),this.hls.trigger(K.BUFFERED_TO_END,void 0)})):(this.tracksEnded(),this.hls.trigger(K.BUFFERED_TO_END,void 0)):"video"===t.type&&this.unblockAudio()}tracksEnded(){this.sourceBuffers.forEach(([e])=>{if(null!==e){let t=this.tracks[e];t&&(t.ending=!1)}})}onLevelUpdated(e,{details:t}){t.fragments.length&&(this.details=t,this.updateDuration())}updateDuration(){this.blockUntilOpen(()=>{let e=this.getDurationAndRange();e&&this.updateMediaSource(e)})}onError(e,t){if(t.details===G.BUFFER_APPEND_ERROR&&t.frag){var i;let e=null==(i=t.errorAction)?void 0:i.nextAutoLevel;$(e)&&e!==t.frag.level&&this.resetAppendErrors()}}resetAppendErrors(){this.appendErrors={audio:0,video:0,audiovideo:0}}trimBuffers(){let{hls:e,details:t,media:i}=this;if(!i||null===t||!this.sourceBufferCount)return;let r=e.config,s=i.currentTime,a=t.levelTargetDuration,n=t.live&&null!==r.liveBackBufferLength?r.liveBackBufferLength:r.backBufferLength;if($(n)&&n>=0){let e=Math.max(n,a),t=Math.floor(s/a)*a-e;this.flushBackBuffer(s,a,t)}let l=r.frontBufferFlushThreshold;if($(l)&&l>0){let e=Math.max(Math.max(r.maxBufferLength,l),a),t=Math.floor(s/a)*a+e;this.flushFrontBuffer(s,a,t)}}flushBackBuffer(e,t,i){this.sourceBuffers.forEach(([e,t])=>{if(t){let s=tJ.getBuffered(t);if(s.length>0&&i>s.start(0)){var r;this.hls.trigger(K.BACK_BUFFER_REACHED,{bufferEnd:i});let t=this.tracks[e];if(null!=(r=this.details)&&r.live)this.hls.trigger(K.LIVE_BACK_BUFFER_REACHED,{bufferEnd:i});else if(null!=t&&t.ended)return void this.log(`Cannot flush ${e} back buffer while SourceBuffer is in ended state`);this.hls.trigger(K.BUFFER_FLUSHING,{startOffset:0,endOffset:i,type:e})}}})}flushFrontBuffer(e,t,i){this.sourceBuffers.forEach(([t,r])=>{if(r){let s=tJ.getBuffered(r),a=s.length;if(a<2)return;let n=s.start(a-1),l=s.end(a-1);i>n||e>=n&&e<=l||this.hls.trigger(K.BUFFER_FLUSHING,{startOffset:n,endOffset:1/0,type:t})}})}getDurationAndRange(){var e;let{details:t,mediaSource:i}=this;if(!t||!this.media||i?.readyState!=="open")return null;let r=t.edge;
79if(t.live&&this.hls.config.liveDurationInfinity){if(t.fragments.length&&i.setLiveSeekableRange){let e=Math.max(0,t.fragmentStart),i=Math.max(e,r);return{duration:1/0,start:e,end:i}}return{duration:1/0}}let s=null==(e=this.overrides)?void 0:e.duration;if(s)return $(s)?{duration:s}:null;let a=this.media.duration;return r>($(i.duration)?i.duration:0)&&r>a||!$(a)?{duration:r}:null}updateMediaSource({duration:e,start:t,end:i}){let r=this.mediaSource;this.media&&r&&"open"===r.readyState&&(r.duration!==e&&($(e)&&this.log(`Updating MediaSource duration to ${e.toFixed(3)}`),r.duration=e),void 0!==t&&void 0!==i&&(this.log(`MediaSource duration is set to ${r.duration}. Setting seekable range to ${t}-${i}.`),r.setLiveSeekableRange(t,i)))}get tracksReady(){let e=this.pendingTrackCount;return e>0&&(e>=this.bufferCodecEventsTotal||this.isPending(this.tracks.audiovideo))}checkPendingTracks(){let{bufferCodecEventsTotal:e,pendingTrackCount:t,tracks:i}=this;if(this.log(`checkPendingTracks (pending: ${t} codec events expected: ${e}) ${tc(i)}`),this.tracksReady){var r;let e=null==(r=this.transferData)?void 0:r.tracks;e&&Object.keys(e).length?this.attachTransferred():this.createSourceBuffers()}}bufferCreated(){if(this.sourceBufferCount){let e={};this.sourceBuffers.forEach(([t,i])=>{if(t){let r=this.tracks[t];e[t]={buffer:i,container:r.container,codec:r.codec,supplemental:r.supplemental,levelCodec:r.levelCodec,id:r.id,metadata:r.metadata}}}),this.hls.trigger(K.BUFFER_CREATED,{tracks:e}),this.log(`SourceBuffers created. Running queue: ${this.operationQueue}`),this.sourceBuffers.forEach(([e])=>{this.executeNext(e)})}else{let e=Error("could not create source buffer for media codec(s)");this.hls.trigger(K.ERROR,{type:N.MEDIA_ERROR,details:G.BUFFER_INCOMPATIBLE_CODECS_ERROR,fatal:!0,error:e,reason:e.message})}}createSourceBuffers(){let{tracks:e,sourceBuffers:t,mediaSource:i}=this;if(!i)throw Error("createSourceBuffers called when mediaSource was null");for(let s in e){let a=e[s];if(this.isPending(a)){let e=this.getTrackCodec(a,s),n=`${a.container};codecs=${e}`;a.codec=e,this.log(`creating sourceBuffer(${n})${this.currentOp(s)?" Queued":""} ${tc(a)}`);try{let e=i.addSourceBuffer(n),r=sk(s),l=[s,e];t[r]=l,a.buffer=e}catch(e){var r;this.error(`error while trying to add sourceBuffer: ${e.message}`),this.shiftAndExecuteNext(s),null==(r=this.operationQueue)||r.removeBlockers(),delete this.tracks[s],this.hls.trigger(K.ERROR,{type:N.MEDIA_ERROR,details:G.BUFFER_ADD_CODEC_ERROR,fatal:!1,error:e,sourceBufferName:s,mimeType:n,parent:a.id});return}this.trackSourceBuffer(s,a)}}this.bufferCreated()}getTrackCodec(e,t){let i=e.supplemental,r=e.codec;i&&("video"===t||"audiovideo"===t)&&eJ(i,"video")&&(r=function(e,t){let i=[];if(e){let t=e.split(",");for(let e=0;e<t.length;e++)eZ(t[e],"video")||i.push(t[e])}return t&&i.push(t),i.join(",")}(r,i));let s=e6(r,e.levelCodec);return s?"audio"===t.slice(0,5)?e8(s,this.appendSource):s:""}trackSourceBuffer(e,t){let i=t.buffer;if(!i)return;let r=this.getTrackCodec(t,e);this.tracks[e]={buffer:i,codec:r,container:t.container,levelCodec:t.levelCodec,supplemental:t.supplemental,metadata:t.metadata,id:t.id,listeners:[]},this.removeBufferListeners(e),this.addBufferListener(e,"updatestart",this.onSBUpdateStart),this.addBufferListener(e,"updateend",this.onSBUpdateEnd),this.addBufferListener(e,"error",this.onSBUpdateError),this.appendSource&&this.addBufferListener(e,"bufferedchange",(e,t)=>{let i=t.removedRanges;null!=i&&i.length&&this.hls.trigger(K.BUFFER_FLUSHED,{type:e})})}get mediaSrc(){var e,t;let i=(null==(e=this.media)||null==(t=e.querySelector)?void 0:t.call(e,"source"))||this.media;return i?.src}onSBUpdateStart(e){let t=this.currentOp(e);t&&t.onStart()}onSBUpdateEnd(e){var t;if((null==(t=this.mediaSource)?void 0:t.readyState)==="closed")return void this.resetBuffer(e);let i=this.currentOp(e);i&&(i.onComplete(),this.shiftAndExecuteNext(e))}onSBUpdateError(e,t){var i;let r=Error(`${e} SourceBuffer error. MediaSource readyState: ${null==(i=this.mediaSource)?void 0:i.readyState}`);this.error(`${r}`,t),this.hls.trigger(K.ERROR,{type:N.MEDIA_ERROR,details:G.BUFFER_APPENDING_ERROR,sourceBufferName:e,error:r,fatal:!1});let s=this.currentOp(e);s&&s.onError(r)}updateTimestampOffset(e,t,i,r,s,a){Math.abs(t-e.timestampOffset)>=i&&(this.log(`Updating ${r} SourceBuffer timestampOffset to ${t} (sn: ${s} cc: ${a})`),e.timestampOffset=t)}removeExecutor(e,t,i){let{media:r,mediaSource:s}=this,a=this.tracks[e],n=a?.buffer;if(!r||!s||!n){this.warn(`Attempting to remove from the ${e} SourceBuffer, but it does not exist`),this.shiftAndExecuteNext(e);return}let l=$(r.duration)?r.duration:1/0,o=$(s.duration)?s.duration:1/0,h=Math.max(0,t),d=Math.min(i,l,o);d>h&&(!a.ending||a.ended)?(a.ended=!1,this.log(`Removing [${h},${d}] from the ${e} SourceBuffer`),n.remove(h,d)):this.shiftAndExecuteNext(e)}appendExecutor(e,t){let i=this.tracks[t],r=i?.buffer;if(!r)throw new sR(`Attempting to append to the ${t} SourceBuffer, but it does not exist`);i.ending=!1,i.ended=!1,r.appendBuffer(e)}blockUntilOpen(e){if(this.isUpdating()||this.isQueued())this.blockBuffers(e).catch(e=>{this.warn(`SourceBuffer blocked callback ${e}
79`),this.stepOperationQueue(this.sourceBufferTypes)});else try{e()}catch(e){this.warn(`Callback run without blocking ${this.operationQueue} ${e}`)}}isUpdating(){return this.sourceBuffers.some(([e,t])=>e&&t.updating)}isQueued(){return this.sourceBuffers.some(([e])=>e&&!!this.currentOp(e))}isPending(e){return!!e&&!e.buffer}blockBuffers(e,t=this.sourceBufferTypes){if(!t.length)return this.log("Blocking operation requested, but no SourceBuffers exist"),Promise.resolve().then(e);let{operationQueue:i}=this,r=t.map(e=>this.appendBlocker(e));return t.length>1&&this.blockedAudioAppend&&this.unblockAudio(),Promise.all(r).then(t=>{i===this.operationQueue&&(e(),this.stepOperationQueue(this.sourceBufferTypes))})}stepOperationQueue(e){e.forEach(e=>{var t;let i=null==(t=this.tracks[e])?void 0:t.buffer;!i||i.updating||this.shiftAndExecuteNext(e)})}append(e,t,i){this.operationQueue&&this.operationQueue.append(e,t,i)}appendBlocker(e){if(this.operationQueue)return this.operationQueue.appendBlocker(e)}currentOp(e){return this.operationQueue?this.operationQueue.current(e):null}executeNext(e){e&&this.operationQueue&&this.operationQueue.executeNext(e)}shiftAndExecuteNext(e){this.operationQueue&&this.operationQueue.shiftAndExecuteNext(e)}get pendingTrackCount(){return Object.keys(this.tracks).reduce((e,t)=>e+ +!!this.isPending(this.tracks[t]),0)}get sourceBufferCount(){return this.sourceBuffers.reduce((e,[t])=>e+ +!!t,0)}get sourceBufferTypes(){return this.sourceBuffers.map(([e])=>e).filter(e=>!!e)}addBufferListener(e,t,i){let r=this.tracks[e];if(!r)return;let s=r.buffer;if(!s)return;let a=i.bind(this,e);r.listeners.push({event:t,listener:a}),s.addEventListener(t,a)}removeBufferListeners(e){let t=this.tracks[e];if(!t)return;let i=t.buffer;i&&(t.listeners.forEach(e=>{i.removeEventListener(e.event,e.listener)}),t.listeners.length=0)}},capLevelController:sI,errorController:class extends et{constructor(e){super("error-controller",e.logger),this.hls=void 0,this.playlistError=0,this.hls=e,this.registerListeners()}registerListeners(){let e=this.hls;e.on(K.ERROR,this.onError,this),e.on(K.MANIFEST_LOADING,this.onManifestLoading,this),e.on(K.LEVEL_UPDATED,this.onLevelUpdated,this)}unregisterListeners(){let e=this.hls;e&&(e.off(K.ERROR,this.onError,this),e.off(K.ERROR,this.onErrorOut,this),e.off(K.MANIFEST_LOADING,this.onManifestLoading,this),e.off(K.LEVEL_UPDATED,this.onLevelUpdated,this))}destroy(){this.unregisterListeners(),this.hls=null}startLoad(e){}stopLoad(){this.playlistError=0}getVariantLevelIndex(e){return e?.type===q?e.level:this.getVariantIndex()}getVariantIndex(){var e;let t=this.hls,i=t.currentLevel;return null!=(e=t.loadLevelObj)&&e.details||-1===i?t.loadLevel:i}variantHasKey(e,t){if(e){var i;if(null!=(i=e.details)&&i.hasKey(t))return!0;let r=e.audioGroups;if(r)return this.hls.allAudioTracks.filter(e=>r.indexOf(e.groupId)>=0).some(e=>{var i;return null==(i=e.details)?void 0:i.hasKey(t)})}return!1}onManifestLoading(){this.playlistError=0}onLevelUpdated(){this.playlistError=0}onError(e,t){var i,r,s;if(t.fatal)return;let a=this.hls,n=t.context;switch(t.details){case G.FRAG_LOAD_ERROR:case G.FRAG_LOAD_TIMEOUT:case G.KEY_LOAD_ERROR:case G.KEY_LOAD_TIMEOUT:t.errorAction=this.getFragRetryOrSwitchAction(t);return;case G.FRAG_PARSING_ERROR:if(null!=(i=t.frag)&&i.gap){t.errorAction=tx();return}case G.FRAG_GAP:case G.FRAG_DECRYPT_ERROR:t.errorAction=this.getFragRetryOrSwitchAction(t),t.errorAction.action=2;return;case G.LEVEL_EMPTY_ERROR:case G.LEVEL_PARSING_ERROR:{let e=t.parent===q?t.level:a.loadLevel;t.details===G.LEVEL_EMPTY_ERROR&&null!=(r=t.context)&&null!=(r=r.levelDetails)&&r.live?t.errorAction=this.getPlaylistRetryOrSwitchAction(t,e):(t.levelRetry=!1,t.errorAction=this.getLevelSwitchAction(t,e))}return;case G.LEVEL_LOAD_ERROR:case G.LEVEL_LOAD_TIMEOUT:"number"==typeof n?.level&&(t.errorAction=this.getPlaylistRetryOrSwitchAction(t,n.level));return;case G.AUDIO_TRACK_LOAD_ERROR:case G.AUDIO_TRACK_LOAD_TIMEOUT:case G.SUBTITLE_LOAD_ERROR:case G.SUBTITLE_TRACK_LOAD_TIMEOUT:if(n){let e=a.loadLevelObj;e&&(n.type===j&&e.hasAudioGroup(n.groupId)||n.type===W&&e.hasSubtitleGroup(n.groupId))&&(t.errorAction=this.getPlaylistRetryOrSwitchAction(t,a.loadLevel),t.errorAction.action=2,t.errorAction.flags=1)}return;case G.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:t.errorAction={action:2,flags:2};return;case G.KEY_SYSTEM_SESSION_UPDATE_FAILED:case G.KEY_SYSTEM_STATUS_INTERNAL_ERROR:case G.KEY_SYSTEM_NO_SESSION:t.errorAction={action:2,flags:4};return;
79case G.BUFFER_ADD_CODEC_ERROR:case G.REMUX_ALLOC_ERROR:case G.BUFFER_APPEND_ERROR:t.errorAction||(t.errorAction=this.getLevelSwitchAction(t,null!=(s=t.level)?s:a.loadLevel));return;case G.INTERNAL_EXCEPTION:case G.BUFFER_APPENDING_ERROR:case G.BUFFER_FULL_ERROR:case G.LEVEL_SWITCH_ERROR:case G.BUFFER_STALLED_ERROR:case G.BUFFER_SEEK_OVER_HOLE:case G.BUFFER_NUDGE_ON_STALL:t.errorAction=tx();return}t.type===N.KEY_SYSTEM_ERROR&&(t.levelRetry=!1,t.errorAction=tx())}getPlaylistRetryOrSwitchAction(e,t){let i=tD(this.hls.config.playlistLoadPolicy,e),r=this.playlistError++;if(tC(i,r,tb(e),e.response))return{action:5,flags:0,retryConfig:i,retryCount:r};let s=this.getLevelSwitchAction(e,t);return i&&(s.retryConfig=i,s.retryCount=r),s}getFragRetryOrSwitchAction(e){let t=this.hls,i=this.getVariantLevelIndex(e.frag),r=t.levels[i],{fragLoadPolicy:s,keyLoadPolicy:a}=t.config,n=tD(tk(e)?a:s,e),l=t.levels.reduce((e,t)=>e+t.fragmentError,0);if(r&&(e.details!==G.FRAG_GAP&&r.fragmentError++,!tI(e)&&tC(n,l,tb(e),e.response)))return{action:5,flags:0,retryConfig:n,retryCount:l};let o=this.getLevelSwitchAction(e,i);return n&&(o.retryConfig=n,o.retryCount=l),o}getLevelSwitchAction(e,t){let i=this.hls;null==t&&(t=i.loadLevel);let r=this.hls.levels[t];if(r){var s,a,n,l;let t=e.details;r.loadError++,t===G.BUFFER_APPEND_ERROR&&r.fragmentError++;let o=-1,{levels:h,loadLevel:d,minAutoLevel:c,maxAutoLevel:f}=i;i.autoLevelEnabled||i.config.preserveManualLevelOnError||(i.loadLevel=-1);let g=null==(s=e.frag)?void 0:s.type,m=(g===Y&&t===G.FRAG_PARSING_ERROR||"audio"===e.sourceBufferName&&(t===G.BUFFER_ADD_CODEC_ERROR||t===G.BUFFER_APPEND_ERROR))&&h.some(({audioCodec:e})=>r.audioCodec!==e),p="video"===e.sourceBufferName&&(t===G.BUFFER_ADD_CODEC_ERROR||t===G.BUFFER_APPEND_ERROR)&&h.some(({codecSet:e,audioCodec:t})=>r.codecSet!==e&&r.audioCodec===t),{type:y,groupId:v}=null!=(a=e.context)?a:{};for(let i=h.length;i--;){let s=(i+d)%h.length;if(s!==d&&s>=c&&s<=f&&0===h[s].loadError){let i=h[s];if(t===G.FRAG_GAP&&g===q&&e.frag){let t=h[s].details;if(t){let i=tL(e.frag,t.fragments,e.frag.start);if(null!=i&&i.gap)continue}}else if(y===j&&i.hasAudioGroup(v)||y===W&&i.hasSubtitleGroup(v)||g===Y&&null!=(n=r.audioGroups)&&n.some(e=>i.hasAudioGroup(e))||g===X&&null!=(l=r.subtitleGroups)&&l.some(e=>i.hasSubtitleGroup(e))||m&&r.audioCodec===i.audioCodec||p&&r.codecSet===i.codecSet||!m&&r.codecSet!==i.codecSet)continue;o=s;break}}if(o>-1&&i.loadLevel!==o)return e.levelRetry=!0,this.playlistError=0,{action:2,flags:0,nextAutoLevel:o}}return{action:2,flags:1}}onErrorOut(e,t){var i;switch(null==(i=t.errorAction)?void 0:i.action){case 0:break;case 2:this.sendAlternateToPenaltyBox(t),t.errorAction.resolved||t.details===G.FRAG_GAP?/MediaSource readyState: ended/.test(t.error.message)&&(this.warn(`MediaSource ended after "${t.sourceBufferName}" sourceBuffer append error. Attempting to recover from media error.`),this.hls.recoverMediaError()):t.fatal=!0}if(t.fatal)return void this.hls.stopLoad()}sendAlternateToPenaltyBox(e){let t=this.hls,i=e.errorAction;if(!i)return;let{flags:r}=i,s=i.nextAutoLevel;switch(r){case 0:this.switchLevel(e,s);break;case 2:{let r=this.getVariantLevelIndex(e.frag),s=t.levels[r],a=s?.attrs["HDCP-LEVEL"];if(i.hdcpLevel=a,"NONE"===a)this.warn("HDCP policy resticted output with HDCP-LEVEL=NONE");else if(a){t.maxHdcpLevel=tn[tn.indexOf(a)-1],i.resolved=!0,this.warn(`Restricting playback to HDCP-LEVEL of "${t.maxHdcpLevel}" or lower`);break}}case 4:{let t=e.decryptdata;if(t){let r=this.hls.levels,s=r.length;for(let i=s;i--;)if(this.variantHasKey(r[i],t)){var a,n;this.log(`Banned key found in level ${i} (${r[i].bitrate}bps) or audio group "${null==(a=r[i].audioGroups)?void 0:a.join(",")}" (${null==(n=e.frag)?void 0:n.type} fragment) ${ed(t.keyId||[])}`),r[i].fragmentError++,r[i].loadError++,this.log(`Removing level ${i} with key error (${e.error})`),this.hls.removeLevel(i)}let l=e.frag;if(this.hls.levels.length<s)i.resolved=!0;else if(l&&l.type!==q){let e=l.decryptdata;e&&!t.matches(e)&&(i.resolved=!0)}}}}i.resolved||this.switchLevel(e,s)}switchLevel(e,t){if(void 0!==t&&e.errorAction&&(this.warn(`switching to level ${t} after ${e.details}`),this.hls.nextAutoLevel=t,e.errorAction.resolved=!0,this.hls.nextLoadLevel=this.hls.nextAutoLevel,e.details===G.BUFFER_ADD_CODEC_ERROR&&e.mimeType&&"audiovideo"!==e.sourceBufferName)){let t=te(e.mimeType),i=this.hls.levels;for(let r=i.length;r--;)i[r][`${e.sourceBufferName}Codec`]===t&&(this.log(`Removing level ${r} for ${e.details} ("${t}" not supported)`),this.hls.removeLevel(r))}}},fpsController:class{constructor(e){this.hls=void 0,this.isVideoPlaybackQualityAvailable=!1,this.timer=void 0,this.media=null,this.lastTime=void 0,this.lastDroppedFrames=0,this.lastDecodedFrames=0,this.streamController=void 0,this.hls=e,this.registerListeners()}setStreamController(e){this.streamController=e}
79registerListeners(){this.hls.on(K.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.on(K.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListeners(){this.hls.off(K.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.off(K.MEDIA_DETACHING,this.onMediaDetaching,this)}destroy(){this.timer&&clearInterval(this.timer),this.unregisterListeners(),this.isVideoPlaybackQualityAvailable=!1,this.media=null}onMediaAttaching(e,t){let i=this.hls.config;if(i.capLevelOnFPSDrop){let e=t.media instanceof self.HTMLVideoElement?t.media:null;this.media=e,e&&"function"==typeof e.getVideoPlaybackQuality&&(this.isVideoPlaybackQualityAvailable=!0),self.clearInterval(this.timer),this.timer=self.setInterval(this.checkFPSInterval.bind(this),i.fpsDroppedMonitoringPeriod)}}onMediaDetaching(){this.media=null}checkFPS(e,t,i){let r=performance.now();if(t){if(this.lastTime){let e=r-this.lastTime,s=i-this.lastDroppedFrames,a=t-this.lastDecodedFrames,n=1e3*s/e,l=this.hls;if(l.trigger(K.FPS_DROP,{currentDropped:s,currentDecoded:a,totalDroppedFrames:i}),n>0&&s>l.config.fpsDroppedMonitoringThreshold*a){let e=l.currentLevel;l.logger.warn("drop FPS ratio greater than max allowed value for currentLevel: "+e),e>0&&(-1===l.autoLevelCapping||l.autoLevelCapping>=e)&&(e-=1,l.trigger(K.FPS_DROP_LEVEL_CAPPING,{level:e,droppedLevel:l.currentLevel}),l.autoLevelCapping=e,this.streamController.nextLevelSwitch())}}this.lastTime=r,this.lastDroppedFrames=i,this.lastDecodedFrames=t}}checkFPSInterval(){let e=this.media;if(e)if(this.isVideoPlaybackQualityAvailable){let t=e.getVideoPlaybackQuality();this.checkFPS(e,t.totalVideoFrames,t.droppedVideoFrames)}else this.checkFPS(e,e.webkitDecodedFrameCount,e.webkitDroppedFrameCount)}},stretchShortVideoTrack:!1,maxAudioFramesDrift:1,forceKeyFrameOnDiscontinuity:!0,abrEwmaFastLive:3,abrEwmaSlowLive:9,abrEwmaFastVoD:3,abrEwmaSlowVoD:9,abrEwmaDefaultEstimate:5e5,abrEwmaDefaultEstimateMax:5e6,abrBandWidthFactor:.95,abrBandWidthUpFactor:.7,abrMaxWithRealBitrate:!1,maxStarvationDelay:4,maxLoadingDelay:4,minAutoBitrate:0,emeEnabled:!1,widevineLicenseUrl:void 0,drmSystems:{},drmSystemOptions:{},requestMediaKeySystemAccessFunc:iT,requireKeySystemAccessOnStart:!1,testBandwidth:!0,progressive:!1,lowLatencyMode:!0,cmcd:void 0,enableDateRangeMetadataCues:!0,enableEmsgMetadataCues:!0,enableEmsgKLVMetadata:!1,enableID3MetadataCues:!0,enableInterstitialPlayback:!0,interstitialAppendInPlace:!0,interstitialLiveLookAhead:10,useMediaCapabilities:!0,preserveManualLevelOnError:!1,certLoadPolicy:{default:{maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:null,errorRetry:null}},keyLoadPolicy:{default:{maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:2e4,backoff:"linear"},errorRetry:{maxNumRetry:8,retryDelayMs:1e3,maxRetryDelayMs:2e4,backoff:"linear"}}},manifestLoadPolicy:{default:{maxTimeToFirstByteMs:1/0,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},playlistLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:2,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},fragLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:12e4,timeoutRetry:{maxNumRetry:4,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:6,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},steeringManifestLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},interstitialAssetListLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:3e4,timeoutRetry:{maxNumRetry:0,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:0,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},manifestLoadingTimeOut:1e4,manifestLoadingMaxRetry:1,manifestLoadingRetryDelay:1e3,manifestLoadingMaxRetryTimeout:64e3,levelLoadingTimeOut:1e4,levelLoadingMaxRetry:4,levelLoadingRetryDelay:1e3,levelLoadingMaxRetryTimeout:64e3,fragLoadingTimeOut:2e4,fragLoadingMaxRetry:6,fragLoadingRetryDelay:1e3,fragLoadingMaxRetryTimeout:64e3},{cueHandler:ns,enableWebVTT:!0,enableIMSC1:!0,enableCEA708Captions:!0,captionsTextTrack1Label:"English",captionsTextTrack1LanguageCode:"en",captionsTextTrack2Label:"Spanish",captionsTextTrack2LanguageCode:"es",captionsTextTrack3Label:"Unknown CC",captionsTextTrack3LanguageCode:"",captionsTextTrack4Label:"Unknown CC",captionsTextTrack4LanguageCode:"",renderTextTracksNatively:!0}),{},{subtitleStreamController:class extends ro{constructor(e,t,i){super(e,t,i,"subt
79itle-stream-controller",X),this.currentTrackId=-1,this.tracksBuffered=[],this.mainDetails=null,this.registerListeners()}onHandlerDestroying(){this.unregisterListeners(),super.onHandlerDestroying(),this.mainDetails=null}registerListeners(){super.registerListeners();let{hls:e}=this;e.on(K.LEVEL_LOADED,this.onLevelLoaded,this),e.on(K.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(K.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.on(K.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(K.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.on(K.BUFFER_FLUSHING,this.onBufferFlushing,this)}unregisterListeners(){super.unregisterListeners();let{hls:e}=this;e.off(K.LEVEL_LOADED,this.onLevelLoaded,this),e.off(K.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(K.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.off(K.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(K.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.off(K.BUFFER_FLUSHING,this.onBufferFlushing,this)}startLoad(e,t){this.stopLoad(),this.state=i6,this.setInterval(500),this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,this.tick()}onManifestLoading(){super.onManifestLoading(),this.mainDetails=null}onMediaDetaching(e,t){this.tracksBuffered=[],super.onMediaDetaching(e,t)}onLevelLoaded(e,t){this.mainDetails=t.details}onSubtitleFragProcessed(e,t){let i,{frag:r,success:s}=t;if(this.fragContextChanged(r)||(eD(r)&&(this.fragPrevious=r),this.state=i6),!s)return;let a=this.tracksBuffered[this.currentTrackId];if(!a)return;let n=r.start;for(let e=0;e<a.length;e++)if(n>=a[e].start&&n<=a[e].end){i=a[e];break}let l=r.start+r.duration;i?i.end=l:(i={start:n,end:l},a.push(i)),this.fragmentTracker.fragBuffered(r),this.fragBufferedComplete(r,null),this.media&&this.tick()}onBufferFlushing(e,t){let{startOffset:i,endOffset:r}=t;if(0===i&&r!==1/0){let e=r-1;if(e<=0)return;t.endOffsetSubtitles=Math.max(0,e),this.tracksBuffered.forEach(t=>{for(let i=0;i<t.length;){if(t[i].end<=e){t.shift();continue}if(t[i].start<e)t[i].start=e;else break;i++}}),this.fragmentTracker.removeFragmentsInRange(i,e,X)}}onError(e,t){let i=t.frag;i?.type===X&&(t.details===G.FRAG_GAP&&this.fragmentTracker.fragBuffered(i,!0),this.fragCurrent&&this.fragCurrent.abortRequests(),this.state!==i8&&(this.state=i6))}onSubtitleTracksUpdated(e,{subtitleTracks:t}){if(this.levels&&sv(this.levels,t)){this.levels=t.map(e=>new td(e));return}this.tracksBuffered=[],this.levels=t.map(e=>{let t=new td(e);return this.tracksBuffered[t.id]=[],t}),this.fragmentTracker.removeFragmentsInRange(0,1/0,X),this.fragPrevious=null,this.mediaBuffer=null}onSubtitleTrackSwitch(e,t){var i;if(this.currentTrackId=t.id,!(null!=(i=this.levels)&&i.length)||-1===this.currentTrackId)return void this.clearInterval();let r=this.levels[this.currentTrackId];null!=r&&r.details?this.mediaBuffer=this.mediaBufferTimeRanges:this.mediaBuffer=null,r&&this.state!==i8&&this.setInterval(500)}onSubtitleTrackLoaded(e,t){var i,r;let{currentTrackId:s,levels:a}=this,{details:n,id:l}=t;if(!a)return void this.warn(`Subtitle tracks were reset while loading level ${l}`);let o=a[l];if(l>=a.length||!o)return;this.log(`Subtitle track ${l} loaded [${n.startSN},${n.endSN}]${n.lastPartSn?`[part-${n.lastPartSn}-${n.lastPartIndex}]`:""},duration:${n.totalduration}`),this.mediaBuffer=this.mediaBufferTimeRanges;let h=0;if(n.live||null!=(i=o.details)&&i.live){if(n.deltaUpdateFailed)return;let e=this.mainDetails;if(!e){this.startFragRequested=!1;return}let t=e.fragments[0];o.details?0===(h=this.alignPlaylists(n,o.details,null==(r=this.levelLastLoaded)?void 0:r.details))&&t&&ij(n,h=t.start):n.hasProgramDateTime&&e.hasProgramDateTime?(i2(n,e),h=n.fragmentStart):t&&ij(n,h=t.start),e&&!this.startFragRequested&&this.setStartPosition(e,h)}o.details=n,this.levelLastLoaded=o,l===s&&(this.hls.trigger(K.SUBTITLE_TRACK_UPDATED,{details:n,id:l,groupId:t.groupId}),this.tick(),n.live&&!this.fragCurrent&&this.media&&this.state===i6&&(tL(null,n.fragments,this.media.currentTime,0)||(this.warn("Subtitle playlist not aligned with playback"),o.details=void 0)))}_handleFragmentLoadComplete(e){let{frag:t,payload:i}=e,r=t.decryptdata,s=this.hls;if(!this.fragContextChanged(t)&&i&&i.byteLength>
790&&null!=r&&r.key&&r.iv&&ie(r.method)){let e=performance.now();this.decrypter.decrypt(new Uint8Array(i),r.key.buffer,r.iv.buffer,it(r.method)).catch(e=>{throw s.trigger(K.ERROR,{type:N.MEDIA_ERROR,details:G.FRAG_DECRYPT_ERROR,fatal:!1,error:e,reason:e.message,frag:t}),e}).then(i=>{let r=performance.now();s.trigger(K.FRAG_DECRYPTED,{frag:t,payload:i,stats:{tstart:e,tdecrypt:r}})}).catch(e=>{this.warn(`${e.name}: ${e.message}`),this.state=i6})}}doTick(){if(!this.media){this.state=i6;return}if(this.state===i6){let{currentTrackId:e,levels:t}=this,i=t?.[e];if(!i||!t.length||!i.details||this.waitForLive(i))return;let{config:r}=this,s=this.getLoadPosition(),{end:a,len:n}=tJ.bufferedInfo(this.tracksBuffered[this.currentTrackId]||[],s,r.maxBufferHole),l=i.details;if(n>this.hls.maxBufferLength+l.levelTargetDuration)return;let o=l.fragments,h=o.length,d=l.edge,c=null,f=this.fragPrevious;if(a<d){let e=r.maxFragLookUpTolerance;(c=tL(f,o,Math.max(o[0].start,a),a>d-e?0:e))||!f||!(f.start<o[0].start)||(c=o[0])}else c=o[h-1];if(!(c=this.filterReplacedPrimary(c,i.details)))return;let g=o[c.sn-l.startSN-1];if(g&&g.cc===c.cc&&this.fragmentTracker.getState(g)===tM&&(c=g),this.fragmentTracker.getState(c)===tM){let e=this.mapToInitFragWhenRequired(c);e&&this.loadFragment(e,i,a)}}}loadFragment(e,t,i){eD(e)?super.loadFragment(e,t,i):this._loadInitSegment(e,t)}get mediaBufferTimeRanges(){return new aA(this.tracksBuffered[this.currentTrackId]||[])}},subtitleTrackController:class extends sy{constructor(e){super(e,"subtitle-track-controller"),this.media=null,this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0,this.queuedDefaultTrack=-1,this.useTextTrackPolling=!1,this.subtitlePollingInterval=-1,this._subtitleDisplay=!0,this.asyncPollTrackChange=()=>this.pollTrackChange(0),this.onTextTracksChanged=()=>{if(this.useTextTrackPolling||self.clearInterval(this.subtitlePollingInterval),!this.media||!this.hls.config.renderTextTracksNatively)return;let e=null,t=ah(this.media.textTracks);for(let i=0;i<t.length;i++)if("hidden"===t[i].mode)e=t[i];else if("showing"===t[i].mode){e=t[i];break}let i=this.findTrackForTextTrack(e);this.subtitleTrack!==i&&this.setSubtitleTrack(i)},this.registerListeners()}destroy(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.currentTrack=null,this.onTextTracksChanged=this.asyncPollTrackChange=null,super.destroy()}get subtitleDisplay(){return this._subtitleDisplay}set subtitleDisplay(e){this._subtitleDisplay=e,this.trackId>-1&&this.toggleTrackModes()}registerListeners(){let{hls:e}=this;e.on(K.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(K.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(K.MANIFEST_LOADING,this.onManifestLoading,this),e.on(K.MANIFEST_PARSED,this.onManifestParsed,this),e.on(K.LEVEL_LOADING,this.onLevelLoading,this),e.on(K.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(K.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(K.ERROR,this.onError,this)}unregisterListeners(){let{hls:e}=this;e.off(K.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(K.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(K.MANIFEST_LOADING,this.onManifestLoading,this),e.off(K.MANIFEST_PARSED,this.onManifestParsed,this),e.off(K.LEVEL_LOADING,this.onLevelLoading,this),e.off(K.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(K.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(K.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){let i=this.media;if(!i)return;let r=!!t.transferMedia;self.clearInterval(this.subtitlePollingInterval),this.useTextTrackPolling||i.textTracks.removeEventListener("change",this.asyncPollTrackChange),this.trackId>-1&&(this.queuedDefaultTrack=this.trackId),this.subtitleTrack=-1,this.media=null,r||ah(i.textTracks).forEac
79h(e=>{al(e)})}onManifestLoading(){this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0}onManifestParsed(e,t){this.tracks=t.subtitleTracks}onSubtitleTrackLoaded(e,t){let{id:i,groupId:r,details:s}=t,a=this.tracksInGroup[i];if(!a||a.groupId!==r)return void this.warn(`Subtitle track with id:${i} and group:${r} not found in active group ${a?.groupId}`);let n=a.details;a.details=t.details,this.log(`Subtitle track ${i} "${a.name}" lang:${a.lang} group:${r} loaded [${s.startSN}-${s.endSN}]`),i===this.trackId&&this.playlistLoaded(i,t,n)}onLevelLoading(e,t){this.switchLevel(t.level)}onLevelSwitching(e,t){this.switchLevel(t.level)}switchLevel(e){let t=this.hls.levels[e];if(!t)return;let i=t.subtitleGroups||null,r=this.groupIds,s=this.currentTrack;if(!i||r?.length!==i?.length||null!=i&&i.some(e=>r?.indexOf(e)===-1)){this.groupIds=i,this.trackId=-1,this.currentTrack=null;let e=this.tracks.filter(e=>!i||-1!==i.indexOf(e.groupId));if(e.length)this.selectDefaultTrack&&!e.some(e=>e.default)&&(this.selectDefaultTrack=!1),e.forEach((e,t)=>{e.id=t});else if(!s&&!this.tracksInGroup.length)return;this.tracksInGroup=e;let t=this.hls.config.subtitlePreference;if(!s&&t){this.selectDefaultTrack=!1;let i=tp(t,e);if(i>-1)s=e[i];else{let e=tp(t,this.tracks);s=this.tracks[e]}}let r=this.findTrackId(s);-1===r&&s&&(r=this.findTrackId(null)),this.log(`Updating subtitle tracks, ${e.length} track(s) found in "${i?.join(",")}" group-id`),this.hls.trigger(K.SUBTITLE_TRACKS_UPDATED,{subtitleTracks:e}),-1!==r&&-1===this.trackId&&this.setSubtitleTrack(r)}}findTrackId(e){let t=this.tracksInGroup,i=this.selectDefaultTrack;for(let r=0;r<t.length;r++){let s=t[r];if(!(i&&!s.default||!i&&!e)&&(!e||ty(s,e)))return r}if(e){for(let i=0;i<t.length;i++){let r=t[i];if(sE(e.attrs,r.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return i}for(let i=0;i<t.length;i++){let r=t[i];if(sE(e.attrs,r.attrs,["LANGUAGE"]))return i}}return -1}findTrackForTextTrack(e){if(e){let t=this.tracksInGroup;for(let i=0;i<t.length;i++)if(sT(t[i],e))return i}return -1}onError(e,t){t.fatal||!t.context||t.context.type!==W||t.context.id!==this.trackId||this.groupIds&&-1===this.groupIds.indexOf(t.context.groupId)||this.checkRetry(t)}get allSubtitleTracks(){return this.tracks}get subtitleTracks(){return this.tracksInGroup}get subtitleTrack(){return this.trackId}set subtitleTrack(e){this.selectDefaultTrack=!1,this.setSubtitleTrack(e)}setSubtitleOption(e){if(this.hls.config.subtitlePreference=e,e){if(-1===e.id)return this.setSubtitleTrack(-1),null;let t=this.allSubtitleTracks;if(this.selectDefaultTrack=!1,t.length){let i=this.currentTrack;if(i&&ty(e,i))return i;let r=tp(e,this.tracksInGroup);if(r>-1){let e=this.tracksInGroup[r];return this.setSubtitleTrack(r),e}if(i)return null;{let i=tp(e,t);if(i>-1)return t[i]}}}return null}loadPlaylist(e){super.loadPlaylist(),this.shouldLoadPlaylist(this.currentTrack)&&this.scheduleLoading(this.currentTrack,e)}loadingPlaylist(e,t){super.loadingPlaylist(e,t);let i=e.id,r=e.groupId,s=this.getUrlWithDirectives(e.url,t),a=e.details,n=a?.age;this.log(`Loading subtitle ${i} "${e.name}" lang:${e.lang} group:${r}${t?.msn!==void 0?" at sn "+t.msn+" part "+t.part:""}${n&&a.live?" age "+n.toFixed(1)+(a.type&&" "+a.type||""):""} ${s}`),this.hls.trigger(K.SUBTITLE_TRACK_LOADING,{url:s,id:i,groupId:r,deliveryDirectives:t||null,track:e})}toggleTrackModes(){let e,{media:t}=this;if(!t)return;let i=ah(t.textTracks),r=this.currentTrack;if(r&&((e=i.filter(e=>sT(r,e))[0])||this.warn(`Unable to find subtitle TextTrack with name "${r.name}" and language "${r.lang}"`)),[].slice.call(i).forEach(t=>{"disabled"!==t.mode&&t!==e&&(t.mode="disabled")}),e){let t=this.subtitleDisplay?"showing":"hidden";e.mode!==t&&(e.mode=t)}}setSubtitleTrack(e){let t=this.tracksInGroup;if(!this.media){this.queuedDefaultTrack=e;return}if(e<-1||e>=t.length||!$(e))return void this.warn(`Invalid subtitle track id: ${e}`);this.selectDefaultTrack=!1;let i=this.currentTrack,r=t[e]||null;if(this.trackId=e,this.currentTrack=r,this.toggleTrackModes(),!r)return void this.hls.trigger(K.SUBTITLE_TRACK_SWITCH,{id:e});let s=!!r.details&&!r.details.live;if(e===this.trackId&&r===i&&s)return;this.log(`Switching to subtitle-track ${e}`+(r?` "${r.name}" lang:${r.lang} group:${r.groupId}`:""));let{id:a,groupId:n="",name:l,type:o,url:h}=r;this.hls.trigger(K.SUBTITLE_TRACK_SWITCH,{id:a,groupId:n,name:l,type:o,url:h});let d=this.switchParams(r.url,i?.details,r.details);this.loadPlaylist(d)}},timelineController:class{constructor(e){this.hls=void 0,this.media=null,this.config=void 0,this.enabled=!0,this.Cues=void 0,this.textTracks=[],this.tracks=[],this.initPTS=[],this.unparsedVttFrags=[],this.captionsTracks={},this.nonNativeCaptionsTracks={},this.cea608Parser1=void 0,this.cea608Parser2=void 0,this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs=ni(),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}}
79,e.on(K.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(K.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(K.MANIFEST_LOADING,this.onManifestLoading,this),e.on(K.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(K.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(K.FRAG_LOADING,this.onFragLoading,this),e.on(K.FRAG_LOADED,this.onFragLoaded,this),e.on(K.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.on(K.FRAG_DECRYPTED,this.onFragDecrypted,this),e.on(K.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(K.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.on(K.BUFFER_FLUSHING,this.onBufferFlushing,this)}destroy(){let{hls:e}=this;e.off(K.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(K.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(K.MANIFEST_LOADING,this.onManifestLoading,this),e.off(K.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(K.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(K.FRAG_LOADING,this.onFragLoading,this),e.off(K.FRAG_LOADED,this.onFragLoaded,this),e.off(K.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.off(K.FRAG_DECRYPTED,this.onFragDecrypted,this),e.off(K.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(K.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.off(K.BUFFER_FLUSHING,this.onBufferFlushing,this),this.hls=this.config=this.media=null,this.cea608Parser1=this.cea608Parser2=void 0}initCea608Parsers(){let e=new a7(this,"textTrack1"),t=new a7(this,"textTrack2"),i=new a7(this,"textTrack3"),r=new a7(this,"textTrack4");this.cea608Parser1=new aB(1,e,t),this.cea608Parser2=new aB(3,i,r)}addCues(e,t,i,r,s){let a=!1;for(let e=s.length;e--;){var n,l;let r=s[e],o=(n=r[0],l=r[1],Math.min(l,i)-Math.max(n,t));if(o>=0&&(r[0]=Math.min(r[0],t),r[1]=Math.max(r[1],i),a=!0,o/(i-t)>.5))return}if(a||s.push([t,i]),this.config.renderTextTracksNatively){let s=this.captionsTracks[e];this.Cues.newCue(s,t,i,r)}else{let s=this.Cues.newCue(null,t,i,r);this.hls.trigger(K.CUES_PARSED,{type:"captions",cues:s,track:e})}}onInitPtsFound(e,{frag:t,id:i,initPTS:r,timescale:s,trackId:a}){let{unparsedVttFrags:n}=this;i===q&&(this.initPTS[t.cc]={baseTime:r,timescale:s,trackId:a}),n.length&&(this.unparsedVttFrags=[],n.forEach(e=>{this.initPTS[e.frag.cc]?this.onFragLoaded(K.FRAG_LOADED,e):this.hls.trigger(K.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:e.frag,error:Error("Subtitle discontinuity domain does not match main")})}))}getExistingTrack(e,t){let{media:i}=this;if(i)for(let r=0;r<i.textTracks.length;r++){let s=i.textTracks[r];if(nt(s,{name:e,lang:t,characteristics:"transcribes-spoken-dialog,describes-music-and-sound"}))return s}return null}createCaptionsTrack(e){this.config.renderTextTracksNatively?this.createNativeTrack(e):this.createNonNativeTrack(e)}createNativeTrack(e){if(this.captionsTracks[e])return;let{captionsProperties:t,captionsTracks:i,media:r}=this,{label:s,languageCode:a}=t[e],n=this.getExistingTrack(s,a);if(n)i[e]=n,al(i[e]),aa(i[e],r);else{let t=this.createTextTrack("captions",s,a);t&&(t[e]=!0,i[e]=t)}}createNonNativeTrack(e){if(this.nonNativeCaptionsTracks[e])return;let t=this.captionsProperties[e];if(!t)return;let i={_id:e,label:t.label,kind:"captions",default:!!t.media&&!!t.media.default,closedCaptions:t.media};this.nonNativeCaptionsTracks[e]=i,this.hls.trigger(K.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:[i]})}createTextTrack(e,t,i){let r=this.media;if(r)return r.addTextTrack(e,t,i)}onMediaAttaching(e,t){this.media=t.media,t.mediaSource||this._cleanTracks()}onMediaDetaching(e,t){let i=!!t.transferMedia;if(this.media=null,i)return;let{captionsTracks:r}=this;Object.keys(r).forEach(e=>{al(r[e]),delete r[e]}),this.nonNativeCaptionsTracks={}}onManifestLoading(){this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs=ni(),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(){let{media:e}=this;if(!e)return;let t=e.textTracks;if(t)for(let e=0;e<t.length;e++)al(t[e])}
79onSubtitleTracksUpdated(e,t){let i=t.subtitleTracks||[],r=i.some(e=>e.textCodec===aJ);if(this.config.enableWebVTT||r&&this.config.enableIMSC1){if(sv(this.tracks,i)){this.tracks=i;return}if(this.textTracks=[],this.tracks=i,this.config.renderTextTracksNatively){let e=this.media,t=e?ah(e.textTracks):null;if(this.tracks.forEach((e,i)=>{let r;if(t){let i=null;for(let r=0;r<t.length;r++)if(t[r]&&nt(t[r],e)){i=t[r],t[r]=null;break}i&&(r=i)}if(r)al(r);else{let t=ne(e);(r=this.createTextTrack(t,e.name,e.lang))&&(r.mode="disabled")}r&&this.textTracks.push(r)}),null!=t&&t.length){let e=t.filter(e=>null!==e).map(e=>e.label);e.length&&this.hls.logger.warn(`Media element contains unused subtitle tracks: ${e.join(", ")}. Replace media element for each source to clear TextTracks and captions menu.`)}}else if(this.tracks.length){let e=this.tracks.map(e=>({label:e.name,kind:e.type.toLowerCase(),default:e.default,subtitleTrack:e}));this.hls.trigger(K.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:e})}}}onManifestLoaded(e,t){this.config.enableCEA708Captions&&t.captions&&t.captions.forEach(e=>{let t=/(?:CC|SERVICE)([1-4])/.exec(e.instreamId);if(!t)return;let i=`textTrack${t[1]}`,r=this.captionsProperties[i];r&&(r.label=e.name,e.lang&&(r.languageCode=e.lang),r.media=e)})}closedCaptionsForLevel(e){let t=this.hls.levels[e.level];return t?.attrs["CLOSED-CAPTIONS"]}onFragLoading(e,t){if(this.enabled&&t.frag.type===q){var i,r;let{cea608Parser1:e,cea608Parser2:s,lastSn:a}=this,{cc:n,sn:l}=t.frag,o=null!=(i=null==(r=t.part)?void 0:r.index)?i:-1;e&&s&&(l!==a+1||l===a&&o!==this.lastPartIndex+1||n!==this.lastCc)&&(e.reset(),s.reset()),this.lastCc=n,this.lastSn=l,this.lastPartIndex=o}}onFragLoaded(e,t){let{frag:i,payload:r}=t;if(i.type===X)if(r.byteLength){let e=i.decryptdata,s="stats"in t;if(null==e||!e.encrypted||s){let e=this.tracks[i.level],s=this.vttCCs;s[i.cc]||(s[i.cc]={start:i.start,prevCC:this.prevCC,new:!0},this.prevCC=i.cc),e&&e.textCodec===aJ?this._parseIMSC1(i,r):this._parseVTTs(t)}}else this.hls.trigger(K.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:i,error:Error("Empty subtitle payload")})}_parseIMSC1(e,t){let i=this.hls;a3(t,this.initPTS[e.cc],t=>{this._appendCues(t,e.level),i.trigger(K.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:e})},t=>{i.logger.log(`Failed to parse IMSC1: ${t}`),i.trigger(K.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:e,error:t})})}_parseVTTs(e){var t,i,r,s,a,n,l,o;let h,d,c,f,g,m,p,y,v,{frag:E,payload:T}=e,{initPTS:S,unparsedVttFrags:L}=this,A=S.length-1;if(!S[E.cc]&&-1===A)return void L.push(e);let R=this.hls;i=null!=(t=E.initSegment)&&t.data?eW(E.initSegment.data,new Uint8Array(T)).buffer:T,r=this.initPTS[E.cc],s=this.vttCCs,a=E.cc,n=E.start,l=e=>{this._appendCues(e,E.level),R.trigger(K.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:E})},o=t=>{let i="Missing initPTS for VTT MPEGTS"===t.message;i?L.push(e):this._fallbackToIMSC1(E,T),R.logger.log(`Failed to parse VTT cue: ${t}`),i&&A>E.cc||R.trigger(K.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:E,error:t})},h=new aq,d=eh(new Uint8Array(i)).trim().replace(aY,`
80`).split(`
81`),c=[],f=r?function(e,t=1){return r6(e,9e4,1/t)}(r.baseTime,r.timescale):0,g="00:00.000",m=0,p=0,v=!0,h.oncue=function(e){let t=s[a],i=s.ccOffset,l=(m-f)/9e4;if(null!=t&&t.new&&(void 0!==p?i=s.ccOffset=t.start:aZ(s,a,l)),l){if(!r){y=Error("Missing initPTS for VTT MPEGTS");return}i=l-s.presentationOffset}let o=e.endTime-e.startTime,h=ss((e.startTime+i-p)*9e4,9e4*n)/9e4;e.startTime=Math.max(h,0),e.endTime=Math.max(h+o,0);let d=e.text.trim();e.text=decodeURIComponent(encodeURIComponent(d)),e.id||(e.id=aQ(e.startTime,e.endTime,d)),e.endTime>0&&c.push(e)},h.onparsingerror=function(e){y=e},h.onflush=function(){y?o(y):l(c)},d.forEach(e=>{if(v)if(aX(e,"X-TIMESTAMP-MAP=")){v=!1,e.slice(16).split(",").forEach(e=>{aX(e,"LOCAL:")?g=e.slice(6):aX(e,"MPEGTS:")&&(m=parseInt(e.slice(7)))});try{p=az(g)/1e3}catch(e){y=e}return}else""===e&&(v=!1);h.parse(e+`
82`)}),h.flush()}_fallbackToIMSC1(e,t){let i=this.tracks[e.level];i.textCodec||a3(t,this.initPTS[e.cc],()=>{i.textCodec=aJ,this._parseIMSC1(e,t)},()=>{i.textCodec="wvtt"})}_appendCues(e,t){let i=this.hls;if(this.config.renderTextTracksNatively){let i=this.textTracks[t];if(!i||"disabled"===i.mode)return;
82e.forEach(e=>an(i,e))}else{let r=this.tracks[t];if(!r)return;let s=r.default?"default":"subtitles"+t;i.trigger(K.CUES_PARSED,{type:"subtitles",cues:e,track:s})}}onFragDecrypted(e,t){let{frag:i}=t;i.type===X&&this.onFragLoaded(K.FRAG_LOADED,t)}onSubtitleTracksCleared(){this.tracks=[],this.captionsTracks={}}onFragParsingUserdata(e,t){if(!this.enabled||!this.config.enableCEA708Captions)return;let{frag:i,samples:r}=t;if(i.type!==q||"NONE"!==this.closedCaptionsForLevel(i))for(let e=0;e<r.length;e++){let t=r[e].bytes;if(t){this.cea608Parser1||this.initCea608Parsers();let i=this.extractCea608Data(t);this.cea608Parser1.addData(r[e].pts,i[0]),this.cea608Parser2.addData(r[e].pts,i[1])}}}onBufferFlushing(e,{startOffset:t,endOffset:i,endOffsetSubtitles:r,type:s}){let{media:a}=this;if(!(!a||a.currentTime<i)){if(!s||"video"===s){let{captionsTracks:e}=this;Object.keys(e).forEach(r=>ao(e[r],t,i))}if(this.config.renderTextTracksNatively&&0===t&&void 0!==r){let{textTracks:e}=this;Object.keys(e).forEach(i=>ao(e[i],t,r))}}}extractCea608Data(e){let t=[[],[]],i=31&e[0],r=2;for(let s=0;s<i;s++){let i=e[r++],s=127&e[r++],a=127&e[r++];if((0!==s||0!==a)&&(4&i)!=0){let e=3&i;(0===e||1===e)&&(t[e].push(s),t[e].push(a))}}return t}},audioStreamController:class extends ro{constructor(e,t,i){super(e,t,i,"audio-stream-controller",Y),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();let{hls:e}=this;e.on(K.LEVEL_LOADED,this.onLevelLoaded,this),e.on(K.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.on(K.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(K.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(K.BUFFER_RESET,this.onBufferReset,this),e.on(K.BUFFER_CREATED,this.onBufferCreated,this),e.on(K.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(K.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(K.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(K.FRAG_LOADING,this.onFragLoading,this),e.on(K.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){let{hls:e}=this;e&&(super.unregisterListeners(),e.off(K.LEVEL_LOADED,this.onLevelLoaded,this),e.off(K.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.off(K.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(K.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(K.BUFFER_RESET,this.onBufferReset,this),e.off(K.BUFFER_CREATED,this.onBufferCreated,this),e.off(K.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(K.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(K.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(K.FRAG_LOADING,this.onFragLoading,this),e.off(K.FRAG_BUFFERED,this.onFragBuffered,this))}onInitPtsFound(e,{frag:t,id:i,initPTS:r,timescale:s,trackId:a}){if(i===q){let e=t.cc,i=this.fragCurrent;if(this.initPTS[e]={baseTime:r,timescale:s,trackId:a},this.log(`InitPTS for cc: ${e} found from main: ${r/s} (${r}/${s}) trackId: ${a}`),this.mainAnchor=t,this.state===rn){let i=this.waitingData;(i||this.loadingParts)&&(!i||i.frag.cc===e)||this.syncWithAnchor(t,i?.frag)}else!this.hls.hasEnoughToStart&&i&&i.cc!==e?(i.abortRequests(),this.syncWithAnchor(t,i)):this.state===i6&&this.tick()}}getLoadPosition(){return!this.startFragRequested&&this.nextLoadPosition>=0?this.nextLoadPosition:super.getLoadPosition()}syncWithAnchor(e,t){var i;let r=(null==(i=this.mainFragLoading)?void 0:i.frag)||null;if(t&&r?.cc===t.cc)return;let s=(r||e).cc,a=tR(this.getLevelDetails(),s,this.getLoadPosition());a&&(this.log(`Syncing with main frag at ${a.start} cc ${a.cc}`),this.startFragRequested=!1,this.nextLoadPosition=a.start,this.resetLoadingState(),this.state===i6&&this.doTickIdle())}startLoad(e,t){if(!this.levels){this.startPosition=e,this.state=i8;return}let i=this.lastCurrentTime;this.stopLoad(),this.setInterval(100),i>
820&&-1===e?(this.log(`Override startPosition with lastCurrentTime @${i.toFixed(3)}`),e=i,this.state=i6):this.state=rt,this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,this.tick()}doTick(){switch(this.state){case i6:this.doTickIdle();break;case rt:{let{levels:e,trackId:t}=this,i=e?.[t],r=i?.details;if(r&&!this.waitForLive(i)){if(this.waitForCdnTuneIn(r))break;this.state=rn}break}case re:this.checkRetryDate();break;case rn:{let e=this.waitingData;if(e){let{frag:t,part:i,cache:r,complete:s}=e,a=this.mainAnchor;if(void 0!==this.initPTS[t.cc]){this.waitingData=null,this.state=i7;let e={frag:t,part:i,payload:r.flush().buffer,networkDetails:null};this._handleFragmentLoadProgress(e),s&&super._handleFragmentLoadComplete(e)}else a&&a.cc!==e.frag.cc&&this.syncWithAnchor(a,e.frag)}else this.state=i6}}this.onTickEnd()}resetLoadingState(){let e=this.waitingData;e&&(this.fragmentTracker.removeFragment(e.frag),this.waitingData=null),super.resetLoadingState()}onTickEnd(){let{media:e}=this;null!=e&&e.readyState&&(this.lastCurrentTime=e.currentTime)}doTickIdle(){var e;let{hls:t,levels:i,media:r,trackId:s}=this,a=t.config;if(!this.buffering||!r&&!this.primaryPrefetch&&(this.startFragRequested||!a.startFragPrefetch)||!(null!=i&&i[s]))return;let n=i[s],l=n.details;if(!l||this.waitForLive(n)||this.waitForCdnTuneIn(l)){this.state=rt,this.startFragRequested=!1;return}let o=this.mediaBuffer?this.mediaBuffer:this.media;this.bufferFlushed&&o&&(this.bufferFlushed=!1,this.afterBufferFlushed(o,eR,Y));let h=this.getFwdBufferInfo(o,Y);if(null===h)return;if(!this.switchingTrack&&this._streamEnded(h,l)){t.trigger(K.BUFFER_EOS,{type:"audio"}),this.state=rs;return}let d=h.len,c=t.maxBufferLength,f=l.fragments,g=f[0].start,m=this.getLoadPosition(),p=this.flushing?m:h.end;if(this.switchingTrack&&r&&l.PTSKnown&&m<g&&(h.end>g||h.nextStart)&&(this.log("Alt audio track ahead of main track, seek to start of alt audio track"),r.currentTime=g+.05),d>=c&&!this.switchingTrack&&p<f[f.length-1].start)return;let y=this.getNextFragment(p,l);if(y&&this.isLoopLoading(y,p)&&(y=this.getNextFragmentLoopLoading(y,l,h,q,c)),!y){this.bufferFlushed=!0;return}if(this.exceedsMaxBuffer(h,c,y))return;let v=(null==(e=this.mainFragLoading)?void 0:e.frag)||null;if(!this.audioOnly&&this.startFragRequested&&v&&eD(y)&&!y.endList&&(!l.live||!this.loadingParts&&p<this.hls.liveSyncPosition)&&("OK"===this.fragmentTracker.getState(v)&&(this.mainFragLoading=v=null),v&&eD(v))){if(y.start>v.end){let e=this.fragmentTracker.getFragAtPos(p,q);e&&e.end>v.end&&(v=e,this.mainFragLoading={frag:e,targetBufferTime:null})}if(y.start>v.end)return}this.loadFragment(y,n,p)}onMediaDetaching(e,t){this.bufferFlushed=this.flushing=!1,super.onMediaDetaching(e,t)}onAudioTracksUpdated(e,{audioTracks:t}){this.resetTransmuxer(),this.levels=t.map(e=>new td(e))}onAudioTrackSwitching(e,t){let i=!!t.url;this.trackId=t.id;let{fragCurrent:r}=this;r&&(r.abortRequests(),this.removeUnbufferedFrags(r.start)),this.resetLoadingState(),i?(this.switchingTrack=t,this.flushAudioIfNeeded(t),this.state!==i8&&(this.setInterval(100),this.state=i6,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;let i=this.cachedTrackLoadedData;i&&(this.cachedTrackLoadedData=null,this.onAudioTrackLoaded(K.AUDIO_TRACK_LOADED,i))}onAudioTrackLoaded(e,t){var i,r;let{levels:s}=this,{details:a,id:n,groupId:l,track:o}=t;if(!s)return void this.warn(`Audio tracks reset while loading track ${n} "${o.name}" of "${l}"`);let h=this.mainDetails;if(!h||a.endCC>h.endCC||h.expired){this.cachedTrackLoadedData=t,this.state!==i8&&(this.state=rt);return}this.cachedTrackLoadedData=null,this.log(`Audio track ${n} "${o.name}" of "${l}" loaded [${a.startSN},${a.endSN}]${a.lastPartSn?`[part-${a.lastPartSn}-${a.lastPartIndex}]`:""},duration:${a.totalduration}`);let d=s[n],c=0;if(a.live||null!=(i=d.details)&&i.live){if(this.checkLiveUpdate(a),a.deltaUpdateFailed)return;d.details&&(c=this.alignPlaylists(a,d.details,null==(r=this.levelLastLoaded)?void 0:r.details)),a.alignedSliding||(i1(a,h),a.alignedSliding||i2(a,h),c=a.fragmentStart)}d.details=a,this.levelLastLoaded=d,this.startFragRequested||this.setStartPosition(h,c),this.hls.trigger(K.AUDIO_TRACK_UPDATED,{details:a,id:n,groupId:t.groupId}),this.state!==rt||this.waitForCdnTuneIn(a)||(this.state=i6),this.tick()}_handleFragmentLoadProgress(e){var t;let i=e.frag,{part:r,payload:s}=e,{config:a,trackId:n,levels:l}=this;if(!l)return void this.warn(`Audio tracks were reset while fragment load was in progress. Fragment ${i.sn} of level ${i.level} will not be buffered`);let o=l[n];if(!o)return void this.warn("Audio track is undefined on fragment load progress");let h=o.details;if(!h){this.warn("Audio track details undefined on fragment load progress"),this.removeUnbufferedFrags(i.start);return}let d=a.defaultAudioCodec||o.audioCodec||"mp4a.40.2",c=this.transmuxer;c||(c=this.transmuxer=new sp(this.hls,Y,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)));let f=this.initPTS[i.cc],g=null==(t=i.initSegment)?void 0:t.data;if(void 0!==f){let e=r?r.index:-1,t=new tz(i.level,i.sn,i.stats.chunkCount,s.byteLength,e,-1!==e);c.push(s,g,d,"",i,r,h.totalduration,!1,t,f)}else{this.log(`Unknown video PTS for cc ${i.cc}, waiting for video PTS before demuxing audio frag ${i.sn} of [${h.startSN} ,${h.endSN}],track ${n}`);let{cache:e}=this.waitingData=this.waitingData||{frag:i,part:r,cache:new rd,complete:!1};e.push(new Uint8Array(s)),this.state!==i8&&(this.state=rn)}}_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;let i=t.tracks.audio;i&&(this.mediaBuffer=i.buffer||null)}onFragLoading(e,t){!this.audioOnly&&t.frag.type===q&&eD(t.frag)&&(this.mainFragLoading=t,this.state===i6&&this.tick())}onFragBuffered(e,t){let{frag:i,part:r}=t;if(i.type!==Y){this.audioOnly||i.type!==q||i.elementaryStreams.video||i.elementaryStreams.audiovideo||(this.audioOnly=!0,this.mainFragLoading=null);return}if(this.fragContextChanged(i))return void this.warn(`Fragment ${i.sn}${r?" p: "+r.index:""} of level ${i.level} finished buffering, but was aborted. state: ${this.state}, audioSwitch: ${this.switchingTrack?this.switchingTrack.name:"false"}`);if(eD(i)){this.fragPrevious=i;let e=this.switchingTrack;e&&(this.bufferedTrack=e,this.switchingTrack=null,this.hls.trigger(K.AUDIO_TRACK_SWITCHED,ee({},e)))}this.fragBufferedComplete(i,r),this.media&&this.tick()}onError(e,t){var i;if(t.fatal){this.state=ra;return}switch(t.details){case G.FRAG_GAP:case G.FRAG_PARSING_ERROR:case G.FRAG_DECRYPT_ERROR:case G.FRAG_LOAD_ERROR:case G.FRAG_LOAD_TIMEOUT:case G.
82KEY_LOAD_ERROR:case G.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(Y,t);break;case G.AUDIO_TRACK_LOAD_ERROR:case G.AUDIO_TRACK_LOAD_TIMEOUT:case G.LEVEL_PARSING_ERROR:t.levelRetry||this.state!==rt||(null==(i=t.context)?void 0:i.type)!==j||(this.state=i6);break;case G.BUFFER_ADD_CODEC_ERROR:case G.BUFFER_APPEND_ERROR:if("audio"!==t.parent)return;this.reduceLengthAndFlushBuffer(t)||this.resetLoadingState();break;case G.BUFFER_FULL_ERROR:if("audio"!==t.parent)return;this.reduceLengthAndFlushBuffer(t)&&(this.bufferedTrack=null,super.flushMainBuffer(0,1/0,"audio"));break;case G.INTERNAL_EXCEPTION:this.recoverWorkerError(t)}}onBufferFlushing(e,{type:t}){t!==eb&&(this.flushing=!0)}onBufferFlushed(e,{type:t}){if(t!==eb){this.flushing=!1,this.bufferFlushed=!0,this.state===rs&&(this.state=i6);let e=this.mediaBuffer||this.media;e&&(this.afterBufferFlushed(e,t,Y),this.tick())}}_handleTransmuxComplete(e){var t;let i="audio",{hls:r}=this,{remuxResult:s,chunkMeta:a}=e,n=this.getCurrentContext(a);if(!n)return void this.resetWhenMissingContext(a);let{frag:l,part:o,level:h}=n,{details:d}=h,{audio:c,text:f,id3:g,initSegment:m}=s;if(this.fragContextChanged(l)||!d)return void this.fragmentTracker.removeFragment(l);if(this.state=ri,this.switchingTrack&&c&&this.completeAudioSwitch(this.switchingTrack),null!=m&&m.tracks){let e=l.initSegment||l;if(this.unhandledEncryptionError(m,l))return;this._bufferInitSegment(h,m.tracks,e,a),r.trigger(K.FRAG_PARSING_INIT_SEGMENT,{frag:e,id:i,tracks:m.tracks})}if(c){let{startPTS:e,endPTS:t,startDTS:i,endDTS:r}=c;o&&(o.elementaryStreams[eR]={startPTS:e,endPTS:t,startDTS:i,endDTS:r}),l.setElementaryStreamInfo(eR,e,t,i,r),this.bufferFragmentData(c,l,o,a)}if(null!=g&&null!=(t=g.samples)&&t.length){let e=Z({id:i,frag:l,details:d},g);r.trigger(K.FRAG_PARSING_METADATA,e)}if(f){let e=Z({id:i,frag:l,details:d},f);r.trigger(K.FRAG_PARSING_USERDATA,e)}}_bufferInitSegment(e,t,i,r){if(this.state!==ri||(t.video&&delete t.video,t.audiovideo&&delete t.audiovideo,!t.audio))return;let s=t.audio;s.id=Y;let a=e.audioCodec;this.log(`Init audio buffer, container:${s.container}, codecs[level/parsed]=[${a}/${s.codec}]`),a&&1===a.split(",").length&&(s.levelCodec=a),this.hls.trigger(K.BUFFER_CODECS,t);let n=s.initSegment;if(null!=n&&n.byteLength){let e={type:"audio",frag:i,part:null,chunkMeta:r,parent:i.type,data:n};this.hls.trigger(K.BUFFER_APPENDING,e)}this.tickImmediate()}loadFragment(e,t,i){let r=this.fragmentTracker.getState(e);if(this.switchingTrack||r===tM||r===tF){var s;if(eD(e))if(null!=(s=t.details)&&s.live&&!this.initPTS[e.cc]){this.log(`Waiting for video PTS in continuity counter ${e.cc} of live stream before loading audio fragment ${e.sn} of level ${this.trackId}`),this.state=rn;let i=this.mainDetails;i&&i.fragmentStart!==t.details.fragmentStart&&i2(t.details,i)}else super.loadFragment(e,t,i);else this._loadInitSegment(e,t)}else this.clearTrackerIfNeeded(e)}flushAudioIfNeeded(e){if(this.media&&this.bufferedTrack){let{name:t,lang:i,assocLang:r,characteristics:s,audioCodec:a,channels:n}=this.bufferedTrack;ty({name:t,lang:i,assocLang:r,characteristics:s,audioCodec:a,channels:n},e,tv)||(tT(e.url,this.hls)?(this.log("Switching audio track : flushing all audio"),super.flushMainBuffer(0,1/0,"audio"),this.bufferedTrack=null):this.bufferedTrack=e)}}completeAudioSwitch(e){let{hls:t}=this;this.flushAudioIfNeeded(e),this.bufferedTrack=e,this.switchingTrack=null,t.trigger(K.AUDIO_TRACK_SWITCHED,ee({},e))}},audioTrackController:class extends sy{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(){let{hls:e}=this;e.on(K.MANIFEST_LOADING,this.onManifestLoading,this),e.on(K.MANIFEST_PARSED,this.onManifestParsed,this),e.on(K.LEVEL_LOADING,this.onLevelLoading,this),e.on(K.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(K.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(K.ERROR,this.onError,this)}unregisterListeners(){let{hls:e}=this;e.off(K.MANIFEST_LOADING,this.onManifestLoading,this),e.off(K.MANIFEST_PARSED,this.onManifestParsed,this),e.off(K.LEVEL_LOADING,this.onLevelLoading,this),e.off(K.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(K.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(K.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){let{id:i,groupId:r,details:s}=t,a=this.tracksInGroup[i];if(!a||a.groupId!==r)return void this.warn(`Audio track with id:${i} and group:${r} not found in active group ${a?.groupId}`);let n=a.details;a.details=t.details,this.log(`Audio track ${i} "${a.name}" lang:${a.lang} group:${r} loaded [${s.startSN}-${s.endSN}]`),i===this.trackId&&this.playlistLoaded(i,t,n)}onLevelLoading(e,t){this.switchLevel(t.level)}onLevelSwitching(e,t){this.switchLevel(t.level)}switchLevel(e){let t=this.hls.levels[e];if(!t)return;let i=t.audioGroups||null,r=this.groupIds,s=this.currentTrack;if(!i||r?.length!==i?.length||null!=i&&i.some(e=>r?.indexOf(e)===-1)){this.groupIds=i,this.trackId=-1,this.currentTrack=null;let e=this.tracks.filter(e=>!i||-1!==i.indexOf(e.groupId));if(e.length)this.selectDefaultTrack&&!e.some(e=>e.default)&&(this.selectDefaultTrack=!1),e.forEach((e,t)=>
82{e.id=t});else if(!s&&!this.tracksInGroup.length)return;this.tracksInGroup=e;let t=this.hls.config.audioPreference;if(!s&&t){let i=tp(t,e,tv);if(i>-1)s=e[i];else{let e=tp(t,this.tracks);s=this.tracks[e]}}let r=this.findTrackId(s);-1===r&&s&&(r=this.findTrackId(null)),this.log(`Updating audio tracks, ${e.length} track(s) found in group(s): ${i?.join(",")}`),this.hls.trigger(K.AUDIO_TRACKS_UPDATED,{audioTracks:e});let n=this.trackId;if(-1!==r&&-1===n)this.setAudioTrack(r);else if(e.length&&-1===n){var a;let t=Error(`No audio track selected for current audio group-ID(s): ${null==(a=this.groupIds)?void 0:a.join(",")} track count: ${e.length}`);this.warn(t.message),this.hls.trigger(K.ERROR,{type:N.MEDIA_ERROR,details:G.AUDIO_TRACK_LOAD_ERROR,fatal:!0,error:t})}}}onError(e,t){t.fatal||!t.context||t.context.type!==j||t.context.id!==this.trackId||this.groupIds&&-1===this.groupIds.indexOf(t.context.groupId)||this.checkRetry(t)}get allAudioTracks(){return this.tracks}get audioTracks(){return this.tracksInGroup}get audioTrack(){return this.trackId}set audioTrack(e){this.selectDefaultTrack=!1,this.setAudioTrack(e)}setAudioOption(e){let t=this.hls;if(t.config.audioPreference=e,e){let s=this.allAudioTracks;
82if(this.selectDefaultTrack=!1,s.length){let a=this.currentTrack;if(a&&ty(e,a,tv))return a;let n=tp(e,this.tracksInGroup,tv);if(n>-1){let e=this.tracksInGroup[n];return this.setAudioTrack(n),e}if(a){var i,r;let a,n,l,o,h,d,c=t.loadLevel;-1===c&&(c=t.firstAutoLevel);let f=(i=t.levels,a=i[r=c],(n=i.reduce((e,t,i)=>{let r=t.uri;return(e[r]||(e[r]=[])).push(i),e},{})[a.uri]).length>1&&(r=Math.max.apply(Math,n)),l=a.videoRange,o=a.frameRate,h=a.codecSet.substring(0,4),(d=tE(i,r,t=>{if(t.videoRange!==l||t.frameRate!==o||t.codecSet.substring(0,4)!==h)return!1;let i=t.audioGroups;return tp(e,s.filter(e=>!i||-1!==i.indexOf(e.groupId)),tv)>-1}))>-1?d:tE(i,r,t=>{let i=t.audioGroups;return tp(e,s.filter(e=>!i||-1!==i.indexOf(e.groupId)),tv)>-1}));if(-1===f)return null;t.nextLoadLevel=f}if(e.channels||e.audioCodec){let t=tp(e,s);if(t>-1)return s[t]}}}return null}setAudioTrack(e){let t=this.tracksInGroup;if(e<0||e>=t.length)return void this.warn(`Invalid audio track id: ${e}`);this.selectDefaultTrack=!1;let i=this.currentTrack,r=t[e],s=r.details&&!r.details.live;if(e===this.trackId&&r===i&&s||(this.log(`Switching to audio-track ${e} "${r.name}" lang:${r.lang} group:${r.groupId} channels:${r.channels}`),this.trackId=e,this.currentTrack=r,this.hls.trigger(K.AUDIO_TRACK_SWITCHING,ee({},r)),s))return;let a=this.switchParams(r.url,i?.details,r.details);this.loadPlaylist(a)}findTrackId(e){let t=this.tracksInGroup;for(let i=0;i<t.length;i++){let r=t[i];if(!(this.selectDefaultTrack&&!r.default)&&(!e||ty(e,r,tv)))return i}if(e){let{name:i,lang:r,assocLang:s,characteristics:a,audioCodec:n,channels:l}=e;for(let e=0;e<t.length;e++)if(ty({name:i,lang:r,assocLang:s,characteristics:a,audioCodec:n,channels:l},t[e],tv))return e;for(let i=0;i<t.length;i++){let r=t[i];if(sE(e.attrs,r.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return i}for(let i=0;i<t.length;i++){let r=t[i];if(sE(e.attrs,r.attrs,["LANGUAGE"]))return i}}return -1}loadPlaylist(e){super.loadPlaylist();let t=this.currentTrack;this.shouldLoadPlaylist(t)&&tT(t.url,this.hls)&&this.scheduleLoading(t,e)}loadingPlaylist(e,t){super.loadingPlaylist(e,t);let i=e.id,r=e.groupId,s=this.getUrlWithDirectives(e.url,t),a=e.details,n=a?.age;this.log(`Loading audio-track ${i} "${e.name}" lang:${e.lang} group:${r}${t?.msn!==void 0?" at sn "+t.msn+" part "+t.part:""}${n&&a.live?" age "+n.toFixed(1)+(a.type&&" "+a.type||""):""} ${s}`),this.hls.trigger(K.AUDIO_TRACK_LOADING,{url:s,id:i,groupId:r,deliveryDirectives:t||null,track:e})}},emeController:at,cmcdController:class{constructor(e){this.hls=void 0,this.config=void 0,this.media=void 0,this.sid=void 0,this.cid=void 0,this.useHeaders=!1,this.includeKeys=void 0,this.initialized=!1,this.starved=!1,this.buffering=!0,this.audioBuffer=void 0,this.videoBuffer=void 0,this.onWaiting=()=>{this.initialized&&(this.starved=!0),this.buffering=!0},this.onPlaying=()=>{this.initialized||(this.initialized=!0),this.buffering=!1},this.applyPlaylistData=e=>{try{this.apply(e,{ot:"m",su:!this.initialized})}catch(e){this.hls.logger.warn("Could not generate manifest CMCD data.",e)}},this.applyFragmentData=e=>{try{let{frag:t,part:i}=e,r=this.hls.levels[t.level],s=this.getObjectType(t),a={d:1e3*(i||t).duration,ot:s};("v"===s||"a"===s||"av"==s)&&(a.br=r.bitrate/1e3,a.tb=this.getTopBandwidth(s)/1e3,a.bl=this.getBufferLength(s));let n=i?this.getNextPart(i):this.getNextFrag(t);null!=n&&n.url&&n.url!==t.url&&(a.nor=n.url),this.apply(e,a)}catch(e){this.hls.logger.warn("Could not generate segment CMCD data.",e)}},this.hls=e;const t=this.config=e.config,{cmcd:i}=t;null!=i&&(t.pLoader=this.createPlaylistLoader(),t.fLoader=this.createFragmentLoader(),this.sid=i.sessionId||e.sessionId,this.cid=i.contentId,this.useHeaders=!0===i.useHeaders,this.includeKeys=i.includeKeys,this.registerListeners())}registerListeners(){let e=this.hls;e.on(K.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(K.MEDIA_DETACHED,this.onMediaDetached,this),e.on(K.BUFFER_CREATED,this.onBufferCreated,this)}unregisterListeners(){let e=this.hls;e.off(K.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(K.MEDIA_DETACHED,this.onMediaDetached,this),e.off(K.BUFFER_CREATED,this.onBufferCreated,this)}destroy(){this.unregisterListeners(),this.onMediaDetached(),this.hls=this.config=this.audioBuffer=this.videoBuffer=null,this.onWaiting=this.onPlaying=this.media=null}onMediaAttached(e,t){this.media=t.media,this.media.addEventListener("waiting",this.onWaiting),this.media.addEventListener("playing",this.onPlaying)}onMediaDetached(){this.media&&(this.media.removeEventListener("waiting",this.onWaiting),this.media.removeEventListener("playing",this.onPlaying),this.media=null)}onBufferCreated(e,t){var i,r;this.audioBuffer=null==(i=t.tracks.audio)?void 0:i.buffer,this.videoBuffer=null==(r=t.tracks.video)?void 0:r.buffer}createData(){var e;return{v:1,sf:"h",sid:this.sid,cid:this.cid,pr:null==(e=this.media)?void 0:e.playbackRate,mtp:this.hls.bandwidthEstimate/1e3}}apply(e,t={}){var i;Z(t,this.createData());let r="i"===t.ot||"v"===t.ot||"av"===t.ot;this.starved&&r&&(t.bs=!0,t.su=!0,this.starved=!1),null==t.su&&(t.su=this.buffering);let{includeKeys:s}=this;s&&(t=Object.keys(t).reduce((e,i)=>(s.includes(i)&&(e[i]=t[i]),e),{}));let a={baseUrl:e.url};this.useHeaders?(e.headers||(e.headers={}),i=e.headers,Z(i,function(e,t={}){let i={};return e?Object.entries(function(e,t){let i={};if(!e)return i;let r=Object.keys(e),s=t?Object.keys(t).reduce((e,i)=>{var r;return null==(r=t[i])||r.forEach(t=>e[t]=i),e},{}):{};return r.reduce((t,i)=>{var r;let a=sV[i]||s[i]||sG;return(null!=(r=t[a])?r:t[a]={})[i]=e[i],t},i)}
82(s6(e,t),t?.customHeaderMap)).reduce((e,[t,i])=>{let r=sU(i,{whitespace:!1});return r&&(e[t]=r),e},i):i}(t,a))):e.url=function(e,t,i){let r=function(e,t={}){if(!e)return"";let i=function(e,t={}){return e?encodeURIComponent(function(e,t={}){return e?sU(s6(e,t),{whitespace:!1}):""}(e,t)):""}(e,t);return`CMCD=${i}`}(t,i);if(!r)return e;if(s9.test(e))return e.replace(s9,r);let s=e.includes("?")?"&":"?";return`${e}${s}${r}`}(e.url,t,a)}getNextFrag(e){var t;let i=null==(t=this.hls.levels[e.level])?void 0:t.details;if(i){let t=e.sn-i.startSN;return i.fragments[t+1]}}getNextPart(e){var t;let{index:i,fragment:r}=e,s=null==(t=this.hls.levels[r.level])||null==(t=t.details)?void 0:t.partList;if(s){let{sn:e}=r;for(let t=s.length-1;t>=0;t--){let r=s[t];if(r.index===i&&r.fragment.sn===e)return s[t+1]}}}getObjectType(e){let{type:t}=e;return"subtitle"===t?"tt":"initSegment"===e.sn?"i":"audio"===t?"a":"main"===t?this.hls.audioTracks.length?"v":"av":void 0}getTopBandwidth(e){let t=0,i,r=this.hls;if("a"===e)i=r.audioTracks;else{let e=r.maxAutoLevel,t=e>-1?e+1:r.levels.length;i=r.levels.slice(0,t)}return i.forEach(e=>{e.bitrate>t&&(t=e.bitrate)}),t>0?t:NaN}getBufferLength(e){let t=this.media,i="a"===e?this.audioBuffer:this.videoBuffer;return i&&t?1e3*tJ.bufferInfo(i,t.currentTime,this.config.maxBufferHole).len:NaN}createPlaylistLoader(){let{pLoader:e}=this.config,t=this.applyPlaylistData,i=e||this.config.loader;return class{constructor(e){this.loader=void 0,this.loader=new i(e)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(e,i,r){t(e),this.loader.load(e,i,r)}}}createFragmentLoader(){let{fLoader:e}=this.config,t=this.applyFragmentData,i=e||this.config.loader;return class{constructor(e){this.loader=void 0,this.loader=new i(e)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(e,i,r){t(e),this.loader.load(e,i,r)}}}},contentSteeringController:class extends et{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(){let e=this.hls;e.on(K.MANIFEST_LOADING,this.onManifestLoading,this),e.on(K.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(K.MANIFEST_PARSED,this.onManifestParsed,this),e.on(K.ERROR,this.onError,this)}unregisterListeners(){let e=this.hls;e&&(e.off(K.MANIFEST_LOADING,this.onManifestLoading,this),e.off(K.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(K.MANIFEST_PARSED,this.onManifestParsed,this),e.off(K.ERROR,this.onError,this))}pathways(){return(this.levels||[]).reduce((e,t)=>(-1===e.indexOf(t.pathwayId)&&e.push(t.pathwayId),e),[])}get pathwayPriority(){return this._pathwayPriority}set pathwayPriority(e){this.updatePathwayPriority(e)}startLoad(){if(this.started=!0,this.clearTimeout(),this.enabled&&this.uri){if(this.updated){let e=1e3*this.timeToLoad-(performance.now()-this.updated);if(e>0)return void this.scheduleRefresh(this.uri,e)}this.loadSteeringManifest(this.uri)}}stopLoad(){this.started=!1,this.loader&&(this.loader.destroy(),this.loader=null),this.clearTimeout()}clearTimeout(){-1!==this.reloadTimer&&(self.clearTimeout(this.reloadTimer),this.reloadTimer=-1)}destroy(){this.unregisterListeners(),this.stopLoad(),this.hls=null,this.levels=this.audioTracks=this.subtitleTracks=null}removeLevel(e){let t=this.levels;t&&(this.levels=t.filter(t=>t!==e))}onManifestLoading(){this.stopLoad(),this.enabled=!0,this.timeToLoad=300,this.updated=0,this.uri=null,this.pathwayId=".",this.levels=this.audioTracks=this.subtitleTracks=null}onManifestLoaded(e,t){let{contentSteering:i}=t;null!==i&&(this.pathwayId=i.pathwayId,this.uri=i.uri,this.started&&this.startLoad())}onManifestParsed(e,t){this.audioTracks=t.audioTracks,this.subtitleTracks=t.subtitleTracks}onError(e,t){let{errorAction:i}=t;if(i?.action===2&&1===i.flags){let e=this.levels,r=this._pathwayPriority,s=this.pathwayId;if(t.context){let{groupId:i,pathwayId:r,type:a}=t.context;i&&e?s=this.getPathwayForGroupId(i,a,s):r&&(s=r)}s in this.penalizedPathways||(this.penalizedPathways[s]=performance.now()),!r&&e&&(r=this.pathways()),r&&r.length>1&&(this.updatePathwayPriority(r),i.resolved=this.pathwayId!==s),t.details!==G.BUFFER_APPEND_ERROR||t.fatal?i.resolved||this.warn(`Could not resolve ${t.details} ("${t.error.message}") with content-steering for Pathway: ${s} levels: ${e&&e.length} priorities: ${tc(r)} penalized: ${tc(this.penalizedPathways)}`):i.resolved=!0}}filterParsedLevels(e){this.levels=e;let t=this.getLevelsForPathway(this.pathwayId);if(0===t.length){let i=e[0].pathwayId;this.log(`No levels found in Pathway ${this.pathwayId}. Setting initial Pathway to "${i}"`),t=this.getLevelsForPathway(i),this.pathwayId=i}return t.length!==e.length&&this.log(`Found ${t.length}/${e.length} levels in Pathway "${this.pathwayId}"`),t}getLevelsForPathway(e){return null===this.levels?[]:this.levels.filter(t=>e===t.pathwayId)}updatePathwayPriority(e){let t;this._pathwayPriority=e;let i=this.penalizedPathways,r=performance.now();
82Object.keys(i).forEach(e=>{r-i[e]>3e5&&delete i[e]});for(let r=0;r<e.length;r++){let s=e[r];if(s in i)continue;if(s===this.pathwayId)return;let a=this.hls.nextLoadLevel,n=this.hls.levels[a];if((t=this.getLevelsForPathway(s)).length>0){this.log(`Setting Pathway to "${s}"`),this.pathwayId=s,iz(t),this.hls.trigger(K.LEVELS_UPDATED,{levels:t});let e=this.hls.levels[a];n&&e&&this.levels&&(e.attrs["STABLE-VARIANT-ID"]!==n.attrs["STABLE-VARIANT-ID"]&&e.bitrate!==n.bitrate&&this.log(`Unstable Pathways change from bitrate ${n.bitrate} to ${e.bitrate}`),this.hls.nextLoadLevel=a);break}}}getPathwayForGroupId(e,t,i){let r=this.getLevelsForPathway(i).concat(this.levels||[]);for(let i=0;i<r.length;i++)if(t===j&&r[i].hasAudioGroup(e)||t===W&&r[i].hasSubtitleGroup(e))return r[i].pathwayId;return i}clonePathways(e){let t=this.levels;if(!t)return;let i={},r={};e.forEach(e=>{let{ID:s,"BASE-ID":a,"URI-REPLACEMENT":n}=e;if(t.some(e=>e.pathwayId===s))return;let l=this.getLevelsForPathway(a).map(e=>{let t=new t5(e.attrs);t["PATHWAY-ID"]=s;let a=t.AUDIO&&`${t.AUDIO}_clone_${s}`,l=t.SUBTITLES&&`${t.SUBTITLES}_clone_${s}`;a&&(i[t.AUDIO]=a,t.AUDIO=a),l&&(r[t.SUBTITLES]=l,t.SUBTITLES=l);let o=ae(e.uri,t["STABLE-VARIANT-ID"],"PER-VARIANT-URIS",n),h=new td({attrs:t,audioCodec:e.audioCodec,bitrate:e.bitrate,height:e.height,name:e.name,url:o,videoCodec:e.videoCodec,width:e.width});if(e.audioGroups)for(let t=1;t<e.audioGroups.length;t++)h.addGroupId("audio",`${e.audioGroups[t]}_clone_${s}`);if(e.subtitleGroups)for(let t=1;t<e.subtitleGroups.length;t++)h.addGroupId("text",`${e.subtitleGroups[t]}_clone_${s}`);return h});t.push(...l),s7(this.audioTracks,i,n,s),s7(this.subtitleTracks,r,n,s)})}loadSteeringManifest(e){let t,i=this.hls.config,r=i.loader;this.loader&&this.loader.destroy(),this.loader=new r(i);try{t=new self.URL(e)}catch{this.enabled=!1,this.log(`Failed to parse Steering Manifest URI: ${e}`);return}if("data:"!==t.protocol){let e=0|(this.hls.bandwidthEstimate||i.abrEwmaDefaultEstimate);t.searchParams.set("_HLS_pathway",this.pathwayId),t.searchParams.set("_HLS_throughput",""+e)}let s={responseType:"json",url:t.href},a=i.steeringManifestLoadPolicy.default,n=a.errorRetry||a.timeoutRetry||{},l={loadPolicy:a,timeout:a.maxLoadTimeMs,maxRetry:n.maxNumRetry||0,retryDelay:n.retryDelayMs||0,maxRetryDelay:n.maxRetryDelayMs||0};this.log(`Requesting steering manifest: ${t}`),this.loader.load(s,l,{onSuccess:(e,i,r,s)=>{this.log(`Loaded steering manifest: "${t}"`);let a=e.data;if(a?.VERSION!==1)return void this.log(`Steering VERSION ${a.VERSION} not supported!`);this.updated=performance.now(),this.timeToLoad=a.TTL;let{"RELOAD-URI":n,"PATHWAY-CLONES":l,"PATHWAY-PRIORITY":o}=a;if(n)try{this.uri=new self.URL(n,t).href}catch{this.enabled=!1,this.log(`Failed to parse Steering Manifest RELOAD-URI: ${n}`);return}this.scheduleRefresh(this.uri||r.url),l&&this.clonePathways(l);let h={steeringManifest:a,url:t.toString()};this.hls.trigger(K.STEERING_MANIFEST_LOADED,h),o&&this.updatePathwayPriority(o)},onError:(e,t,i,r)=>{if(this.log(`Error loading steering manifest: ${e.code} ${e.text} (${t.url})`),this.stopLoad(),410===e.code){this.enabled=!1,this.log(`Steering manifest ${t.url} no longer available`);return}let s=1e3*this.timeToLoad;if(429===e.code){let e=this.loader;if("function"==typeof e?.getResponseHeader){let t=e.getResponseHeader("Retry-After");t&&(s=1e3*parseFloat(t))}this.log(`Steering manifest ${t.url} rate limited`);return}this.scheduleRefresh(this.uri||t.url,s)},onTimeout:(e,t,i)=>{this.log(`Timeout loading steering manifest (${t.url})`),this.scheduleRefresh(this.uri||t.url)}})}scheduleRefresh(e,t=1e3*this.timeToLoad){this.clearTimeout(),this.reloadTimer=self.setTimeout(()=>{var t;let i=null==(t=this.hls)?void 0:t.media;i&&!i.ended?this.loadSteeringManifest(e):this.scheduleRefresh(e,1e3*this.timeToLoad)},t)}},interstitialsController:class extends et{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}
82,this.onSeeking=()=>{var e,t;let i=this.currentTime;if(void 0===i||this.playbackDisabled||!this.schedule)return;let r=i-this.timelinePos;if(Math.abs(r)<1/7056e5)return;let s=r<=-.01;-1!==this.timelinePos||this.effectivePlayingItem||this.checkStart(),this.timelinePos=i,this.bufferedPos=i;let a=this.playingItem;if(!a)return void this.checkBuffer();if(s&&this.schedule.resetErrorsInRange(i,i-r)&&this.updateSchedule(!0),this.checkBuffer(),s&&i<a.start||i>=a.end){let t=this.findItemIndex(a),r=this.schedule.findItemIndexAtTime(i);if(-1===r&&(r=t+(s?-1:1),this.log(`seeked ${s?"back ":""}to position not covered by schedule ${i} (resolving from ${t} to ${r})`)),!this.isInterstitial(a)&&null!=(e=this.media)&&e.paused&&(this.shouldPlay=!1),!s&&r>t){let e=this.schedule.findJumpRestrictedIndex(t+1,r);if(e>t)return void this.setSchedulePosition(e)}this.setSchedulePosition(r);return}let n=this.playingAsset;if(!n){if(this.playingLastItem&&this.isInterstitial(a)){let e=a.event.assetList[0];e&&(this.endedItem=this.playingItem,this.playingItem=null,this.setScheduleToAssetAtTime(i,e))}return}let l=n.timelineStart,o=n.duration||0;(s&&i<l||i>=l+o)&&(null!=(t=a.event)&&t.appendInPlace&&(this.clearAssetPlayers(a.event,a),this.flushFrontBuffer(i)),this.setScheduleToAssetAtTime(i,n))},this.onTimeupdate=()=>{let e=this.currentTime;if(void 0===e||this.playbackDisabled||(-1!==this.timelinePos||this.effectivePlayingItem||this.checkStart(),!(e>this.timelinePos)))return;this.timelinePos=e,e>this.bufferedPos&&this.checkBuffer();let t=this.playingItem;if(!t||this.playingLastItem)return;if(e>=t.end){this.timelinePos=t.end;let e=this.findItemIndex(t);this.setSchedulePosition(e+1)}let i=this.playingAsset;!i||e>=i.timelineStart+(i.duration||0)&&this.setScheduleToAssetAtTime(e,i)},this.onScheduleUpdate=(e,t)=>{let i=this.schedule;if(!i)return;let r=this.playingItem,s=i.events||[],a=i.items||[],n=i.durations,l=e.map(e=>e.identifier),o=!!(s.length||l.length);(o||t)&&this.log(`INTERSTITIALS_UPDATED (${s.length}): ${s}
83Schedule: ${a.map(e=>aE(e))} pos: ${this.timelinePos}`),l.length&&this.log(`Removed events ${l}`);let h=null,d=null;r&&(h=this.updateItem(r,this.timelinePos),this.itemsMatch(r,h)?this.playingItem=h:this.waitingItem=this.endedItem=null),this.waitingItem=this.updateItem(this.waitingItem),this.endedItem=this.updateItem(this.endedItem);let c=this.bufferingItem;if(c&&(d=this.updateItem(c,this.bufferedPos),this.itemsMatch(c,d)?this.bufferingItem=d:c.event&&(this.bufferingItem=this.playingItem,this.clearInterstitial(c.event,null))),e.forEach(e=>{e.assetList.forEach(e=>{this.clearAssetPlayer(e.identifier,null)})}),this.playerQueue.forEach(e=>{if(e.interstitial.appendInPlace){let t=e.assetItem.timelineStart,i=e.timelineOffset-t;if(i)try{e.timelineOffset=t}catch(r){Math.abs(i)>.025&&this.warn(`${r} ("${e.assetId}" ${e.timelineOffset}->${t})`)}}}),o||t){if(this.hls.trigger(K.INTERSTITIALS_UPDATED,{events:s.slice(0),schedule:a.slice(0),durations:n,removedIds:l}),this.isInterstitial(r)&&l.includes(r.event.identifier)){this.warn(`Interstitial "${r.event.identifier}" removed while playing`),this.primaryFallback(r.event);return}r&&this.trimInPlace(h,r),c&&d!==h&&this.trimInPlace(d,c),this.checkBuffer()}},this.hls=e,this.HlsPlayerClass=t,this.assetListLoader=new aT(e),this.schedule=new av(this.onScheduleUpdate,e.logger),this.registerListeners()}registerListeners(){let e=this.hls;e&&(e.on(K.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(K.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(K.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(K.MANIFEST_LOADING,this.onManifestLoading,this),e.on(K.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(K.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(K.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),e.on(K.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.on(K.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),e.on(K.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),e.on(K.ASSET_LIST_LOADED,this.onAssetListLoaded,this),e.on(K.BUFFER_APPENDED,this.onBufferAppended,this),e.on(K.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(K.BUFFERED_TO_END,this.onBufferedToEnd,this),e.on(K.MEDIA_ENDED,this.onMediaEnded,this),e.on(K.ERROR,this.onError,this),e.on(K.DESTROYING,this.onDestroying,this))}unregisterListeners(){let e=this.hls;
83e&&(e.off(K.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(K.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(K.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(K.MANIFEST_LOADING,this.onManifestLoading,this),e.off(K.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(K.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(K.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),e.off(K.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.off(K.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),e.off(K.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),e.off(K.ASSET_LIST_LOADED,this.onAssetListLoaded,this),e.off(K.BUFFER_CODECS,this.onBufferCodecs,this),e.off(K.BUFFER_APPENDED,this.onBufferAppended,this),e.off(K.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(K.BUFFERED_TO_END,this.onBufferedToEnd,this),e.off(K.MEDIA_ENDED,this.onMediaEnded,this),e.off(K.ERROR,this.onError,this),e.off(K.DESTROYING,this.onDestroying,this))}startLoad(){this.resumeBuffering()}stopLoad(){this.pauseBuffering()}resumeBuffering(){var e;null==(e=this.getBufferingPlayer())||e.resumeBuffering()}pauseBuffering(){var e;null==(e=this.getBufferingPlayer())||e.pauseBuffering()}destroy(){this.unregisterListeners(),this.stopLoad(),this.assetListLoader&&this.assetListLoader.destroy(),this.emptyPlayerQueue(),this.clearScheduleState(),this.schedule&&this.schedule.destroy(),this.media=this.detachedData=this.mediaSelection=this.requiredTracks=this.altSelection=this.schedule=this.manager=null,this.hls=this.HlsPlayerClass=this.log=null,this.assetListLoader=null,this.onPlay=this.onPause=this.onSeeking=this.onTimeupdate=null,this.onScheduleUpdate=null}onDestroying(){let e=this.primaryMedia||this.media;e&&this.removeMediaListeners(e)}removeMediaListeners(e){i4(e,"play",this.onPlay),i4(e,"pause",this.onPause),i4(e,"seeking",this.onSeeking),i4(e,"timeupdate",this.onTimeupdate)}onMediaAttaching(e,t){let i=this.media=t.media;i3(i,"seeking",this.onSeeking),i3(i,"timeupdate",this.onTimeupdate),i3(i,"play",this.onPlay),i3(i,"pause",this.onPause)}onMediaAttached(e,t){let i=this.effectivePlayingItem,r=this.detachedData;if(this.detachedData=null,null===i)this.checkStart();else if(!r){this.clearScheduleState();let e=this.findItemIndex(i);this.setSchedulePosition(e)}}clearScheduleState(){this.log("clear schedule state"),this.playingItem=this.bufferingItem=this.waitingItem=this.endedItem=this.playingAsset=this.endedAsset=this.bufferingAsset=null}onMediaDetaching(e,t){let i=!!t.transferMedia,r=this.media;if(this.media=null,!i&&(r&&this.removeMediaListeners(r),this.detachedData)){let e=this.getBufferingPlayer();e&&(this.log(`Removing schedule state for detachedData and ${e}`),this.playingAsset=this.endedAsset=this.bufferingAsset=this.bufferingItem=this.waitingItem=this.detachedData=null,e.detachMedia()),this.shouldPlay=!1}}get interstitialsManager(){if(!this.hls)return null;if(this.manager)return this.manager;let e=this,t=t=>t&&e.getAssetPlayer(t.identifier),i=(i,s,a,n,l)=>{if(i){let o=i[s].start,h=i.event;if(h){if("playout"===s||h.timelineOccupancy!==au.Point){let e=t(a);e?.interstitial===h&&(o+=e.assetItem.startOffset+e[l])}}else o+=("bufferedPos"===n?r():e[n])-i.start;return o}return 0},r=()=>{let t=e.bufferedPos;return t===Number.MAX_VALUE?s("primary"):Math.max(t,0)},s=t=>{var i,r;return null!=(i=e.primaryDetails)&&i.live?e.primaryDetails.edge:(null==(r=e.schedule)?void 0:r.durations[t])||0},a=(r,s)=>{var a,n;let l=e.effectivePlayingItem;if(null!=l&&null!=(a=l.event)&&a.restrictions.skip||!e.schedule)return;e.log(`seek to ${r} "${s}"`);let o=e.effectivePlayingItem,h=e.schedule.findItemIndexAtTime(r,s),d=null==(n=e.schedule.items)?void 0:n[h],c=e.getBufferingPlayer(),f=c?.interstitial,g=f?.appendInPlace,m=o&&e.itemsMatch(o,d);if(o&&(g||m)){let a=t(e.playingAsset),n=a?.media||e.primaryMedia;if(n){let t="primary"===s?n.currentTime:i(o,s,e.playingAsset,"timelinePos","currentTime"),l=r-t,h=(g?t:n.currentTime)+l;if(h>=0&&(!a||g||h<=a.duration)){n.currentTime=h;return}}}if(d){let t=r;if("primary"!==s){let e=r-d[s].start;t=d.start+e}let i=!e.isInterstitial(d);if((!e.isInterstitial(o)||o.event.appendInPlace)&&(i||d.event.appendInPlace)){let i=e.media||(g?c?.media:null);i&&(i.currentTime=t)}else if(o){let a=e.findItemIndex(o);if(h>a){let t=e.schedule.findJumpRestrictedIndex(a+1,h);if(t>a)return void e.setSchedulePosition(t)}let n=0;if(i)e.timelinePos=t,e.checkBuffer();else{let e=d.event.assetList,t=r-(d[s]||d).start;for(let i=e.length;i--;){let r=e[i];if(r.duration&&t>=r.startOffset&&t<r.startOffset+r.duration){n=i;break}}}e.setSchedulePosition(h,n)}}},n=()=>{let t=e.effectivePlayingItem;if(e.isInterstitial(t))return t;let i=e.bufferingItem||e.waitingItem;return e.isInterstitial(i)?i:null},l={get bufferedEnd(){let t=e.bufferingItem||e.waitingItem,r=e.bufferingItem;if(r&&r===t){var o;return i(r,"playout",e.bufferingAsset,"bufferedPos","bufferedEnd")-r.playout.start||(null==(o=e.bufferingAsset)?void 0:o.startOffset)||0}return 0},get currentTime(){let t=n(),r=e.effectivePlayingItem;return r&&r===t?i(r,"playout",e.effectivePlayingAsset,"timelinePos","currentTime")-r.playout.start:0},set currentTime(u){let t=n(),i=e.effectivePlayingItem;i&&i===t&&a(u+i.playout.start,"playout")},get duration(){let e=n();return e?e.playout.end-e.playout.start:0},get assetPlayers(){var h;let t=null==(h=n())?void 0:h.event.assetList;return t?t.map(t=>e.getAssetPlayer(t.identifier)):[]},get playingIndex(){var d;let t=null==(d=n())?void 0:d.event;return t&&e.effectivePlayingAsset?t.findAssetIndex(e.effectivePlayingAsset):-1},get scheduleItem(){return n()}};return this.manager={get events(){var c;return(null==(c=e.schedule)||null==(c=c.events)?void 0:c.slice(0))||[]},get schedule(){var f;return(null==(f=e.schedule)||null==(f=f.items)?void 0:f.slice(0))||[]},get interstitialPlayer(){return n()?l:null},get playerQueue(){return e.playerQueue.slice(0)},get bufferingAsset(){return e.bufferingAsset},get bufferingItem(){return e.bufferingItem||e.waitingItem},get bufferingIndex(){let t=e.bufferingItem||e.waitingItem;return e.findItemIndex(t)},get playingAsset(){return e.effectivePlayingAsset},get playingItem(){return e.effectivePlayingItem},get playingIndex(){let t=e.effectivePlayingItem;return e.findItemIndex(t)},primary:{get bufferedEnd(){return r()},get currentTime(){let t=e.timelinePos;return t>0?t:0},set currentTime(u){a(u,"primary")},get duration(){return s("primary")},get seekableStart(){var g;return(null==(g=e.primaryDetails)?void 0:g.fragmentStart)||0}},integrated:{get bufferedEnd(){return i(e.bufferingItem||e.waitingItem,"integrated",e.bufferingAsset,"bufferedPos","bufferedEnd")},get currentTime(){return i(e.effectivePlayingItem,"integrated",e.effectivePlayingAsset,"timelinePos","currentTime")},set currentTime(u){a(u,"integrated")},get duration(){return s("integrated")},get seekableStart(){var m;return((t,i)=>{var r,s;if(0!==t&&"primary"!==i&&null!=(r=e.schedule)&&r.length){let r=e.schedule.findItemIndexAtTime(t),a=null==(s=e.schedule.items)?void 0:s[r];if(a)return t+(a[i].start-a.start)}return t})((null==(m=e.primaryDetails)?void 0:m.fragmentStart)||0,"integrated")}},skip:()=>{let t=e.effectivePlayingItem,i=t?.event;if(i&&!i.restrictions.skip){let r=e.findItemIndex(t);i.appendInPlace?a(t.playout.start+t.event.duration+.001,"playout"):e.advanceAfterAssetEnded(i,r,1/0)}}}}get effectivePlayingItem(){return this.waitingItem||this.playingItem||this.endedItem}get effectivePlayingAsset(){return this.playingAsset||this.endedAsset}get playingLastItem(){var e;let t=this.playingItem,i=null==(e=this.schedule)?void 0:e.items;return!!this.playbackStarted&&!!t&&!!i&&this.findItemIndex(t)===i.length-1}get playbackStarted(){return null!==this.effectivePlayingItem}get currentTime(){var e,t;if(null===this.mediaSelection)return;let i=this.waitingItem||this.playingItem;if(this.isInterstitial(i)&&!i.event.appendInPlace)return;let r=this.media;!r&&null!=(e=this.bufferingItem)&&null!=(e=e.event)&&e.appendInPlace&&(r=this.primaryMedia);let s=null==(t=r)?void 0:t.currentTime;if(!(void 0===s||!$(s)))return s}get primaryMedia(){var e;return this.media||(null==(e=this.detachedData)?void 0:e.media)||null}isInterstitial(e){return!!(null!=e&&e.event)}retreiveMediaSource(e,t){let i=this.getAssetPlayer(e);i&&this.transferMediaFromPlayer(i,t)}transferMediaFromPlayer(e,t){let i=e.interstitial.appendInPlace,r=e.media;if(i&&r===this.primaryMedia){if(this.bufferingAsset=null,(!t||this.isInterstitial(t)&&!t.event.appendInPlace)&&t&&r){this.detachedData={media:r};return}let i=e.transferMedia();this.log(`transfer MediaSource from ${e} ${tc(i)}`),this.detachedData=i}else t&&r&&(this.shouldPlay||(this.shouldPlay=!r.paused))}transferMediaTo(e,t){var i,r;let s;if(e.media===t)return;let a=null,n=this.hls,l=e!==n,o=l&&e.interstitial.appendInPlace,h=null==(i=this.detachedData)?void 0:i.mediaSource;if(n.media)o&&(a=n.transferMedia(),this.detachedData=a),s="Primary";
83else if(h){let e=this.getBufferingPlayer();e?(a=e.transferMedia(),s=`${e}`):s="detached MediaSource"}else s="detached media";if(!a){if(h)a=this.detachedData,this.log(`using detachedData: MediaSource ${tc(a)}`);else if(!this.detachedData||n.media===t){let e=this.playerQueue;e.length>1&&e.forEach(e=>{if(l&&e.interstitial.appendInPlace!==o){let t=e.interstitial;this.clearInterstitial(e.interstitial,null),t.appendInPlace=!1,t.appendInPlace&&this.warn(`Could not change append strategy for queued assets ${t}`)}}),this.hls.detachMedia(),this.detachedData={media:t}}}let d=a&&"mediaSource"in a&&(null==(r=a.mediaSource)?void 0:r.readyState)!=="closed",c=d&&a?a:t;this.log(`${d?"transfering MediaSource":"attaching media"} to ${l?e:"Primary"} from ${s} (media.currentTime: ${t.currentTime})`);let f=this.schedule;if(c===a&&f){let t=l&&e.assetId===f.assetIdAtEnd;c.overrides={duration:f.duration,endOfStream:!l||t,cueRemoval:!l}}e.attachMedia(c)}onInterstitialCueEnter(){this.onTimeupdate()}checkStart(){let e=this.schedule,t=e?.events;if(!t||this.playbackDisabled||!this.media)return;-1===this.bufferedPos&&(this.bufferedPos=0);let i=this.timelinePos,r=this.effectivePlayingItem;if(-1===i){let i=this.hls.startPosition;if(this.timelinePos=i,0===t.length)this.setSchedulePosition(0);else if(t[0].cue.pre){this.log(aL("checkStart (preroll)",i));let r=e.findEventIndex(t[0].identifier);this.setSchedulePosition(r)}else if(i>=0||!this.primaryLive){this.log(aL("checkStart",i));let t=this.timelinePos=i>0?i:0,r=e.findItemIndexAtTime(t);this.setSchedulePosition(r)}else 0===this.hls.liveSyncPosition?this.setSchedulePosition(0):this.log("[checkStart] waiting for live start")}else if(r&&!this.playingItem){this.log(aL("checkStart (playing item)",r.start));let t=e.findItemIndex(r);this.setSchedulePosition(t)}}advanceAssetBuffering(e,t){let i=e.event,r=i.findAssetIndex(t),s=am(i,r);if(i.isAssetPastPlayoutLimit(s)){if(this.schedule){var a;let t=null==(a=this.schedule.items)?void 0:a[this.findItemIndex(e)+1];t&&this.bufferedToItem(t)}}else this.bufferedToEvent(e,s)}advanceAfterAssetEnded(e,t,i){let r=am(e,i);if(e.isAssetPastPlayoutLimit(r)){if(this.schedule){let i=this.schedule.items;if(i){let r=t+1;if(r>=i.length)return void this.setSchedulePosition(-1);let s=e.resumeTime;this.timelinePos<s&&(this.log(aL("advanceAfterAssetEnded",s)),this.timelinePos=s,e.appendInPlace&&this.advanceInPlace(s),this.checkBuffer(this.bufferedPos<s)),this.setSchedulePosition(r)}}}else{if(e.appendInPlace){let t=e.assetList[r];t&&this.advanceInPlace(t.timelineStart)}this.setSchedulePosition(t,r)}}setScheduleToAssetAtTime(e,t){let i=this.schedule;if(!i)return;let r=t.parentIdentifier,s=i.getEvent(r);if(s){let t=i.findEventIndex(r),a=i.findAssetIndex(s,e);this.advanceAfterAssetEnded(s,t,a-1)}}setSchedulePosition(e,t){var i,r,s;let a=null==(i=this.schedule)?void 0:i.items;if(!a||this.playbackDisabled)return;let n=e>=0?a[e]:null;this.log(`setSchedulePosition ${e}, ${t} (${n&&aE(n)}) pos: ${this.timelinePos}`);let l=this.waitingItem||this.playingItem,o=this.playingLastItem;if(this.isInterstitial(l)){let i=l.event,h=this.playingAsset,d=h?.identifier,c=d?this.getAssetPlayer(d):null;if(c&&d&&(!this.eventItemsMatch(l,n)||void 0!==t&&d!==i.assetList[t].identifier)){let t=i.findAssetIndex(h);if(this.log(`INTERSTITIAL_ASSET_ENDED ${t+1}/${i.assetList.length} ${ap(h)}`),this.endedAsset=h,this.playingAsset=null,this.hls.trigger(K.INTERSTITIAL_ASSET_ENDED,{asset:h,assetListIndex:t,event:i,schedule:a.slice(0),scheduleIndex:e,player:c}),l!==this.playingItem){this.itemsMatch(l,this.playingItem)&&!this.playingAsset&&this.advanceAfterAssetEnded(i,this.findItemIndex(this.playingItem),t);return}this.retreiveMediaSource(d,n),c.media&&!(null!=(r=this.detachedData)&&r.mediaSource)&&c.detachMedia()}if(!this.eventItemsMatch(l,n)&&(this.endedItem=l,this.playingItem=null,this.log(`INTERSTITIAL_ENDED ${i} ${aE(l)}`),i.hasPlayed=!0,this.hls.trigger(K.INTERSTITIAL_ENDED,{event:i,schedule:a.slice(0),scheduleIndex:e}),i.cue.once)){this.updateSchedule();let e=null==(s=this.schedule)?void 0:s.items;if(n&&e){let i=this.findItemIndex(n);this.advanceSchedule(i,e,t,l,o)}return}}this.advanceSchedule(e,a,t,l,o)}advanceSchedule(e,t,i,r,s){let a=this.schedule;if(!a)return;let n=t[e]||null,l=this.primaryMedia,o=this.playerQueue;if(o.length&&o.forEach(t=>{let i=t.interstitial,r=a.findEventIndex(i.identifier);(r<e||r>e+1)&&this.clearInterstitial(i,n)}),this.isInterstitial(n)){this.timelinePos=Math.min(Math.max(this.timelinePos,n.start),n.end);let s=n.event;if(void 0===i){i=a.findAssetIndex(s,this.timelinePos);let t=am(s,i-1);
83if(s.isAssetPastPlayoutLimit(t)||s.appendInPlace&&this.timelinePos===n.end)return void this.advanceAfterAssetEnded(s,e,i);i=t}let o=this.waitingItem;this.assetsBuffered(n,l)||this.setBufferingItem(n);let h=this.preloadAssets(s,i);if(this.eventItemsMatch(n,o||r)||(this.waitingItem=n,this.log(`INTERSTITIAL_STARTED ${aE(n)} ${s.appendInPlace?"append in place":""}`),this.hls.trigger(K.INTERSTITIAL_STARTED,{event:s,schedule:t.slice(0),scheduleIndex:e})),!s.assetListLoaded)return void this.log(`Waiting for ASSET-LIST to complete loading ${s}`);if(s.assetListLoader&&(s.assetListLoader.destroy(),s.assetListLoader=void 0),!l)return void this.log(`Waiting for attachMedia to start Interstitial ${s}`);this.waitingItem=this.endedItem=null,this.playingItem=n;let d=s.assetList[i];if(!d)return void this.advanceAfterAssetEnded(s,e,i||0);if(h||(h=this.getAssetPlayer(d.identifier)),null===h||h.destroyed){let e=s.assetList.length;this.warn(`asset ${i+1}/${e} player destroyed ${s}`),(h=this.createAssetPlayer(s,d,i)).loadSource()}if(!this.eventItemsMatch(n,this.bufferingItem)&&s.appendInPlace&&this.isAssetBuffered(d))return;this.startAssetPlayer(h,i,t,e,l),this.shouldPlay&&aS(h.media)}else n?(this.resumePrimary(n,e,r),this.shouldPlay&&aS(this.hls.media)):s&&this.isInterstitial(r)&&(this.endedItem=null,this.playingItem=r,r.event.appendInPlace||this.attachPrimary(a.durations.primary,null))}get playbackDisabled(){return!1===this.hls.config.enableInterstitialPlayback}get primaryDetails(){var e;return null==(e=this.mediaSelection)?void 0:e.main.details}get primaryLive(){var e;return!!(null!=(e=this.primaryDetails)&&e.live)}resumePrimary(e,t,i){var r,s;if(this.playingItem=e,this.playingAsset=this.endedAsset=null,this.waitingItem=this.endedItem=null,this.bufferedToItem(e),this.log(`resuming ${aE(e)}`),!(null!=(r=this.detachedData)&&r.mediaSource)){let i=this.timelinePos;(i<e.start||i>=e.end)&&(i=this.getPrimaryResumption(e,t),this.log(aL("resumePrimary",i)),this.timelinePos=i),this.attachPrimary(i,e)}if(!i)return;let a=null==(s=this.schedule)?void 0:s.items;a&&(this.log(`INTERSTITIALS_PRIMARY_RESUMED ${aE(e)}`),this.hls.trigger(K.INTERSTITIALS_PRIMARY_RESUMED,{schedule:a.slice(0),scheduleIndex:t}),this.checkBuffer())}getPrimaryResumption(e,t){let i=e.start;if(this.primaryLive){let e=this.primaryDetails;if(0===t)return this.hls.startPosition;if(e&&(i<e.fragmentStart||i>e.edge))return this.hls.liveSyncPosition||-1}return i}isAssetBuffered(e){let t=this.getAssetPlayer(e.identifier);return null!=t&&t.hls?t.hls.bufferedToEnd:tJ.bufferInfo(this.primaryMedia,this.timelinePos,0).end+1>=e.timelineStart+(e.duration||0)}attachPrimary(e,t,i){t?this.setBufferingItem(t):this.bufferingItem=this.playingItem,this.bufferingAsset=null;let r=this.primaryMedia;if(!r)return;let s=this.hls;s.media?this.checkBuffer():(this.transferMediaTo(s,r),i&&this.startLoadingPrimaryAt(e,i)),i||(this.log(aL("attachPrimary",e)),this.timelinePos=e,this.startLoadingPrimaryAt(e,i))}startLoadingPrimaryAt(e,t){var i;let r=this.hls;!r.loadingEnabled||!r.media||Math.abs(((null==(i=r.mainForwardBufferInfo)?void 0:i.start)||r.media.currentTime)-e)>.5?r.startLoad(e,t):r.bufferingEnabled||r.resumeBuffering()}onManifestLoading(){var e;this.stopLoad(),null==(e=this.schedule)||e.reset(),this.emptyPlayerQueue(),this.clearScheduleState(),this.shouldPlay=!1,this.bufferedPos=this.timelinePos=-1,this.mediaSelection=this.altSelection=this.manager=this.requiredTracks=null,this.hls.off(K.BUFFER_CODECS,this.onBufferCodecs,this),this.hls.on(K.BUFFER_CODECS,this.onBufferCodecs,this)}onLevelUpdated(e,t){if(-1===t.level||!this.schedule)return;let i=this.hls.levels[t.level];if(!i.details)return;let r=ee(ee({},this.mediaSelection||this.altSelection),{},{main:i});this.mediaSelection=r,this.schedule.parseInterstitialDateRanges(r,this.hls.config.interstitialAppendInPlace),!this.effectivePlayingItem&&this.schedule.items&&this.checkStart()}onAudioTrackUpdated(e,t){let i=this.hls.audioTracks[t.id],r=this.mediaSelection;if(!r){this.altSelection=ee(ee({},this.altSelection),{},{audio:i});return}let s=ee(ee({},r),{},{audio:i});this.mediaSelection=s}onSubtitleTrackUpdated(e,t){let i=this.hls.subtitleTracks[t.id],r=this.mediaSelection;if(!r){this.altSelection=ee(ee({},this.altSelection),{},{subtitles:i});return}let s=ee(ee({},r),{},{subtitles:i});this.mediaSelection=s}onAudioTrackSwitching(e,t){let i=tm(t);this.playerQueue.forEach(({hls:e})=>
83e&&(e.setAudioOption(t)||e.setAudioOption(i)))}onSubtitleTrackSwitch(e,t){let i=tm(t);this.playerQueue.forEach(({hls:e})=>e&&(e.setSubtitleOption(t)||-1!==t.id&&e.setSubtitleOption(i)))}onBufferCodecs(e,t){let i=t.tracks;i&&(this.requiredTracks=i)}onBufferAppended(e,t){this.checkBuffer()}onBufferFlushed(e,t){let i=this.playingItem;if(i&&!this.itemsMatch(i,this.bufferingItem)&&!this.isInterstitial(i)){let e=this.timelinePos;this.bufferedPos=e,this.checkBuffer()}}onBufferedToEnd(e){if(!this.schedule)return;let t=this.schedule.events;if(this.bufferedPos<Number.MAX_VALUE&&t){for(let e=0;e<t.length;e++){let r=t[e];if(r.cue.post){var i;let e=this.schedule.findEventIndex(r.identifier),t=null==(i=this.schedule.items)?void 0:i[e];this.isInterstitial(t)&&this.eventItemsMatch(t,this.bufferingItem)&&this.bufferedToItem(t,0);break}}this.bufferedPos=Number.MAX_VALUE}}onMediaEnded(e){let t=this.playingItem;if(!this.playingLastItem&&t){let e=this.findItemIndex(t);this.setSchedulePosition(e+1)}else this.shouldPlay=!1}updateItem(e,t){var i;let r=null==(i=this.schedule)?void 0:i.items;return e&&r&&r[this.findItemIndex(e,t)]||null}trimInPlace(e,t){if(this.isInterstitial(e)&&e.event.appendInPlace&&t.end-e.end>.25){e.event.assetList.forEach((t,i)=>{e.event.isAssetPastPlayoutLimit(i)&&this.clearAssetPlayer(t.identifier,null)});let i=e.end+.25,r=tJ.bufferInfo(this.primaryMedia,i,0);(r.end>i||(r.nextStart||0)>i)&&(this.log(`trim buffered interstitial ${aE(e)} (was ${aE(t)})`),this.attachPrimary(i,null,!0),this.flushFrontBuffer(i))}}itemsMatch(e,t){return!!t&&(e===t||e.event&&t.event&&this.eventItemsMatch(e,t)||!e.event&&!t.event&&this.findItemIndex(e)===this.findItemIndex(t))}eventItemsMatch(e,t){var i;return!!t&&(e===t||e.event.identifier===(null==(i=t.event)?void 0:i.identifier))}findItemIndex(e,t){return e&&this.schedule?this.schedule.findItemIndex(e,t):-1}updateSchedule(e=!1){var t;let i=this.mediaSelection;i&&(null==(t=this.schedule)||t.updateSchedule(i,[],e))}checkBuffer(e){var t;let i=null==(t=this.schedule)?void 0:t.items;if(!i)return;let r=tJ.bufferInfo(this.primaryMedia,this.timelinePos,0);e&&(this.bufferedPos=this.timelinePos),e||(e=r.len<1),this.updateBufferedPos(r.end,i,e)}updateBufferedPos(e,t,i){let r=this.schedule,s=this.bufferingItem;if(this.bufferedPos>e||!r)return;if(1===t.length&&this.itemsMatch(t[0],s)){this.bufferedPos=e;return}let a=this.playingItem,n=this.findItemIndex(a),l=r.findItemIndexAtTime(e);if(this.bufferedPos<e){var o;let i=this.findItemIndex(s),r=Math.min(i+1,t.length-1),a=t[r];if((-1===l&&s&&e>=s.end||null!=(o=a.event)&&o.appendInPlace&&e+.01>=a.start)&&(l=r),this.isInterstitial(s)){let e=s.event;if(r-n>1&&!1===e.appendInPlace||0===e.assetList.length&&e.assetListLoader)return}if(this.bufferedPos=e,l>i&&l>n)this.bufferedToItem(a);else{let t=this.primaryDetails;this.primaryLive&&t&&e>t.edge-t.targetduration&&a.start<t.edge+this.hls.config.interstitialLiveLookAhead&&this.isInterstitial(a)&&this.preloadAssets(a.event,0)}}else i&&a&&!this.itemsMatch(a,s)&&(l===n?this.bufferedToItem(a):l===n+1&&this.bufferedToItem(t[l]))}assetsBuffered(e,t){return 0!==e.event.assetList.length&&!e.event.assetList.some(e=>{let i=this.getAssetPlayer(e.identifier);return!(null!=i&&i.bufferedInPlaceToEnd(t))})}setBufferingItem(e){let t=this.bufferingItem,i=this.schedule;if(!this.itemsMatch(e,t)&&i){let{items:r,events:s}=i;if(!r||!s)return t;let a=this.isInterstitial(e),n=this.getBufferingPlayer();this.bufferingItem=e,this.bufferedPos=Math.max(e.start,Math.min(e.end,this.timelinePos));let l=n?n.remaining:t?t.end-this.timelinePos:0;if(this.log(`INTERSTITIALS_BUFFERED_TO_BOUNDARY ${aE(e)}`+(t?` (${l.toFixed(2)} remaining)`:"")),!this.playbackDisabled)if(a){let t=i.findAssetIndex(e.event,this.bufferedPos);e.event.assetList.forEach((e,i)=>{let r=this.getAssetPlayer(e.identifier);r&&(i===t&&r.loadSource(),r.resumeBuffering())})}else this.hls.resumeBuffering(),this.playerQueue.forEach(e=>e.pauseBuffering());this.hls.trigger(K.INTERSTITIALS_BUFFERED_TO_BOUNDARY,{events:s.slice(0),schedule:r.slice(0),bufferingIndex:this.findItemIndex(e),playingIndex:this.findItemIndex(this.playingItem)})}else this.bufferingItem!==e&&(this.bufferingItem=e);return t}bufferedToItem(e,t=0){let i=this.setBufferingItem(e);if(!this.playbackDisabled){if(this.isInterstitial(e))this.bufferedToEvent(e,t);else if(null!==i){this.bufferingAsset=null;let t=this.detachedData;t&&t.mediaSource?this.attachPrimary(e.start,e,!0):this.preloadPrimary(e)}}}preloadPrimary(e){let t=this.findItemIndex(e),i=this.getPrimaryResumption(e,t);this.startLoadingPrimaryAt(i)}bufferedToEvent(e,t){let i=e.event,r=0===i.assetList.length&&!i.assetListLoader,s=i.cue.once;if(r||!s){let e=this.preloadAssets(i,t);if(null!=e&&e.interstitial.appendInPlace){let t=this.primaryMedia;t&&this.bufferAssetPlayer(e,t)}}}preloadAssets(e,t){let i=e.assetUrl,r=e.assetList.length,s=0===r&&!e.assetListLoader,a=e.cue.once;if(s){let s=e.timelineStart;if(e.appendInPlace){var n;let t=this.playingItem;this.isInterstitial(t)||(null==t||null==(n=t.nextEvent)?void 0:n.identifier)!==e.identifier||this.flushFrontBuffer(s+.25)}let a,l=0;if(!this.playingItem&&this.primaryLive&&-1===(l=this.hls.startPosition)&&(l=this.hls.liveSyncPosition||0),l&&!(e.cue.pre||e.cue.post)){let e=l-s;e>0&&(a=Math.round(1e3*e)/1e3)}if(this.log(`Load interstitial asset ${t+1}/${i?1:r} ${e}${a?` live-start: ${l} start-offset: ${a}`:""}`),i)return this.createAsset(e,0,0,s,e.duration,i);let o=this.assetListLoader.loadAssetList(e,a);o&&(e.assetListLoader=o)}else if(!a&&r){for(let i=t;i<r;i++){let t=e.assetList[i],r=this.getAssetPlayerQueueIndex(t.identifier);(-1===r||this.playerQueue[r].destroyed)&&!t.error&&this.createAssetPlayer(e,t,i)}let i=e.assetList[t];if(i){let e=this.getAssetPlayer(i.identifier);return e&&e.loadSource(),e}}return null}flushFrontBuffer(e){let t=this.requiredTracks;t&&(this.log(`Removing front buffer starting at ${e}`),Object.keys(t).forEach(t=>{this.hls.trigger(K.BUFFER_FLUSHING,{startOffset:e,endOffset:1/0,type:t})}))}getAssetPlayerQueueIndex(e){let t=this.playerQueue;for(let i=0;i<t.length;i++)if(e===t[i].assetId)return i;return -1}getAssetPlayer(e){let t=this.getAssetPlayerQueueIndex(e);return this.playerQueue[t]||null}
83getBufferingPlayer(){let{playerQueue:e,primaryMedia:t}=this;if(t){for(let i=0;i<e.length;i++)if(e[i].media===t)return e[i]}return null}createAsset(e,t,i,r,s,a){let n={parentIdentifier:e.identifier,identifier:`${e.identifier}-${t+1}-${ad(a)}`,duration:s,startOffset:i,timelineStart:r,uri:a};return this.createAssetPlayer(e,n,t)}createAssetPlayer(e,t,i){let r=this.hls,s=r.userConfig,a=s.videoPreference,n=r.loadLevelObj||r.levels[r.currentLevel];(a||n)&&(a=Z({},a),n.videoCodec&&(a.videoCodec=n.videoCodec),n.videoRange&&(a.allowedVideoRanges=[n.videoRange]));let l=r.audioTracks[r.audioTrack],o=r.subtitleTracks[r.subtitleTrack],h=0;if(this.primaryLive||e.appendInPlace){let e=this.timelinePos-t.timelineStart;if(e>1){let i=t.duration;i&&e<i&&(h=e)}}let d=t.identifier,c=ee(ee({},s),{},{maxMaxBufferLength:Math.min(180,r.config.maxMaxBufferLength),autoStartLoad:!0,startFragPrefetch:!0,primarySessionId:r.sessionId,assetPlayerId:d,abrEwmaDefaultEstimate:r.bandwidthEstimate,interstitialsController:void 0,startPosition:h,liveDurationInfinity:!1,testBandwidth:!1,videoPreference:a,audioPreference:l||s.audioPreference,subtitlePreference:o||s.subtitlePreference});e.appendInPlace&&(e.appendInPlaceStarted=!0,t.timelineStart&&(c.timelineOffset=t.timelineStart));let f=c.cmcd;null!=f&&f.sessionId&&f.contentId&&(c.cmcd=Z({},f,{contentId:ad(t.uri)})),this.getAssetPlayer(d)&&this.warn(`Duplicate date range identifier ${e} and asset ${d}`);let g=new ay(this.HlsPlayerClass,c,e,t);this.playerQueue.push(g),e.assetList[i]=t;let m=!0,p=r=>{if(r.live){var s;let t=Error(`Interstitials MUST be VOD assets ${e}`),r={fatal:!0,type:N.OTHER_ERROR,details:G.INTERSTITIAL_ASSET_ITEM_ERROR,error:t},a=(null==(s=this.schedule)?void 0:s.findEventIndex(e.identifier))||-1;this.handleAssetItemError(r,e,a,i,t.message);return}let a=r.edge-r.fragmentStart,n=t.duration;(m||null===n||a>n)&&(m=!1,this.log(`Interstitial asset "${d}" duration change ${n} > ${a}`),t.duration=a,this.updateSchedule())};g.on(K.LEVEL_UPDATED,(e,{details:t})=>p(t)),g.on(K.LEVEL_PTS_UPDATED,(e,{details:t})=>p(t)),g.on(K.EVENT_CUE_ENTER,()=>this.onInterstitialCueEnter());let y=(e,t)=>{let i=this.getAssetPlayer(d);if(i&&t.tracks){i.off(K.BUFFER_CODECS,y),i.tracks=t.tracks;let e=this.primaryMedia;this.bufferingAsset===i.assetItem&&e&&!i.media&&this.bufferAssetPlayer(i,e)}};g.on(K.BUFFER_CODECS,y);let v=()=>{var i;let r=this.getAssetPlayer(d);if(this.log(`buffered to end of asset ${r}`),!r||!this.schedule)return;let s=this.schedule.findEventIndex(e.identifier),a=null==(i=this.schedule.items)?void 0:i[s];this.isInterstitial(a)&&this.advanceAssetBuffering(a,t)};g.on(K.BUFFERED_TO_END,v);let E=t=>()=>{if(!this.getAssetPlayer(d)||!this.schedule)return;this.shouldPlay=!0;let i=this.schedule.findEventIndex(e.identifier);this.advanceAfterAssetEnded(e,i,t)};return g.once(K.MEDIA_ENDED,E(i)),g.once(K.PLAYOUT_LIMIT_REACHED,E(1/0)),g.on(K.ERROR,(t,r)=>{if(!this.schedule)return;let s=this.getAssetPlayer(d);r.details===G.BUFFER_STALLED_ERROR?null!=s&&s.appendInPlace?this.handleInPlaceStall(e):(this.onTimeupdate(),this.checkBuffer(!0)):this.handleAssetItemError(r,e,this.schedule.findEventIndex(e.identifier),i,`Asset player error ${r.error} ${e}`)}),g.on(K.DESTROYING,()=>{if(!this.getAssetPlayer(d)||!this.schedule)return;let t=Error(`Asset player destroyed unexpectedly ${d}`),r={fatal:!0,type:N.OTHER_ERROR,details:G.INTERSTITIAL_ASSET_ITEM_ERROR,error:t};this.handleAssetItemError(r,e,this.schedule.findEventIndex(e.identifier),i,t.message)}),this.log(`INTERSTITIAL_ASSET_PLAYER_CREATED ${ap(t)}`),this.hls.trigger(K.INTERSTITIAL_ASSET_PLAYER_CREATED,{asset:t,assetListIndex:i,event:e,player:g}),g}clearInterstitial(e,t){this.clearAssetPlayers(e,t),e.reset()}clearAssetPlayers(e,t){e.assetList.forEach(e=>{this.clearAssetPlayer(e.identifier,t)})}resetAssetPlayer(e){let t=this.getAssetPlayerQueueIndex(e);if(-1!==t){this.log(`reset asset player "${e}" after error`);let i=this.playerQueue[t];this.transferMediaFromPlayer(i,null),i.resetDetails()}}clearAssetPlayer(e,t){let i=this.getAssetPlayerQueueIndex(e);if(-1!==i){let e=this.playerQueue[i];this.log(`clear ${e} toSegment: ${t&&aE(t)}`),this.transferMediaFromPlayer(e,t),this.playerQueue.splice(i,1),e.destroy()}}emptyPlayerQueue(){let e;for(;e=this.playerQueue.pop();)e.destroy();this.playerQueue=[]}
83startAssetPlayer(e,t,i,r,s){let{interstitial:a,assetItem:n,assetId:l}=e,o=a.assetList.length,h=this.playingAsset;this.endedAsset=null,this.playingAsset=n,h&&h.identifier===l||(h&&(this.clearAssetPlayer(h.identifier,i[r]),delete h.error),this.log(`INTERSTITIAL_ASSET_STARTED ${t+1}/${o} ${ap(n)}`),this.hls.trigger(K.INTERSTITIAL_ASSET_STARTED,{asset:n,assetListIndex:t,event:a,schedule:i.slice(0),scheduleIndex:r,player:e})),this.bufferAssetPlayer(e,s)}bufferAssetPlayer(e,t){var i,r;if(!this.schedule)return;let{interstitial:s,assetItem:a}=e,n=this.schedule.findEventIndex(s.identifier),l=null==(i=this.schedule.items)?void 0:i[n];if(!l)return;e.loadSource(),this.setBufferingItem(l),this.bufferingAsset=a;let o=this.getBufferingPlayer();if(o===e)return;let h=s.appendInPlace;if(h&&o?.interstitial.appendInPlace===!1)return;let d=o?.tracks||(null==(r=this.detachedData)?void 0:r.tracks)||this.requiredTracks;if(h&&a!==this.playingAsset){if(!e.tracks)return void this.log(`Waiting for track info before buffering ${e}`);if(d&&!eo(d,e.tracks)){let t=Error(`Asset ${ap(a)} SourceBuffer tracks ('${Object.keys(e.tracks)}') are not compatible with primary content tracks ('${Object.keys(d)}')`),i={fatal:!0,type:N.OTHER_ERROR,details:G.INTERSTITIAL_ASSET_ITEM_ERROR,error:t},r=s.findAssetIndex(a);this.handleAssetItemError(i,s,n,r,t.message);return}}this.transferMediaTo(e,t)}handleInPlaceStall(e){let t=this.schedule,i=this.primaryMedia;if(!t||!i)return;let r=i.currentTime,s=t.findAssetIndex(e,r),a=e.assetList[s];if(a){let n=this.getAssetPlayer(a.identifier);if(n){let l=n.currentTime||r-a.timelineStart,o=n.duration-l;if(this.warn(`Stalled at ${l} of ${l+o} in ${n} ${e} (media.currentTime: ${r})`),l&&(o/i.playbackRate<.5||n.bufferedInPlaceToEnd(i))&&n.hls){let i=t.findEventIndex(e.identifier);this.advanceAfterAssetEnded(e,i,s)}}}}advanceInPlace(e){let t=this.primaryMedia;t&&t.currentTime<e&&(t.currentTime=e)}handleAssetItemError(e,t,i,r,s){if(e.details===G.BUFFER_STALLED_ERROR)return;let a=t.assetList[r]||null;if(this.warn(`INTERSTITIAL_ASSET_ERROR ${a&&ap(a)} ${e.error}`),!this.schedule)return;let n=a?.identifier||"",l=this.getAssetPlayerQueueIndex(n),o=this.playerQueue[l]||null,h=this.schedule.items,d=Z({},e,{fatal:!1,errorAction:tx(!0),asset:a,assetListIndex:r,event:t,schedule:h,scheduleIndex:i,player:o});if(this.hls.trigger(K.INTERSTITIAL_ASSET_ERROR,d),!e.fatal)return;let c=this.playingAsset,f=this.bufferingAsset,g=Error(s);if(a&&(this.clearAssetPlayer(n,null),a.error=g),t.assetList.some(e=>!e.error))for(let e=r;e<t.assetList.length;e++)this.resetAssetPlayer(t.assetList[e].identifier);else t.error=g;this.updateSchedule(!0),t.error?this.primaryFallback(t):c&&c.identifier===n?this.advanceAfterAssetEnded(t,i,r):f&&f.identifier===n&&this.isInterstitial(this.bufferingItem)&&this.advanceAssetBuffering(this.bufferingItem,f)}primaryFallback(e){let t=e.timelineStart,i=this.effectivePlayingItem,r=this.timelinePos;if(i){this.log(`Fallback to primary from event "${e.identifier}" start: ${t} pos: ${r} playing: ${aE(i)} error: ${e.error}`),-1===r&&(r=this.hls.startPosition);let s=this.updateItem(i,r);this.itemsMatch(i,s)&&this.clearInterstitial(e,null),e.appendInPlace&&(this.attachPrimary(t,null),this.flushFrontBuffer(t))}else if(-1===r)return void this.checkStart();if(!this.schedule)return;let s=this.schedule.findItemIndexAtTime(r);this.setSchedulePosition(s)}onAssetListLoaded(e,t){var i,r,s;let a=t.event,n=a.identifier,l=t.assetListResponse.ASSETS;if(!(null!=(i=this.schedule)&&i.hasEvent(n)))return;let o=a.timelineStart,h=a.duration,d=0;l.forEach((e,t)=>{let i=parseFloat(e.DURATION);this.createAsset(a,t,d,o+d,i,e.URI),d+=i}),a.duration=d,this.log(`Loaded asset-list with duration: ${d} (was: ${h}) ${a}`);let c=this.waitingItem,f=c?.event.identifier===n;this.updateSchedule();let g=null==(r=this.bufferingItem)?void 0:r.event;if(f){let e=this.schedule.findEventIndex(n),t=null==(s=this.schedule.items)?void 0:s[e];if(t){if(!this.playingItem&&this.timelinePos>t.end&&this.schedule.findItemIndexAtTime(this.timelinePos)!==e){a.error=Error(`Interstitial ${l.length?"no longer within playback range":"asset-list is empty"} ${this.timelinePos} ${a}`),this.log(a.error.message),this.updateSchedule(!0),this.primaryFallback(a);return}this.setBufferingItem(t)}this.setSchedulePosition(e)}else if(g?.identifier===n){let e=a.assetList[0];if(e){let t=this.getAssetPlayer(e.identifier);if(g.appendInPlace){let e=this.primaryMedia;t&&e&&this.bufferAssetPlayer(t,e)}else t&&t.loadSource()}}}onError(e,t){if(this.schedule)switch(t.details){case G.ASSET_LIST_PARSING_ERROR:case G.ASSET_LIST_LOAD_ERROR:case G.ASSET_LIST_LOAD_TIMEOUT:{let e=t.interstitial;e&&(this.updateSchedule(!0),this.primaryFallback(e));break}case G.BUFFER_STALLED_ERROR:{let e=this.endedItem||this.waitingItem||this.playingItem;if(this.isInterstitial(e)&&e.event.appendInPlace)return void this.handleInPlaceStall(e.event);this.log(`Primary player stall @${this.timelinePos} bufferedPos: ${this.bufferedPos}`),this.onTimeupdate(),this.checkBuffer(!0)}}}}});
83class nc extends tX{constructor(e,t){super("gap-controller",e.logger),this.hls=void 0,this.fragmentTracker=void 0,this.media=null,this.mediaSource=void 0,this.nudgeRetry=0,this.stallReported=!1,this.stalled=null,this.moved=!1,this.seeking=!1,this.buffered={},this.lastCurrentTime=0,this.ended=0,this.waiting=0,this.onMediaPlaying=()=>{this.ended=0,this.waiting=0},this.onMediaWaiting=()=>{var e;null!=(e=this.media)&&e.seeking||(this.waiting=self.performance.now(),this.tick())},this.onMediaEnded=()=>{if(this.hls){var e;this.ended=(null==(e=this.media)?void 0:e.currentTime)||1,this.hls.trigger(K.MEDIA_ENDED,{stalled:!1})}},this.hls=e,this.fragmentTracker=t,this.registerListeners()}registerListeners(){let{hls:e}=this;e&&(e.on(K.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(K.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(K.BUFFER_APPENDED,this.onBufferAppended,this))}unregisterListeners(){let{hls:e}=this;e&&(e.off(K.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(K.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(K.BUFFER_APPENDED,this.onBufferAppended,this))}destroy(){super.destroy(),this.unregisterListeners(),this.media=this.hls=this.fragmentTracker=null,this.mediaSource=void 0}onMediaAttached(e,t){this.setInterval(100),this.mediaSource=t.mediaSource;let i=this.media=t.media;i3(i,"playing",this.onMediaPlaying),i3(i,"waiting",this.onMediaWaiting),i3(i,"ended",this.onMediaEnded)}onMediaDetaching(e,t){this.clearInterval();let{media:i}=this;i&&(i4(i,"playing",this.onMediaPlaying),i4(i,"waiting",this.onMediaWaiting),i4(i,"ended",this.onMediaEnded),this.media=null),this.mediaSource=void 0}onBufferAppended(e,t){this.buffered=t.timeRanges}get hasBuffered(){return Object.keys(this.buffered).length>0}tick(){var e;if(!(null!=(e=this.media)&&e.readyState)||!this.hasBuffered)return;let t=this.media.currentTime;this.poll(t,this.lastCurrentTime),this.lastCurrentTime=t}poll(e,t){var i,r,s;let a=null==(i=this.hls)?void 0:i.config;if(!a)return;let n=this.media;if(!n)return;let{seeking:l}=n,o=this.seeking&&!l,h=!this.seeking&&l,d=n.paused&&!l||n.ended||0===n.playbackRate;if(this.seeking=l,e!==t){t&&(this.ended=0),this.moved=!0,l||(this.nudgeRetry=0,a.nudgeOnVideoHole&&!d&&e>t&&this.nudgeOnVideoHole(e,t)),0===this.waiting&&this.stallResolved(e);return}if(h||o){o&&this.stallResolved(e);return}if(d){this.nudgeRetry=0,this.stallResolved(e),!this.ended&&n.ended&&this.hls&&(this.ended=e||1,this.hls.trigger(K.MEDIA_ENDED,{stalled:!1}));return}if(!tJ.getBuffered(n).length){this.nudgeRetry=0;return}let c=tJ.bufferInfo(n,e,0),f=c.nextStart||0,g=this.fragmentTracker;if(l&&g&&this.hls){let t=nf(this.hls.inFlightFragments,e),i=c.len>2,r=!f||t||f-e>2&&!g.getPartialFragment(e);if(i||r)return;this.moved=!1}let m=null==(r=this.hls)?void 0:r.latestLevelDetails;if(!this.moved&&null!==this.stalled&&g){if(!(c.len>0)&&!f)return;let t=Math.max(f,c.start||0)-e,i=null!=m&&m.live?2*m.targetduration:2,r=nm(e,g);if(t>0&&(t<=i||r)){n.paused||this._trySkipBufferHole(r);return}}let p=a.detectStallWithCurrentTimeMs,y=self.performance.now(),v=this.waiting,E=this.stalled;if(null===E)if(v>0&&y-v<p)E=this.stalled=v;else{this.stalled=y;return}let T=y-E;if(!l&&(T>=p||v)&&this.hls){if((null==(s=this.mediaSource)?void 0:s.readyState)==="ended"&&!(null!=m&&m.live)&&1>Math.abs(e-(m?.edge||0))){if(this.ended)return;this.ended=e||1,this.hls.trigger(K.MEDIA_ENDED,{stalled:!0});return}if(this._reportStall(c),!this.media||!this.hls)return}let S=tJ.bufferInfo(n,e,a.maxBufferHole);this._tryFixBufferStall(S,T,e)}stallResolved(e){let t=this.stalled;if(t&&this.hls&&(this.stalled=null,this.stallReported)){let i=self.performance.now()-t;this.log(`playback not stuck anymore @${e}, after ${Math.round(i)}ms`),this.stallReported=!1,this.waiting=0,this.hls.trigger(K.STALL_RESOLVED,{})}}nudgeOnVideoHole(e,t){var i;let r=this.buffered.video;if(this.hls&&this.media&&this.fragmentTracker&&null!=(i=this.buffered.audio)&&i.length&&r&&r.length>1&&e>r.end(0)){let i=tJ.bufferedInfo(tJ.timeRangesToArray(this.buffered.audio),e,0);if(i.len>1&&t>=i.start){let i=tJ.timeRangesToArray(r),s=tJ.bufferedInfo(i,t,0).bufferedIndex;if(s>-1&&s<i.length-1){let t=tJ.bufferedInfo(i,e,0).bufferedIndex,r=i[s].end,a=i[s+1].start;if((-1===t||t>s)&&a-r<1&&e-r<2){let i=Error(`nudging playhead to flush pipeline after video hole. currentTime: ${e} hole: ${r} -> ${a} buffered index: ${t}`);this.warn(i.message),this.media.currentTime+=1e-6;let s=nm(e,this.fragmentTracker);s&&"fragment"in s?s=s.fragment:s||(s=void 0);let n=tJ.bufferInfo(this.media,e,0);this.hls.trigger(K.ERROR,{type:N.MEDIA_ERROR,details:G.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:i,reason:i.message,frag:s,buffer:n.len,bufferInfo:n})}}}}}_tryFixBufferStall(e,t,i){var r,s;let{fragmentTracker:a,media:n}=this,l=null==(r=this.hls)?void 0:r.config;if(!n||!a||!l)return;let o=null==(s=this.hls)?void 0:s.latestLevelDetails,h=nm(i,a);if((h||null!=o&&o.live&&i<o.fragmentStart)&&(this._trySkipBufferHole(h)||!this.media))return;let d=e.buffered,c=this.adjacentTraversal(e,i);(d&&d.length>1&&e.len>l.maxBufferHole||e.nextStart&&(e.nextStart-i<l.maxBufferHole||c))&&(t>1e3*l.highBufferWatchdogPeriod||this.waiting)&&(this.warn("Trying to nudge playhead over buffer-hole"),this._tryNudgeBuffer(e))}adjacentTraversal(e,t){let i=this.fragmentTracker,r=e.nextStart;if(i&&r){let e=i.getFragAtPos(t,q),s=i.getFragAtPos(r,q);if(e&&s)return s.sn-e.sn<2}return!1}_reportStall(e){let{hls:t,media:i,stallReported:r,stalled:s}=this;if(!r&&null!==s&&i&&t){this.stallReported=!0;let r=Error(`Playback stalling at @${i.currentTime} due to low buffer (${tc(e)})`);this.warn(r.message),t.trigger(K.ERROR,{type:N.MEDIA_ERROR,details:G.BUFFER_STALLED_ERROR,fatal:!1,error:r,buffer:e.len,bufferInfo:e,stalled:{start:s}})}}_trySkipBufferHole(e){var t,i;let{fragmentTracker:r,media:s}=this,a=null==(t=this.hls)?void 0:t.config;if(!s||!r||!a)return 0;let n=s.currentTime,l=tJ.bufferInfo(s,n,0),o=n<l.start?l.start:l.nextStart;if(o&&this.hls){let t=l.len<=a.maxBufferHole,h=l.len>0&&l.len<1&&s.readyState<3,d=o-n;if(d>0&&(t||h)){if(d>a.maxBufferHole){let t=!1;if(0===n){let e=r.getAppendedFrag(0,q);e&&o<e.end&&(t=!0)}if(!t&&e){if(!(null!=(i=this.hls.loadLevelObj)&&i.details)||nf(this.hls.inFlightFragments,o))return 0;let t=!1,s=e.end;for(;s<o;){let e=nm(s,r);if(e)s+=e.duration;else{t=!0;break}}if(t)return 0}}let t=Math.max(o+.05,n+.1);if(this.warn(`skipping hole, adjusting currentTime from ${n} to ${t}`),this.moved=!0,s.currentTime=t,!(null!=e&&e.gap)){let i=Error(`fragment loaded with buffer holes, seeking from ${n} to ${t}`),r={type:N.MEDIA_ERROR,details:G.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:i,reason:i.message,buffer:l.len,bufferInfo:l};e&&("fragment"in e?r.part=e:r.frag=e),this.hls.trigger(K.ERROR,r)}return t}}return 0}_tryNudgeBuffer(e){let{hls:t,media:i,nudgeRetry:r}=this,s=t?.config;if(!i||!s)return 0;let a=i.currentTime;if(this.nudgeRetry++,r<s.nudgeMaxRetry){let n=a+(r+1)*s.nudgeOffset,l=Error(`Nudging 'currentTime' from ${a} to ${n}`);this.warn(l.message),i.currentTime=n,t.trigger(K.ERROR,{type:N.MEDIA_ERROR,details:G.BUFFER_NUDGE_ON_STALL,error:l,fatal:!1,buffer:e.len,bufferInfo:e})}else{let i=Error(`Playhead still not moving while enough data buffered @${a} after ${s.nudgeMaxRetry} nudges`);this.error(i.message),t.trigger(K.ERROR,{type:N.MEDIA_ERROR,details:G.BUFFER_STALLED_ERROR,error:i,fatal:!0,buffer:e.len,bufferInfo:e})}}}function nf(e,t){let i=ng(e.main);if(i&&i.start<=t)return i;let r=ng(e.audio);return r&&r.start<=t?r:null}function ng(e){if(!e)return null;switch(e.state){case i6:case i8:case rs:case ra:return null}return e.frag}function nm(e,t){return t.getAppendedFrag(e,q)||t.getPartialFragment(e)}function np(){if(!(typeof self>"u"))return self.VTTCue||self.TextTrackCue}function ny(e,t,i,r,s){let a=new e(t,i,"");try{a.value=r,s&&(a.type=s)}catch{a=new e(t,i,tc(s?ee({type:s},r):r))}return a}let nv=(()=>{let e=np();try{e&&new e(0,1/0,"")}catch{return Number.MAX_VALUE}return 1/0})();
83class nE{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(K.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(){let{hls:e}=this;e&&(e.on(K.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(K.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(K.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(K.MANIFEST_LOADING,this.onManifestLoading,this),e.on(K.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.on(K.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(K.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(K.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))}_unregisterListeners(){let{hls:e}=this;e&&(e.off(K.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(K.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(K.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(K.MANIFEST_LOADING,this.onManifestLoading,this),e.off(K.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.off(K.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(K.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(K.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))}onMediaAttaching(e,t){var i;this.media=t.media,(null==(i=t.overrides)?void 0:i.cueRemoval)===!1&&(this.removeCues=!1)}onMediaAttached(){var e;let t=null==(e=this.hls)?void 0:e.latestLevelDetails;t&&this.updateDateRangeCues(t)}onMediaDetaching(e,t){this.media=null,t.transferMedia||(this.id3Track&&(this.removeCues&&al(this.id3Track,this.onEventCueEnter),this.id3Track=null),this.dateRangeCuesAppended={})}onManifestLoading(){this.dateRangeCuesAppended={}}createTrack(e){let t=this.getID3Track(e.textTracks);return t.mode="hidden",t}getID3Track(e){if(this.media){for(let t=0;t<e.length;t++){let i=e[t];if("metadata"===i.kind&&"id3"===i.label)return aa(i,this.media),i}return this.media.addTextTrack("metadata","id3")}}onFragParsingMetadata(e,t){if(!this.media||!this.hls)return;let{enableEmsgMetadataCues:i,enableID3MetadataCues:r}=this.hls.config;if(!i&&!r)return;let{samples:s}=t;this.id3Track||(this.id3Track=this.createTrack(this.media));let a=np();if(a)for(let e=0;e<s.length;e++){let t=s[e].type;if(t===rC.emsg&&!i||!r)continue;let n=rD(s[e].data),l=s[e].pts,o=l+s[e].duration;o>nv&&(o=nv),o-l<=0&&(o=l+.25);for(let e=0;e<n.length;e++){let i=n[e];if(!r_(i)){this.updateId3CueEnds(l,t);let e=ny(a,l,o,i,t);e&&this.id3Track.addCue(e)}}}}updateId3CueEnds(e,t){var i;let r=null==(i=this.id3Track)?void 0:i.cues;if(r)for(let i=r.length;i--;){let s=r[i];s.type===t&&s.startTime<e&&s.endTime===nv&&(s.endTime=e)}}onBufferFlushing(e,{startOffset:t,endOffset:i,type:r}){let{id3Track:s,hls:a}=this;if(!a)return;let{config:{enableEmsgMetadataCues:n,enableID3MetadataCues:l}}=a;s&&(n||l)&&ao(s,t,i,"audio"===r?e=>e.type===rC.audioId3&&l:"video"===r?e=>e.type===rC.emsg&&n:e=>e.type===rC.audioId3&&l||e.type===rC.emsg&&n)}onLevelUpdated(e,{details:t}){this.updateDateRangeCues(t,!0)}onLevelPtsUpdated(e,t){Math.abs(t.drift)>.01&&this.updateDateRangeCues(t.details)}updateDateRangeCues(e,t){var i,r;if(!this.hls||!this.media)return;let{assetPlayerId:s,timelineOffset:a,enableDateRangeMetadataCues:n,interstitialsController:l}=this.hls.config;if(!n)return;let o=np();if(s&&a&&!l){let{fragmentStart:t,fragmentEnd:i}=e,r=this.assetCue;r?(r.startTime=t,r.endTime=i):o&&(r=this.assetCue=ny(o,t,i,{assetPlayerId:this.hls.config.assetPlayerId},"hlsjs.interstitial.asset"))&&(r.id=s,this.id3Track||(this.id3Track=this.createTrack(this.media)),this.id3Track.addCue(r),r.addEventListener("enter",this.onEventCueEnter))}if(!e.hasProgramDateTime)return;let{id3Track:h}=this,{dateRanges:d}=e,c=Object.keys(d),f=this.dateRangeCuesAppended;if(h&&t)if(null!=(i=h.cues)&&i.length){let e=Object.keys(f).filter(e=>!c.includes(e));for(let t=e.length;t--;){let i=e[t],s=null==(r=f[i])?void 0:r.cues;delete f[i],s&&Object.keys(s).forEach(e=>{let t=s[e];if(t){t.removeEventListener("enter",this.onEventCueEnter);try{h.removeCue(t)}catch{}}})}}else f=this.dateRangeCuesAppended={};let g=e.fragments[e.fragments.length-1];if(!(0===c.length||!$(g?.programDateTime))){this.id3Track||(this.id3Track=this.createTrack(this.media));for(let e=0;e<c.length;e++){let t=c[e],i=d[t],r=i.startTime,s=f[t],a=s?.cues||{},n=s?.durationKnown||!1,h=nv,{duration:g,endDate:m}=i;if(m&&null!==g)h=r+g,n=!0;else if(i.endOnNext&&!n){let e=c.reduce((e,t)=>
83{if(t!==i.id){let r=d[t];if(r.class===i.class&&r.startDate>i.startDate&&(!e||i.startDate<e.startDate))return r}return e},null);e&&(h=e.startTime,n=!0)}let p=Object.keys(i.attr);for(let e=0;e<p.length;e++){let d=p[e];if("ID"===d||"CLASS"===d||"CUE"===d||"START-DATE"===d||"DURATION"===d||"END-DATE"===d||"END-ON-NEXT"===d)continue;let c=a[d];if(c)n&&!(null!=s&&s.durationKnown)?c.endTime=h:Math.abs(c.startTime-r)>.01&&(c.startTime=r,c.endTime=h);else if(o){let e=i.attr[d];("SCTE35-OUT"===d||"SCTE35-IN"===d||"SCTE35-CMD"===d)&&(e=eu(e));let s=ny(o,r,h,{key:d,data:e},rC.dateRange);s&&(s.id=t,this.id3Track.addCue(s),a[d]=s,l&&("X-ASSET-LIST"===d||"X-ASSET-URL"===d)&&s.addEventListener("enter",this.onEventCueEnter))}}f[t]={cues:a,dateRange:i,durationKnown:n}}}}}class nT{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=()=>{let{media:e}=this,t=this.levelDetails;if(!e||!t)return;this.currentTime=e.currentTime;let i=this.computeLatency();if(null===i)return;this._latency=i;let{lowLatencyMode:r,maxLiveSyncPlaybackRate:s}=this.config;if(!r||1===s||!t.live)return;let a=this.targetLatency;if(null===a)return;let n=i-a;if(n<Math.min(this.maxLatency,a+t.targetduration)&&n>.05&&this.forwardBufferLength>1){let t=Math.min(Math.min(2,Math.max(1,s)),Math.max(1,Math.round(2/(1+Math.exp(-.75*n-this.edgeStalled))*20)/20));this.changeMediaPlaybackRate(e,t)}else 1!==e.playbackRate&&0!==e.playbackRate&&this.changeMediaPlaybackRate(e,1)},this.hls=e,this.config=e.config,this.registerListeners()}get levelDetails(){var e;return(null==(e=this.hls)?void 0:e.latestLevelDetails)||null}get latency(){return this._latency||0}get maxLatency(){let{config:e}=this;if(void 0!==e.liveMaxLatencyDuration)return e.liveMaxLatencyDuration;let t=this.levelDetails;return t?e.liveMaxLatencyDurationCount*t.targetduration:0}get targetLatency(){let e=this.levelDetails;if(null===e||null===this.hls)return null;let{holdBack:t,partHoldBack:i,targetduration:r}=e,{liveSyncDuration:s,liveSyncDurationCount:a,lowLatencyMode:n}=this.config,l=this.hls.userConfig,o=n&&i||t;return(this._targetLatencyUpdated||l.liveSyncDuration||l.liveSyncDurationCount||0===o)&&(o=void 0!==s?s:a*r),o+Math.min(this.stallCount*this.config.liveSyncOnStallIncrease,r)}set targetLatency(e){this.stallCount=0,this.config.liveSyncDuration=e,this._targetLatencyUpdated=!0}get liveSyncPosition(){let e=this.estimateLiveEdge(),t=this.targetLatency;if(null===e||null===t)return null;let i=this.levelDetails;if(null===i)return null;let r=i.edge,s=e-t-this.edgeStalled;return Math.min(Math.max(r-i.totalduration,s),r-(this.config.lowLatencyMode&&i.partTarget||i.targetduration))}get drift(){let e=this.levelDetails;return null===e?1:e.drift}get edgeStalled(){let e=this.levelDetails;if(null===e)return 0;let t=3*(this.config.lowLatencyMode&&e.partTarget||e.targetduration);return Math.max(e.age-t,0)}get forwardBufferLength(){let{media:e}=this,t=this.levelDetails;if(!e||!t)return 0;let i=e.buffered.length;return(i?e.buffered.end(i-1):t.edge)-this.currentTime}destroy(){this.unregisterListeners(),this.onMediaDetaching(),this.hls=null}registerListeners(){let{hls:e}=this;e&&(e.on(K.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(K.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(K.MANIFEST_LOADING,this.onManifestLoading,this),e.on(K.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(K.ERROR,this.onError,this))}unregisterListeners(){let{hls:e}=this;e&&(e.off(K.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(K.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(K.MANIFEST_LOADING,this.onManifestLoading,this),e.off(K.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(K.ERROR,this.onError,this))}onMediaAttached(e,t){this.media=t.media,this.media.addEventListener("timeupdate",this.onTimeupdate)}onMediaDetaching(){this.media&&(this.media.removeEventListener("timeupdate",this.onTimeupdate),this.media=null)}onManifestLoading(){this._latency=null,this.stallCount=0}onLevelUpdated(e,{details:t}){t.advanced&&this.onTimeupdate(),!t.live&&this.media&&this.media.removeEventListener("timeupdate",this.onTimeupdate)}onError(e,t){var i;t.details===G.BUFFER_STALLED_ERROR&&(this.stallCount++,this.hls&&null!=(i=this.levelDetails)&&i.live&&this.hls.logger.warn("[latency-controller]: Stall detected, adjusting target latency"))}changeMediaPlaybackRate(e,t){var i,r;e.playbackRate!==t&&(null==(i=this.hls)||i.logger.debug(`[latency-controller]: latency=${this.latency.toFixed(3)}, targetLatency=${null==(r=this.targetLatency)?void 0:r.toFixed(3)}, forwardBufferLength=${this.forwardBufferLength.toFixed(3)}: adjusting playback rate from ${e.playbackRate} to ${t}`),e.playbackRate=t)}estimateLiveEdge(){let e=this.levelDetails;return null===e?null:e.edge+e.age}computeLatency(){let e=this.estimateLiveEdge();return null===e?null:e-this.currentTime}}class nS extends sy{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(){let{hls:e}=this;e.on(K.MANIFEST_LOADING,this.onManifestLoading,this),e.on(K.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(K.LEVEL_LOADED,this.onLevelLoaded,this),e.on(K.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(K.FRAG_BUFFERED,this.onFragBuffered,this),e.on(K.ERROR,this.onError,this)}_unregisterListeners(){let{hls:e}=this;e.off(K.MANIFEST_LOADING,this.onManifestLoading,this),e.off(K.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(K.LEVEL_LOADED,this.onLevelLoaded,this),e.off(K.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(K.FRAG_BUFFERED,this.onFragBuffered,this),e.off(K.ERROR,this.onError,this)}destroy(){this._unregisterListeners(),this.steering=null,this.resetLevels(),super.destroy()}
83stopLoad(){this._levels.forEach(e=>{e.loadError=0,e.fragmentError=0}),super.stopLoad()}resetLevels(){this._startLevel=void 0,this.manualLevelIndex=-1,this.currentLevelIndex=-1,this.currentLevel=null,this._levels=[],this._maxAutoLevel=-1}onManifestLoading(e,t){this.resetLevels()}onManifestLoaded(e,t){let i=this.hls.config.preferManagedMediaSource,r=[],s={},a={},n=!1,l=!1,o=!1;t.levels.forEach(e=>{let t=e.attrs,{audioCodec:h,videoCodec:d}=e;h&&(e.audioCodec=h=e8(h,i)||void 0),d&&(d=e.videoCodec=function(e){let t=e.split(",");for(let e=0;e<t.length;e++){let i=t[e].split(".");i.length>2&&"avc1"===i[0]&&(t[e]=`avc1.${parseInt(i[1]).toString(16)}${("000"+parseInt(i[2]).toString(16)).slice(-4)}`)}return t.join(",")}(d));let{width:c,height:f,unknownCodecs:g}=e,m=g?.length||0;if(n||(n=!!(c&&f)),l||(l=!!d),o||(o=!!h),m||h&&!this.isAudioSupported(h)||d&&!this.isVideoSupported(d))return void this.log(`Some or all CODECS not supported "${t.CODECS}"`);let{CODECS:p,"FRAME-RATE":y,"HDCP-LEVEL":v,"PATHWAY-ID":E,RESOLUTION:T,"VIDEO-RANGE":S}=t,L=`${E||"."}-${e.bitrate}-${T}-${y}-${p}-${S}-${v}`;if(s[L])if(s[L].uri===e.url||e.attrs["PATHWAY-ID"])s[L].addGroupId("audio",t.AUDIO),s[L].addGroupId("text",t.SUBTITLES);else{let t=a[L]+=1;e.attrs["PATHWAY-ID"]=Array(t+1).join(".");let i=this.createLevel(e);s[L]=i,r.push(i)}else{let t=this.createLevel(e);s[L]=t,a[L]=1,r.push(t)}}),this.filterAndSortMediaOptions(r,t,n,l,o)}createLevel(e){let t=new td(e),i=e.supplemental;if(null!=i&&i.videoCodec&&!this.isVideoSupported(i.videoCodec)){let e=Error(`SUPPLEMENTAL-CODECS not supported "${i.videoCodec}"`);this.log(e.message),t.supportedResult=tr(e,[])}return t}isAudioSupported(e){return eJ(e,"audio",this.hls.config.preferManagedMediaSource)}isVideoSupported(e){return eJ(e,"video",this.hls.config.preferManagedMediaSource)}filterAndSortMediaOptions(e,t,i,r,s){var a,n;let l=[],o=[],h=e,d=(null==(a=t.stats)?void 0:a.parsing)||{};if((i||r)&&s&&(h=h.filter(({videoCodec:e,videoRange:t,width:i,height:r})=>{var s;return(!!e||!!(i&&r))&&!!(s=t)&&tl.indexOf(s)>-1})),0===h.length){Promise.resolve().then(()=>{if(this.hls){let e="no level with compatible codecs found in manifest",i=e;t.levels.length&&(i=`one or more CODECS in variant not supported: ${tc(t.levels.map(e=>e.attrs.CODECS).filter((e,t,i)=>i.indexOf(e)===t))}`,this.warn(i),e+=` (${i})`);let r=Error(e);this.hls.trigger(K.ERROR,{type:N.MEDIA_ERROR,details:G.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:t.url,error:r,reason:i})}}),d.end=performance.now();return}t.audioTracks&&nL(l=t.audioTracks.filter(e=>!e.audioCodec||this.isAudioSupported(e.audioCodec))),t.subtitles&&nL(o=t.subtitles);let c=h.slice(0);h.sort((e,t)=>{if(e.attrs["HDCP-LEVEL"]!==t.attrs["HDCP-LEVEL"])return(e.attrs["HDCP-LEVEL"]||"")>(t.attrs["HDCP-LEVEL"]||"")?1:-1;if(i&&e.height!==t.height)return e.height-t.height;if(e.frameRate!==t.frameRate)return e.frameRate-t.frameRate;if(e.videoRange!==t.videoRange)return tl.indexOf(e.videoRange)-tl.indexOf(t.videoRange);if(e.videoCodec!==t.videoCodec){let i=e2(e.videoCodec),r=e2(t.videoCodec);if(i!==r)return r-i}if(e.uri===t.uri&&e.codecSet!==t.codecSet){let i=e3(e.codecSet),r=e3(t.codecSet);if(i!==r)return r-i}return e.averageBitrate!==t.averageBitrate?e.averageBitrate-t.averageBitrate:0});let f=c[0];if(this.steering&&(h=this.steering.filterParsedLevels(h)).length!==c.length){for(let e=0;e<c.length;e++)if(c[e].pathwayId===h[0].pathwayId){f=c[e];break}}this._levels=h;for(let e=0;e<h.length;e++)if(h[e]===f){this._firstLevel=e;let t=f.bitrate,i=this.hls.bandwidthEstimate;if(this.log(`manifest loaded, ${h.length} level(s) found, first bitrate: ${t}`),(null==(n=this.hls.userConfig)?void 0:n.abrEwmaDefaultEstimate)===void 0){let e=Math.min(t,this.hls.config.abrEwmaDefaultEstimateMax);e>i&&i===this.hls.abrEwmaDefaultEstimate&&(this.hls.bandwidthEstimate=e)}break}let g=s&&!r,m=this.hls.config,p=!!(m.audioStreamController&&m.audioTrackController),y={levels:h,audioTracks:l,subtitleTracks:o,sessionData:t.sessionData,sessionKeys:t.sessionKeys,firstLevel:this._firstLevel,stats:t.stats,audio:s,video:r,altAudio:p&&!g&&l.some(e=>!!e.url)};d.end=performance.now(),this.hls.trigger(K.MANIFEST_PARSED,y)}get levels(){return 0===this._levels.length?null:this._levels}get loadLevelObj(){return this.currentLevel}get level(){return this.currentLevelIndex}set level(e){let t=this._levels;if(0===t.length)return;if(e<0||e>=t.length){let i=Error("invalid level idx"),r=e<0;
83if(this.hls.trigger(K.ERROR,{type:N.OTHER_ERROR,details:G.LEVEL_SWITCH_ERROR,level:e,fatal:r,error:i,reason:i.message}),r)return;e=Math.min(e,t.length-1)}let i=this.currentLevelIndex,r=this.currentLevel,s=r?r.attrs["PATHWAY-ID"]:void 0,a=t[e],n=a.attrs["PATHWAY-ID"];if(this.currentLevelIndex=e,this.currentLevel=a,i===e&&r&&s===n)return;this.log(`Switching to level ${e} (${a.height?a.height+"p ":""}${a.videoRange?a.videoRange+" ":""}${a.codecSet?a.codecSet+" ":""}@${a.bitrate})${n?" with Pathway "+n:""} from level ${i}${s?" with Pathway "+s:""}`);let l={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(K.LEVEL_SWITCHING,l);let o=a.details;if(!o||o.live){let e=this.switchParams(a.uri,r?.details,o);this.loadPlaylist(e)}}get manualLevel(){return this.manualLevelIndex}set manualLevel(e){this.manualLevelIndex=e,void 0===this._startLevel&&(this._startLevel=e),-1!==e&&(this.level=e)}get firstLevel(){return this._firstLevel}set firstLevel(e){this._firstLevel=e}get startLevel(){if(void 0===this._startLevel){let e=this.hls.config.startLevel;return void 0!==e?e:this.hls.firstAutoLevel}return this._startLevel}set startLevel(e){this._startLevel=e}get pathways(){return this.steering?this.steering.pathways():[]}get pathwayPriority(){return this.steering?this.steering.pathwayPriority:null}set pathwayPriority(e){if(this.steering){let t=this.steering.pathways(),i=e.filter(e=>-1!==t.indexOf(e));if(e.length<1)return void this.warn(`pathwayPriority ${e} should contain at least one pathway from list: ${t}`);this.steering.pathwayPriority=i}}onError(e,t){t.fatal||!t.context||t.context.type===V&&t.context.level===this.level&&this.checkRetry(t)}onFragBuffered(e,{frag:t}){if(void 0!==t&&t.type===q){let e=t.elementaryStreams;if(!Object.keys(e).some(t=>!!e[t]))return;let i=this._levels[t.level];null!=i&&i.loadError&&(this.log(`Resetting level error count of ${i.loadError} on frag buffered`),i.loadError=0)}}onLevelLoaded(e,t){var i,r;let{level:s,details:a}=t,n=t.levelInfo;if(!n){this.warn(`Invalid level index ${s}`),null!=(r=t.deliveryDirectives)&&r.skip&&(a.deltaUpdateFailed=!0);return}if(n===this.currentLevel||t.withoutMultiVariant){0===n.fragmentError&&(n.loadError=0);let e=n.details;e===t.details&&e.advanced&&(e=void 0),this.playlistLoaded(s,t,e)}else null!=(i=t.deliveryDirectives)&&i.skip&&(a.deltaUpdateFailed=!0)}loadPlaylist(e){super.loadPlaylist(),this.shouldLoadPlaylist(this.currentLevel)&&this.scheduleLoading(this.currentLevel,e)}loadingPlaylist(e,t){super.loadingPlaylist(e,t);let i=this.getUrlWithDirectives(e.uri,t),r=this.currentLevelIndex,s=e.attrs["PATHWAY-ID"],a=e.details,n=a?.age;this.log(`Loading level index ${r}${t?.msn!==void 0?" at sn "+t.msn+" part "+t.part:""}${s?" Pathway "+s:""}${n&&a.live?" age "+n.toFixed(1)+(a.type&&" "+a.type||""):""} ${i}`),this.hls.trigger(K.LEVEL_LOADING,{url:i,level:r,levelInfo:e,pathwayId:e.attrs["PATHWAY-ID"],id:0,deliveryDirectives:t||null})}get nextLoadLevel(){return -1!==this.manualLevelIndex?this.manualLevelIndex:this.hls.nextAutoLevel}set nextLoadLevel(e){this.level=e,-1===this.manualLevelIndex&&(this.hls.nextAutoLevel=e)}removeLevel(e){var t;if(1===this._levels.length)return;let i=this._levels.filter((t,i)=>i!==e||(this.steering&&this.steering.removeLevel(t),t===this.currentLevel&&(this.currentLevel=null,this.currentLevelIndex=-1,t.details&&t.details.fragments.forEach(e=>e.level=-1)),!1));iz(i),this._levels=i,this.currentLevelIndex>-1&&null!=(t=this.currentLevel)&&t.details&&(this.currentLevelIndex=this.currentLevel.details.fragments[0].level),this.manualLevelIndex>-1&&(this.manualLevelIndex=this.currentLevelIndex);let r=i.length-1;this._firstLevel=Math.min(this._firstLevel,r),this._startLevel&&(this._startLevel=Math.min(this._startLevel,r)),this.hls.trigger(K.LEVELS_UPDATED,{levels:i})}onLevelsUpdated(e,{levels:t}){this._levels=t}checkMaxAutoUpdated(){let{autoLevelCapping:e,maxAutoLevel:t,maxHdcpLevel:i}=this.hls;this._maxAutoLevel!==t&&(this._maxAutoLevel=t,this.hls.trigger(K.MAX_AUTO_LEVEL_UPDATED,{autoLevelCapping:e,levels:this.levels,maxAutoLevel:t,minAutoLevel:this.hls.minAutoLevel,maxHdcpLevel:i}))}}function nL(e){let t={};
83e.forEach(e=>{let i=e.groupId||"";e.id=t[i]=t[i]||0,t[i]++})}function nA(){return self.SourceBuffer||self.WebKitSourceBuffer}function nR(){if(!el())return!1;let e=nA();return!e||e.prototype&&"function"==typeof e.prototype.appendBuffer&&"function"==typeof e.prototype.remove}class nb extends ro{constructor(e,t,i){super(e,t,i,"stream-controller",q),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=()=>{let e=this.media,t=e?e.currentTime:null;if(null===t||!$(t)||(this.log(`Media seeked to ${t.toFixed(3)}`),!this.getBufferedFrag(t)))return;let i=this.getFwdBufferInfoAtPos(e,t,q,0);null===i||0===i.len?this.warn(`Main forward buffer length at ${t} on "seeked" event ${i?i.len:"empty"})`):this.tick()},this.registerListeners()}registerListeners(){super.registerListeners();let{hls:e}=this;e.on(K.MANIFEST_PARSED,this.onManifestParsed,this),e.on(K.LEVEL_LOADING,this.onLevelLoading,this),e.on(K.LEVEL_LOADED,this.onLevelLoaded,this),e.on(K.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.on(K.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(K.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.on(K.BUFFER_CREATED,this.onBufferCreated,this),e.on(K.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(K.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(K.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){super.unregisterListeners();let{hls:e}=this;e.off(K.MANIFEST_PARSED,this.onManifestParsed,this),e.off(K.LEVEL_LOADED,this.onLevelLoaded,this),e.off(K.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.off(K.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(K.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.off(K.BUFFER_CREATED,this.onBufferCreated,this),e.off(K.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(K.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(K.FRAG_BUFFERED,this.onFragBuffered,this)}onHandlerDestroying(){this.onMediaPlaying=this.onMediaSeeked=null,this.unregisterListeners(),super.onHandlerDestroying()}startLoad(e,t){if(this.levels){let{lastCurrentTime:i,hls:r}=this;if(this.stopLoad(),this.setInterval(100),this.level=-1,!this.startFragRequested){let e=r.startLevel;-1===e&&(r.config.testBandwidth&&this.levels.length>1?(e=0,this.bitrateTest=!0):e=r.firstAutoLevel),r.nextLoadLevel=e,this.level=r.loadLevel,this._hasEnoughToStart=!!t}i>0&&-1===e&&!t&&(this.log(`Override startPosition with lastCurrentTime @${i.toFixed(3)}`),e=i),this.state=i6,this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,this.tick()}else this._forceStartLoad=!0,this.state=i8}stopLoad(){this._forceStartLoad=!1,super.stopLoad()}doTick(){switch(this.state){case rl:{let{levels:e,level:t}=this,i=e?.[t],r=i?.details;if(!r||r.live&&(this.levelLastLoaded!==i||this.waitForLive(i)))this.hls.nextLoadLevel!==this.level&&(this.state=i6);else{if(this.waitForCdnTuneIn(r))break;this.state=i6}break}case re:this.checkRetryDate()}this.state===i6&&this.doTickIdle(),this.onTickEnd()}onTickEnd(){var e;super.onTickEnd(),null!=(e=this.media)&&e.readyState&&!1===this.media.seeking&&(this.lastCurrentTime=this.media.currentTime),this.checkFragmentChanged()}doTickIdle(){let{hls:e,levelLastLoaded:t,levels:i,media:r}=this;if(null===t||!r&&!this.primaryPrefetch&&(this.startFragRequested||!e.config.startFragPrefetch)||this.altAudio&&this.audioOnly)return;let s=this.buffering?e.nextLoadLevel:e.loadLevel;if(!(null!=i&&i[s]))return;let a=i[s],n=this.getMainFwdBufferInfo();if(null===n)return;let l=this.getLevelDetails();if(l&&this._streamEnded(n,l)){let e={};2===this.altAudio&&(e.type="video"),this.hls.trigger(K.BUFFER_EOS,e),this.state=rs;return}if(!this.buffering)return;e.loadLevel!==s&&-1===e.manualLevel&&this.log(`Adapting to level ${s} from level ${this.level}`),this.level=e.nextLoadLevel=s;let o=a.details;if(!o||this.state===rl||this.waitForLive(a)){this.level=s,this.state=rl,this.startFragRequested=!1;return}let h=n.len,d=this.getMaxBufferLength(a.maxBitrate);
83if(h>=d)return;this.backtrackFragment&&this.backtrackFragment.start>n.end&&(this.backtrackFragment=null);let c=this.backtrackFragment?this.backtrackFragment.start:n.end,f=this.getNextFragment(c,o);if(this.couldBacktrack&&!this.fragPrevious&&f&&eD(f)&&"OK"!==this.fragmentTracker.getState(f)){var g;let e=(null!=(g=this.backtrackFragment)?g:f).sn-o.startSN,t=o.fragments[e-1];t&&f.cc===t.cc&&(f=t,this.fragmentTracker.removeFragment(t))}else this.backtrackFragment&&n.len&&(this.backtrackFragment=null);if(f&&this.isLoopLoading(f,c)){if(!f.gap){let e=this.audioOnly&&!this.altAudio?eR:eb,t=(e===eb?this.videoBuffer:this.mediaBuffer)||this.media;t&&this.afterBufferFlushed(t,e,q)}f=this.getNextFragmentLoopLoading(f,o,n,q,d)}f&&(this.exceedsMaxBuffer(n,d,f)||(!f.initSegment||f.initSegment.data||this.bitrateTest||(f=f.initSegment),this.loadFragment(f,a,c)))}loadFragment(e,t,i){let r=this.fragmentTracker.getState(e);r===tM||r===tF?eD(e)?this.bitrateTest?(this.log(`Fragment ${e.sn} of level ${e.level} is being downloaded to test bitrate and will not be buffered`),this._loadBitrateTestFrag(e,t)):super.loadFragment(e,t,i):this._loadInitSegment(e,t):this.clearTrackerIfNeeded(e)}getBufferedFrag(e){return this.fragmentTracker.getBufferedFrag(e,q)}followingBufferedFrag(e){return e?this.getBufferedFrag(e.end+.5):null}immediateLevelSwitch(){if(this.abortCurrentFrag(),this.flushMainBuffer(0,1/0),0!==this.altAudio){var e;((null==(e=this.getLevelDetails())?void 0:e.fragmentStart)||0)>this.lastCurrentTime&&super.flushMainBuffer(0,1/0,"audio")}}nextLevelSwitch(){let{levels:e,media:t}=this;if(null!=t&&t.readyState){let i,r=this.getAppendedFrag(t.currentTime);r&&r.start>1&&this.flushMainBuffer(0,r.start-1);let s=this.getLevelDetails();if(null!=s&&s.live){let e=this.getMainFwdBufferInfo();if(!e||e.len<2*s.targetduration)return}if(!t.paused&&e){let t=e[this.hls.nextLoadLevel],r=this.fragLastKbps;i=r&&this.fragCurrent?this.fragCurrent.duration*t.maxBitrate/(1e3*r)+1:0}else i=0;let a=this.getBufferedFrag(t.currentTime+i);if(a){let e=this.followingBufferedFrag(a);if(e){this.abortCurrentFrag();let t=e.maxStartPTS?e.maxStartPTS:e.start,i=e.duration,r=Math.max(a.end,t+Math.min(Math.max(i-this.config.maxFragLookUpTolerance,i*(this.couldBacktrack?.5:.125)),i*(this.couldBacktrack?.75:.25)));this.flushMainBuffer(r,1/0)}}}}abortCurrentFrag(){let e=this.fragCurrent;switch(this.fragCurrent=null,this.backtrackFragment=null,e&&(e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.state){case i9:case i7:case re:case ri:case rr:this.state=i6}this.nextLoadPosition=this.getLoadPosition()}flushMainBuffer(e,t){super.flushMainBuffer(e,t,2===this.altAudio?"video":null)}onMediaAttached(e,t){super.onMediaAttached(e,t);let i=t.media;i3(i,"playing",this.onMediaPlaying),i3(i,"seeked",this.onMediaSeeked)}onMediaDetaching(e,t){let{media:i}=this;i&&(i4(i,"playing",this.onMediaPlaying),i4(i,"seeked",this.onMediaSeeked)),this.videoBuffer=null,this.fragPlaying=null,super.onMediaDetaching(e,t),t.transferMedia||(this._hasEnoughToStart=!1)}onManifestLoading(){super.onManifestLoading(),this.log("Trigger BUFFER_RESET"),this.hls.trigger(K.BUFFER_RESET,void 0),this.couldBacktrack=!1,this.fragLastKbps=0,this.fragPlaying=this.backtrackFragment=null,this.altAudio=0,this.audioOnly=!1}onManifestParsed(e,t){var i;let r,s=!1,a=!1;for(let e=0;e<t.levels.length;e++){let i=t.levels[e].audioCodec;i&&(s=s||-1!==i.indexOf("mp4a.40.2"),a=a||-1!==i.indexOf("mp4a.40.5"))}this.audioCodecSwitch=s&&a&&"function"!=typeof(null==(r=nA())||null==(i=r.prototype)?void 0:i.changeType),this.audioCodecSwitch&&this.log("Both AAC/HE-AAC audio found in levels; declaring level codec as HE-AAC"),this.levels=t.levels,this.startFragRequested=!1}onLevelLoading(e,t){let{levels:i}=this;if(!i||this.state!==i6)return;let r=t.levelInfo;(!r.details||r.details.live&&(this.levelLastLoaded!==r||r.details.expired)||this.waitForCdnTuneIn(r.details))&&(this.state=rl)}onLevelLoaded(e,t){var i,r;let{levels:s,startFragRequested:a}=this,n=t.level,l=t.details,o=l.totalduration;if(!s)return void this.warn(`Levels were reset while loading level ${n}`);this.log(`Level ${n} loaded [${l.startSN},${l.endSN}]${l.lastPartSn?`[part-${l.lastPartSn}-${l.lastPartIndex}]`:""}, cc [${l.startCC}, ${l.endCC}] duration:${o}`);let h=t.levelInfo,d=this.fragCurrent;d&&(this.state===i7||this.state===re)&&d.level!==t.level&&d.loader&&this.abortCurrentFrag();let c=0;if(l.live||null!=(i=h.details)&&i.live){if(this.checkLiveUpdate(l),l.deltaUpdateFailed)return;c=this.alignPlaylists(l,h.details,null==(r=this.levelLastLoaded)?void 0:r.details)}if(h.details=l,this.levelLastLoaded=h,a||this.setStartPosition(l,c),this.hls.trigger(K.LEVEL_UPDATED,{details:l,level:n}),this.state===rl){if(this.waitForCdnTuneIn(l))return;this.state=i6}a&&l.live&&this.synchronizeToLiveEdge(l),this.tick()}
83synchronizeToLiveEdge(e){let{config:t,media:i}=this;if(!i)return;let r=this.hls.liveSyncPosition,s=this.getLoadPosition(),a=e.fragmentStart,n=e.edge,l=s>=a-t.maxFragLookUpTolerance&&s<=n;if(null!==r&&i.duration>r&&(s<r||!l)){let a=void 0!==t.liveMaxLatencyDuration?t.liveMaxLatencyDuration:t.liveMaxLatencyDurationCount*e.targetduration;if((!l&&i.readyState<4||s<n-a)&&(this._hasEnoughToStart||(this.nextLoadPosition=r),i.readyState))if(this.warn(`Playback: ${s.toFixed(3)} is located too far from the end of live sliding playlist: ${n}, reset currentTime to : ${r.toFixed(3)}`),"buffered"===this.config.liveSyncMode){var o;let e=tJ.bufferInfo(i,r,0);if(!(null!=(o=e.buffered)&&o.length)||e.start<=s){i.currentTime=r;return}let{nextStart:t}=tJ.bufferedInfo(e.buffered,s,0);t&&(i.currentTime=t)}else i.currentTime=r}}_handleFragmentLoadProgress(e){var t;let i=e.frag,{part:r,payload:s}=e,{levels:a}=this;if(!a)return void this.warn(`Levels were reset while fragment load was in progress. Fragment ${i.sn} of level ${i.level} will not be buffered`);let n=a[i.level];if(!n)return void this.warn(`Level ${i.level} not found on progress`);let l=n.details;if(!l){this.warn(`Dropping fragment ${i.sn} of level ${i.level} after level details were reset`),this.fragmentTracker.removeFragment(i);return}let o=n.videoCodec,h=l.PTSKnown||!l.live,d=null==(t=i.initSegment)?void 0:t.data,c=this._getAudioCodec(n),f=this.transmuxer=this.transmuxer||new sp(this.hls,q,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)),g=r?r.index:-1,m=new tz(i.level,i.sn,i.stats.chunkCount,s.byteLength,g,-1!==g),p=this.initPTS[i.cc];f.push(s,d,c,o,i,r,l.totalduration,h,m,p)}onAudioTrackSwitching(e,t){let i=this.hls,r=0!==this.altAudio;if(tT(t.url,i))this.altAudio=1;else{if(this.mediaBuffer!==this.media){this.log("Switching on main audio, use media.buffered to schedule main fragment loading"),this.mediaBuffer=this.media;let e=this.fragCurrent;e&&(this.log("Switching to main audio track, cancel main fragment load"),e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.resetTransmuxer(),this.resetLoadingState()}else this.audioOnly&&this.resetTransmuxer();if(r){this.altAudio=0,this.fragmentTracker.removeAllFragments(),i.once(K.BUFFER_FLUSHED,()=>{this.hls&&this.hls.trigger(K.AUDIO_TRACK_SWITCHED,t)}),i.trigger(K.BUFFER_FLUSHING,{startOffset:0,endOffset:1/0,type:null});return}i.trigger(K.AUDIO_TRACK_SWITCHED,t)}}onAudioTrackSwitched(e,t){let i=tT(t.url,this.hls);if(i){let e=this.videoBuffer;e&&this.mediaBuffer!==e&&(this.log("Switching on alternate audio, use video.buffered to schedule main fragment loading"),this.mediaBuffer=e)}this.altAudio=2*!!i,this.tick()}onBufferCreated(e,t){let i=t.tracks,r,s,a=!1;for(let e in i){let t=i[e];if("main"===t.id){if(s=e,r=t,"video"===e){let t=i[e];t&&(this.videoBuffer=t.buffer)}}else a=!0}a&&r?(this.log(`Alternate track found, use ${s}.buffered to schedule main fragment loading`),this.mediaBuffer=r.buffer):this.mediaBuffer=this.media}onFragBuffered(e,t){let{frag:i,part:r}=t,s=i.type===q;if(s){if(this.fragContextChanged(i)){this.warn(`Fragment ${i.sn}${r?" p: "+r.index:""} of level ${i.level} finished buffering, but was aborted. state: ${this.state}`),this.state===rr&&(this.state=i6);return}let e=r?r.stats:i.stats;this.fragLastKbps=Math.round(8*e.total/(e.buffering.end-e.loading.first)),eD(i)&&(this.fragPrevious=i),this.fragBufferedComplete(i,r)}let a=this.media;a&&(!this._hasEnoughToStart&&tJ.getBuffered(a).length&&(this._hasEnoughToStart=!0,this.seekToStartPos()),s&&this.tick())}get hasEnoughToStart(){return this._hasEnoughToStart}onError(e,t){var i;if(t.fatal){this.state=ra;return}switch(t.details){case G.FRAG_GAP:case G.FRAG_PARSING_ERROR:case G.FRAG_DECRYPT_ERROR:case G.FRAG_LOAD_ERROR:case G.FRAG_LOAD_TIMEOUT:case G.KEY_LOAD_ERROR:case G.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(q,t);break;case G.LEVEL_LOAD_ERROR:case G.LEVEL_LOAD_TIMEOUT:case G.LEVEL_PARSING_ERROR:t.levelRetry||this.state!==rl||(null==(i=t.context)?void 0:i.type)!==V||(this.state=i6);break;case G.BUFFER_ADD_CODEC_ERROR:case G.BUFFER_APPEND_ERROR:if("main"!==t.parent)return;this.reduceLengthAndFlushBuffer(t)&&this.resetLoadingState();break;case G.BUFFER_FULL_ERROR:if("main"!==t.parent)return;this.reduceLengthAndFlushBuffer(t)&&(!this.config.interstitialsController&&this.config.assetPlayerId?this._hasEnoughToStart=!0:this.flushMainBuffer(0,1/0));break;case G.INTERNAL_EXCEPTION:this.recoverWorkerError(t)}}onFragLoadEmergencyAborted(){this.state=i6,this._hasEnoughToStart||(this.startFragRequested=!1,this.nextLoadPosition=this.lastCurrentTime),this.tickImmediate()}onBufferFlushed(e,{type:t}){if(t!==eR||!this.altAudio){let e=(t===eb?this.videoBuffer:this.mediaBuffer)||this.media;e&&(this.afterBufferFlushed(e,t,q),this.tick())}}onLevelsUpdated(e,t){this.level>-1&&this.fragCurrent&&(this.level=this.fragCurrent.level,-1===this.level&&this.resetWhenMissingContext(this.fragCurrent)),this.levels=t.levels}swapAudioCodec(){this.audioCodecSwap=!this.audioCodecSwap}seekToStartPos(){let{media:e}=this;if(!e)return;let t=e.currentTime,i=this.startPosition;if(i>=0&&t<i){if(e.seeking)return void this.log(`could not seek to ${i}, already seeking at ${t}`);let r=this.timelineOffset;r&&i&&(i+=r);let s=this.getLevelDetails(),a=tJ.getBuffered(e),n=a.length?a.start(0):0,l=n-i,o=Math.max(this.config.maxBufferHole,this.config.maxFragLookUpTolerance);(this.config.startOnSegmentBoundary||l>0&&(l<o||this.loadingParts&&l<2*(s?.partTarget||0)))&&(this.log(`adjusting start position by ${l} to match buffer start`),i+=l,this.startPosition=i),t<i&&(this.log(`seek to target start position ${i} from current time ${t} buffer start ${n}`),e.currentTime=i)}}_getAudioCodec(e){let t=this.config.defaultAudioCodec||e.audioCodec;return this.audioCodecSwap&&t&&(this.log("Swapping audio codec"),t=-1!==t.indexOf("mp4a.40.5")?"mp4a.40.2":"mp4a.40.5"),t}_loadBitrateTestFrag(e,t){e.bitrateTest=!0,this._doFragLoad(e,t).then(e=>{let{hls:i}=this,r=e?.frag;if(!r||this.fragContextChanged(r))return;t.fragmentError=0,this.state=i6,this.startFragRequested=!1,this.bitrateTest=!1;let s=r.stats;s.parsing.start=s.parsing.end=s.buffering.start=s.buffering.end=self.performance.now(),i.trigger(K.FRAG_LOADED,e),r.bitrateTest=!1}
83).catch(t=>{this.state===i8||this.state===ra||(this.warn(t),this.resetFragmentLoading(e))})}_handleTransmuxComplete(e){let t=this.playlistType,{hls:i}=this,{remuxResult:r,chunkMeta:s}=e,a=this.getCurrentContext(s);if(!a)return void this.resetWhenMissingContext(s);let{frag:n,part:l,level:o}=a,{video:h,text:d,id3:c,initSegment:f}=r,{details:g}=o,m=this.altAudio?void 0:r.audio;if(this.fragContextChanged(n))return void this.fragmentTracker.removeFragment(n);if(this.state=ri,f){let e=f.tracks;if(e){let r=n.initSegment||n;if(this.unhandledEncryptionError(f,n))return;this._bufferInitSegment(o,e,r,s),i.trigger(K.FRAG_PARSING_INIT_SEGMENT,{frag:r,id:t,tracks:e})}let r=f.initPTS,a=f.timescale,l=this.initPTS[n.cc];if($(r)&&(!l||l.baseTime!==r||l.timescale!==a)){let e=f.trackId;this.initPTS[n.cc]={baseTime:r,timescale:a,trackId:e},i.trigger(K.INIT_PTS_FOUND,{frag:n,id:t,initPTS:r,timescale:a,trackId:e})}}if(h&&g){m&&"audiovideo"===h.type&&this.logMuxedErr(n);let e=g.fragments[n.sn-1-g.startSN],t=n.sn===g.startSN,i=!e||n.cc>e.cc;if(!1!==r.independent){let{startPTS:e,endPTS:r,startDTS:a,endDTS:o}=h;if(l)l.elementaryStreams[h.type]={startPTS:e,endPTS:r,startDTS:a,endDTS:o};else if(h.firstKeyFrame&&h.independent&&1===s.id&&!i&&(this.couldBacktrack=!0),h.dropped&&h.independent){let s=this.getMainFwdBufferInfo(),a=(s?s.end:this.getLoadPosition())+this.config.maxBufferHole,l=h.firstKeyFramePTS?h.firstKeyFramePTS:e;if(!t&&a<l-this.config.maxBufferHole&&!i)return void this.backtrack(n);i&&(n.gap=!0),n.setElementaryStreamInfo(h.type,n.start,r,n.start,o,!0)}else t&&e-(g.appliedTimelineOffset||0)>2&&(n.gap=!0);n.setElementaryStreamInfo(h.type,e,r,a,o),this.backtrackFragment&&(this.backtrackFragment=n),this.bufferFragmentData(h,n,l,s,t||i)}else{if(!t&&!i)return void this.backtrack(n);n.gap=!0}}if(m){let{startPTS:e,endPTS:t,startDTS:i,endDTS:r}=m;l&&(l.elementaryStreams[eR]={startPTS:e,endPTS:t,startDTS:i,endDTS:r}),n.setElementaryStreamInfo(eR,e,t,i,r),this.bufferFragmentData(m,n,l,s)}if(g&&null!=c&&c.samples.length){let e={id:t,frag:n,details:g,samples:c.samples};i.trigger(K.FRAG_PARSING_METADATA,e)}if(g&&d){let e={id:t,frag:n,details:g,samples:d.samples};i.trigger(K.FRAG_PARSING_USERDATA,e)}}logMuxedErr(e){this.warn(`${eD(e)?"Media":"Init"} segment with muxed audiovideo where only video expected: ${e.url}`)}_bufferInitSegment(e,t,i,r){if(this.state!==ri)return;this.audioOnly=!!t.audio&&!t.video,this.altAudio&&!this.audioOnly&&(delete t.audio,t.audiovideo&&this.logMuxedErr(i));let{audio:s,video:a,audiovideo:n}=t;if(s){let i=e.audioCodec,r=e6(s.codec,i);"mp4a"===r&&(r="mp4a.40.5");let a=navigator.userAgent.toLowerCase();if(this.audioCodecSwitch){r&&(r=-1!==r.indexOf("mp4a.40.5")?"mp4a.40.2":"mp4a.40.5");let e=s.metadata;e&&"channelCount"in e&&1!==(e.channelCount||1)&&-1===a.indexOf("firefox")&&(r="mp4a.40.5")}r&&-1!==r.indexOf("mp4a.40.5")&&-1!==a.indexOf("android")&&"audio/mpeg"!==s.container&&(r="mp4a.40.2",this.log(`Android: force audio codec to ${r}`)),i&&i!==r&&this.log(`Swapping manifest audio codec "${i}" for "${r}"`),s.levelCodec=r,s.id=q,this.log(`Init audio buffer, container:${s.container}, codecs[selected/level/parsed]=[${r||""}/${i||""}/${s.codec}]`),delete t.audiovideo}if(a){a.levelCodec=e.videoCodec,a.id=q;let i=a.codec;if(i?.length===4)switch(i){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"}this.log(`Init video buffer, container:${a.container}, codecs[level/parsed]=[${e.videoCodec||""}/${i}]${a.codec!==i?" parsed-corrected="+a.codec:""}${a.supplemental?" supplemental="+a.supplemental:""}`),delete t.audiovideo}n&&(this.log(`Init audiovideo buffer, container:${n.container}, codecs[level/parsed]=[${e.codecs}/${n.codec}]`),delete t.video,delete t.audio);let l=Object.keys(t);if(l.length){if(this.hls.trigger(K.BUFFER_CODECS,t),!this.hls)return;l.forEach(e=>{let s=t[e].initSegment;null!=s&&s.byteLength&&this.hls.trigger(K.BUFFER_APPENDING,{type:e,data:s,frag:i,part:null,chunkMeta:r,parent:i.type})})}this.tickImmediate()}getMainFwdBufferInfo(){let e=this.mediaBuffer&&2===this.altAudio?this.mediaBuffer:this.media;return this.getFwdBufferInfo(e,q)}get maxBufferLength(){let{levels:e,level:t}=this,i=e?.[t];return i?this.getMaxBufferLength(i.maxBitrate):this.config.maxBufferLength}backtrack(e){this.couldBacktrack=!0,this.backtrackFragment=e,this.resetTransmuxer(),this.flushBufferGap(e),this.fragmentTracker.removeFragment(e),this.fragPrevious=null,this.nextLoadPosition=e.start,this.state=i6}checkFragmentChanged(){let e=this.media,t=null;if(e&&e.readyState>1&&!1===e.seeking){let i=e.currentTime;if(tJ.isBuffered(e,i)?t=this.getAppendedFrag(i):tJ.isBuffered(e,i+.
831)&&(t=this.getAppendedFrag(i+.1)),t){this.backtrackFragment=null;let e=this.fragPlaying,i=t.level;(!e||t.sn!==e.sn||e.level!==i)&&(this.fragPlaying=t,this.hls.trigger(K.FRAG_CHANGED,{frag:t}),e&&e.level===i||this.hls.trigger(K.LEVEL_SWITCHED,{level:i}))}}}get nextLevel(){let e=this.nextBufferedFrag;return e?e.level:-1}get currentFrag(){var e;if(this.fragPlaying)return this.fragPlaying;let t=(null==(e=this.media)?void 0:e.currentTime)||this.lastCurrentTime;return $(t)?this.getAppendedFrag(t):null}get currentProgramDateTime(){var e;let t=(null==(e=this.media)?void 0:e.currentTime)||this.lastCurrentTime;if($(t)){let e=this.getLevelDetails(),i=this.currentFrag||(e?tL(null,e.fragments,t):null);if(i){let e=i.programDateTime;if(null!==e)return new Date(e+(t-i.start)*1e3)}}return null}get currentLevel(){let e=this.currentFrag;return e?e.level:-1}get nextBufferedFrag(){let e=this.currentFrag;return e?this.followingBufferedFrag(e):null}get forceStartLoad(){return this._forceStartLoad}}class nk extends et{constructor(e,t){super("key-loader",t),this.config=void 0,this.keyIdToKeyInfo={},this.emeController=null,this.config=e}abort(e){for(let i in this.keyIdToKeyInfo){let r=this.keyIdToKeyInfo[i].loader;if(r){var t;if(e&&e!==(null==(t=r.context)?void 0:t.frag.type))return;r.abort()}}}detach(){for(let e in this.keyIdToKeyInfo){let t=this.keyIdToKeyInfo[e];(t.mediaKeySessionContext||t.decryptdata.isCommonEncryption)&&delete this.keyIdToKeyInfo[e]}}destroy(){for(let e in this.detach(),this.keyIdToKeyInfo){let t=this.keyIdToKeyInfo[e].loader;t&&t.destroy()}this.keyIdToKeyInfo={}}createKeyLoadError(e,t=G.KEY_LOAD_ERROR,i,r,s){return new tY({type:N.NETWORK_ERROR,details:t,fatal:!1,frag:e,response:s,error:i,networkDetails:r})}loadClear(e,t,i){if(this.emeController&&this.config.emeEnabled&&!this.emeController.getSelectedKeySystemFormats().length){if(t.length)for(let r=0,s=t.length;r<s;r++){let a=t[r];if(e.cc<=a.cc&&(!eD(e)||!eD(a)||e.sn<a.sn)||!i&&r==s-1)return this.emeController.selectKeySystemFormat(a).then(e=>{if(!this.emeController)return;a.setKeyFormat(e);let t=iy(e);if(t)return this.emeController.getKeySystemAccess([t])})}if(this.config.requireKeySystemAccessOnStart){let e=iE(this.config);if(e.length)return this.emeController.getKeySystemAccess(e)}}return null}load(e){return!e.decryptdata&&e.encrypted&&this.emeController&&this.config.emeEnabled?this.emeController.selectKeySystemFormat(e).then(t=>this.loadInternal(e,t)):this.loadInternal(e)}loadInternal(e,t){var i,r;t&&e.setKeyFormat(t);let s=e.decryptdata;if(!s){let i=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,G.KEY_LOAD_ERROR,i))}let a=s.uri;if(!a)return Promise.reject(this.createKeyLoadError(e,G.KEY_LOAD_ERROR,Error(`Invalid key URI: "${a}"`)));let n=nI(s),l=this.keyIdToKeyInfo[n];if(null!=(i=l)&&i.decryptdata.key)return s.key=l.decryptdata.key,Promise.resolve({frag:e,keyInfo:l});if(this.emeController&&null!=(r=l)&&r.keyLoadPromise)switch(this.emeController.getKeyStatus(l.decryptdata)){case"usable":case"usable-in-future":return l.keyLoadPromise.then(t=>{let{keyInfo:i}=t;return s.key=i.decryptdata.key,{frag:e,keyInfo:i}})}switch(this.log(`${this.keyIdToKeyInfo[n]?"Rel":"L"}oading${s.keyId?" keyId: "+ed(s.keyId):""} URI: ${s.uri} from ${e.type} ${e.level}`),l=this.keyIdToKeyInfo[n]={decryptdata:s,keyLoadPromise:null,loader:null,mediaKeySessionContext:null},s.method){case"SAMPLE-AES":case"SAMPLE-AES-CENC":case"SAMPLE-AES-CTR":return"identity"===s.keyFormat?this.loadKeyHTTP(l,e):this.loadKeyEME(l,e);case"AES-128":case"AES-256":case"AES-256-CTR":return this.loadKeyHTTP(l,e);default:return Promise.reject(this.createKeyLoadError(e,G.KEY_LOAD_ERROR,Error(`Key supplied with unsupported METHOD: "${s.method}"`)))}}loadKeyEME(e,t){let i={frag:t,keyInfo:e};if(this.emeController&&this.config.emeEnabled){var r,s;if(!e.decryptdata.keyId&&null!=(r=t.initSegment)&&r.data){let i,r=(s=t.initSegment.data,i=[],eV(s,e=>i.push(e.subarray(8,24))),i);if(r.length){let t=r[0];t.some(e=>0!==e)?(this.log(`Using keyId found in init segment ${ed(t)}`),iA.setKeyIdForUri(e.decryptdata.uri,t)):(t=iA.addKeyIdForUri(e.decryptdata.uri),this.log(`Generating keyId to patch media ${ed(t)}`)),e.decryptdata.keyId=t}}return e.decryptdata.keyId||eD(t)?(e.keyLoadPromise=this.emeController.loadKey(i).then(t=>(e.mediaKeySessionContext=t,i))).catch(i=>{throw e.keyLoadPromise=null,"data"in i&&(i.data.frag=t),i}):Promise.resolve(i)}return Promise.resolve(i)}loadKeyHTTP(e,t){let i=this.config,r=new i.loader(i);return t.keyLoader=e.loader=r,e.keyLoadPromise=new Promise((s,a)=>{let n={keyInfo:e,frag:t,responseType:"arraybuffer",url:e.decryptdata.uri},l=i.keyLoadPolicy.default,o={loadPolicy:l,timeout:l.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0};r.load(n,o,{onSuccess:(e,t,i,r)=>{let{frag:n,keyInfo:l}=i,o=nI(l.decryptdata);if(!n.decryptdata||l!==this.keyIdToKeyInfo[o])return a(this.createKeyLoadError(n,G.KEY_LOAD_ERROR,Error("after key load, decryptdata unset or changed"),r));l.decryptdata.key=n.decryptdata.key=new Uint8Array(e.data),n.keyLoader=null,l.loader=null,s({frag:n,keyInfo:l})},onError:(e,i,r,s)=>{this.resetLoader(i),a(this.createKeyLoadError(t,G.KEY_LOAD_ERROR,Error(`HTTP Error ${e.code} loading key ${e.text}`),r,ee({url:n.url,data:void 0},e)))},onTimeout:(e,i,r)=>{this.resetLoader(i),a(this.createKeyLoadError(t,G.KEY_LOAD_TIMEOUT,Error("key loading timed out"),r))},onAbort:(e,i,r)=>{this.resetLoader(i),a(this.createKeyLoadError(t,G.INTERNAL_ABORTED,Error("key loading aborted"),r))}})})}
83resetLoader(e){let{frag:t,keyInfo:i,url:r}=e,s=i.loader;t.keyLoader===s&&(t.keyLoader=null,i.loader=null);let a=nI(i.decryptdata)||r;delete this.keyIdToKeyInfo[a],s&&s.destroy()}}function nI(e){if(e.keyFormat!==ig){let t=e.keyId;if(t)return ed(t)}return e.uri}function nD(e){let{type:t}=e;switch(t){case j:return Y;case W:return X;default:return q}}function n_(e,t){let i=e.url;return(void 0===i||0===i.indexOf("data:"))&&(i=t.url),i}class nP{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(){let{hls:e}=this;e.on(K.MANIFEST_LOADING,this.onManifestLoading,this),e.on(K.LEVEL_LOADING,this.onLevelLoading,this),e.on(K.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.on(K.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),e.on(K.LEVELS_UPDATED,this.onLevelsUpdated,this)}unregisterListeners(){let{hls:e}=this;e.off(K.MANIFEST_LOADING,this.onManifestLoading,this),e.off(K.LEVEL_LOADING,this.onLevelLoading,this),e.off(K.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.off(K.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),e.off(K.LEVELS_UPDATED,this.onLevelsUpdated,this)}createInternalLoader(e){let t=this.hls.config,i=t.pLoader,r=t.loader,s=new(i||r)(t);return this.loaders[e.type]=s,s}getInternalLoader(e){return this.loaders[e.type]}resetInternalLoader(e){this.loaders[e]&&delete this.loaders[e]}destroyInternalLoaders(){for(let e in this.loaders){let t=this.loaders[e];t&&t.destroy(),this.resetInternalLoader(e)}}destroy(){this.variableList=null,this.unregisterListeners(),this.destroyInternalLoaders()}onManifestLoading(e,t){let{url:i}=t;this.variableList=null,this.load({id:null,level:0,responseType:"text",type:H,url:i,deliveryDirectives:null,levelOrTrack:null})}onLevelLoading(e,t){let{id:i,level:r,pathwayId:s,url:a,deliveryDirectives:n,levelInfo:l}=t;this.load({id:i,level:r,pathwayId:s,responseType:"text",type:V,url:a,deliveryDirectives:n,levelOrTrack:l})}onAudioTrackLoading(e,t){let{id:i,groupId:r,url:s,deliveryDirectives:a,track:n}=t;this.load({id:i,groupId:r,level:null,responseType:"text",type:j,url:s,deliveryDirectives:a,levelOrTrack:n})}onSubtitleTrackLoading(e,t){let{id:i,groupId:r,url:s,deliveryDirectives:a,track:n}=t;this.load({id:i,groupId:r,level:null,responseType:"text",type:W,url:s,deliveryDirectives:a,levelOrTrack:n})}onLevelsUpdated(e,t){let i=this.loaders[V];if(i){let e=i.context;e&&!t.levels.some(t=>t===e.levelOrTrack)&&(i.abort(),delete this.loaders[V])}}load(e){var t;let i,r=this.hls.config,s=this.getInternalLoader(e);if(s){let t=this.hls.logger,i=s.context;if(i&&i.levelOrTrack===e.levelOrTrack&&(i.url===e.url||i.deliveryDirectives&&!e.deliveryDirectives))return void(i.url===e.url?t.log(`[playlist-loader]: ignore ${e.url} ongoing request`):t.log(`[playlist-loader]: ignore ${e.url} in favor of ${i.url}`));t.log(`[playlist-loader]: aborting previous loader for type: ${e.type}`),s.abort()}if(i=e.type===H?r.manifestLoadPolicy.default:Z({},r.playlistLoadPolicy.default,{timeoutRetry:null,errorRetry:null}),s=this.createInternalLoader(e),$(null==(t=e.deliveryDirectives)?void 0:t.part)){let t;if(e.type===V&&null!==e.level?t=this.hls.levels[e.level].details:e.type===j&&null!==e.id?t=this.hls.audioTracks[e.id].details:e.type===W&&null!==e.id&&(t=this.hls.subtitleTracks[e.id].details),t){let e=t.partTarget,r=t.targetduration;if(e&&r){let t=1e3*Math.max(3*e,.8*r);i=Z({},i,{maxTimeToFirstByteMs:Math.min(t,i.maxTimeToFirstByteMs),maxLoadTimeMs:Math.min(t,i.maxTimeToFirstByteMs)})}}}let a=i.errorRetry||i.timeoutRetry||{},n={loadPolicy:i,timeout:i.maxLoadTimeMs,maxRetry:a.maxNumRetry||0,retryDelay:a.retryDelayMs||0,maxRetryDelay:a.maxRetryDelayMs||0};s.load(e,n,{onSuccess:(e,t,i,r)=>{let s=this.getInternalLoader(i);this.resetInternalLoader(i.type);let a=e.data;t.parsing.start=performance.now(),iP.isMediaPlaylist(a)||i.type!==H?this.handleTrackOrLevelPlaylist(e,t,i,r||null,s):this.handleMasterPlaylist(e,t,i,r)},onError:(e,t,i,r)=>{this.handleNetworkError(t,i,!1,e,r)},onTimeout:(e,t,i)=>{this.handleNetworkError(t,i,!0,void 0,e)}})}
83checkAutostartLoad(){if(!this.hls)return;let{config:{autoStartLoad:e,startPosition:t},forceStartLoad:i}=this.hls;(e||i)&&(this.hls.logger.log(`${e?"auto":"force"} startLoad with configured startPosition ${t}`),this.hls.startLoad(t))}handleMasterPlaylist(e,t,i,r){let s=this.hls,a=e.data,n=n_(e,i),l=iP.parseMasterPlaylist(a,n);if(l.playlistParsingError){t.parsing.end=performance.now(),this.handleManifestParsingError(e,i,l.playlistParsingError,r,t);return}let{contentSteering:o,levels:h,sessionData:d,sessionKeys:c,startTimeOffset:f,variableList:g}=l;this.variableList=g,h.forEach(e=>{let{unknownCodecs:t}=e;if(t){let{preferManagedMediaSource:i}=this.hls.config,{audioCodec:r,videoCodec:s}=e;for(let a=t.length;a--;){let n=t[a];eJ(n,"audio",i)?(e.audioCodec=r=r?`${r},${n}`:n,eQ.audio[r.substring(0,4)]=2,t.splice(a,1)):eJ(n,"video",i)&&(e.videoCodec=s=s?`${s},${n}`:n,eQ.video[s.substring(0,4)]=2,t.splice(a,1))}}});let{AUDIO:m=[],SUBTITLES:p,"CLOSED-CAPTIONS":y}=iP.parseMasterPlaylistMedia(a,n,l);m.length&&!m.some(e=>!e.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"),m.unshift({type:"main",name:"main",groupId:"main",default:!1,autoselect:!1,forced:!1,id:-1,attrs:new t5({}),bitrate:0,url:""})),s.trigger(K.MANIFEST_LOADED,{levels:h,audioTracks:m,subtitles:p,captions:y,contentSteering:o,url:n,stats:t,networkDetails:r,sessionData:d,sessionKeys:c,startTimeOffset:f,variableList:g})}handleTrackOrLevelPlaylist(e,t,i,r,s){let a=this.hls,{id:n,level:l,type:o}=i,h=n_(e,i),d=$(l)?l:$(n)?n:0,c=nD(i),f=iP.parseLevelPlaylist(e.data,h,d,c,0,this.variableList);if(o===H){let e={attrs:new t5({}),bitrate:0,details:f,name:"",url:h};f.requestScheduled=t.loading.start+iW(f,0),a.trigger(K.MANIFEST_LOADED,{levels:[e],audioTracks:[],url:h,stats:t,networkDetails:r,sessionData:null,sessionKeys:null,contentSteering:null,startTimeOffset:null,variableList:null})}t.parsing.end=performance.now(),i.levelDetails=f,this.handlePlaylistLoaded(f,e,t,i,r,s)}handleManifestParsingError(e,t,i,r,s){this.hls.trigger(K.ERROR,{type:N.NETWORK_ERROR,details:G.MANIFEST_PARSING_ERROR,fatal:t.type===H,url:e.url,err:i,error:i,reason:i.message,response:e,context:t,networkDetails:r,stats:s})}handleNetworkError(e,t,i=!1,r,s){let a=`A network ${i?"timeout":"error"+(r?" (status "+r.code+")":"")} occurred while loading ${e.type}`;e.type===V?a+=`: ${e.level} id: ${e.id}`:(e.type===j||e.type===W)&&(a+=` id: ${e.id} group-id: "${e.groupId}"`);let n=Error(a);this.hls.logger.warn(`[playlist-loader]: ${a}`);let l=G.UNKNOWN,o=!1,h=this.getInternalLoader(e);switch(e.type){case H:l=i?G.MANIFEST_LOAD_TIMEOUT:G.MANIFEST_LOAD_ERROR,o=!0;break;case V:l=i?G.LEVEL_LOAD_TIMEOUT:G.LEVEL_LOAD_ERROR,o=!1;break;case j:l=i?G.AUDIO_TRACK_LOAD_TIMEOUT:G.AUDIO_TRACK_LOAD_ERROR,o=!1;break;case W:l=i?G.SUBTITLE_TRACK_LOAD_TIMEOUT:G.SUBTITLE_LOAD_ERROR,o=!1}h&&this.resetInternalLoader(e.type);let d={type:N.NETWORK_ERROR,details:l,fatal:o,url:e.url,loader:h,context:e,error:n,networkDetails:t,stats:s};r&&(d.response=ee({url:t?.url||e.url,data:void 0},r)),this.hls.trigger(K.ERROR,d)}handlePlaylistLoaded(e,t,i,r,s,a){let n=this.hls,{type:l,level:o,levelOrTrack:h,id:d,groupId:c,deliveryDirectives:f}=r,g=n_(t,r),m=nD(r),p="number"==typeof r.level&&m===q?o:void 0,y=e.playlistParsingError;if(y){if(this.hls.logger.warn(`${y} ${e.url}`),!n.config.ignorePlaylistParsingErrors)return void n.trigger(K.ERROR,{type:N.NETWORK_ERROR,details:G.LEVEL_PARSING_ERROR,fatal:!1,url:g,error:y,reason:y.message,response:t,context:r,level:p,parent:m,networkDetails:s,stats:i});e.playlistParsingError=null}if(!e.fragments.length){let a=e.playlistParsingError=Error("No Segments found in Playlist");n.trigger(K.ERROR,{type:N.NETWORK_ERROR,details:G.LEVEL_EMPTY_ERROR,fatal:!1,url:g,error:a,reason:a.message,response:t,context:r,level:p,parent:m,networkDetails:s,stats:i});return}switch(e.live&&a&&(a.getCacheAge&&(e.ageHeader=a.getCacheAge()||0),(!a.getCacheAge||isNaN(e.ageHeader))&&(e.ageHeader=0)),l){case H:case V:if(p)if(h){if(h!==n.levels[p]){let e=n.levels.indexOf(h);e>-1&&(p=e)}}else p=0;n.trigger(K.LEVEL_LOADED,{details:e,levelInfo:h||n.levels[0],level:p||0,id:d||0,stats:i,networkDetails:s,deliveryDirectives:f,withoutMultiVariant:l===H});break;case j:n.trigger(K.AUDIO_TRACK_LOADED,{details:e,track:h,id:d||0,groupId:c||"",stats:i,networkDetails:s,deliveryDirectives:f});break;case W:n.trigger(K.SUBTITLE_TRACK_LOADED,{details:e,track:h,id:d||0,groupId:c||"",stats:i,networkDetails:s,deliveryDirectives:f})}}}class nC{static get version(){return rm}static isMSESupported(){return nR()}static isSupported(){if(!nR())return!1;let e=el();
83return"function"==typeof e?.isTypeSupported&&(["avc1.42E01E,mp4a.40.2","av01.0.01M.08","vp09.00.50.08"].some(t=>e.isTypeSupported(e1(t,"video")))||["mp4a.40.2","fLaC"].some(t=>e.isTypeSupported(e1(t,"audio"))))}static getMediaSource(){return el()}static get Events(){return K}static get MetadataSchema(){return rC}static get ErrorTypes(){return N}static get ErrorDetails(){return G}static get DefaultConfig(){return nC.defaultConfig?nC.defaultConfig:nu}static set DefaultConfig(e){nC.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 rg,this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.abrController=void 0,this.bufferController=void 0,this.capLevelController=void 0,this.latencyController=void 0,this.levelController=void 0,this.streamController=void 0,this.audioStreamController=void 0,this.subtititleStreamController=void 0,this.audioTrackController=void 0,this.subtitleTrackController=void 0,this.interstitialsController=void 0,this.gapController=void 0,this.emeController=void 0,this.cmcdController=void 0,this._media=null,this._url=null,this._sessionId=void 0,this.triggeringException=void 0,this.started=!1;const t=this.logger=function(e,t,i){let r=es();if("object"==typeof console&&!0===e||"object"==typeof e){let s=["debug","log","info","warn","error"];s.forEach(t=>{r[t]=ea(t,e,i)});try{r.log(`Debug logs enabled for "${t}" in hls.js version 1.6.16`)}catch{return es()}s.forEach(t=>{en[t]=ea(t,e)})}else Z(en,r);return r}(e.debug||!1,"Hls instance",e.assetPlayerId),i=this.config=function(e,t,i){if((t.liveSyncDurationCount||t.liveMaxLatencyDurationCount)&&(t.liveSyncDuration||t.liveMaxLatencyDuration))throw Error("Illegal hls.js config: don't mix up liveSyncDurationCount/liveMaxLatencyDurationCount and liveSyncDuration/liveMaxLatencyDuration");if(void 0!==t.liveMaxLatencyDurationCount&&(void 0===t.liveSyncDurationCount||t.liveMaxLatencyDurationCount<=t.liveSyncDurationCount))throw Error('Illegal hls.js config: "liveMaxLatencyDurationCount" must be greater than "liveSyncDurationCount"');if(void 0!==t.liveMaxLatencyDuration&&(void 0===t.liveSyncDuration||t.liveMaxLatencyDuration<=t.liveSyncDuration))throw Error('Illegal hls.js config: "liveMaxLatencyDuration" must be greater than "liveSyncDuration"');let r=function e(t){return t&&"object"==typeof t?Array.isArray(t)?t.map(e):Object.keys(t).reduce((i,r)=>(i[r]=e(t[r]),i),{}):t}(e),s=["TimeOut","MaxRetry","RetryDelay","MaxRetryTimeout"];return["manifest","level","frag"].forEach(e=>{let a=`${"level"===e?"playlist":e}LoadPolicy`,n=void 0===t[a],l=[];s.forEach(i=>{let s=`${e}Loading${i}`,o=t[s];if(void 0!==o&&n){l.push(s);let e=r[a].default;switch(t[a]={default:e},i){case"TimeOut":e.maxLoadTimeMs=o,e.maxTimeToFirstByteMs=o;break;case"MaxRetry":e.errorRetry.maxNumRetry=o,e.timeoutRetry.maxNumRetry=o;break;case"RetryDelay":e.errorRetry.retryDelayMs=o,e.timeoutRetry.retryDelayMs=o;break;case"MaxRetryTimeout":e.errorRetry.maxRetryDelayMs=o,e.timeoutRetry.maxRetryDelayMs=o}}}),l.length&&i.warn(`hls.js config: "${l.join('", "')}" setting(s) are deprecated, use "${a}": ${tc(t[a])}`)}),ee(ee({},r),t)}(nC.DefaultConfig,e,t);this.userConfig=e,i.progressive&&function(e,t){let i=e.loader;i!==nn&&i!==nd?(t.log("[config]: Custom loader detected, cannot enable progressive streaming"),e.progressive=!1):function(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch{}return!1}()&&(e.loader=nn,e.progressive=!0,e.enableSoftwareAES=!0,t.log("[config]: Progressive streaming enabled, using FetchLoader"))}(i,t);const{abrController:r,bufferController:s,capLevelController:a,errorController:n,fpsController:l}=i,o=new n(this),h=this.abrController=new r(this),d=new t$(this),c=i.interstitialsController,f=c?this.interstitialsController=new c(this,nC):null,g=this.bufferController=new s(this,d),m=this.capLevelController=new a(this),p=new l(this),y=new nP(this),v=i.contentSteeringController,E=v?new v(this):null,T=this.levelController=new nS(this,E),S=new nE(this),L=new nk(this.config,this.logger),A=this.streamController=new nb(this,d,L),R=this.gapController=new nc(this,d);
vendor: 4,098 bytes, line 83
83m.setStreamController(A),p.setStreamController(A);const b=[y,T,A];f&&b.splice(1,0,f),E&&b.splice(1,0,E),this.networkControllers=b;const k=[h,g,R,m,p,S,d];this.audioTrackController=this.createController(i.audioTrackController,b);const I=i.audioStreamController;I&&b.push(this.audioStreamController=new I(this,d,L)),this.subtitleTrackController=this.createController(i.subtitleTrackController,b);const D=i.subtitleStreamController;D&&b.push(this.subtititleStreamController=new D(this,d,L)),this.createController(i.timelineController,k),L.emeController=this.emeController=this.createController(i.emeController,k),this.cmcdController=this.createController(i.cmcdController,k),this.latencyController=this.createController(nT,k),this.coreComponents=k,b.push(o);const _=o.onErrorOut;"function"==typeof _&&this.on(K.ERROR,_,o),this.on(K.MANIFEST_LOADED,y.onManifestLoaded,y)}createController(e,t){if(e){let i=new e(this);return t&&t.push(i),i}return null}on(e,t,i=this){this._emitter.on(e,t,i)}once(e,t,i=this){this._emitter.once(e,t,i)}removeAllListeners(e){this._emitter.removeAllListeners(e)}off(e,t,i=this,r){this._emitter.off(e,t,i,r)}listeners(e){return this._emitter.listeners(e)}emit(e,t,i){return this._emitter.emit(e,t,i)}trigger(e,t){if(this.config.debug)return this.emit(e,e,t);try{return this.emit(e,e,t)}catch(t){if(this.logger.error("An internal error happened while handling event "+e+'. Error message: "'+t.message+'". Here is a stacktrace:',t),!this.triggeringException){this.triggeringException=!0;let i=e===K.ERROR;this.trigger(K.ERROR,{type:N.OTHER_ERROR,details:G.INTERNAL_EXCEPTION,fatal:i,event:e,error:t}),this.triggeringException=!1}}return!1}listenerCount(e){return this._emitter.listenerCount(e)}destroy(){this.logger.log("destroy"),this.trigger(K.DESTROYING,void 0),this.detachMedia(),this.removeAllListeners(),this._autoLevelCapping=-1,this._url=null,this.networkControllers.forEach(e=>e.destroy()),this.networkControllers.length=0,this.coreComponents.forEach(e=>e.destroy()),this.coreComponents.length=0;let e=this.config;e.xhrSetup=e.fetchSetup=void 0,this.userConfig=null}attachMedia(e){if(!e||"media"in e&&!e.media){let t=Error(`attachMedia failed: invalid argument (${e})`);this.trigger(K.ERROR,{type:N.OTHER_ERROR,details:G.ATTACH_MEDIA_ERROR,fatal:!0,error:t});return}this.logger.log("attachMedia"),this._media&&(this.logger.warn("media must be detached before attaching"),this.detachMedia());let t="media"in e,i=t?e.media:e,r=t?e:{media:i};this._media=i,this.trigger(K.MEDIA_ATTACHING,r)}detachMedia(){this.logger.log("detachMedia"),this.trigger(K.MEDIA_DETACHING,{}),this._media=null}transferMedia(){this._media=null;let e=this.bufferController.transferMedia();return this.trigger(K.MEDIA_DETACHING,{transferMedia:e}),e}loadSource(e){this.stopLoad();let t=this.media,i=this._url,r=this._url=eL.buildAbsoluteURL(self.location.href,e,{alwaysNormalize:!0});this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.logger.log(`loadSource:${r}`),t&&i&&(i!==r||this.bufferController.hasSourceTypes())&&(this.detachMedia(),this.attachMedia(t)),this.trigger(K.MANIFEST_LOADING,{url:e})}get url(){return this._url}get hasEnoughToStart(){return this.streamController.hasEnoughToStart}get startPosition(){return this.streamController.startPositionValue}startLoad(e=-1,t){this.logger.log(`startLoad(${e+(t?", <skip seek to start>":"")})`),this.started=!0,this.resumeBuffering();for(let i=0;i<this.networkControllers.length&&(this.networkControllers[i].startLoad(e,t),!(!this.started||!this.networkControllers));i++);}stopLoad(){this.logger.log("stopLoad"),this.started=!1;for(let e=0;e<this.networkControllers.length&&(this.networkControllers[e].stopLoad(),!(this.started||!this.networkControllers));e++);}get loadingEnabled(){return this.started}get bufferingEnabled(){return this.streamController.bufferingEnabled}resumeBuffering(){this.bufferingEnabled||(this.logger.log("resume buffering"),this.networkControllers.forEach(e=>{e.resumeBuffering&&e.resumeBuffering()}))}pauseBuffering(){this.bufferingEnabled&&(this.logger.log("pause buffering"),this.networkControllers.forEach(e
83=>{e.pauseBuffering&&e.pauseBuffering()}))}get inFlightFragments(){let e={[q]:this.streamController.inFlightFrag};return this.audioStreamController&&(e[Y]=this.audioStreamController.inFlightFrag),this.subtititleStreamController&&(e[X]=this.subtititleStreamController.inFlightFrag),e}swapAudioCodec(){this.logger.log("swapAudioCodec"),this.streamController.swapAudioCodec()}recoverMediaError(){this.logger.log("recoverMediaError");let e=this._media,t=e?.currentTime;this.detachMedia(),e&&(this.attachMedia(e),t&&this.startLoad(t))}removeLevel(e){this.levelController.removeLevel(e)}get sessionId(){let e=this._sessionId;return e||(e=this._sessionId=function(){try{return crypto.randomUUID()}catch{try{let e=URL.createObjectURL(new Blob),t=e.toString();return URL.revokeObjectURL(e),t.slice(t.lastIndexOf("/")+1)}catch{let e=new Date().getTime();return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,t=>{let i=(e+16*Math.random())%16|0;return e=Math.floor(e/16),("x"==t?i:3&i|8).toString(16)})}}}()),e}get levels(){return this.levelController.levels||[]}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(){let e=this.levelController.startLevel;return -1===e&&this.abrController.forcedAutoLevel>-1?this.abrController.forcedAutoLevel:e}set startLevel(e){this.logger.log(`set startLevel:${e}`),-1!==e&&(e=Math.max(e,this.minAutoLevel)),this.levelController.startLevel=e}get capLevelToPlayerSize(){return this.config.capLevelToPlayerSize}set capLevelToPlayerSize(e){let 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(){let{bwEstimator:e}=this.abrController;return e?e.getEstimate():NaN}set bandwidthEstimate(e){this.abrController.resetEstimator(e)}get abrEwmaDefaultEstimate(){let{bwEstimator:e}=this.abrController;return e?e.defaultEstimate:NaN}get ttfbEstimate(){let{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){tn.indexOf(e)>-1&&this._maxHdcpLevel!==e&&(this._maxHdcpLevel=e,this.levelController.checkMaxAutoUpdated())}get autoLevelEnabled(){return -1===this.levelController.manualLevel}get manualLevel(){return this.levelController.manualLevel}get minAutoLevel(){let{levels:e,config:{minAutoBitrate:t}}=this;if(!e)return 0;let i=e.length;for(let r=0;r<i;r++)if(e[r].maxBitrate>=t)return r;return 0}get maxAutoLevel(){let e,{levels:t,autoLevelCapping:i,maxHdcpLevel:r}=this;if(e=-1===i&&null!=t&&t.length?t.length-1:i,r)for(let i=e;i--;){let e=t[i].attrs["HDCP-LEVEL"];if(e&&e<=r)return i}return e}get firstAutoLevel(){return this.abrController.firstAutoLevel}get nextAutoLevel(){return this.abrController.nextAutoLevel}set nextAutoLevel(e){this.abrController.nextAutoLevel=e}get playingDate(){return this.streamController.currentProgramDateTime}get mainForwardBufferInfo(){return this.streamController.getMainFwdBufferInfo()}get maxBufferLength(){return this.streamController.maxBufferLength}setAudioOption(e){var t;return(null==(t=this.audioTrackController)?void 0:t.setAudioOption(e))||null}
83setSubtitleOption(e){var t;return(null==(t=this.subtitleTrackController)?void 0:t.setSubtitleOption(e))||null}get allAudioTracks(){let e=this.audioTrackController;return e?e.allAudioTracks:[]}get audioTracks(){let e=this.audioTrackController;return e?e.audioTracks:[]}get audioTrack(){let e=this.audioTrackController;return e?e.audioTrack:-1}set audioTrack(e){let t=this.audioTrackController;t&&(t.audioTrack=e)}get allSubtitleTracks(){let e=this.subtitleTrackController;return e?e.allSubtitleTracks:[]}get subtitleTracks(){let e=this.subtitleTrackController;return e?e.subtitleTracks:[]}get subtitleTrack(){let e=this.subtitleTrackController;return e?e.subtitleTrack:-1}get media(){return this._media}set subtitleTrack(e){let t=this.subtitleTrackController;t&&(t.subtitleTrack=e)}get subtitleDisplay(){let e=this.subtitleTrackController;return!!e&&e.subtitleDisplay}set subtitleDisplay(e){let t=this.subtitleTrackController;t&&(t.subtitleDisplay=e)}get lowLatencyMode(){return this.config.lowLatencyMode}set lowLatencyMode(e){this.config.lowLatencyMode=e}get liveSyncPosition(){return this.latencyController.liveSyncPosition}get latency(){return this.latencyController.latency}get maxLatency(){return this.latencyController.maxLatency}get targetLatency(){return this.latencyController.targetLatency}set targetLatency(e){this.latencyController.targetLatency=e}get drift(){return this.latencyController.drift}get forceStartLoad(){return this.streamController.forceStartLoad}get pathways(){return this.levelController.pathways}get pathwayPriority(){return this.levelController.pathwayPriority}set pathwayPriority(e){this.levelController.pathwayPriority=e}get bufferedToEnd(){var e;return!!(null!=(e=this.bufferController)&&e.bufferedToEnd)}get interstitialsManager(){var e;return(null==(e=this.interstitialsController)?void 0:e.interstitialsManager)||null}getMediaDecodingInfo(e,t=this.allAudioTracks){return ts(e,tg(t),navigator.mediaCapabilities)}}nC.defaultConfig=void 0;let nw=(i=function(e){if(!e?.prototype)return e;let t=F(e,"video");(!t||`${t}`.includes("[native code]"))&&Object.defineProperty(e.prototype,"videoTracks",{get(){var e=this;let t=v(e).videoTracks;if(!t&&(t=new S,v(e).videoTracks=t,M)){let i=M.call(e.nativeEl??e);for(let t of i)E(e,t);i.addEventListener("change",()=>{t.dispatchEvent(new Event("change"))}),i.addEventListener("addtrack",r=>{if([...t].some(e=>e instanceof k)){for(let e of i)T(e);return}E(e,r.track)}),i.addEventListener("removetrack",e=>{T(e.track)})}return t}});let i=F(e,"audio");(!i||`${i}`.includes("[native code]"))&&Object.defineProperty(e.prototype,"audioTracks",{get(){var e=this;let t=v(e).audioTracks;
83if(!t&&(t=new w,v(e).audioTracks=t,O)){let i=O.call(e.nativeEl??e);for(let t of i)P(e,t);i.addEventListener("change",()=>{t.dispatchEvent(new Event("change"))}),i.addEventListener("addtrack",r=>{if([...t].some(e=>e instanceof x)){for(let e of i)C(e);return}P(e,r.track)}),i.addEventListener("removetrack",e=>{C(e.track)})}return t}}),"addVideoTrack"in e.prototype||(e.prototype.addVideoTrack=function(e,t="",i=""){let r=new k;return r.kind=e,r.label=t,r.language=i,E(this,r),r}),"removeVideoTrack"in e.prototype||(e.prototype.removeVideoTrack=T),"addAudioTrack"in e.prototype||(e.prototype.addAudioTrack=function(e,t="",i=""){let r=new x;return r.kind=e,r.label=t,r.language=i,P(this,r),r}),"removeAudioTrack"in e.prototype||(e.prototype.removeAudioTrack=C),"videoRenditions"in e.prototype||Object.defineProperty(e.prototype,"videoRenditions",{get(){return r(this)}});let r=e=>{let t=v(e).videoRenditions;return t||(v(t=new R).media=new WeakRef(e),v(e).videoRenditions=t),t};"audioRenditions"in e.prototype||Object.defineProperty(e.prototype,"audioRenditions",{get(){return s(this)}});let s=e=>{let t=v(e).audioRenditions;return t||(v(t=new D).media=new WeakRef(e),v(e).audioRenditions=t),t};return e}(m),class extends i{static shadowRootOptions={...i.shadowRootOptions};static getTemplateHTML=(e,t={})=>{let{src:r,...s}=e;return`
84        <script type="application/json" id="config">
85          ${JSON.stringify(t.config||{})}
86        </script>
87        ${i.getTemplateHTML(s)}
88      `};#l=null;#i=null;constructor(){super(),this.#h("config")}get config(){return this.#i}set config(e){this.#i=e}attributeChangedCallback(e,t,i){"src"!==e&&super.attributeChangedCallback(e,t,i),"src"===e&&t!=i&&this.load()}#n(){var e,t;null==(e=this.#l)||e.remove(),null==(t=this.nativeEl)||t.removeEventListener("webkitcurrentplaybacktargetiswirelesschanged",this.#a),this.api&&(this.api.detachMedia(),this.api.destroy(),this.api=null)}async load(){var e,t;let i=!this.api;if(this.#n(),this.src){if(i&&!this.#i&&(this.#i=JSON.parse((null==(e=this.shadowRoot.getElementById("config"))?void 0:e.textContent)||"{}")),nC.isSupported()){switch(await Promise.resolve(),this.api=new nC({liveDurationInfinity:!0,autoStartLoad:!1,...this.config}),this.api.loadSource(this.src),this.api.attachMedia(this.nativeEl),this.nativeEl.preload){case"none":{let e=()=>this.api.startLoad();this.nativeEl.addEventListener("play",e,{once:!0}),this.api.on(nC.Events.DESTROYING,()=>{this.nativeEl.removeEventListener("play",e)});break}case"metadata":{let e=this.api.config.maxBufferLength,t=this.api.config.maxBufferSize;this.api.config.maxBufferLength=1,this.api.config.maxBufferSize=1;let i=()=>{this.api.config.maxBufferLength=e,this.api.config.maxBufferSize=t};this.nativeEl.addEventListener("play",i,{once:!0}),this.api.on(nC.Events.DESTROYING,()=>{this.nativeEl.removeEventListener("play",i)}),this.api.startLoad();break}default:this.api.startLoad()}this.nativeEl.webkitCurrentPlaybackTargetIsWireless&&this.api.stopLoad(),this.nativeEl.addEventListener("webkitcurrentplaybacktargetiswirelesschanged",this.#a),this.#l=document.createElement("source"),this.#l.setAttribute("type","application/x-mpegURL"),this.#l.setAttribute("src",this.src),this.nativeEl.disableRemotePlayback=!1,this.nativeEl.append(this.#l);let e=new WeakMap;this.api.on(nC.Events.MANIFEST_PARSED,(t,i)=>{this.nativeEl.autoplay&&this.nativeEl.paused&&this.nativeEl.play().catch(e=>{console.warn("Autoplay failed:",e)}),s();let r=this.videoTracks.getTrackById("main");for(let[t,s]of(r||((r=this.addVideoTrack("main")).id="main",r.selected=!0),i.levels.entries())){let i=r.addRendition(s.url[0],s.width,s.height,s.videoCodec,s.bitrate);e.set(s,`${t}`),i.id=`${t}`}for(let[e,t]of i.audioTracks.entries()){let i=t.default?"main":"alternative",r=this.addAudioTrack(i,t.name,t.lang);r.id=`${e}`,t.default&&(r.enabled=!0)}}),this.audioTracks.addEventListener("change",()=>{var e;let t=+(null==(e=[...this.audioTracks].find(e=>e.enabled))?void 0:e.id),i=this.api.audioTracks.map(e=>e.id);t!=this.api.audioTrack&&i.includes(t)&&(this.api.audioTrack=t)}),this.api.on(nC.Events.LEVELS_UPDATED,(t,i)=>{let r=this.videoTracks[this.videoTracks.selectedIndex??0];if(!r)return;let s=i.levels.map(t=>e.get(t));for(let e of this.videoRenditions)e.id&&!s.includes(e.id)&&r.removeRendition(e)});let i=null;this.api.on(nC.Events.ERROR,(e,t)=>
88{t.type===nC.ErrorTypes.NETWORK_ERROR&&t.details===nC.ErrorDetails.FRAG_LOAD_ERROR&&(i=t.frag.level)}),this.api.on(nC.Events.LEVEL_SWITCHED,(e,t)=>{let r=t.level;null!==i&&r<i&&(console.warn(`⚠️ hls.js downgraded quality from level ${i} to ${r} due to fragment load failure.`),this.videoRenditions.selectedIndex=r,i=null)});let r=e=>{let t=e.target.selectedIndex;t!=this.api.nextLevel&&(this.api.nextLevel=t)};null==(t=this.videoRenditions)||t.addEventListener("change",r);let s=()=>{for(let e of this.videoTracks)this.removeVideoTrack(e);for(let e of this.audioTracks)this.removeAudioTrack(e)};this.api.once(nC.Events.DESTROYING,s);return}await Promise.resolve(),this.nativeEl.canPlayType("application/vnd.apple.mpegurl")&&(this.nativeEl.src=this.src)}}#a=()=>{var e,t,i;null!=(e=this.nativeEl)&&e.webkitCurrentPlaybackTargetIsWireless?null==(t=this.api)||t.stopLoad():null==(i=this.api)||i.startLoad()};#h(e){if(Object.prototype.hasOwnProperty.call(this,e)){let t=this[e];delete this[e],this[e]=t}}});globalThis.customElements&&!globalThis.customElements.get("hls-video")&&globalThis.customElements.define("hls-video",nw);var nx=new Set(["style","children","ref","key","suppressContentEditableWarning","suppressHydrationWarning","dangerouslySetInnerHTML"]),nM={className:"class",htmlFor:"for"};function nO(e){return e.toLowerCase()}function nF(e){return"boolean"==typeof e?e?"":void 0:"function"!=typeof e&&("object"!=typeof e||null===e)?e:void 0}function n$(e,t,i){var r;e[t]=i,null==i&&t in((null==(r=globalThis.HTMLElement)?void 0:r.prototype)??{})&&e.removeAttribute(t)}var nB=function({react:e,tagName:t,elementClass:i,events:r,displayName:s,defaultProps:a,toAttributeName:n=nO,toAttributeValue:l=nF}){let o=Number.parseInt(e.version)>=19,h=e.forwardRef((s,h)=>{var d,c;let f=e.useRef(null),g=e.useRef(new Map),m={},p={},y={},v={};for(let[e,t]of Object.entries(s)){if(nx.has(e)){y[e]=t;continue}let r=n(nM[e]??e);if(i.prototype&&e in i.prototype&&!(e in((null==(d=globalThis.HTMLElement)?void 0:d.prototype)??{}))&&!(null!=(c=i.observedAttributes)&&c.some(e=>e===r))){v[e]=t;continue}if(e.startsWith("on")){m[e]=t;continue}let s=l(t);r&&null!=s&&(p[r]=String(s),o||(y[r]=s)),r&&o&&(s!==nF(t)?y[r]=s:y[r]=t)}if("u">typeof window){for(let t in m){let i=m[t],s=t.endsWith("Capture"),a=(r?.[t]??t.slice(2).toLowerCase()).slice(0,s?-7:void 0);e.useLayoutEffect(()=>{let e=f?.current;if(!(!e||"function"!=typeof i))return e.addEventListener(a,i,s),()=>{e.removeEventListener(a,i,s)}},[f?.current,i])}e.useLayoutEffect(()=>{if(null===f.current)return;let e=new Map;for(let t in v)n$(f.current,t,v[t]),g.current.delete(t),e.set(t,v[t]);for(let[e,t]of g.current)n$(f.current,e,void 0);g.current=e})}if(typeof window>"u"&&i?.getTemplateHTML&&i?.shadowRootOptions){let{mode:t,delegatesFocus:r}=i.shadowRootOptions;y.children=[e.createElement("template",{shadowrootmode:t,shadowrootdelegatesfocus:r,dangerouslySetInnerHTML:{__html:i.getTemplateHTML(p,s)},key:"ce-la-react-ssr-template-shadow-root"}),y.children]}return e.createElement(t,{...a,...y,ref:e.useCallback(e=>{f.current=e,"function"==typeof h?h(e):null!==h&&(h.current=e)},[h])},y.children)});return h.displayName=s??i.name,h}({react:l.default,tagName:"hls-video",elementClass:nw,toAttributeName:e=>"muted"===e?"":"defaultMuted"===e?"muted":nO(e)}),nU=e.i(400684);function nN(e){globalThis.reportError?.(Error(`VideoPlayer: ${e}`))}e.s(["HlsVideoPlayer",0,function({video:e,thumbnail:t,options:i,className:r}){let s=e?.playlists?.find(e=>e?.endsWith(".m3u8")),a=t?.url??e?.thumbnails?.[0]?.url??void 0;return s?(0,n.jsx)(nB,{src:s,poster:a,autoplay:!0,defaultMuted:!0,loop:!0,playsInline:!0,className:(0,nU.cn)("[--media-object-fit:cover]",r),onError:e=>{let t=e.currentTarget?.error;nN(`${s} failed with ${t?`${t.code}: ${t.message}`:"an unknown error"}`)},...i}):(nN(`no m3u8 playlist for ${e?.id}`),null)}],381245)},880154,e=>{e.n(e.i(381245))}]);
89
90//# debugId=448a9f9d-f240-7e99-45d2-8d91745482af

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.