@jaaq/jaaq-sdk-js 1.5.0 → 1.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,8 +1,8 @@
1
- !function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).JaaqWebComponents={})}(this,function(t){"use strict";const e=Number.isFinite||function(t){return"number"==typeof t&&isFinite(t)},i=Number.isSafeInteger||function(t){return"number"==typeof t&&Math.abs(t)<=s},s=Number.MAX_SAFE_INTEGER||9007199254740991;let r=function(t){return t.NETWORK_ERROR="networkError",t.MEDIA_ERROR="mediaError",t.KEY_SYSTEM_ERROR="keySystemError",t.MUX_ERROR="muxError",t.OTHER_ERROR="otherError",t}({}),n=function(t){return t.KEY_SYSTEM_NO_KEYS="keySystemNoKeys",t.KEY_SYSTEM_NO_ACCESS="keySystemNoAccess",t.KEY_SYSTEM_NO_SESSION="keySystemNoSession",t.KEY_SYSTEM_NO_CONFIGURED_LICENSE="keySystemNoConfiguredLicense",t.KEY_SYSTEM_LICENSE_REQUEST_FAILED="keySystemLicenseRequestFailed",t.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED="keySystemServerCertificateRequestFailed",t.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED="keySystemServerCertificateUpdateFailed",t.KEY_SYSTEM_SESSION_UPDATE_FAILED="keySystemSessionUpdateFailed",t.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED="keySystemStatusOutputRestricted",t.KEY_SYSTEM_STATUS_INTERNAL_ERROR="keySystemStatusInternalError",t.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR="keySystemDestroyMediaKeysError",t.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR="keySystemDestroyCloseSessionError",t.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR="keySystemDestroyRemoveSessionError",t.MANIFEST_LOAD_ERROR="manifestLoadError",t.MANIFEST_LOAD_TIMEOUT="manifestLoadTimeOut",t.MANIFEST_PARSING_ERROR="manifestParsingError",t.MANIFEST_INCOMPATIBLE_CODECS_ERROR="manifestIncompatibleCodecsError",t.LEVEL_EMPTY_ERROR="levelEmptyError",t.PLAYLIST_UNCHANGED_ERROR="playlistUnchangedError",t.LEVEL_LOAD_ERROR="levelLoadError",t.LEVEL_LOAD_TIMEOUT="levelLoadTimeOut",t.LEVEL_PARSING_ERROR="levelParsingError",t.LEVEL_SWITCH_ERROR="levelSwitchError",t.AUDIO_TRACK_LOAD_ERROR="audioTrackLoadError",t.AUDIO_TRACK_LOAD_TIMEOUT="audioTrackLoadTimeOut",t.SUBTITLE_LOAD_ERROR="subtitleTrackLoadError",t.SUBTITLE_TRACK_LOAD_TIMEOUT="subtitleTrackLoadTimeOut",t.FRAG_LOAD_ERROR="fragLoadError",t.FRAG_LOAD_TIMEOUT="fragLoadTimeOut",t.FRAG_DECRYPT_ERROR="fragDecryptError",t.FRAG_PARSING_ERROR="fragParsingError",t.FRAG_GAP="fragGap",t.REMUX_ALLOC_ERROR="remuxAllocError",t.KEY_LOAD_ERROR="keyLoadError",t.KEY_LOAD_TIMEOUT="keyLoadTimeOut",t.BUFFER_ADD_CODEC_ERROR="bufferAddCodecError",t.BUFFER_INCOMPATIBLE_CODECS_ERROR="bufferIncompatibleCodecsError",t.BUFFER_APPEND_ERROR="bufferAppendError",t.BUFFER_APPENDING_ERROR="bufferAppendingError",t.BUFFER_APPEND_NO_PROGRESS="bufferAppendNoProgress",t.BUFFER_STALLED_ERROR="bufferStalledError",t.BUFFER_FULL_ERROR="bufferFullError",t.BUFFER_SEEK_OVER_HOLE="bufferSeekOverHole",t.BUFFER_NUDGE_ON_STALL="bufferNudgeOnStall",t.ASSET_LIST_LOAD_ERROR="assetListLoadError",t.ASSET_LIST_LOAD_TIMEOUT="assetListLoadTimeout",t.ASSET_LIST_PARSING_ERROR="assetListParsingError",t.INTERSTITIAL_ASSET_ITEM_ERROR="interstitialAssetItemError",t.INTERNAL_EXCEPTION="internalException",t.INTERNAL_ABORTED="aborted",t.ATTACH_MEDIA_ERROR="attachMediaError",t.MEDIA_SOURCE_REQUIRES_RESET="mediaSourceRequiresReset",t.UNKNOWN="unknown",t}({}),a=function(t){return t.MEDIA_ATTACHING="hlsMediaAttaching",t.MEDIA_ATTACHED="hlsMediaAttached",t.MEDIA_DETACHING="hlsMediaDetaching",t.MEDIA_DETACHED="hlsMediaDetached",t.MEDIA_ENDED="hlsMediaEnded",t.STALL_RESOLVED="hlsStallResolved",t.BUFFER_RESET="hlsBufferReset",t.BUFFER_CODECS="hlsBufferCodecs",t.BUFFER_CREATED="hlsBufferCreated",t.BUFFER_APPENDING="hlsBufferAppending",t.BUFFER_APPENDED="hlsBufferAppended",t.BUFFER_EOS="hlsBufferEos",t.BUFFERED_TO_END="hlsBufferedToEnd",t.BUFFER_FLUSHING="hlsBufferFlushing",t.BUFFER_FLUSHED="hlsBufferFlushed",t.MANIFEST_LOADING="hlsManifestLoading",t.MANIFEST_LOADED="hlsManifestLoaded",t.MANIFEST_PARSED="hlsManifestParsed",t.LEVEL_SWITCHING="hlsLevelSwitching",t.LEVEL_SWITCHED="hlsLevelSwitched",t.LEVEL_LOADING="hlsLevelLoading",t.LEVEL_LOADED="hlsLevelLoaded",t.LEVEL_UPDATED="hlsLevelUpdated",t.LEVEL_PTS_UPDATED="hlsLevelPtsUpdated",t.LEVELS_UPDATED="hlsLevelsUpdated",t.AUDIO_TRACKS_UPDATED="hlsAudioTracksUpdated",t.AUDIO_TRACK_SWITCHING="hlsAudioTrackSwitching",t.AUDIO_TRACK_SWITCHED="hlsAudioTrackSwitched",t.AUDIO_TRACK_LOADING="hlsAudioTrackLoading",t.AUDIO_TRACK_LOADED="hlsAudioTrackLoaded",t.AUDIO_TRACK_UPDATED="hlsAudioTrackUpdated",t.SUBTITLE_TRACKS_UPDATED="hlsSubtitleTracksUpdated",t.SUBTITLE_TRACKS_CLEARED="hlsSubtitleTracksCleared",t.SUBTITLE_TRACK_SWITCH="hlsSubtitleTrackSwitch",t.SUBTITLE_TRACK_LOADING="hlsSubtitleTrackLoading",t.SUBTITLE_TRACK_LOADED="hlsSubtitleTrackLoaded",t.SUBTITLE_TRACK_UPDATED="hlsSubtitleTrackUpdated",t.SUBTITLE_FRAG_PROCESSED="hlsSubtitleFragProcessed",t.CUES_PARSED="hlsCuesParsed",t.NON_NATIVE_TEXT_TRACKS_FOUND="hlsNonNativeTextTracksFound",t.INIT_PTS_FOUND="hlsInitPtsFound",t.FRAG_LOADING="hlsFragLoading",t.FRAG_LOAD_EMERGENCY_ABORTED="hlsFragLoadEmergencyAborted",t.FRAG_LOADED="hlsFragLoaded",t.FRAG_DECRYPTED="hlsFragDecrypted",t.FRAG_PARSING_INIT_SEGMENT="hlsFragParsingInitSegment",t.FRAG_PARSING_USERDATA="hlsFragParsingUserdata",t.FRAG_PARSING_METADATA="hlsFragParsingMetadata",t.FRAG_PARSED="hlsFragParsed",t.FRAG_BUFFERED="hlsFragBuffered",t.FRAG_CHANGED="hlsFragChanged",t.FPS_DROP="hlsFpsDrop",t.FPS_DROP_LEVEL_CAPPING="hlsFpsDropLevelCapping",t.MAX_AUTO_LEVEL_UPDATED="hlsMaxAutoLevelUpdated",t.ERROR="hlsError",t.DESTROYING="hlsDestroying",t.KEY_LOADING="hlsKeyLoading",t.KEY_LOADED="hlsKeyLoaded",t.LIVE_BACK_BUFFER_REACHED="hlsLiveBackBufferReached",t.BACK_BUFFER_REACHED="hlsBackBufferReached",t.STEERING_MANIFEST_LOADED="hlsSteeringManifestLoaded",t.ASSET_LIST_LOADING="hlsAssetListLoading",t.ASSET_LIST_LOADED="hlsAssetListLoaded",t.INTERSTITIALS_UPDATED="hlsInterstitialsUpdated",t.INTERSTITIALS_BUFFERED_TO_BOUNDARY="hlsInterstitialsBufferedToBoundary",t.INTERSTITIAL_ASSET_PLAYER_CREATED="hlsInterstitialAssetPlayerCreated",t.INTERSTITIAL_STARTED="hlsInterstitialStarted",t.INTERSTITIAL_ASSET_STARTED="hlsInterstitialAssetStarted",t.INTERSTITIAL_ASSET_ENDED="hlsInterstitialAssetEnded",t.INTERSTITIAL_ASSET_ERROR="hlsInterstitialAssetError",t.INTERSTITIAL_ENDED="hlsInterstitialEnded",t.INTERSTITIALS_PRIMARY_RESUMED="hlsInterstitialsPrimaryResumed",t.PLAYOUT_LIMIT_REACHED="hlsPlayoutLimitReached",t.EVENT_CUE_ENTER="hlsEventCueEnter",t}({});function o(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var l,h={exports:{}};var d=(l||(l=1,function(t){var e,i,s,r,n;e=/^(?=((?:[a-zA-Z0-9+\-.]+:)?))\1(?=((?:\/\/[^\/?#]*)?))\2(?=((?:(?:[^?#\/]*\/)*[^;?#\/]*)?))\3((?:;[^?#]*)?)(\?[^#]*)?(#[^]*)?$/,i=/^(?=([^\/?#]*))\1([^]*)$/,s=/(?:\/|^)\.(?=\/)/g,r=/(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g,n={buildAbsoluteURL:function(t,e,s){if(s=s||{},t=t.trim(),!(e=e.trim())){if(!s.alwaysNormalize)return t;var r=n.parseURL(t);if(!r)throw new Error("Error trying to parse base URL.");return r.path=n.normalizePath(r.path),n.buildURLFromParts(r)}var a=n.parseURL(e);if(!a)throw new Error("Error trying to parse relative URL.");if(a.scheme)return s.alwaysNormalize?(a.path=n.normalizePath(a.path),n.buildURLFromParts(a)):e;var o=n.parseURL(t);if(!o)throw new Error("Error trying to parse base URL.");if(!o.netLoc&&o.path&&"/"!==o.path[0]){var l=i.exec(o.path);o.netLoc=l[1],o.path=l[2]}o.netLoc&&!o.path&&(o.path="/");var h={scheme:o.scheme,netLoc:a.netLoc,path:null,params:a.params,query:a.query,fragment:a.fragment};if(!a.netLoc&&(h.netLoc=o.netLoc,"/"!==a.path[0]))if(a.path){var d=o.path,c=d.substring(0,d.lastIndexOf("/")+1)+a.path;h.path=n.normalizePath(c)}else h.path=o.path,a.params||(h.params=o.params,a.query||(h.query=o.query));return null===h.path&&(h.path=s.alwaysNormalize?n.normalizePath(a.path):a.path),n.buildURLFromParts(h)},parseURL:function(t){var i=e.exec(t);return i?{scheme:i[1]||"",netLoc:i[2]||"",path:i[3]||"",params:i[4]||"",query:i[5]||"",fragment:i[6]||""}:null},normalizePath:function(t){for(t=t.split("").reverse().join("").replace(s,"");t.length!==(t=t.replace(r,"")).length;);return t.split("").reverse().join("")},buildURLFromParts:function(t){return t.scheme+t.netLoc+t.path+t.params+t.query+t.fragment}},t.exports=n}(h)),h.exports);class c{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}}}let u=function(t){return t.MANIFEST="manifest",t.LEVEL="level",t.AUDIO_TRACK="audioTrack",t.SUBTITLE_TRACK="subtitleTrack",t.MEDIA_FRAGMENT="media-fragment",t.KEY="key",t.STEERING_MANIFEST="steering-manifest",t.SERVER_CERTIFICATE="server-certificate",t.INTERSTITIAL_ASSET_LIST="interstitial-asset-list",t}({}),f=function(t){return t.MAIN="main",t.AUDIO="audio",t.SUBTITLE="subtitle",t}({});var g="audio",m="video",p="audiovideo";class v{constructor(t){this._byteRange=null,this._url=null,this._stats=null,this._streams=null,this.base=void 0,this.relurl=void 0,"string"==typeof t&&(t={url:t}),this.base=t,function(t,e){const i=A(t,e);i&&(i.enumerable=!0,Object.defineProperty(t,e,i))}(this,"stats")}setByteRange(t,e){const i=t.split("@",2);let s;s=1===i.length?(null==e?void 0:e.byteRangeEndOffset)||0:parseInt(i[1]),this._byteRange=[s,parseInt(i[0])+s]}get baseurl(){return this.base.url}get byteRange(){return null===this._byteRange?[]:this._byteRange}get byteRangeStartOffset(){return this.byteRange[0]}get byteRangeEndOffset(){return this.byteRange[1]}get elementaryStreams(){return null===this._streams&&(this._streams={[g]:null,[m]:null,[p]:null}),this._streams}set elementaryStreams(t){this._streams=t}get hasStats(){return null!==this._stats}get hasStreams(){return null!==this._streams}get stats(){return null===this._stats&&(this._stats=new c),this._stats}set stats(t){this._stats=t}get url(){return!this._url&&this.relurl&&(this._url=d.buildAbsoluteURL(this.baseurl,this.relurl,{alwaysNormalize:!0})),this._url||""}set url(t){this._url=t}clearElementaryStreamInfo(){const{elementaryStreams:t}=this;t[g]=null,t[m]=null,t[p]=null,this.url=null}}function y(t){return"initSegment"!==t.sn}function E(t,e){return t.sn===(null==e?void 0:e.sn)&&t.level===e.level}function T(t,e){return t.sn===(null==e?void 0:e.sn)&&t.level===e.level&&t.cc===e.cc}class S extends v{constructor(t,e){super(e),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=t}get byteLength(){if(this.hasStats){const t=this.stats.total;if(t)return t}if(this.byteRange.length){const t=this.byteRange[0],i=this.byteRange[1];if(e(t)&&e(i))return i-t}return null}get bitrate(){return this.byteLength?8*this.byteLength/this.duration:this._bitrate?this._bitrate:null}set bitrate(t){this._bitrate=t}get decryptdata(){var t;const{levelkeys:e}=this;if(!e||e.NONE)return null;if(e.identity)this._decryptdata||(this._decryptdata=e.identity.getDecryptData(this.sn));else if(null==(t=this._decryptdata)||!t.keyId){const t=Object.keys(e);if(1===t.length){const i=this._decryptdata=e[t[0]]||null;i&&(this._decryptdata=i.getDecryptData(this.sn,e))}}return this._decryptdata}get end(){return this.start+this.duration}get endProgramDateTime(){if(null===this.programDateTime)return null;const t=e(this.duration)?this.duration:0;return this.programDateTime+1e3*t}get encrypted(){var t;if(null!=(t=this._decryptdata)&&t.encrypted)return!0;if(this.levelkeys){var e;const t=Object.keys(this.levelkeys),i=t.length;if(i>1||1===i&&null!=(e=this.levelkeys[t[0]])&&e.encrypted)return!0}return!1}get programDateTime(){return null===this._programDateTime&&this.rawProgramDateTime&&(this.programDateTime=Date.parse(this.rawProgramDateTime)),this._programDateTime}set programDateTime(t){e(t)?this._programDateTime=t:this._programDateTime=this.rawProgramDateTime=null}get ref(){return y(this)?(this._ref||(this._ref={base:this.base,start:this.start,duration:this.duration,sn:this.sn,programDateTime:this.programDateTime}),this._ref):null}addStart(t){this.setStart(this.start+t)}setStart(t){this.start=t,this._ref&&(this._ref.start=t)}setDuration(t){this.duration=t,this._ref&&(this._ref.duration=t)}setKeyFormat(t){const e=this.levelkeys;if(e){var i;const s=e[t];!s||null!=(i=this._decryptdata)&&i.keyId||(this._decryptdata=s.getDecryptData(this.sn,e))}}abortRequests(){var t,e;null==(t=this.loader)||t.abort(),null==(e=this.keyLoader)||e.abort()}setElementaryStreamInfo(t,e,i,s,r,n=!1){const{elementaryStreams:a}=this,o=a[t];o?(o.startPTS=Math.min(o.startPTS,e),o.endPTS=Math.max(o.endPTS,i),o.startDTS=Math.min(o.startDTS,s),o.endDTS=Math.max(o.endDTS,r)):a[t]={startPTS:e,endPTS:i,startDTS:s,endDTS:r,partial:n}}}class b extends v{constructor(t,e,i,s,r){super(i),this.fragOffset=0,this.duration=0,this.independent=!1,this.relurl=void 0,this.fragment=void 0,this.index=void 0,this.gap=!1,this.duration=t.decimalFloatingPoint("DURATION"),this.gap=t.bool("GAP"),this.independent=t.bool("INDEPENDENT"),this.relurl=t.enumeratedString("URI"),this.fragment=e,this.index=s;const n=t.enumeratedString("BYTERANGE");n&&this.setByteRange(n,r),r&&(this.fragOffset=r.fragOffset+r.duration)}get start(){return this.fragment.start+this.fragOffset}get end(){return this.start+this.duration}get loaded(){const{elementaryStreams:t}=this;return!!(t.audio||t.video||t.audiovideo||this.fragment.type===f.SUBTITLE&&this.stats.loading.end>0)}}function A(t,e){const i=Object.getPrototypeOf(t);if(i){const t=Object.getOwnPropertyDescriptor(i,e);return t||A(i,e)}}function L(t,e,i){return(e=function(t){var e=function(t,e){if("object"!=typeof t||!t)return t;var i=t[Symbol.toPrimitive];if(void 0!==i){var s=i.call(t,e);if("object"!=typeof s)return s;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:e+""}(e))in t?Object.defineProperty(t,e,{value:i,enumerable:!0,configurable:!0,writable:!0}):t[e]=i,t}function I(){return I=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var i=arguments[e];for(var s in i)({}).hasOwnProperty.call(i,s)&&(t[s]=i[s])}return t},I.apply(null,arguments)}function R(t,e){var i=Object.keys(t);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(t);e&&(s=s.filter(function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable})),i.push.apply(i,s)}return i}function k(t){for(var e=1;e<arguments.length;e++){var i=null!=arguments[e]?arguments[e]:{};e%2?R(Object(i),!0).forEach(function(e){L(t,e,i[e])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(i)):R(Object(i)).forEach(function(e){Object.defineProperty(t,e,Object.getOwnPropertyDescriptor(i,e))})}return t}function _(t,e){if(null==t)return{};var i,s,r=function(t,e){if(null==t)return{};var i={};for(var s in t)if({}.hasOwnProperty.call(t,s)){if(-1!==e.indexOf(s))continue;i[s]=t[s]}return i}(t,e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(t);for(s=0;s<n.length;s++)i=n[s],-1===e.indexOf(i)&&{}.propertyIsEnumerable.call(t,i)&&(r[i]=t[i])}return r}function D(t){switch(t.details){case n.FRAG_LOAD_TIMEOUT:case n.KEY_LOAD_TIMEOUT:case n.LEVEL_LOAD_TIMEOUT:case n.MANIFEST_LOAD_TIMEOUT:case n.AUDIO_TRACK_LOAD_TIMEOUT:case n.SUBTITLE_TRACK_LOAD_TIMEOUT:case n.ASSET_LIST_LOAD_TIMEOUT:return!0}return!1}function w(t){return t.details.startsWith("key")}function P(t){return w(t)&&!!t.frag&&!t.frag.decryptdata}function C(t,e){const i=D(e);return t.default[(i?"timeout":"error")+"Retry"]}function x(t,e){const i="linear"===t.backoff?1:Math.pow(2,e);return Math.min(i*t.retryDelayMs,t.maxRetryDelayMs)}function M(t){return k(k({},t),{errorRetry:null,timeoutRetry:null})}function O(t,e,i,s){if(!t)return!1;const r=null==s?void 0:s.code,n=e<t.maxNumRetry&&(function(t){return F(t)||!!t&&(t<400||t>499)}(r)||!!i);return t.shouldRetry?t.shouldRetry(t,e,i,s,n):n}function F(t){return 0===t&&!1===navigator.onLine}function N(t,e){return e>0&&t.loadError>0&&0!==t.loadErrorTime&&self.performance.now()-t.loadErrorTime>e}class ${constructor(t,e=0,i=0){this.halfLife=void 0,this.alpha_=void 0,this.estimate_=void 0,this.totalWeight_=void 0,this.halfLife=t,this.alpha_=t?Math.exp(Math.log(.5)/t):0,this.estimate_=e,this.totalWeight_=i}sample(t,e){const i=Math.pow(this.alpha_,t);this.estimate_=e*(1-i)+i*this.estimate_,this.totalWeight_+=t}getTotalWeight(){return this.totalWeight_}getEstimate(){if(this.alpha_){const t=1-Math.pow(this.alpha_,this.totalWeight_);if(t)return this.estimate_/t}return this.estimate_}}class B{constructor(t,e,i,s=100){this.defaultEstimate_=void 0,this.minWeight_=void 0,this.minDelayMs_=void 0,this.slow_=void 0,this.fast_=void 0,this.defaultTTFB_=void 0,this.ttfb_=void 0,this.defaultEstimate_=i,this.minWeight_=.001,this.minDelayMs_=50,this.slow_=new $(t),this.fast_=new $(e),this.defaultTTFB_=s,this.ttfb_=new $(t)}update(t,e){const{slow_:i,fast_:s,ttfb_:r}=this;i.halfLife!==t&&(this.slow_=new $(t,i.getEstimate(),i.getTotalWeight())),s.halfLife!==e&&(this.fast_=new $(e,s.getEstimate(),s.getTotalWeight())),r.halfLife!==t&&(this.ttfb_=new $(t,r.getEstimate(),r.getTotalWeight()))}sample(t,e){if(e<=0)return;const i=Math.min(this.minDelayMs_,e/1e5),s=8*e,r=Math.max(t,i)/1e3,n=s/r;this.fast_.sample(r,n),this.slow_.sample(r,n)}sampleTTFB(t){const e=t/1e3,i=Math.sqrt(2)*Math.exp(-Math.pow(e,2)/2);this.ttfb_.sample(i,Math.max(t,5))}canEstimate(){return this.fast_.getTotalWeight()>=this.minWeight_}getEstimate(){return this.canEstimate()?Math.min(this.fast_.getEstimate(),this.slow_.getEstimate()):this.defaultEstimate_}getEstimateTTFB(){return this.ttfb_.getTotalWeight()>=this.minWeight_?this.ttfb_.getEstimate():this.defaultTTFB_}get defaultEstimate(){return this.defaultEstimate_}destroy(){}}class U{constructor(t,e){this.trace=void 0,this.debug=void 0,this.log=void 0,this.warn=void 0,this.info=void 0,this.error=void 0;const i=`[${t}]:`;this.trace=G,this.debug=e.debug.bind(null,i),this.log=e.log.bind(null,i),this.warn=e.warn.bind(null,i),this.info=e.info.bind(null,i),this.error=e.error.bind(null,i)}}const G=function(){},K={trace:G,debug:G,log:G,warn:G,info:G,error:G};function V(){return I({},K)}function j(t,e,i){return e[t]?e[t].bind(e):function(t,e){const i=self.console[t];return i?i.bind(self.console,`${e?"["+e+"] ":""}[${t}] >`):G}(t,i)}const H=V();const q=H;function Y(t=!0){if("undefined"==typeof self)return;return(t||!self.MediaSource)&&self.ManagedMediaSource||self.MediaSource||self.WebKitMediaSource}function W(t,e){const i=Object.keys(t),s=Object.keys(e),r=i.length,n=s.length;return!r||!n||r===n&&!i.some(t=>-1===s.indexOf(t))}function z(t){return t instanceof ArrayBuffer||"undefined"!=typeof SharedArrayBuffer&&t instanceof SharedArrayBuffer}const X="utf-16be",Q="utf-16le",Z="utf-8";function J(t,e){if(t<0)return-J(-t,e);const i=Math.pow(10,e);if(Math.abs(t*i%1-.5)<Number.EPSILON){const e=Math.floor(t*i);return(e%2==0?e:e+1)/i}return Math.round(t*i)/i}function tt(){try{return crypto.randomUUID()}catch(t){try{const t=URL.createObjectURL(new Blob),e=t.toString();return URL.revokeObjectURL(t),e.slice(e.lastIndexOf("/")+1)}catch(t){let e=(new Date).getTime();return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,t=>{const i=(e+16*Math.random())%16|0;return e=Math.floor(e/16),("x"==t?i:3&i|8).toString(16)})}}}function et(t,e){return e+10<=t.length&&73===t[e]&&68===t[e+1]&&51===t[e+2]&&t[e+3]<255&&t[e+4]<255&&t[e+6]<128&&t[e+7]<128&&t[e+8]<128&&t[e+9]<128}function it(t,e){let i=0;return i=(127&t[e])<<21,i|=(127&t[e+1])<<14,i|=(127&t[e+2])<<7,i|=127&t[e+3],i}function st(t,e){return et(t,e)&&it(t,e+6)+10<=t.length-e}function rt(t,e){return e+10<=t.length&&51===t[e]&&68===t[e+1]&&73===t[e+2]&&t[e+3]<255&&t[e+4]<255&&t[e+6]<128&&t[e+7]<128&&t[e+8]<128&&t[e+9]<128}function nt(t,e){const i=e;let s=0;for(;et(t,e);){s+=10;s+=it(t,e+6),rt(t,e+10)&&(s+=10),e+=s}if(s>0)return t.subarray(i,i+s)}function at(t,e=0,i=1/0){return function(t,e,i,s){const r=(n=t,z(n)?n:n.buffer);var n;let a=1;"BYTES_PER_ELEMENT"in s&&(a=s.BYTES_PER_ELEMENT);const o=(c=t,c&&z(c.buffer)&&void 0!==c.byteLength&&void 0!==c.byteOffset?t.byteOffset:0),l=(o+t.byteLength)/a,h=(o+e)/a,d=Math.floor(Math.max(0,Math.min(h,l)));var c;return new s(r,d,Math.floor(Math.min(d+Math.max(i,0),l))-d)}(t,e,i,Uint8Array)}function ot(t,e=!1){const i=e?t.indexOf(0):t.length,s=function(t,e={}){let i;i=z(t)?new DataView(t):new DataView(t.buffer,t.byteOffset,t.byteLength);let s=0,{encoding:r}=e;if(!r){const t=i.getUint8(0),e=i.getUint8(1);239==t&&187==e&&191==i.getUint8(2)?(r=Z,s=3):254==t&&255==e?(r=X,s=2):255==t&&254==e?(r=Q,s=2):r=Z}if("undefined"!=typeof TextDecoder)return new TextDecoder(r).decode(i);const{byteLength:n}=i,a=r!==X;let o,l="";for(;s<n;){switch(r){case Z:if(o=i.getUint8(s),o<128)s++;else if(o>=194&&o<=223)if(s+1<n){const t=i.getUint8(s+1);t>=128&&t<=191?(o=(31&o)<<6|63&t,s+=2):s++}else s++;else if(o>=224&&o<=239)if(s+2<=n-1){const t=i.getUint8(s+1),e=i.getUint8(s+2);t>=128&&t<=191&&e>=128&&e<=191?(o=(15&o)<<12|(63&t)<<6|63&e,s+=3):s++}else s++;else if(o>=240&&o<=244)if(s+3<=n-1){const t=i.getUint8(s+1),e=i.getUint8(s+2),r=i.getUint8(s+3);t>=128&&t<=191&&e>=128&&e<=191&&r>=128&&r<=191?(o=(7&o)<<18|(63&t)<<12|(63&e)<<6|63&r,s+=4):s++}else s++;else s++;break;case X:case"utf-16":case Q:o=i.getUint16(s,a),s+=2}l+=String.fromCodePoint(o)}return l}(new DataView(t.buffer,t.byteOffset,i),{encoding:Z});return e?s:s.replace(/\0/g,"")}function lt(t){const e={key:t.type,description:"",data:"",mimeType:null,pictureType:null};if(t.size<2)return;if(3!==t.data[0])return void console.log("Ignore frame with unrecognized character encoding");const i=t.data.subarray(1).indexOf(0);if(-1===i)return;const s=ot(at(t.data,1,i)),r=t.data[2+i],n=t.data.subarray(3+i).indexOf(0);if(-1===n)return;const a=ot(at(t.data,3+i,n));let o;var l;return"--\x3e"===s?o=ot(at(t.data,4+i+n)):o=z(l=t.data.subarray(4+i+n))?l:0==l.byteOffset&&l.byteLength==l.buffer.byteLength?l.buffer:new Uint8Array(l).buffer,e.mimeType=s,e.pictureType=r,e.description=a,e.data=o,e}function ht(t){return"PRIV"===t.type?function(t){if(t.size<2)return;const e=ot(t.data,!0),i=new Uint8Array(t.data.subarray(e.length+1));return{key:t.type,info:e,data:i.buffer}}(t):"W"===t.type[0]?function(t){if("WXXX"===t.type){if(t.size<2)return;let e=1;const i=ot(t.data.subarray(e),!0);e+=i.length+1;const s=ot(t.data.subarray(e));return{key:t.type,info:i,data:s}}const e=ot(t.data);return{key:t.type,info:"",data:e}}(t):"APIC"===t.type?lt(t):function(t){if(t.size<2)return;if("TXXX"===t.type){let e=1;const{data:i}=t,s=ot(i.subarray(e),!0);e+=s.length+1;const r=ot(i.subarray(e));return{key:t.type,info:s,data:r}}const e=ot(t.data.subarray(1));return{key:t.type,info:"",data:e}}(t)}function dt(t){const e=String.fromCharCode(t[0],t[1],t[2],t[3]),i=it(t,4);return{type:e,size:i,data:t.subarray(10,10+i)}}function ct(t){let e=0;const i=[];for(;et(t,e);){const s=it(t,e+6);t[e+5]>>6&1&&(e+=10),e+=10;const r=e+s;for(;e+10<r;){const s=dt(t.subarray(e)),r=ht(s);r&&i.push(r),e+=s.size+10}rt(t,e)&&(e+=10)}return i}function ut(t){return t&&"PRIV"===t.key&&"com.apple.streaming.transportStreamTimestamp"===t.info}function ft(t){if(8===t.data.byteLength){const e=new Uint8Array(t.data),i=1&e[3];let s=(e[4]<<23)+(e[5]<<15)+(e[6]<<7)+e[7];return s/=45,i&&(s+=47721858.84),Math.round(s)}}function gt(t){const e=ct(t);for(const t of e)if(ut(t))return ft(t)}function mt(t){let e="";for(let i=0;i<t.length;i++){let s=t[i].toString(16);s.length<2&&(s="0"+s),e+=s}return e}function pt(t){return Uint8Array.from(t.replace(/^0x/,"").replace(/([\da-fA-F]{2}) ?/g,"0x$1 ").replace(/ +$/,"").split(" ")).buffer}function vt(t){return Uint8Array.from(atob(t),t=>t.charCodeAt(0))}function yt(t){return String.fromCharCode.apply(null,t)}const Et=Math.pow(2,32)-1,Tt={avc1:1635148593,avcC:1635148611,hvc1:1752589105,hvcC:1752589123,btrt:1651798644,dinf:1684631142,dref:1685218662,esds:1702061171,free:1718773093,ftyp:1718909296,hdlr:1751411826,mdat:1835295092,mdhd:1835296868,mdia:1835297121,mfhd:1835427940,minf:1835626086,moof:1836019558,moov:1836019574,mp4a:1836069985,".mp3":778924083,dac3:1684103987,"ac-3":1633889587,mvex:1836475768,mvhd:1836476516,pasp:1885434736,sdtp:1935963248,stbl:1937007212,stco:1937007471,stsc:1937011555,stsd:1937011556,stsz:1937011578,stts:1937011827,tfdt:1952867444,tfhd:1952868452,traf:1953653094,trak:1953653099,trun:1953658222,trex:1953654136,tkhd:1953196132,vmhd:1986881636,smhd:1936549988},St={video:1,audio:2,id3:3,text:4};function bt(t,e){const i=t[e]<<8|t[e+1];return i<0?65536+i:i}function At(t,e){const i=t[e]<<24|t[e+1]<<16|t[e+2]<<8|t[e+3];return i<0?4294967296+i:i}function Lt(t,e){let i=At(t,e);return i*=Math.pow(2,32),i+=At(t,e+4),i}function It(t,e){let i="";for(let s=e;s<t.length;s++)if(i+=String.fromCharCode(t[s]),0===t[s])return i;return null}function Rt(t,e){return t[e]<<24|t[e+1]<<16|t[e+2]<<8|t[e+3]}function kt(t,e,i){t[e]=i>>24,t[e+1]=i>>16&255,t[e+2]=i>>8&255,t[e+3]=255&i}function _t(t,e,i){const s=e.byteOffset-t.byteOffset-8,r=8+i,n=e.byteLength+8-r;n<8||(kt(t,s,r),kt(t,s+r,n),kt(t,s+r+4,Tt.free))}function Dt(t,e){return[t.byteOffset-e-8,t.byteOffset-e+t.byteLength]}function wt(t,e){e.sort((t,e)=>t[0]-e[0]);const i=e.reduce((t,[e,i])=>t+i-e,0),s=new Uint8Array(t.byteLength-i);let r=0,n=0;for(let i=0;i<e.length;i++){const[a,o]=e[i];s.set(t.subarray(r,a),n),n+=a-r,r=o}s.set(t.subarray(r),n);return{result:s,dropped:i,droppedBefore:t=>e.reduce((e,[i,s])=>s<=t?e+s-i:e,0)}}function Pt(t,e){const i=[];return e.length?(Ct(t,e,0,0,t.byteLength,i),i):i}function Ct(t,e,i,s,r,n){const a=e[i];if(4!==(null==a?void 0:a.length))return;const o=a.charCodeAt(0),l=a.charCodeAt(1),h=a.charCodeAt(2),d=a.charCodeAt(3),c=e.length-1;for(let a=s;a<r;){const s=a+8<=r,u=a+4<=r?16777216*t[a]+(t[a+1]<<16|t[a+2]<<8|t[a+3]):At(t,a),f=u>1?a+u:r;if(s&&t[a+4]===o&&t[a+5]===l&&t[a+6]===h&&t[a+7]===d){const s=Math.min(f,r);i===c?n.push(t.subarray(a+8,s)):Ct(t,e,i+1,a+8,s,n)}a=f}}function xt(t){const e=[],i=t[0];let s=8;const r=At(t,s);s+=4;let n=0,a=0;0===i?(n=At(t,s),a=At(t,s+4),s+=8):(n=Lt(t,s),a=Lt(t,s+8),s+=16),s+=2;let o=t.length+a;const l=bt(t,s);s+=2;for(let i=0;i<l;i++){let i=s;const n=At(t,i);i+=4;const a=2147483647&n;if(1===(2147483648&n)>>>31)return q.warn("SIDX has hierarchical references (not supported)"),null;const l=At(t,i);i+=4,e.push({referenceSize:a,subsegmentDuration:l,info:{duration:l/r,start:o,end:o+a-1}}),o+=a,i+=4,s=i}return{earliestPresentationTime:n,timescale:r,version:i,referencesCount:l,references:e}}function Mt(t){const e=[],i=Pt(t,["moov","trak"]);for(let t=0;t<i.length;t++){const s=i[t],r=Pt(s,["tkhd"])[0];if(r){let t=r[0];const i=At(r,0===t?12:20),n=Pt(s,["mdia","mdhd"])[0];if(n){t=n[0];const r=At(n,0===t?12:20),a=Pt(s,["mdia","hdlr"])[0];if(a){const t=yt(a.subarray(8,12)),n={soun:g,vide:m}[t],o=Ot(Pt(s,["mdia","minf","stbl","stsd"])[0]);n?(e[i]={timescale:r,type:n,stsd:o},e[n]=k({timescale:r,id:i},o)):e[i]={timescale:r,type:t,stsd:o}}}}}return Pt(t,["moov","mvex","trex"]).forEach(t=>{const i=At(t,4),s=e[i];s&&(s.default={duration:At(t,12),sampleSize:At(t,16),flags:At(t,20)})}),e}function Ot(t){const e=t.subarray(8),i=e.subarray(86),s=yt(e.subarray(4,8));let r,n=s;const a="enca"===s||"encv"===s;if(a){const t=Pt(e,[s])[0];Pt(t.subarray("enca"===s?28:78),["sinf"]).forEach(t=>{const e=Pt(t,["schm"])[0];if(e){const i=yt(e.subarray(4,8));if("cbcs"===i||"cenc"===i){const e=Pt(t,["frma"])[0];e&&(n=yt(e))}}})}const o=n;switch(n){case"avc1":case"avc2":case"avc3":case"avc4":{const t=Pt(i,["avcC"])[0];t&&t.length>3&&(n+="."+$t(t[1])+$t(t[2])+$t(t[3]),r=Ft("avc1"===o?"dva1":"dvav",i));break}case"mp4a":{const t=Pt(e,[s])[0],i=Pt(t.subarray(28),["esds"])[0];if(i&&i.length>7){let t=4;if(3!==i[t++])break;t=Nt(i,t),t+=2;const e=i[t++];if(128&e&&(t+=2),64&e&&(t+=i[t++]),4!==i[t++])break;t=Nt(i,t);const s=i[t++];if(64!==s)break;if(n+="."+$t(s),t+=12,5!==i[t++])break;t=Nt(i,t);const r=i[t++];let a=(248&r)>>3;31===a&&(a+=1+((7&r)<<3)+((224&i[t])>>5)),n+="."+a}break}case"hvc1":case"hev1":{const t=Pt(i,["hvcC"])[0];if(t&&t.length>12){const e=t[1],i=["","A","B","C"][e>>6],s=31&e,r=At(t,2),a=(32&e)>>5?"H":"L",o=t[12],l=t.subarray(6,12);n+="."+i+s,n+="."+function(t){let e=0;for(let i=0;i<32;i++)e|=(t>>i&1)<<31-i;return e>>>0}(r).toString(16).toUpperCase(),n+="."+a+o;let h="";for(let t=l.length;t--;){const e=l[t];if(e||h){h="."+e.toString(16).toUpperCase()+h}}n+=h}r=Ft("hev1"==o?"dvhe":"dvh1",i);break}case"dvh1":case"dvhe":case"dvav":case"dva1":case"dav1":n=Ft(n,i)||n;break;case"vp09":{const t=Pt(i,["vpcC"])[0];if(t&&t.length>6){const e=t[4],i=t[5],s=t[6]>>4&15;n+="."+Bt(e)+"."+Bt(i)+"."+Bt(s)}break}case"av01":{const t=Pt(i,["av1C"])[0];if(t&&t.length>2){const e=t[1]>>>5,s=31&t[1],a=t[2]>>>7?"H":"M",o=(64&t[2])>>6,l=(32&t[2])>>5,h=2===e&&o?l?12:10:o?10:8,d=(16&t[2])>>4,c=(8&t[2])>>3,u=(4&t[2])>>2,f=3&t[2],g=1,m=1,p=1,v=0;n+="."+e+"."+Bt(s)+a+"."+Bt(h)+"."+d+"."+c+u+f+"."+Bt(g)+"."+Bt(m)+"."+Bt(p)+"."+v,r=Ft("dav1",i)}break}}return{codec:n,encrypted:a,supplemental:r}}function Ft(t,e){const i=Pt(e,["dvvC"]),s=i.length?i[0]:Pt(e,["dvcC"])[0];if(s){const e=s[2]>>1&127,i=s[2]<<5&32|s[3]>>3&31;return t+"."+Bt(e)+"."+Bt(i)}}function Nt(t,e){const i=e+5;for(;128&t[e++]&&e<i;);return e}function $t(t){return("0"+t.toString(16).toUpperCase()).slice(-2)}function Bt(t){return(t<10?"0":"")+t}function Ut(t,e){Pt(t,["moov","trak"]).forEach(t=>{const i=Pt(t,["mdia","minf","stbl","stsd"])[0];if(!i)return;const s=i.subarray(8);let r=Pt(s,["enca"]);const n=r.length>0;n||(r=Pt(s,["encv"])),r.forEach(t=>{Pt(n?t.subarray(28):t.subarray(78),["sinf"]).forEach(t=>{const i=Gt(t);i&&e(i,n)})})})}function Gt(t){const e=Pt(t,["schm"])[0];if(e){const i=yt(e.subarray(4,8));if("cbcs"===i||"cenc"===i){const e=Pt(t,["schi","tenc"])[0];if(e)return e}}}let Kt;function Vt(t){if("undefined"==typeof TextDecoder)return ot(t);return(Kt||(Kt=new TextDecoder("utf-8"))).decode(t).replace(/\0/g,"")}function jt(t,i,s,r,n){const a={};let o=!1;const l=function(t){const e=t.byteLength,i=[];for(let s=0;s<e;){const r=s+8<=e,n=s+4<=e?16777216*t[s]+(t[s+1]<<16|t[s+2]<<8|t[s+3]):At(t,s),a=n>1?s+n:e;if(r&&109===t[s+4]&&111===t[s+5]&&111===t[s+6]&&102===t[s+7]){const r=Math.min(a,e);for(let e=s+8;e<r;){const n=e+8<=r,a=e+4<=r?16777216*t[e]+(t[e+1]<<16|t[e+2]<<8|t[e+3]):At(t,e),o=a>1?e+a:r;if(n&&116===t[e+4]&&114===t[e+5]&&97===t[e+6]&&102===t[e+7]){const n=Math.min(o,r);let a,l;const h=[];for(let i=e+8;i<n;){const e=i+8<=n,s=i+4<=n?16777216*t[i]+(t[i+1]<<16|t[i+2]<<8|t[i+3]):At(t,i),r=s>1?i+s:n;if(e&&116===t[i+4]){const e=Math.min(r,n);102===t[i+5]&&104===t[i+6]&&100===t[i+7]?l||(l=t.subarray(i+8,e)):102===t[i+5]&&100===t[i+6]&&116===t[i+7]?a||(a=t.subarray(i+8,e)):114===t[i+5]&&117===t[i+6]&&110===t[i+7]&&h.push(t.subarray(i+8,e))}i=r}i.push({moofOffset:t.byteOffset+s,tfdt:a,tfhd:l,truns:h})}e=o}}s=a}return i}(t),h=t.byteLength;for(let u=0;u<l.length;u++){const{moofOffset:f,tfdt:g,tfhd:p,truns:v}=l[u],y=At(p,4),E=i[y];if(!E)continue;const T=a[y]||(a[y]={start:NaN,duration:0,sampleCount:0,trun:[],timescale:E.timescale,type:E.type});let S;if(g){const t=g[0];S=At(g,4),1===t&&(S===Et?s.warn("[mp4-demuxer]: Ignoring assumed invalid signed 64-bit track fragment decode time"):(S*=Et+1,S+=At(g,8))),e(S)&&(!e(T.start)||S<T.start)&&(T.start=S),n&&e(S)&&(n.timeOffset=S/n.timescale)}const b=(null==n?void 0:n.trackId)===y&&E.type===m,A=E.default,L=16777215&At(p,0);let I,R=(null==A?void 0:A.duration)||0,k=(null==A?void 0:A.sampleSize)||0,_=8;1&L&&(_+=8),2&L&&(_+=4),8&L&&(R=At(p,_),I=p.byteOffset-t.byteOffset+_,_+=4),16&L&&(k=At(p,_));let D=0;const w=!!(1&L),P=!w&&!!(131072&L);w?(D=At(p,8),D*=Math.pow(2,32),D+=At(p,12)):P&&(D=f);let C=S||0,x=0,M=R;for(let i=0;i<v.length;i++){const s=v[i],a=At(s,4),o=T.sampleCount;T.sampleCount+=a;const l=1&s[3];let u=0;const f=4&s[3],g=1&s[2],m=2&s[2],p=4&s[2],y=8&s[2];let E=8;if(l&&(u=Rt(s,E),E+=4),f){1&s[E+1]||void 0!==T.keyFrameIndex||(T.keyFrameIndex=o),E+=4}let S,A,L,_=D+u;if(!r&&0===s[1]&&6===s[2]&&1===s[3]){var d,c;const i=C,r=_,o=E;let l=-1,u=0,f=0,g=null!=(d=null==n?void 0:n.timeOffset)?d:0;const m=R/(null!=(c=null==n?void 0:n.timescale)?c:1),p=!0===(null==n?void 0:n.isHEVCFlavor),v=p?2:1;for(let e=0;e<a;e++){const i=0===s[E]?s[E+1]<<16|s[E+2]<<8|s[E+3]:At(s,E),r=-1===l&&void 0===T.keyFrameIndex&&!(1&s[E+5]);E+=8;const a=_+i;if(b){if(i>0){let e=_;do{const i=0===t[e]?t[e+1]<<16|t[e+2]<<8|t[e+3]:At(t,e);e+=4;const s=t[e],r=p?s>>1&63:31&s;(p?39===r||40===r:6===r)&&Wt(t.subarray(e,e+i),v,g,n.samples),e+=i}while(e<a)}g+=m}_=a,r&&(l=e,u=_)}if(_<=h)f=a;else{let t=r,e=o;for(let i=0;i<a;i++){if(t+=0===s[e]?s[e+1]<<16|s[e+2]<<8|s[e+3]:At(s,e),t>h)break;f=i+1,e+=8}}if(b&&(n.timeOffset=g),-1!==l&&u<=h&&void 0===T.keyFrameIndex&&(T.keyFrameIndex=l,T.keyFrameStart=i+l*R),f){(!e(T.ptsMin)||i<T.ptsMin)&&(T.ptsMin=i);const t=i+f*R;(!e(T.ptsMax)||t>T.ptsMax)&&(T.ptsMax=t)}const y=R*a;C=i+y,x+=y;continue}r&&(S=[],A={sampleOffset:_,samples:S,defaultSampleDurationOffset:I},_<=h&&T.trun.push(A));for(let i=0;i<a;i++){let a,o,l;g?(r&&(a=s.byteOffset-t.byteOffset+E),M=At(s,E),E+=4):M=R,m?(L=At(s,E),E+=4):L=k,p&&(l=1&s[E+1]?1:0,r&&(o={isNonSync:l,dependsOn:1==(3&s[E])?1:2}),E+=4);let d=0;if(y){d=0===s[0]?At(s,E):Rt(s,E),E+=4}if(b){let e=_,i=0;for(;i<L;){const s=At(t,e);e+=4,Yt(n.isHEVCFlavor,t[e])&&Wt(t.subarray(e,e+s),n.isHEVCFlavor?2:1,n.timeOffset+d/n.timescale,n.samples),e+=s,i+=s+4}n.timeOffset+=M/n.timescale}if(_+=L,_<=h){A&&void 0!==a&&(A.lastSampleDurationOffset=a),0===l&&void 0===T.keyFrameIndex&&(T.keyFrameIndex=i,T.keyFrameStart=C);const t=C+d;(!e(T.ptsMin)||t<T.ptsMin)&&(T.ptsMin=t),(!e(T.ptsMax)||t+M>T.ptsMax)&&(T.ptsMax=t+M),S&&(S[i]={cts:d,duration:M,flags:o,size:L})}C+=M,x+=M}!x&&R&&(x+=R*a)}T.duration+=x,T.duration&&(o=!0)}if(!o){let i=1/0,s=0;const r=Pt(t,["sidx"]);for(let t=0;t<r.length;t++){const e=xt(r[t]);if(null!=e&&e.references){i=Math.min(i,e.earliestPresentationTime/e.timescale);const t=e.references.reduce((t,e)=>t+e.info.duration||0,0);s=Math.max(s,t+e.earliestPresentationTime/e.timescale)}}s&&e(s)&&Object.keys(a).forEach(t=>{a[t].duration||(a[t].duration=s*a[t].timescale-a[t].start)})}return a}function Ht(t,e){const i=new Uint8Array(t.length+e.length);return i.set(t),i.set(e,t.length),i}function qt(t){if(!t)return!1;const e=t.substring(0,4);return"hvc1"===e||"hev1"===e||"dvh1"===e||"dvhe"===e}function Yt(t,e){if(t){const t=e>>1&63;return 39===t||40===t}return 6===(31&e)}function Wt(t,e,i,s){const r=zt(t);let n=0;n+=e;let a=0,o=0,l=0;for(;n<r.length;){a=0;do{if(n>=r.length)break;l=r[n++],a+=l}while(255===l);o=0;do{if(n>=r.length)break;l=r[n++],o+=l}while(255===l);const t=r.length-n;let e=n;if(o<t)n+=o;else if(o>t){q.error(`Malformed SEI payload. ${o} is too small, only ${t} bytes left to parse.`);break}if(4===a){if(181===r[e++]){const t=bt(r,e);if(e+=2,49===t){const t=At(r,e);if(e+=4,1195456820===t){const t=r[e++];if(3===t){const n=r[e++],o=64&n,l=o?2+3*(31&n):0,h=new Uint8Array(l);if(o){h[0]=n;for(let t=1;t<l;t++)h[t]=r[e++]}s.push({type:t,payloadType:a,pts:i,bytes:h})}}}}}else if(5===a&&o>16){const t=[];for(let i=0;i<16;i++){const s=r[e++].toString(16);t.push(1==s.length?"0"+s:s),3!==i&&5!==i&&7!==i&&9!==i||t.push("-")}const n=o-16,l=new Uint8Array(n);for(let t=0;t<n;t++)l[t]=r[e++];s.push({payloadType:a,pts:i,uuid:t.join(""),userData:Vt(l),userDataBytes:l})}}}function zt(t){const e=t.byteLength;let i,s=t.indexOf(3,3);for(;-1!==s;)0===t[s-1]&&0===t[s-2]&&(i||(i=[])).push(s),s=t.indexOf(3,s+1);if(!i)return t;const r=e-i.length,n=new Uint8Array(r);let a=0,o=0;for(let e=0;e<r;o++,e++)o===i[a]&&(o++,a++),n[e]=t[o];return n}function Xt(t,e,i){if(16!==t.byteLength)throw new RangeError("Invalid system id");let s,r,n;s=0,r=new Uint8Array,n=new Uint8Array;const a=new Uint8Array(4);return i.byteLength>0&&new DataView(a.buffer).setUint32(0,i.byteLength,!1),function(t,...e){const i=e.length;let s=8,r=i;for(;r--;)s+=e[r].byteLength;const n=new Uint8Array(s);for(n[0]=s>>24&255,n[1]=s>>16&255,n[2]=s>>8&255,n[3]=255&s,n.set(t,4),r=0,s=8;r<i;r++)n.set(e[r],s),s+=e[r].byteLength;return n}([112,115,115,104],new Uint8Array([0,0,0,0]),t,n,r,a,i)}function Qt(t){const e=[];if(t instanceof ArrayBuffer){const i=t.byteLength;let s=0;for(;s+32<i;){const i=Zt(new DataView(t,s));e.push(i),s+=i.size}}return e}function Zt(t){const e=t.getUint32(0),i=t.byteOffset,s=t.byteLength;if(s<e)return{offset:i,size:s};if(1886614376!==t.getUint32(4))return{offset:i,size:e};const r=t.getUint32(8)>>>24;if(0!==r&&1!==r)return{offset:i,size:e};const n=t.buffer,a=mt(new Uint8Array(n,i+12,16));let o=null,l=null,h=0;if(0===r)h=28;else{const r=t.getUint32(28);if(!r||s<32+16*r)return{offset:i,size:e};o=[];for(let t=0;t<r;t++)o.push(new Uint8Array(n,i+32+16*t,16));h=32+16*r}if(!h)return{offset:i,size:e};const d=t.getUint32(h);return e-32<d?{offset:i,size:e}:(l=new Uint8Array(n,i+h+4,d),0===r&&(o=function(t){const e=[];for(let i=0;i<t.length;){const s=t[i++],r=7&s;if(0===r){for(;128&t[i++];);continue}if(2!==r){i+=1===r?8:4;continue}let n=0;for(let e=0,s=128;128&s;e+=7)n|=(127&(s=t[i++]))<<e;if(s>>3==2)if(32===n){const s=new Uint8Array(16);for(let e=0;e<16;e++)s[e]=parseInt(String.fromCharCode(t[i+2*e],t[i+2*e+1]),16);e.push(s)}else 16===n&&e.push(t.subarray(i,i+16));i+=n}return e}(l)),{version:r,systemId:a,kids:o,data:l,offset:i,size:e})}const Jt=re("userAgent"),te=re("vendor");let ee,ie,se;function re(t){try{return navigator[t]||""}catch(t){}return""}function ne(){if(void 0===ee){const t=Jt.match(/Chrome\/(\d+)/i);ee=t?parseInt(t[1]):0}return ee}function ae(){return/\(Windows.+Firefox\//i.test(Jt)}const oe={audio:{a3ds:1,"ac-3":.95,"ac-4":1,alac:.9,alaw:1,dra1:1,"dts+":1,"dts-":1,dtsc:1,dtse:1,dtsh:1,"ec-3":.9,enca:1,fLaC:.9,flac:.9,FLAC:.9,g719:1,g726:1,m4ae:1,mha1:1,mha2:1,mhm1:1,mhm2:1,mlpa:1,mp4a:1,"raw ":1,Opus:1,opus:1,samr:1,sawb:1,sawp:1,sevc:1,sqcp:1,ssmv:1,twos:1,ulaw:1},video:{avc1:1,avc2:1,avc3:1,avc4:1,avcp:1,av01:.8,dav1:.8,drac:1,dva1:1,dvav:1,dvh1:.7,dvhe:.7,encv:1,hev1:.75,hvc1:.75,mjp2:1,mp4v:1,mvc1:1,mvc2:1,mvc3:1,mvc4:1,resv:1,rv60:1,s263:1,svc1:1,svc2:1,"vc-1":1,vp08:1,vp09:.9},text:{stpp:1,wvtt:1},image:{mjpg:1}};function le(t,e){const i=oe[e];return!!i&&!!i[t.slice(0,4)]}function he(t,e,i=!0){return!t.split(",").some(t=>!de(t,e,i))}function de(t,e,i=!0){var s;const r=Y(i);return null!=(s=null==r?void 0:r.isTypeSupported(ce(t,e)))&&s}function ce(t,e){return`${e}/mp4;codecs=${t}`}function ue(t){if(t){const e=t.substring(0,4);return oe.video[e]}return 2}function fe(t){const e=ae();return t.split(",").reduce((t,i)=>{const s=e&&qt(i)?9:oe.video[i];return s?(2*s+t)/(t?3:2):(oe.audio[i]+t)/(t?2:1)},0)}const ge={};const me=/flac|opus|mp4a\.40\.34/i;function pe(t,e=!0){return t.replace(me,t=>function(t,e=!0){if(ge[t])return ge[t];const i={flac:["flac","fLaC","FLAC"],opus:["opus","Opus"],"mp4a.40.34":["mp3"]}[t];for(let r=0;r<i.length;r++){var s;if(de(i[r],"audio",e))return ge[t]=i[r],i[r];if("mp3"===i[r]&&null!=(s=Y(e))&&s.isTypeSupported("audio/mpeg"))return""}return t}(t.toLowerCase(),e))}function ve(t,e){if(t&&(t.length>4||-1!==["ac-3","ec-3","alac","fLaC","Opus"].indexOf(t))&&(ye(t,"audio")||ye(t,"video")))return t;if(e){const i=e.split(",");if(i.length>1){if(t)for(let e=i.length;e--;)if(i[e].substring(0,4)===t.substring(0,4))return i[e];return i[0]}}return e||t}function ye(t,e){return le(t,e)&&de(t,e)}function Ee(t){if(t.startsWith("av01.")){const e=t.split("."),i=["0","111","01","01","01","0"];for(let t=e.length;t>4&&t<10;t++)e[t]=i[t-4];return e.join(".")}return t}function Te(t){const e=Y(t)||{isTypeSupported:()=>!1};return{mpeg:e.isTypeSupported("audio/mpeg"),mp3:e.isTypeSupported('audio/mp4; codecs="mp3"'),ac3:e.isTypeSupported('audio/mp4; codecs="ac-3"')}}function Se(t){return t.replace(/^.+codecs=["']?([^"']+).*$/,"$1")}const be={supported:!1,smooth:!1,powerEfficient:!1},Ae={supported:!0,configurations:[],decodingInfoResults:[{supported:!0,powerEfficient:!0,smooth:!0}]};function Le(t,e){return{supported:!1,configurations:e,decodingInfoResults:[be],error:t}}function Ie(t,i,s,r,n,a){const o=t.videoCodec,l=t.audioCodec?t.audioGroups:null,h=null==a?void 0:a.audioCodec,d=null==a?void 0:a.channels,c=d?parseInt(d):h?1/0:2;let u=null;if(null!=l&&l.length)try{u=1===l.length&&l[0]?i.groups[l[0]].channels:l.reduce((t,e)=>{if(e){const s=i.groups[e];if(!s)throw new Error(`Audio track group ${e} not found`);Object.keys(s.channels).forEach(e=>{t[e]=(t[e]||0)+s.channels[e]})}return t},{2:0})}catch(t){return!0}return void 0!==o&&(o.split(",").some(t=>qt(t))||t.width>1920&&t.height>1088||t.height>1920&&t.width>1088||t.frameRate>Math.max(r,30)||"SDR"!==t.videoRange&&t.videoRange!==s||t.bitrate>Math.max(n,8e6))||!!u&&e(c)&&Object.keys(u).some(t=>parseInt(t)>c)}function Re(t,e,i,s={}){const r=t.videoCodec;if(!r&&!t.audioCodec||!i)return Promise.resolve(Ae);const n=[],a=function(t){var e;const i=null==(e=t.videoCodec)?void 0:e.split(","),s=_e(t),r=t.width||640,n=t.height||480,a=t.frameRate||30,o=t.videoRange.toLowerCase();return i?i.map(t=>{const e={contentType:ce(Ee(t),"video"),width:r,height:n,bitrate:s,framerate:a};return"sdr"!==o&&(e.transferFunction=o),e}):[]}(t),o=a.length,l=function(t,e,i){var s;const r=null==(s=t.audioCodec)?void 0:s.split(","),n=_e(t);if(r&&t.audioGroups)return t.audioGroups.reduce((t,s)=>{var a;const o=s?null==(a=e.groups[s])?void 0:a.tracks:null;return o?o.reduce((t,e)=>{if(e.groupId===s){const s=parseFloat(e.channels||"");r.forEach(e=>{const r={contentType:ce(e,"audio"),bitrate:i?ke(e,n):n};s&&(r.channels=""+s),t.push(r)})}return t},t):t},[]);return[]}(t,e,o>0),h=l.length;for(let t=o||1*h||1;t--;){const e={type:"media-source"};if(o&&(e.video=a[t%o]),h){e.audio=l[t%h];const i=e.audio.bitrate;e.video&&i&&(e.video.bitrate-=i)}n.push(e)}if(r){const t=navigator.userAgent;if(r.split(",").some(t=>qt(t))&&ae())return Promise.resolve(Le(new Error(`Overriding Windows Firefox HEVC MediaCapabilities result based on user-agent string: (${t})`),n))}return Promise.all(n.map(t=>{const e=function(t){let e="";const{audio:i,video:s}=t;if(s){e+=`${Se(s.contentType)}_r${s.height}x${s.width}f${Math.ceil(s.framerate)}${s.transferFunction||"sd"}_${Math.ceil(s.bitrate/1e5)}`}if(i){e+=`${s?"_":""}${Se(i.contentType)}_c${i.channels}`}return e}(t);return s[e]||(s[e]=i.decodingInfo(t))})).then(t=>({supported:!t.some(t=>!t.supported),configurations:n,decodingInfoResults:t})).catch(t=>({supported:!1,configurations:n,decodingInfoResults:[],error:t}))}function ke(t,e){if(e<=1)return 1;let i=128e3;return"ec-3"===t?i=768e3:"ac-3"===t&&(i=64e4),Math.min(e/2,i)}function _e(t){return 1e3*Math.ceil(Math.max(.9*t.bitrate,t.averageBitrate)/1e3)||1}function De(t,e,i){const s=encodeURIComponent(e),r=`${s}=${encodeURIComponent(i)}`;let n=!1;const a=[];t.search.substring(1).split("&").forEach(t=>{t===s||t.startsWith(s+"=")?n||(a.push(r),n=!0):t&&a.push(t)}),n||a.push(r),t.search=a.join("&")}const we=["NONE","TYPE-0","TYPE-1",null];const Pe=["SDR","PQ","HLG"];var Ce="",xe="YES",Me="v2";function Oe(t){const{canSkipUntil:e,canSkipDateRanges:i,age:s}=t;return e&&s<e/2?i?Me:xe:Ce}class Fe{constructor(t,e,i){this.msn=void 0,this.part=void 0,this.skip=void 0,this.msn=t,this.part=e,this.skip=i}addDirectives(t){const e=new self.URL(t);return void 0!==this.msn&&De(e,"_HLS_msn",this.msn.toString()),void 0!==this.part&&De(e,"_HLS_part",this.part.toString()),this.skip&&De(e,"_HLS_skip",this.skip),e.href}}class Ne{constructor(t){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.imageCodec=void 0,this.iframes=void 0,this.details=void 0,this.fragmentError=0,this.loadError=0,this.loadErrorTime=0,this.loaded=void 0,this.realBitrate=0,this.supportedPromise=void 0,this.supportedResult=void 0,this._avgBitrate=0,this._audioGroups=void 0,this._subtitleGroups=void 0,this._urlId=0,this.url=[t.url],this._attrs=[t.attrs],this.bitrate=t.bitrate,t.details&&(this.details=t.details),this.id=t.id||0,this.name=t.name,this.width=t.width||0,this.height=t.height||0,this.frameRate=t.attrs.optionalFloat("FRAME-RATE",0),this._avgBitrate=t.attrs.decimalInteger("AVERAGE-BANDWIDTH"),this.audioCodec=t.audioCodec,this.videoCodec=t.videoCodec,"imageCodec"in t&&(this.imageCodec=t.imageCodec),this.codecSet=[t.videoCodec,t.audioCodec].filter(t=>!!t).map(t=>t.substring(0,4)).join(","),"supplemental"in t){var e;this.supplemental=t.supplemental;const i=null==(e=t.supplemental)?void 0:e.videoCodec;i&&i!==t.videoCodec&&(this.codecSet+=`,${i.substring(0,4)}`)}"iframes"in t&&t.iframes?this.iframes=!0:(this.addGroupId("audio",t.attrs.AUDIO),this.addGroupId("text",t.attrs.SUBTITLES))}get maxBitrate(){return Math.max(this.realBitrate,this.bitrate)}get averageBitrate(){return this._avgBitrate||this.realBitrate||this.bitrate}get attrs(){return this._attrs[0]}get codecs(){return this.attrs.CODECS||""}get pathwayId(){return this.attrs["PATHWAY-ID"]||"."}get videoRange(){return this.attrs["VIDEO-RANGE"]||"SDR"}get score(){return this.attrs.optionalFloat("SCORE",0)}get uri(){return this.url[0]||""}hasAudioGroup(t){return $e(this._audioGroups,t)}hasSubtitleGroup(t){return $e(this._subtitleGroups,t)}get audioGroups(){return this._audioGroups}get subtitleGroups(){return this._subtitleGroups}addGroupId(t,e){if(e)if("audio"===t){let t=this._audioGroups;t||(t=this._audioGroups=[]),-1===t.indexOf(e)&&t.push(e)}else if("text"===t){let t=this._subtitleGroups;t||(t=this._subtitleGroups=[]),-1===t.indexOf(e)&&t.push(e)}}get urlId(){return 0}set urlId(t){}get audioGroupIds(){return this.audioGroups?[this.audioGroupId]:void 0}get textGroupIds(){return this.subtitleGroups?[this.textGroupId]:void 0}get audioGroupId(){var t;return null==(t=this.audioGroups)?void 0:t[0]}get textGroupId(){var t;return null==(t=this.subtitleGroups)?void 0:t[0]}addFallback(){}}function $e(t,e){return!(!e||!t)&&-1!==t.indexOf(e)}function Be(t,e){let i=!1,s=[];if(t&&(i="SDR"!==t,s=[t]),e){s=e.allowedVideoRanges||Pe.slice(0);const t="SDR"!==s.join("")&&!e.videoCodec;i=void 0!==e.preferHDR?e.preferHDR:t&&function(){if("function"==typeof matchMedia){const t=matchMedia("(dynamic-range: high)"),e=matchMedia("bad query");if(t.media!==e.media)return!0===t.matches}return!1}(),i||(s=["SDR"])}return{preferHDR:i,allowedVideoRanges:s}}const Ue=(t,e)=>JSON.stringify(t,(t=>{const e=new WeakSet;return(i,s)=>{if(t&&(s=t(i,s)),"object"==typeof s&&null!==s){if(e.has(s))return;e.add(s)}return s}})(e));function Ge(t,e){q.log(`[abr] start candidates with "${t}" ignored because ${e}`)}function Ke(t){return t.reduce((t,e)=>{let i=t.groups[e.groupId];i||(i=t.groups[e.groupId]={tracks:[],channels:{2:0},hasDefault:!1,hasAutoSelect:!1}),i.tracks.push(e);const s=e.channels||"2";return i.channels[s]=(i.channels[s]||0)+1,i.hasDefault=i.hasDefault||e.default,i.hasAutoSelect=i.hasAutoSelect||e.autoselect,i.hasDefault&&(t.hasDefaultAudio=!0),i.hasAutoSelect&&(t.hasAutoSelectAudio=!0),t},{hasDefaultAudio:!1,hasAutoSelectAudio:!1,groups:{}})}function Ve(t){if(!t)return t;const{lang:e,assocLang:i,characteristics:s,channels:r,audioCodec:n}=t;return{lang:e,assocLang:i,characteristics:s,channels:r,audioCodec:n}}function je(t,e,i){if("attrs"in t){const i=e.indexOf(t);if(-1!==i)return i}for(let s=0;s<e.length;s++){if(He(t,e[s],i))return s}return-1}function He(t,e,i){const{groupId:s,name:r,lang:n,assocLang:a,default:o}=t,l=t.forced;return(void 0===s||e.groupId===s)&&(void 0===r||e.name===r)&&(void 0===n||function(t,e="--"){if(t.length===e.length)return t===e;return t.startsWith(e)||e.startsWith(t)}(n,e.lang))&&(void 0===a||e.assocLang===a)&&(void 0===o||e.default===o)&&(void 0===l||e.forced===l)&&(!("characteristics"in t)||function(t,e=""){const i=t.split(","),s=e.split(",");return i.length===s.length&&!i.some(t=>-1===s.indexOf(t))}(t.characteristics||"",e.characteristics))&&(void 0===i||i(t,e))}function qe(t,e){const{audioCodec:i,channels:s}=t;return!(void 0!==i&&(e.audioCodec||"").substring(0,4)!==i.substring(0,4)||void 0!==s&&s!==(e.channels||"2"))}function Ye(t,e,i){for(let s=e;s>-1;s--)if(i(t[s]))return s;for(let s=e+1;s<t.length;s++)if(i(t[s]))return s;return-1}function We(t,e){var i;return!!t&&t!==(null==(i=e.loadLevelObj)?void 0:i.uri)}function ze(t,e){return!e||-1!==e.indexOf(t)}function Xe(t,e){if(e||t){const i=I({},e);return t&&(t.videoCodec&&(i.videoCodec=t.videoCodec),t.videoRange&&(i.allowedVideoRanges=[t.videoRange])),i}}const Qe=function(t,e){let i=0,s=t.length-1,r=null,n=null;for(;i<=s;){r=(i+s)/2|0,n=t[r];const a=e(n);if(a>0)i=r+1;else{if(!(a<0))return n;s=r-1}}return null};function Ze(t,e,i=0,s=0,r=.005){let n=null;if(t){n=e[1+t.sn-e[0].sn]||null;const s=t.endDTS-i;s>0&&s<15e-7&&(i+=15e-7),n&&t.level!==n.level&&n.end<=t.end&&(n=e[2+t.sn-e[0].sn]||null)}else 0===i&&0===e[0].start&&(n=e[0]);if(n&&((!t||t.level===n.level)&&0===Je(i,s,n)||function(t,e,i){if(0===(null==e?void 0:e.start)&&e.level<t.level&&(e.endPTS||0)>0){const s=e.tagList.reduce((t,e)=>("INF"===e[0]&&(t+=parseFloat(e[1])),t),i);return t.start<=s}return!1}(n,t,Math.min(r,s))))return n;const a=Qe(e,Je.bind(null,i,s));return!a||a===t&&n?n:a}function Je(t=0,e=0,i){if(i.start<=t&&i.start+i.duration>t)return 0;const s=Math.min(e,i.duration+(i.deltaPTS?i.deltaPTS:0));return i.start+i.duration-s<=t?1:i.start-s>t&&i.start?-1:0}function ti(t,e,i){const s=1e3*Math.min(e,i.duration+(i.deltaPTS?i.deltaPTS:0));return(i.endProgramDateTime||0)-s>t}function ei(t,e,i){if(t&&t.startCC<=e&&t.endCC>=e){let s=t.fragments;const{fragmentHint:r}=t;let n;return r&&(s=s.concat(r)),Qe(s,t=>t.cc<e?1:t.cc>e?-1:(n=t,t.end<=i?1:t.start>i?-1:0)),n||null}return null}function ii(t,e){return e===t.endSN&&t.fragmentHint?t.fragmentHint:t.fragments[1+e-t.startSN]||null}var si=0,ri=2,ni=3,ai=5,oi=0,li=1,hi=2,di=4,ci=8,ui=16;function fi(t){const e=t.details;return e===n.BUFFER_ADD_CODEC_ERROR||e===n.MEDIA_SOURCE_REQUIRES_RESET||e===n.BUFFER_APPEND_ERROR&&!gi(t)}function gi(t){return t.details===n.BUFFER_APPEND_ERROR&&("QuotaExceededError"===t.error.name||"InvalidStateError"===t.error.name)}function mi(t){const e={action:si,flags:oi};return t&&(e.resolved=!0),e}var pi="NOT_LOADED",vi="APPENDING",yi="PARTIAL",Ei="OK";class Ti{constructor(t){this.activePartLists=Object.create(null),this.endListFragments=Object.create(null),this.fragments=Object.create(null),this.timeRanges=Object.create(null),this.bufferPadding=.2,this.hls=void 0,this.hasGaps=!1,this.hls=t,this._registerListeners()}_registerListeners(){const{hls:t}=this;t&&(t.on(a.MANIFEST_LOADING,this.onManifestLoading,this),t.on(a.BUFFER_APPENDED,this.onBufferAppended,this),t.on(a.FRAG_BUFFERED,this.onFragBuffered,this),t.on(a.FRAG_LOADED,this.onFragLoaded,this))}_unregisterListeners(){const{hls:t}=this;t&&(t.off(a.MANIFEST_LOADING,this.onManifestLoading,this),t.off(a.BUFFER_APPENDED,this.onBufferAppended,this),t.off(a.FRAG_BUFFERED,this.onFragBuffered,this),t.off(a.FRAG_LOADED,this.onFragLoaded,this))}destroy(){this._unregisterListeners(),this.hls=this.fragments=this.activePartLists=this.endListFragments=this.timeRanges=null}getAppendedFrag(t,e){const i=this.activePartLists[e];if(i)for(let e=i.length;e--;){const s=i[e];if(!s)break;if(s.start<=t&&t<=s.end&&s.loaded)return s}return this.getBufferedFrag(t,e)}getBufferedFrag(t,e){return this.getFragAtPos(t,e,!0)}getFragAtPos(t,e,i){const{fragments:s}=this,r=Object.keys(s);for(let n=r.length;n--;){const a=s[r[n]];if((null==a?void 0:a.body.type)===e&&(!i||a.buffered)){const e=a.body;if(e.start<=t&&t<=e.end)return e}}return null}detectEvictedFragments(t,e,i,s,r,n){this.timeRanges&&(this.timeRanges[t]=e);const o=(null==r?void 0:r.fragment.sn)||-1;Object.keys(this.fragments).forEach(r=>{const l=this.fragments[r];if(!l||!this.hls)return;const h=l.body;if(o>=h.sn)return;if(!l.buffered&&(!l.loaded||n))return void(h.type===i&&this.removeFragment(h));const d=l.range[t];if(d)if(0!==d.time.length){if(d.time.some(t=>{const i=!this.isTimeBuffered(t.startPTS,t.endPTS,e);return i&&this.removeFragment(h),i}),s&&s!==h&&ne()){const t=s.endPTS,e=h.startPTS;if(t&&e&&l.range.video){const i=e-t;i<0&&i>-.1&&(this.removeFragment(h),this.hls.trigger(a.BUFFER_FLUSHING,{startOffset:t+.004,endOffset:1/0,type:"video"}))}}}else this.removeFragment(h)})}detectPartialFragments(t){const e=this.timeRanges,{frag:i,part:s,id:r}=t;if(!e||!y(i))return;const n=bi(i),a=this.fragments[n];if(!a||a.buffered&&i.gap)return;const o=!i.relurl;Object.keys(e).forEach(t=>{const n=i.elementaryStreams[t];if(!n)return;const l=e[t],h=o||!0===n.partial;a.range[t]=this.getBufferedTimes(i,s,h,l),this.detectEvictedFragments(t,l,r,i,s)}),a.loaded=null;const l=Object.keys(a.range);if(l.length){if(this.bufferedEnd(a,i),Si(a)||this.removeParts(i.sn-1,i.type),!s){const t=Math.min(.004,i.duration);l.some(e=>{var s;const r=null==(s=a.range[e])?void 0:s.time,n=0===r.length||1===r.length&&r[0].endPTS-r[0].startPTS<t;return n&&this.addAsGap(i),n})}}else this.removeFragment(i)}addAsGap(t){t.gap=!0,this.removeFragment(t),this.fragBuffered(t,!0)}bufferedEnd(t,e){t.buffered=!0;(t.body.endList=e.endList||t.body.endList)&&!e.gap&&(this.endListFragments[t.body.type]=t)}removeParts(t,e){const i=this.activePartLists[e];i&&(this.activePartLists[e]=Ai(i,e=>e.fragment.sn>=t))}fragBuffered(t,e){const i=bi(t);let s=this.fragments[i];return!s&&e&&(s=this.fragments[i]={body:t,appendedPTS:null,loaded:null,buffered:!1,range:Object.create(null)},t.gap&&(this.hasGaps=!0)),s&&(s.loaded=null,this.bufferedEnd(s,t)),s}getBufferedTimes(t,e,i,s){const r={time:[],partial:i},n=t.start,a=t.end,o=t.minEndPTS||a,l=t.maxStartPTS||n;for(let t=0;t<s.length;t++){const e=s.start(t)-this.bufferPadding,i=s.end(t)+this.bufferPadding;if(l>=e&&o<=i){r.time.push({startPTS:Math.max(n,s.start(t)),endPTS:Math.min(a,s.end(t))});break}if(n<i&&a>e){const e=Math.max(n,s.start(t)),i=Math.min(a,s.end(t));i>e&&(r.partial=!0,r.time.push({startPTS:e,endPTS:i}))}else if(a<=e)break}return r}getPartialFragment(t){let e,i,s,r=null,n=0;const{bufferPadding:a,fragments:o}=this;return Object.keys(o).forEach(l=>{const h=o[l];h&&Si(h)&&(i=h.body.start-a,s=h.body.end+a,t>=i&&t<=s&&(e=Math.min(t-i,s-t),n<=e&&(r=h.body,n=e)))}),r}isEndListAppended(t){const e=this.endListFragments[t];return void 0!==e&&(e.buffered||Si(e))}getState(t){const e=bi(t),i=this.fragments[e];return i?i.buffered?Si(i)?yi:Ei:vi:pi}isTimeBuffered(t,e,i){let s,r;for(let n=0;n<i.length;n++){if(s=i.start(n)-this.bufferPadding,r=i.end(n)+this.bufferPadding,t>=s&&e<=r)return!0;if(e<=s)return!1}return!1}onManifestLoading(){this.removeAllFragments()}onFragLoaded(t,e){if(!y(e.frag)||e.frag.bitrateTest)return;const i=e.frag,s=e.part?null:e,r=bi(i);this.fragments[r]={body:i,appendedPTS:null,loaded:s,buffered:!1,range:Object.create(null)}}onBufferAppended(t,e){const{frag:i,part:s,timeRanges:r}=e;if(!y(i))return;const n=i.type;if(s){let t=this.activePartLists[n];t||(this.activePartLists[n]=t=[]),t.push(s)}this.timeRanges=r}onFragBuffered(t,e){this.detectPartialFragments(e)}hasFragment(t){const e=bi(t);return!!this.fragments[e]}hasFragments(t){const{fragments:e}=this,i=Object.keys(e);if(!t)return i.length>0;for(let s=i.length;s--;){const r=e[i[s]];if((null==r?void 0:r.body.type)===t)return!0}return!1}hasParts(t){var e;return!(null==(e=this.activePartLists[t])||!e.length)}getBackBufferEvictionEnd(t,e,i){const{fragments:s}=this;let r=0,n=0;const a=Object.keys(s);for(let o=0;o<a.length;o++){const l=s[a[o]];if(!l||!l.buffered||l.body.type!==e)continue;const h=l.body;if(h.gap)return 0;const d=h.hasStats&&h.stats.loaded||h.byteLength||h.bitrate&&8*h.bitrate*h.duration;if(h.end<=t&&d&&(r+=d,n=Math.max(n,h.end),r>=i))return n}return n>0?n:0}removeFragmentsInRange(t,e,i,s,r){s&&!this.hasGaps||Object.keys(this.fragments).forEach(n=>{const a=this.fragments[n];if(!a)return;const o=a.body;o.type!==i||s&&!o.gap||o.start<e&&o.end>t&&(a.buffered||r)&&this.removeFragment(o)})}removeFragment(t){const e=bi(t);t.clearElementaryStreamInfo();const i=this.activePartLists[t.type];if(i){const e=t.sn;this.activePartLists[t.type]=Ai(i,t=>t.fragment.sn!==e)}delete this.fragments[e],t.endList&&delete this.endListFragments[t.type]}removeAllFragments(){var t;this.fragments=Object.create(null),this.endListFragments=Object.create(null),this.activePartLists=Object.create(null),this.hasGaps=!1;const e=null==(t=this.hls)||null==(t=t.latestLevelDetails)?void 0:t.partList;e&&e.forEach(t=>t.clearElementaryStreamInfo())}}function Si(t){var e,i,s,r;return t.buffered&&!!(t.body.gap||null!=(e=t.range.video)&&e.partial||null!=(i=t.range.audio)&&i.partial||null!=(s=t.range.audiovideo)&&s.partial||null!=(r=t.range.subs)&&r.partial)}function bi(t){return`${t.type}_${t.level}_${t.sn}`}function Ai(t,e){return t.filter(t=>{const i=e(t);return i||t.clearElementaryStreamInfo(),i})}var Li=0,Ii=1;class Ri{constructor(t,e,i){this.subtle=void 0,this.aesIV=void 0,this.aesMode=void 0,this.subtle=t,this.aesIV=e,this.aesMode=i}decrypt(t,e){switch(this.aesMode){case Li:return this.subtle.decrypt({name:"AES-CBC",iv:this.aesIV},e,t);case Ii:return this.subtle.decrypt({name:"AES-CTR",counter:this.aesIV,length:64},e,t);default:throw new Error(`[AESCrypto] invalid aes mode ${this.aesMode}`)}}}class ki{constructor(){this.rcon=[0,1,2,4,8,16,32,64,128,27,54],this.subMix=[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)],this.invSubMix=[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)],this.sBox=new Uint32Array(256),this.invSBox=new Uint32Array(256),this.key=new Uint32Array(0),this.ksRows=0,this.keySize=0,this.keySchedule=void 0,this.invKeySchedule=void 0,this.initTable()}uint8ArrayToUint32Array_(t){const e=new DataView(t),i=new Uint32Array(4);for(let t=0;t<4;t++)i[t]=e.getUint32(4*t);return i}initTable(){const t=this.sBox,e=this.invSBox,i=this.subMix,s=i[0],r=i[1],n=i[2],a=i[3],o=this.invSubMix,l=o[0],h=o[1],d=o[2],c=o[3],u=new Uint32Array(256);let f=0,g=0,m=0;for(m=0;m<256;m++)u[m]=m<128?m<<1:m<<1^283;for(m=0;m<256;m++){let i=g^g<<1^g<<2^g<<3^g<<4;i=i>>>8^255&i^99,t[f]=i,e[i]=f;const o=u[f],m=u[o],p=u[m];let v=257*u[i]^16843008*i;s[f]=v<<24|v>>>8,r[f]=v<<16|v>>>16,n[f]=v<<8|v>>>24,a[f]=v,v=16843009*p^65537*m^257*o^16843008*f,l[i]=v<<24|v>>>8,h[i]=v<<16|v>>>16,d[i]=v<<8|v>>>24,c[i]=v,f?(f=o^u[u[u[p^o]]],g^=u[u[g]]):f=g=1}}expandKey(t){const e=this.uint8ArrayToUint32Array_(t);let i=!0,s=0;for(;s<e.length&&i;)i=e[s]===this.key[s],s++;if(i)return;this.key=e;const r=this.keySize=e.length;if(4!==r&&6!==r&&8!==r)throw new Error("Invalid aes key size="+r);const n=this.ksRows=4*(r+6+1);let a,o;const l=this.keySchedule=new Uint32Array(n),h=this.invKeySchedule=new Uint32Array(n),d=this.sBox,c=this.rcon,u=this.invSubMix,f=u[0],g=u[1],m=u[2],p=u[3];let v,y;for(a=0;a<n;a++)a<r?v=l[a]=e[a]:(y=v,a%r===0?(y=y<<8|y>>>24,y=d[y>>>24]<<24|d[y>>>16&255]<<16|d[y>>>8&255]<<8|d[255&y],y^=c[a/r|0]<<24):r>6&&a%r===4&&(y=d[y>>>24]<<24|d[y>>>16&255]<<16|d[y>>>8&255]<<8|d[255&y]),l[a]=v=(l[a-r]^y)>>>0);for(o=0;o<n;o++)a=n-o,y=3&o?l[a]:l[a-4],h[o]=o<4||a<=4?y:f[d[y>>>24]]^g[d[y>>>16&255]]^m[d[y>>>8&255]]^p[d[255&y]],h[o]=h[o]>>>0}networkToHostOrderSwap(t){return t<<24|(65280&t)<<8|(16711680&t)>>8|t>>>24}decrypt(t,e,i){const s=this.keySize+6,r=this.invKeySchedule,n=this.invSBox,a=this.invSubMix,o=a[0],l=a[1],h=a[2],d=a[3],c=this.uint8ArrayToUint32Array_(i);let u=c[0],f=c[1],g=c[2],m=c[3];const p=new Int32Array(t),v=new Int32Array(p.length);let y,E,T,S,b,A,L,I,R,k,_,D,w,P;const C=this.networkToHostOrderSwap;for(;e<p.length;){for(R=C(p[e]),k=C(p[e+1]),_=C(p[e+2]),D=C(p[e+3]),b=R^r[0],A=D^r[1],L=_^r[2],I=k^r[3],w=4,P=1;P<s;P++)y=o[b>>>24]^l[A>>16&255]^h[L>>8&255]^d[255&I]^r[w],E=o[A>>>24]^l[L>>16&255]^h[I>>8&255]^d[255&b]^r[w+1],T=o[L>>>24]^l[I>>16&255]^h[b>>8&255]^d[255&A]^r[w+2],S=o[I>>>24]^l[b>>16&255]^h[A>>8&255]^d[255&L]^r[w+3],b=y,A=E,L=T,I=S,w+=4;y=n[b>>>24]<<24^n[A>>16&255]<<16^n[L>>8&255]<<8^n[255&I]^r[w],E=n[A>>>24]<<24^n[L>>16&255]<<16^n[I>>8&255]<<8^n[255&b]^r[w+1],T=n[L>>>24]<<24^n[I>>16&255]<<16^n[b>>8&255]<<8^n[255&A]^r[w+2],S=n[I>>>24]<<24^n[b>>16&255]<<16^n[A>>8&255]<<8^n[255&L]^r[w+3],v[e]=C(y^u),v[e+1]=C(S^f),v[e+2]=C(T^g),v[e+3]=C(E^m),u=R,f=k,g=_,m=D,e+=4}return v.buffer}}class _i{constructor(t,e,i){this.subtle=void 0,this.key=void 0,this.aesMode=void 0,this.subtle=t,this.key=e,this.aesMode=i}expandKey(){const t=function(t){switch(t){case Li:return"AES-CBC";case Ii:return"AES-CTR";default:throw new Error(`[FastAESKey] invalid aes mode ${t}`)}}(this.aesMode);return this.subtle.importKey("raw",this.key,{name:t},!1,["encrypt","decrypt"])}}class Di{constructor(t,e){if(this.logEnabled=!0,this.decryptRange=void 0,this.subtle=null,this.softwareDecrypter=null,this.key=null,this.fastAesKey=null,this.remainderData=null,this.currentIV=null,this.currentResult=null,this.useSoftware=void 0,this.enableSoftwareAES=void 0,this.enableSoftwareAES=t.enableSoftwareAES,!0!==e)try{const t=self.crypto;t&&(this.subtle=t.subtle||t.webkitSubtle)}catch(t){}this.useSoftware=!this.subtle}destroy(){this.subtle=null,this.softwareDecrypter=null,this.key=null,this.fastAesKey=null,this.remainderData=null,this.currentIV=null,this.currentResult=null}isSync(){return this.useSoftware}flush(){const{currentResult:t,remainderData:e}=this;if(!t||e)return this.reset(),null;const i=new Uint8Array(t);this.reset();const s=this.decryptRange;return s?0===s.start&&s.end>=i.length?i:i.slice(s.start,s.end):function(t){const e=t.byteLength,i=e&&new DataView(t.buffer).getUint8(e-1);return i?t.slice(0,e-i):t}(i)}reset(){this.currentResult=null,this.currentIV=null,this.remainderData=null,this.softwareDecrypter&&(this.softwareDecrypter=null)}decrypt(t,e,i,s,r){return this.decryptRange=r,this.useSoftware||r?new Promise((r,n)=>{const a=ArrayBuffer.isView(t)?t:new Uint8Array(t);this.softwareDecrypt(a,e,i,s);const o=this.flush();o?r(o.buffer):n(new Error("[softwareDecrypt] Failed to decrypt data"))}):this.webCryptoDecrypt(new Uint8Array(t),e,i,s)}softwareDecrypt(t,e,i,s){const{currentIV:r,currentResult:n,remainderData:a}=this;if(s!==Li||16!==e.byteLength)return q.warn("SoftwareDecrypt: can only handle AES-128-CBC"),null;this.logOnce("JS AES decrypt"),a&&(t=Ht(a,t),this.remainderData=null);const o=this.getValidChunk(t);if(!o.length)return null;r&&(i=r);let l=this.softwareDecrypter;l||(l=this.softwareDecrypter=new ki),l.expandKey(e);const h=n;return this.currentResult=l.decrypt(o.buffer,0,i),this.currentIV=o.slice(-16).buffer,h||null}webCryptoDecrypt(t,e,i,s){if(this.key!==e||!this.fastAesKey){if(!this.subtle)return Promise.resolve(this.onWebCryptoError(t,e,i,s));this.key=e,this.fastAesKey=new _i(this.subtle,e,s)}return this.fastAesKey.expandKey().then(e=>{if(!this.subtle)return Promise.reject(new Error("web crypto not initialized"));this.logOnce("WebCrypto AES decrypt");return new Ri(this.subtle,new Uint8Array(i),s).decrypt(t.buffer,e)}).catch(r=>(q.warn(`[decrypter]: WebCrypto Error, disable WebCrypto API, ${r.name}: ${r.message}`),this.onWebCryptoError(t,e,i,s)))}onWebCryptoError(t,e,i,s){const r=this.enableSoftwareAES;if(r){this.useSoftware=!0,this.logEnabled=!0,this.softwareDecrypt(t,e,i,s);const r=this.flush();if(r)return r.buffer}throw new Error("WebCrypto"+(r?" and softwareDecrypt":"")+": failed to decrypt data")}getValidChunk(t){let e=t;const i=t.length-t.length%16;return i!==t.length&&(e=t.slice(0,i),this.remainderData=t.slice(i)),e}logOnce(t){this.logEnabled&&(q.log(`[decrypter]: ${t}`),this.logEnabled=!1)}}const wi=Math.pow(2,17);class Pi{constructor(t){this.config=void 0,this.loader=null,this.partLoadTimeout=-1,this.config=t}destroy(){this.loader&&(this.loader.destroy(),this.loader=null)}abort(){this.loader&&this.loader.abort()}load(t,e,i,s){const a=t.url;if(!a)return Promise.reject(new Oi({type:r.NETWORK_ERROR,details:n.FRAG_LOAD_ERROR,fatal:!1,frag:t,error:new Error("Fragment does not have a "+(a?"part list":"url")),networkDetails:null}));this.abort();const o=this.config,l=o.fLoader,h=o.loader;return new Promise((d,c)=>{if(this.loader&&this.loader.destroy(),t.gap){if(t.tagList.some(t=>"GAP"===t[0]))return void c(Mi(t));t.gap=!1}const u=this.loader=l?new l(o):new h(o),f=Ci(t,null,e);t.loader=u;const g=M(o.fragLoadPolicy.default),m={loadPolicy:g,timeout:g.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:"initSegment"===t.sn?1/0:wi};u.stats.retry=t.stats.retry,t.stats=u.stats;const p={onSuccess:(e,i,s,r)=>{this.resetLoader(t,u);let n=e.data;s.resetIV&&t.decryptdata&&(t.decryptdata.iv=new Uint8Array(n.slice(0,16)),n=n.slice(16)),d({frag:t,part:null,payload:n,networkDetails:r})},onError:(e,i,s,o)=>{this.resetLoader(t,u),c(new Oi({type:r.NETWORK_ERROR,details:n.FRAG_LOAD_ERROR,fatal:!1,frag:t,response:k({url:a,data:void 0},e),error:new Error(`HTTP Error ${e.code} ${e.text}`),networkDetails:s,stats:o}))},onAbort:(e,i,s)=>{this.resetLoader(t,u),c(new Oi({type:r.NETWORK_ERROR,details:n.INTERNAL_ABORTED,fatal:!1,frag:t,error:new Error("Aborted"),networkDetails:s,stats:e}))},onTimeout:(e,i,s)=>{this.resetLoader(t,u),c(new Oi({type:r.NETWORK_ERROR,details:n.FRAG_LOAD_TIMEOUT,fatal:!1,frag:t,error:new Error(`Timeout after ${m.timeout}ms`),networkDetails:s,stats:e}))}};if(i){const e=this.gateProgress(i,s);p.onProgress=(i,s,r,n)=>e({frag:t,part:null,payload:r,networkDetails:n})}u.load(f,m,p)})}gateProgress(t,e){let i=t;if(e){const s=[];let r=!1;e.then(()=>{r=!0,s.forEach(e=>t(e)),s.length=0}).catch(()=>{}),i=e=>{r?t(e):s.push(e)}}return i}loadPart(t,e,i){this.abort();const s=this.config,a=s.fLoader,o=s.loader;return new Promise((l,h)=>{if(this.loader&&this.loader.destroy(),t.gap||e.gap)return void h(Mi(t,e));const d=this.loader=a?new a(s):new o(s),c=Ci(t,e);t.loader=d;const u=M(s.fragLoadPolicy.default),f={loadPolicy:u,timeout:u.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:wi};e.stats=d.stats,d.load(c,f,{onSuccess:(s,r,n,a)=>{this.resetLoader(t,d),this.updateStatsFromPart(t,e);const o={frag:t,part:e,payload:s.data,networkDetails:a};i(o),l(o)},onError:(i,s,a,o)=>{this.resetLoader(t,d),h(new Oi({type:r.NETWORK_ERROR,details:n.FRAG_LOAD_ERROR,fatal:!1,frag:t,part:e,response:k({url:c.url,data:void 0},i),error:new Error(`HTTP Error ${i.code} ${i.text}`),networkDetails:a,stats:o}))},onAbort:(i,s,a)=>{t.stats.aborted=e.stats.aborted,this.resetLoader(t,d),h(new Oi({type:r.NETWORK_ERROR,details:n.INTERNAL_ABORTED,fatal:!1,frag:t,part:e,error:new Error("Aborted"),networkDetails:a,stats:i}))},onTimeout:(i,s,a)=>{this.resetLoader(t,d),h(new Oi({type:r.NETWORK_ERROR,details:n.FRAG_LOAD_TIMEOUT,fatal:!1,frag:t,part:e,error:new Error(`Timeout after ${f.timeout}ms`),networkDetails:a,stats:i}))}})})}updateStatsFromPart(t,e){const i=t.stats,s=e.stats,r=s.total;if(i.loaded+=s.loaded,r){const s=Math.round(t.duration/e.duration),n=Math.min(Math.round(i.loaded/r),s),a=(s-n)*Math.round(i.loaded/n);i.total=i.loaded+a}else i.total=Math.max(i.loaded,i.total);const n=i.loading,a=s.loading;n.start?n.first+=a.first-a.start:(n.start=a.start,n.first=a.first),n.end=a.end}resetLoader(t,e){t.loader=null,t.url=null,this.loader===e&&(self.clearTimeout(this.partLoadTimeout),this.loader=null),e.destroy()}}function Ci(t,e=null,i){const s=e||t,r={type:u.MEDIA_FRAGMENT,frag:t,part:e,responseType:"arraybuffer",url:s.url,headers:{},rangeStart:0,rangeEnd:0},n=xi(t,e,i);return n.resetIV&&(r.resetIV=!0),n.byteRange&&(r.rangeStart=n.byteRange.start,r.rangeEnd=n.byteRange.end),r}function xi(t,i=null,s){const r={},n=i||t,a=n.byteRangeStartOffset,o=n.byteRangeEndOffset;var l,h;if(e(a)&&e(o))if("initSegment"!==t.sn&&!s||"AES-128"!==(h=null==(l=t.decryptdata)?void 0:l.method)&&"AES-256"!==h)r.byteRange={start:a,end:o};else{let t=16*Math.floor(a/16);const e=16*Math.ceil(o/16);r.decryptRange={start:a-t,end:o-t},t>=16&&(r.resetIV=!0,t-=16),r.byteRange={start:t,end:e}}return r}function Mi(t,e){const i=new Error(`GAP ${t.gap?"tag":"attribute"} found`),s={type:r.MEDIA_ERROR,details:n.FRAG_GAP,fatal:!1,frag:t,error:i,networkDetails:null};return e&&(s.part=e),(e||t).stats.aborted=!0,new Oi(s)}class Oi extends Error{constructor(t){super(t.error.message),this.data=void 0,this.data=t}}class Fi extends U{constructor(t,e){super(t,e),this._boundTick=void 0,this._tickTimer=null,this._tickInterval=null,this._tickCallCount=0,this._boundTick=this.tick.bind(this)}destroy(){this.onHandlerDestroying(),this.onHandlerDestroyed()}onHandlerDestroying(){this.clearNextTick(),this.clearInterval()}onHandlerDestroyed(){}hasInterval(){return!!this._tickInterval}hasNextTick(){return!!this._tickTimer}setInterval(t){return!this._tickInterval&&(this._tickCallCount=0,this._tickInterval=self.setInterval(this._boundTick,t),!0)}clearInterval(){return!!this._tickInterval&&(self.clearInterval(this._tickInterval),this._tickInterval=null,!0)}clearNextTick(){return!!this._tickTimer&&(self.clearTimeout(this._tickTimer),this._tickTimer=null,!0)}tick(){this._tickCallCount++,1===this._tickCallCount?(this.doTick(),this._tickCallCount>1&&this.tickImmediate(),this._tickCallCount=0):(this.log(`possible exception thrown in task-loop (${this.constructor.name}.doTick)`),this._tickCallCount=0)}tickImmediate(){this.clearNextTick(),this._tickTimer=self.setTimeout(this._boundTick,0)}doTick(){}}class Ni{constructor(t,e,i,s=0,r=-1,n=!1,a,o,l){this.level=void 0,this.sn=void 0,this.part=void 0,this.id=void 0,this.size=void 0,this.partial=void 0,this.iframe=void 0,this.duration=void 0,this.decryptRange=void 0,this.transmuxing={start:0,executeStart:0,executeEnd:0,end:0},this.buffering={audio:{start:0,executeStart:0,executeEnd:0,end:0},video:{start:0,executeStart:0,executeEnd:0,end:0},audiovideo:{start:0,executeStart:0,executeEnd:0,end:0}},this.level=t,this.sn=e,this.id=i,this.size=s,this.part=r,this.partial=n,this.duration=a||0,this.decryptRange=l,this.iframe=o||!1}}const $i={length:0,start:()=>0,end:()=>0};class Bi{static isBuffered(t,e){if(t){const i=Bi.getBuffered(t);for(let t=i.length;t--;)if(e>=i.start(t)&&e<=i.end(t))return!0}return!1}static bufferedRanges(t){if(t){const e=Bi.getBuffered(t);return Bi.timeRangesToArray(e)}return[]}static timeRangesToArray(t){const e=[];for(let i=0;i<t.length;i++)e.push({start:t.start(i),end:t.end(i)});return e}static bufferInfo(t,e,i){if(t){const s=Bi.bufferedRanges(t);if(s.length)return Bi.bufferedInfo(s,e,i)}return{len:0,start:e,end:e,bufferedIndex:-1}}static bufferedInfo(t,e,i){e=Math.max(0,e),t.length>1&&t.sort((t,e)=>t.start-e.start||e.end-t.end);let s=-1,r=[];if(i)for(let n=0;n<t.length;n++){e>=t[n].start&&e<=t[n].end&&(s=n);const a=r.length;if(a){const e=r[a-1].end;t[n].start-e<i?t[n].end>e&&(r[a-1].end=t[n].end):r.push(t[n])}else r.push(t[n])}else r=t;let n,a=0,o=e,l=e;for(let t=0;t<r.length;t++){const h=r[t].start,d=r[t].end;if(-1===s&&e>=h&&e<=d&&(s=t),e+i>=h&&e<d)o=h,l=d,a=l-e;else if(e+i<h){n=h;break}}return{len:a,start:o||0,end:l||0,nextStart:n,buffered:t,bufferedIndex:s}}static getBuffered(t){try{return t.buffered||$i}catch(t){return q.log("failed to get media.buffered",t),$i}}}const Ui=/\{\$([a-zA-Z0-9-_]+)\}/g;function Gi(t){return Ui.lastIndex=0,Ui.test(t)}function Ki(t,e){if(null!==t.variableList||t.hasVariableRefs){const i=t.variableList;return e.replace(Ui,e=>{const s=e.substring(2,e.length-1),r=null==i?void 0:i[s];return void 0===r?(t.playlistParsingError||(t.playlistParsingError=new Error(`Missing preceding EXT-X-DEFINE tag for Variable Reference: "${s}"`)),e):r})}return e}function Vi(t,e,i){let s,r,n=t.variableList;if(n||(t.variableList=n={}),"QUERYPARAM"in e){s=e.QUERYPARAM;try{const t=new self.URL(i).searchParams;if(!t.has(s))throw new Error(`"${s}" does not match any query parameter in URI: "${i}"`);r=t.get(s)}catch(e){t.playlistParsingError||(t.playlistParsingError=new Error(`EXT-X-DEFINE QUERYPARAM: ${e.message}`))}}else s=e.NAME,r=e.VALUE;s in n?t.playlistParsingError||(t.playlistParsingError=new Error(`EXT-X-DEFINE duplicate Variable Name declarations: "${s}"`)):n[s]=r||""}function ji(t,e,i){const s=e.IMPORT;if(i&&s in i){let e=t.variableList;e||(t.variableList=e={}),e[s]=i[s]}else t.playlistParsingError||(t.playlistParsingError=new Error(`EXT-X-DEFINE IMPORT attribute not found in Multivariant Playlist: "${s}"`))}const Hi=/^(\d+)x(\d+)$/,qi=/(.+?)=(".*?"|.*?)(?:,|$)/g;class Yi{constructor(t,e){"string"==typeof t&&(t=Yi.parseAttrList(t,e)),I(this,t)}get clientAttrs(){return Object.keys(this).filter(t=>"X-"===t.substring(0,2))}decimalInteger(t){const e=parseInt(this[t],10);return e>Number.MAX_SAFE_INTEGER?1/0:e}hexadecimalInteger(t){if(this[t]){let e=(this[t]||"0x").slice(2);e=(1&e.length?"0":"")+e;const i=new Uint8Array(e.length/2);for(let t=0;t<e.length/2;t++)i[t]=parseInt(e.slice(2*t,2*t+2),16);return i}return null}hexadecimalIntegerAsNumber(t){const e=parseInt(this[t],16);return e>Number.MAX_SAFE_INTEGER?1/0:e}decimalFloatingPoint(t){return parseFloat(this[t])}optionalFloat(t,e){const i=this[t];return i?parseFloat(i):e}enumeratedString(t){return this[t]}enumeratedStringList(t,e){const i=this[t];return(i?i.split(/[ ,]+/):[]).reduce((t,e)=>(t[e.toLowerCase()]=!0,t),e)}bool(t){return"YES"===this[t]}decimalResolution(t){const e=Hi.exec(this[t]);if(null!==e)return{width:parseInt(e[1],10),height:parseInt(e[2],10)}}static parseAttrList(t,e){let i;const s={};for(qi.lastIndex=0;null!==(i=qi.exec(t));){const r=i[1].trim();let n=i[2];const a=0===n.indexOf('"')&&n.lastIndexOf('"')===n.length-1;let o=!1;if(a)n=n.slice(1,-1);else switch(r){case"IV":case"SCTE35-CMD":case"SCTE35-IN":case"SCTE35-OUT":o=!0}if(e&&(a||o))n=Ki(e,n);else if(!o&&!a)switch(r){case"CLOSED-CAPTIONS":if("NONE"===n)break;case"ALLOWED-CPC":case"CLASS":case"ASSOC-LANGUAGE":case"AUDIO":case"BYTERANGE":case"CHANNELS":case"CHARACTERISTICS":case"CODECS":case"DATA-ID":case"END-DATE":case"GROUP-ID":case"ID":case"IMPORT":case"INSTREAM-ID":case"KEYFORMAT":case"KEYFORMATVERSIONS":case"LANGUAGE":case"NAME":case"PATHWAY-ID":case"QUERYPARAM":case"RECENTLY-REMOVED-DATERANGES":case"SERVER-URI":case"STABLE-RENDITION-ID":case"STABLE-VARIANT-ID":case"START-DATE":case"SUBTITLES":case"SUPPLEMENTAL-CODECS":case"URI":case"VALUE":case"VIDEO":case"X-ASSET-LIST":case"X-ASSET-URI":q.warn(`${t}: attribute ${r} is missing quotes`)}s[r]=n}return s}}function Wi(t){return"ID"!==t&&"CLASS"!==t&&"CUE"!==t&&"START-DATE"!==t&&"DURATION"!==t&&"END-DATE"!==t&&"END-ON-NEXT"!==t}function zi(t){return"SCTE35-OUT"===t||"SCTE35-IN"===t||"SCTE35-CMD"===t}class Xi{constructor(t,i,s=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=(null==i?void 0:i.tagAnchor)||null,this.tagOrder=null!=(r=null==i?void 0:i.tagOrder)?r:s,i){const e=i.attr;for(const i in e)if(Object.prototype.hasOwnProperty.call(t,i)&&t[i]!==e[i]){q.warn(`DATERANGE tag attribute: "${i}" does not match for tags with ID: "${t.ID}"`),this._badValueForSameId=i;break}t=I(new Yi({}),e,t)}if(this.attr=t,i?(this._startDate=i._startDate,this._cue=i._cue,this._endDate=i._endDate,this._dateAtEnd=i._dateAtEnd):this._startDate=new Date(t["START-DATE"]),"END-DATE"in t){const s=(null==i?void 0:i.endDate)||new Date(t["END-DATE"]);e(s.getTime())&&(this._endDate=s)}}get id(){return this.attr.ID}get class(){return this.attr.CLASS}get cue(){const t=this._cue;return void 0===t?this._cue=this.attr.enumeratedStringList(this.attr.CUE?"CUE":"X-CUE",{pre:!1,post:!1,once:!1}):t}get startTime(){const{tagAnchor:t}=this;return null===t||null===t.programDateTime?(q.warn(`Expected tagAnchor Fragment with PDT set for DateRange "${this.id}": ${t}`),NaN):t.start+(this.startDate.getTime()-t.programDateTime)/1e3}get startDate(){return this._startDate}get endDate(){const t=this._endDate||this._dateAtEnd;if(t)return t;const e=this.duration;return null!==e?this._dateAtEnd=new Date(this._startDate.getTime()+1e3*e):null}get duration(){if("DURATION"in this.attr){const t=this.attr.decimalFloatingPoint("DURATION");if(e(t))return t}else if(this._endDate)return(this._endDate.getTime()-this._startDate.getTime())/1e3;return null}get plannedDuration(){return"PLANNED-DURATION"in this.attr?this.attr.decimalFloatingPoint("PLANNED-DURATION"):null}get endOnNext(){return this.attr.bool("END-ON-NEXT")}get isInterstitial(){return"com.apple.hls.interstitial"===this.class}get isValid(){return!!this.id&&!this._badValueForSameId&&e(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)}get invalidReason(){return this.id?this._badValueForSameId?`Date range ${this._badValueForSameId} mismatch`:e(this.startDate.getTime())?!this.isInterstitial||"X-ASSET-URI"in this.attr||"X-ASSET-LIST"in this.attr?this.isValid?null:"Unknown (check DURATION(|END|NEXT), CLASS, and CUE)":"Interstitial Date range missing X-ASSET-(LIST|URI)":"Date range invalid start date":"Missing ID"}}class Qi{constructor(t){this.PTSKnown=!1,this.alignedSliding=!1,this.averagetargetduration=void 0,this.endCC=0,this.endSN=0,this.fragments=void 0,this.fragmentHint=void 0,this.partList=null,this.dateRanges=void 0,this.dateRangeTagCount=0,this.live=!0,this.iframesOnly=!1,this.requestScheduled=-1,this.ageHeader=0,this.advancedDateTime=void 0,this.updated=!0,this.advanced=!0,this.misses=0,this.startCC=0,this.startSN=0,this.startTimeOffset=null,this.targetduration=0,this.totalduration=0,this.type=null,this.url=void 0,this.m3u8="",this.version=null,this.canBlockReload=!1,this.canSkipUntil=0,this.canSkipDateRanges=!1,this.skippedSegments=0,this.recentlyRemovedDateranges=void 0,this.partHoldBack=0,this.holdBack=0,this.partTarget=0,this.preloadHint=void 0,this.renditionReports=void 0,this.tuneInGoal=0,this.deltaUpdateFailed=void 0,this.driftStartTime=0,this.driftEndTime=0,this.driftStart=0,this.driftEnd=0,this.encryptedFragments=void 0,this.playlistParsingError=null,this.variableList=null,this.hasVariableRefs=!1,this.appliedTimelineOffset=void 0,this.fragments=[],this.encryptedFragments=[],this.dateRanges={},this.url=t}reloaded(t){if(!t)return this.advanced=!0,void(this.updated=!0);const e=this.lastPartSn-t.lastPartSn,i=this.lastPartIndex-t.lastPartIndex;this.updated=this.endSN!==t.endSN||!!i||!!e||!this.live,this.advanced=this.endSN>t.endSN||e>0||0===e&&i>0,this.updated||this.advanced?this.misses=0:this.misses=t.misses+1}hasKey(t){return this.encryptedFragments.some(e=>{let i=e.decryptdata;return i||(e.setKeyFormat(t.keyFormat),i=e.decryptdata),!!i&&t.matches(i)})}get hasProgramDateTime(){return!!this.fragments.length&&e(this.fragments[this.fragments.length-1].programDateTime)}get levelTargetDuration(){return this.averagetargetduration||this.targetduration||10}get drift(){const t=this.driftEndTime-this.driftStartTime;if(t>0){return 1e3*(this.driftEnd-this.driftStart)/t}return 1}get edge(){return this.partEnd||this.fragmentEnd}get partEnd(){var t;return null!=(t=this.partList)&&t.length?this.partList[this.partList.length-1].end:this.fragmentEnd}get fragmentEnd(){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 t;return null!=(t=this.partList)&&t.length?this.partList[this.partList.length-1].index:-1}get maxPartIndex(){const t=this.partList;if(t){const e=this.lastPartIndex;if(-1!==e){for(let i=t.length;i--;)if(t[i].index>e)return t[i].index;return e}}return 0}get lastPartSn(){var t;return null!=(t=this.partList)&&t.length?this.partList[this.partList.length-1].fragment.sn:this.endSN}get expired(){if(this.live&&this.age&&this.misses<3){const t=this.partEnd-this.fragmentStart;return this.age>Math.max(t,this.totalduration)+this.levelTargetDuration}return!1}}function Zi(t,e){return t.length===e.length&&!t.some((t,i)=>t!==e[i])}function Ji(t,e){return!t&&!e||!(!t||!e)&&Zi(t,e)}function ts(t){return"AES-128"===t||"AES-256"===t||"AES-256-CTR"===t}function es(t){switch(t){case"AES-128":case"AES-256":return Li;case"AES-256-CTR":return Ii;default:throw new Error(`invalid full segment method ${t}`)}}function is(t){return Uint8Array.from(unescape(encodeURIComponent(t)),t=>t.charCodeAt(0))}function ss(t){const e=function(t,e,i){const s=t[e];t[e]=t[i],t[i]=s};e(t,0,3),e(t,1,2),e(t,4,5),e(t,6,7)}function rs(t){const e=t.split(":");let i=null;if("data"===e[0]&&2===e.length){const t=e[1].split(";"),s=t[t.length-1].split(",");if(2===s.length){const e="base64"===s[0],r=s[1];e?(t.splice(-1,1),i=vt(r)):i=function(t){const e=is(t).subarray(0,16),i=new Uint8Array(16);return i.set(e,16-e.length),i}(r)}}return i}const ns="undefined"!=typeof self?self:void 0;var as={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.fps",PLAYREADY:"com.microsoft.playready",WIDEVINE:"com.widevine.alpha"},os="org.w3.clearkey",ls="com.apple.streamingkeydelivery",hs="com.microsoft.playready",ds="urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed";function cs(t){switch(t){case ls:return as.FAIRPLAY;case hs:return as.PLAYREADY;case ds:return as.WIDEVINE;case os:return as.CLEARKEY}}var us="edef8ba979d64acea3c827dcd51d21ed";function fs(t){switch(t){case as.FAIRPLAY:return ls;case as.PLAYREADY:return hs;case as.WIDEVINE:return ds;case as.CLEARKEY:return os}}function gs(t){const{drmSystems:e,widevineLicenseUrl:i}=t,s=e?[as.FAIRPLAY,as.WIDEVINE,as.PLAYREADY,as.CLEARKEY].filter(t=>!!e[t]):[];return!s[as.WIDEVINE]&&i&&s.push(as.WIDEVINE),s}const ms=null!=ns&&null!=(ps=ns.navigator)&&ps.requestMediaKeySystemAccess?self.navigator.requestMediaKeySystemAccess.bind(self.navigator):null;var ps;function vs(t){const e=yt(new Uint16Array(t.buffer,t.byteOffset,t.byteLength/2)),i=e.substring(e.indexOf("<"),e.length),s=(new DOMParser).parseFromString(i,"text/xml").getElementsByTagName("KID")[0];if(s){const t=s.childNodes[0]?s.childNodes[0].nodeValue:s.getAttribute("VALUE");if(t){const e=vt(t).subarray(0,16);return ss(e),e}}return null}let ys={};class Es{static clearKeyUriToKeyIdMap(){ys={}}static setKeyIdForUri(t,e){ys[t]=e}static addKeyIdForUri(t){const e=Object.keys(ys).length%Number.MAX_SAFE_INTEGER,i=new Uint8Array(16);return new DataView(i.buffer,12,4).setUint32(0,e),ys[t]=i,i}constructor(t,e,i,s=[1],r=null,n){this.uri=void 0,this.method=void 0,this.keyFormat=void 0,this.keyFormatVersions=void 0,this.encrypted=void 0,this.isCommonEncryption=void 0,this.iv=null,this.key=null,this.keyId=null,this.pssh=null,this.scheme=void 0,this.method=t,this.uri=e,this.keyFormat=i,this.keyFormatVersions=s,this.iv=r,this.encrypted=!!t&&"NONE"!==t,this.isCommonEncryption=this.encrypted&&!ts(t),null!=n&&n.startsWith("0x")&&(this.keyId=new Uint8Array(pt(n)))}matches(t){return t.uri===this.uri&&t.method===this.method&&t.encrypted===this.encrypted&&t.keyFormat===this.keyFormat&&Zi(t.keyFormatVersions,this.keyFormatVersions)&&Ji(t.iv,this.iv)&&Ji(t.keyId,this.keyId)}isSupported(){if(this.method){if(ts(this.method)||"NONE"===this.method)return!0;if("identity"===this.keyFormat)return"SAMPLE-AES"===this.method;switch(this.keyFormat){case ls:case ds:case hs:case os:return-1!==["SAMPLE-AES","SAMPLE-AES-CENC","SAMPLE-AES-CTR"].indexOf(this.method)}}return!1}getDecryptData(t,e){var i;if(!this.encrypted||!this.uri)return null;if(ts(this.method)){let e=this.iv;e||("number"!=typeof t&&(q.warn(`missing IV for initialization segment with method="${this.method}" - compliance issue`),t=0),e=function(t){const e=new Uint8Array(16);for(let i=12;i<16;i++)e[i]=t>>8*(15-i)&255;return e}(t));return new Es(this.method,this.uri,"identity",this.keyFormatVersions,e)}if(this.keyId){const t=ys[this.uri];if(t&&!Zi(this.keyId,t)&&Es.setKeyIdForUri(this.uri,this.keyId),this.pssh)return this}const s=rs(this.uri);if(s)switch(this.keyFormat){case ds:if(this.pssh=s,!this.keyId){const t=Qt(s.buffer).filter(t=>t.systemId===us);if(t.length){var r;const e=t[0];this.keyId=null!=(r=e.kids)&&r.length?e.kids[0]:null}}this.keyId||(this.keyId=Ts(e));break;case hs:{const t=new Uint8Array([154,4,240,121,152,64,66,134,171,146,230,91,224,136,95,149]);this.pssh=Xt(t,0,s),this.keyId=vs(s);break}default:{let t=s.subarray(0,16);if(16!==t.length){const e=new Uint8Array(16);e.set(t,16-t.length),t=e}this.keyId=t;break}}if(16!==(null==(i=this.keyId)?void 0:i.byteLength)){let t;t=function(t){const e=null==t?void 0:t[ds];if(e)return e.keyId;return null}(e),t||(t=Ts(e),t||(t=ys[this.uri])),t&&(this.keyId=t,Es.setKeyIdForUri(this.uri,t))}return this}}function Ts(t){const e=null==t?void 0:t[hs];if(e){const t=rs(e.uri);if(t)return vs(t)}return null}const Ss=/#EXT-X-STREAM-INF:([^\r\n]*)(?:[\r\n](?:#[^\r\n]*)?)*([^\r\n]+)|#EXT-X-(I-FRAME-STREAM-INF|SESSION-DATA|SESSION-KEY|DEFINE|CONTENT-STEERING|START):([^\r\n]*)(?:[\r\n]+|$)/g,bs=/#EXT-X-MEDIA:(.*)/g,As=/^#EXT(?:INF|-X-TARGETDURATION):/m,Ls=new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,/(?!#) *(\S[^\r\n]*)/.source,/#.*/.source].join("|"),"g"),Is=new RegExp([/#EXT-X-(PROGRAM-DATE-TIME|BYTERANGE|DATERANGE|DEFINE|KEY|MAP|PART|PART-INF|PLAYLIST-TYPE|PRELOAD-HINT|RENDITION-REPORT|SERVER-CONTROL|SKIP|START):(.+)/.source,/#EXT-X-(BITRATE|DISCONTINUITY-SEQUENCE|MEDIA-SEQUENCE|TARGETDURATION|VERSION): *(\d+)/.source,/#EXT-X-(DISCONTINUITY|ENDLIST|GAP|INDEPENDENT-SEGMENTS|I-FRAMES-ONLY)/.source,/(#)([^:]*):(.*)/.source,/(#)(.*)(?:.*)\r?\n?/.source].join("|"));class Rs{static findGroup(t,e){for(let i=0;i<t.length;i++){const s=t[i];if(s.id===e)return s}}static resolve(t,e){return d.buildAbsoluteURL(e,t,{alwaysNormalize:!0})}static isMediaPlaylist(t){return As.test(t)}static parseMasterPlaylist(t,e){const i={contentSteering:null,levels:[],iframeVariants:[],playlistParsingError:null,sessionData:null,sessionKeys:null,startTimeOffset:null,variableList:null,hasVariableRefs:Gi(t)},s=[];if(Ss.lastIndex=0,!t.startsWith("#EXTM3U"))return i.playlistParsingError=new Error("no EXTM3U delimiter"),i;let r;for(;null!=(r=Ss.exec(t));)if(r[1]){const t=ks(new Yi(r[1],i),r[2],e,i,s);t&&i.levels.push(t)}else if(r[3]){const t=r[3],n=r[4];switch(t){case"I-FRAME-STREAM-INF":{const t=new Yi(n,i),r=ks(t,t.URI,e,i,s,!0);r&&i.iframeVariants.push(r)}break;case"SESSION-DATA":{const t=new Yi(n,i),e=t["DATA-ID"];e&&(null===i.sessionData&&(i.sessionData={}),i.sessionData[e]=t);break}case"SESSION-KEY":{const t=ws(n,e,i);t.encrypted&&t.isSupported()?(null===i.sessionKeys&&(i.sessionKeys=[]),i.sessionKeys.push(t)):q.warn(`[Keys] Ignoring invalid EXT-X-SESSION-KEY tag: "${n}"`);break}case"DEFINE":Vi(i,new Yi(n,i),e);break;case"CONTENT-STEERING":{const t=new Yi(n,i);i.contentSteering={uri:Rs.resolve(t["SERVER-URI"],e),pathwayId:t["PATHWAY-ID"]||"."};break}case"START":i.startTimeOffset=Ps(n)}}const n=s.length>0&&s.length<i.levels.length;return i.levels=n?s:i.levels,0===i.levels.length&&(i.playlistParsingError=new Error("no levels found in manifest")),i}static parseMasterPlaylistMedia(t,e,i){let s;const r={},n=i.levels,a={AUDIO:n.map(t=>({id:t.attrs.AUDIO,audioCodec:t.audioCodec})),SUBTITLES:n.map(t=>({id:t.attrs.SUBTITLES,textCodec:t.textCodec})),"CLOSED-CAPTIONS":[]};let o=0;for(bs.lastIndex=0;null!==(s=bs.exec(t));){const t=new Yi(s[1],i),n=t.TYPE;if(n){const i=a[n],s=r[n]||[];r[n]=s;const l=t.LANGUAGE,h=t["ASSOC-LANGUAGE"],d=t.CHANNELS,c=t.CHARACTERISTICS,u=t["INSTREAM-ID"],f={attrs:t,bitrate:0,id:o++,groupId:t["GROUP-ID"]||"",name:t.NAME||l||"",type:n,default:t.bool("DEFAULT"),autoselect:t.bool("AUTOSELECT"),forced:t.bool("FORCED"),lang:l,url:t.URI?Rs.resolve(t.URI,e):""};if(h&&(f.assocLang=h),d&&(f.channels=d),c&&(f.characteristics=c),u&&(f.instreamId=u),null!=i&&i.length){const t=Rs.findGroup(i,f.groupId)||i[0];xs(f,t,"audioCodec"),xs(f,t,"textCodec")}s.push(f)}}return r}static parseLevelPlaylist(t,i,s,r,n,a){var o;const l={url:i},h=new Qi(i),d=h.fragments,c=[];let u,f,g,m,p=null,v=0,y=0,E=0,T=0,A=0,L=null,R=new S(r,l),k=-1,_=!1,D=null;if(Ls.lastIndex=0,h.m3u8=t,h.hasVariableRefs=Gi(t),"#EXTM3U"!==(null==(o=Ls.exec(t))?void 0:o[0]))return h.playlistParsingError=new Error("Missing format identifier #EXTM3U"),h;for(;null!==(u=Ls.exec(t));){_&&(_=!1,R=new S(r,l),R.playlistOffset=E,R.setStart(E),R.sn=v,R.cc=T,A&&(R.bitrate=A),R.level=s,p&&(R.initSegment=p,p.rawProgramDateTime&&(R.rawProgramDateTime=p.rawProgramDateTime,p.rawProgramDateTime=null),D&&(R.setByteRange(D),D=null)));const t=u[1];if(t){R.duration=parseFloat(t);const e=(" "+u[2]).slice(1);R.title=e||null,R.tagList.push(e?["INF",t,e]:["INF",t])}else if(u[3]){if(e(R.duration)){var w;R.playlistOffset=E,R.setStart(E),g&&Fs(R,g,h),R.sn=v,R.level=s,R.cc=T;const t=(" "+u[3]).slice(1);R.relurl=Ki(h,t),Ms(R,L,c),L=R,E+=R.duration,v++,y=0;const e=R.byteRange;if(2===e.length&&(R.bitrate=8*(e[1]-e[0])/R.duration|0),h.iframesOnly&&e[0]&&(null==(w=p)?void 0:w.cc)!==T){const t=new S(r,l);t.relurl=R.relurl,t.setByteRange(`${Math.min(e[0],1316)}@0`),t.level=s,t.sn="initSegment",g&&(t.levelkeys=g,g.identity&&(t._decryptdata=g.identity.getDecryptData(0))),p=t,R.initSegment=p}d.push(R),_=!0}}else{if(u=u[0].match(Is),!u){q.warn("No matches on slow regex match for level playlist!");continue}for(f=1;f<u.length&&void 0===u[f];f++);const t=(" "+u[f]).slice(1),n=(" "+u[f+1]).slice(1),o=u[f+2]?(" "+u[f+2]).slice(1):null;switch(t){case"BYTERANGE":L?R.setByteRange(n,L):R.setByteRange(n);break;case"PROGRAM-DATE-TIME":R.rawProgramDateTime=n,R.tagList.push(["PROGRAM-DATE-TIME",n]),-1===k&&(k=d.length);break;case"PLAYLIST-TYPE":h.type&&Ns(h,t,u),h.type=n.toUpperCase();break;case"MEDIA-SEQUENCE":0!==h.startSN?Ns(h,t,u):null!==L&&$s(h,t,u),h.startSN=parseInt(n),v=h.startSN+h.skippedSegments;break;case"SKIP":{h.skippedSegments&&Ns(h,t,u);const i=new Yi(n,h),s=i.decimalInteger("SKIPPED-SEGMENTS");if(e(s)){h.skippedSegments+=s;for(let t=s;t--;)d.push(null);v+=s}const r=i.enumeratedString("RECENTLY-REMOVED-DATERANGES");r&&(h.recentlyRemovedDateranges=(h.recentlyRemovedDateranges||[]).concat(r.split("\t")));break}case"TARGETDURATION":0!==h.targetduration&&Ns(h,t,u),h.targetduration=Math.max(parseInt(n),1);break;case"VERSION":null!==h.version&&Ns(h,t,u),h.version=parseInt(n);break;case"INDEPENDENT-SEGMENTS":break;case"I-FRAMES-ONLY":h.iframesOnly=!0;break;case"ENDLIST":h.live||Ns(h,t,u),h.live=!1;break;case"#":(n||o)&&R.tagList.push(o?[n,o]:[n]);break;case"DISCONTINUITY":T++,R.tagList.push(["DIS"]);break;case"GAP":R.gap=!0,R.tagList.push([t]);break;case"BITRATE":R.tagList.push([t,n]),A=1e3*parseInt(n),e(A)?R.bitrate=A:A=0;break;case"DATERANGE":{const t=new Yi(n,h),e=new Xi(t,h.dateRanges[t.ID],h.dateRangeTagCount);h.dateRangeTagCount++,e.isValid||h.skippedSegments?h.dateRanges[e.id]=e:q.log(`Ignoring invalid DATERANGE tag: ${e.invalidReason}: ${n}`),R.tagList.push(["EXT-X-DATERANGE",n]);break}case"DEFINE":{const t=new Yi(n,h);"IMPORT"in t?ji(h,t,a):Vi(h,t,i)}break;case"DISCONTINUITY-SEQUENCE":0!==h.startCC&&Ns(h,t,u),h.startCC=T=parseInt(n),d.forEach(t=>t&&(t.cc=T));break;case"KEY":{const t=ws(n,i,h);if(t.isSupported()){if("NONE"===t.method){g=void 0;break}g||(g={});const e=g[t.keyFormat];null!=e&&e.matches(t)||(e&&(g=I({},g)),g[t.keyFormat]=t)}else q.warn(`[Keys] Ignoring unsupported EXT-X-KEY tag: "${n}"`);break}case"START":h.startTimeOffset=Ps(n);break;case"MAP":{const t=new Yi(n,h);if(R.duration){const e=new S(r,l);Os(e,t,s,g),p=e,R.initSegment=p,p.rawProgramDateTime&&!R.rawProgramDateTime&&(R.rawProgramDateTime=p.rawProgramDateTime)}else{const e=R.byteRangeEndOffset;if(e){const t=R.byteRangeStartOffset;D=`${e-t}@${t}`}else D=null;Os(R,t,s,g),p=R,_=!0}p.cc=T;break}case"SERVER-CONTROL":m&&Ns(h,t,u),m=new Yi(n),h.canBlockReload=m.bool("CAN-BLOCK-RELOAD"),h.canSkipUntil=m.optionalFloat("CAN-SKIP-UNTIL",0),h.canSkipDateRanges=h.canSkipUntil>0&&m.bool("CAN-SKIP-DATERANGES"),h.partHoldBack=m.optionalFloat("PART-HOLD-BACK",0),h.holdBack=m.optionalFloat("HOLD-BACK",0);break;case"PART-INF":{h.partTarget&&Ns(h,t,u);const e=new Yi(n);h.partTarget=e.decimalFloatingPoint("PART-TARGET");break}case"PART":{let t=h.partList;t||(t=h.partList=[]);const e=y>0?t[t.length-1]:void 0,i=y++,s=new Yi(n,h),r=new b(s,R,l,i,e);t.push(r),R.duration+=r.duration;break}case"PRELOAD-HINT":{const t=new Yi(n,h);h.preloadHint=t;break}case"RENDITION-REPORT":{const t=new Yi(n,h);h.renditionReports=h.renditionReports||[],h.renditionReports.push(t);break}default:q.warn(`line parsed but not handled: ${u}`)}}}L&&!L.relurl?(d.pop(),E-=L.duration,h.partList&&(h.fragmentHint=L)):h.partList&&(Ms(R,L,c),R.cc=T,h.fragmentHint=R,g&&Fs(R,g,h)),h.targetduration||(h.playlistParsingError=new Error("Missing Target Duration"));const P=d.length,C=d[0],x=d[P-1];if(E+=h.skippedSegments*h.targetduration,E>0&&P&&x){h.averagetargetduration=E/P;const t=x.sn;h.endSN="initSegment"!==t?t:0,h.live||(x.endList=!0),k>0&&(!function(t,e,i){if(i||(i=t[e]),!i)return;for(let s=e;s--;){const e=t[s];if(!e)return;e.programDateTime=i.programDateTime-1e3*e.duration,i=e}}(d,k,k>P-1?R:null),C&&c.unshift(C))}return h.fragmentHint&&(E+=h.fragmentHint.duration),h.totalduration=E,c.length&&h.dateRangeTagCount&&C&&_s(c,h),h.endCC=T,h}}function ks(t,e,i,s,r,n){var a;if(void 0===e)return null;const o=Ki(s,e),l={attrs:t,bitrate:t.decimalInteger("BANDWIDTH")||t.decimalInteger("AVERAGE-BANDWIDTH"),name:t.NAME,url:Rs.resolve(o,i)},h=t.decimalResolution("RESOLUTION");h&&(l.width=h.width,l.height=h.height),Cs(t.CODECS,l);const d=t["SUPPLEMENTAL-CODECS"];return d&&(l.supplemental={},Cs(d,l.supplemental)),null!=(a=l.unknownCodecs)&&a.length||r.push(l),n&&(l.iframes=!0),l}function _s(t,e){let i=t.length;if(!i){if(!e.hasProgramDateTime)return;{const s=e.fragments[e.fragments.length-1];t.push(s),i++}}const s=t[i-1],r=e.live?1/0:e.totalduration,n=Object.keys(e.dateRanges);for(let o=n.length;o--;){const l=e.dateRanges[n[o]],h=l.startDate.getTime();l.tagAnchor=s.ref;for(let s=i;s--;){var a;if((null==(a=t[s])?void 0:a.sn)<e.startSN)break;const i=Ds(e,h,t,s,r);if(i){l.tagAnchor=i.ref;break}}}}function Ds(t,e,i,s,r){const n=i[s];if(n){const o=n.programDateTime;if(e>=o||0===s){var a;if(e<=o+1e3*(((null==(a=i[s+1])?void 0:a.start)||r)-n.start)){const r=n.sn-t.startSN,a=t.fragments;if(r>=0&&r<a.length){if(a.length>i.length){const n=i[s+1]||a[a.length-1];for(let i=Math.min(n.sn-t.startSN,a.length-1);i>r;i--){const t=a[i].programDateTime;if(e>=t&&e<t+1e3*a[i].duration)return a[i]}}return a[r]}}}}return null}function ws(t,e,i){var s,r;const n=new Yi(t,i),a=null!=(s=n.METHOD)?s:"",o=n.URI,l=n.hexadecimalInteger("IV"),h=n.KEYFORMATVERSIONS,d=null!=(r=n.KEYFORMAT)?r:"identity";o&&n.IV&&!l&&q.error(`Invalid IV: ${n.IV}`);const c=o?Rs.resolve(o,e):"",u=(h||"1").split("/").map(Number).filter(Number.isFinite);return new Es(a,c,d,u,l,n.KEYID)}function Ps(t){const i=new Yi(t).decimalFloatingPoint("TIME-OFFSET");return e(i)?i:null}function Cs(t,e){let i=(t||"").split(/[ ,]+/).filter(t=>t);["video","audio","text","image"].forEach(t=>{const s=i.filter(e=>le(e,t));s.length&&(e[`${t}Codec`]=s.map(t=>t.split("/")[0]).join(","),i=i.filter(t=>-1===s.indexOf(t)))}),e.unknownCodecs=i}function xs(t,e,i){const s=e[i];s&&(t[i]=s)}function Ms(t,e,i){t.rawProgramDateTime?i.push(t):null!=e&&e.programDateTime&&(t.programDateTime=e.endProgramDateTime)}function Os(t,e,i,s){t.relurl=e.URI,e.BYTERANGE&&t.setByteRange(e.BYTERANGE),t.level=i,t.sn="initSegment",s&&(t.levelkeys=s),t.initSegment=null}function Fs(t,e,i){t.levelkeys=e;const{encryptedFragments:s}=i;s.length&&s[s.length-1].levelkeys===e||!Object.keys(e).some(t=>e[t].isCommonEncryption)||s.push(t)}function Ns(t,e,i){t.playlistParsingError=new Error(`#EXT-X-${e} must not appear more than once (${i[0]})`)}function $s(t,e,i){t.playlistParsingError=new Error(`#EXT-X-${e} must appear before the first Media Segment (${i[0]})`)}function Bs(t,i){const s=i.startPTS;if(e(s)){let e,r=0;i.sn>t.sn?(r=s-t.start,e=t):(r=t.start-s,e=i),e.duration!==r&&e.setDuration(r)}else if(i.sn>t.sn){t.cc===i.cc&&t.minEndPTS?i.setStart(t.start+(t.minEndPTS-t.start)):i.setStart(t.start+t.duration)}else i.setStart(Math.max(t.start-i.duration,0))}function Us(t,i,s,r,n,a,o,l){r-s<=0&&(l.warn("Fragment should have a positive duration",i),r=s+i.duration,a=n+i.duration);let h=s,d=r;const c=i.startPTS,u=i.endPTS;if(e(c)){const o=Math.abs(c-s);t&&o>t.totalduration?l.warn(`media timestamps and playlist times differ by ${o}s for level ${i.level} ${t.url}`):e(i.deltaPTS)?i.deltaPTS=Math.max(o,i.deltaPTS):i.deltaPTS=o,h=Math.max(s,c),s=Math.min(s,c),n=void 0!==i.startDTS?Math.min(n,i.startDTS):n,d=Math.min(r,u),r=Math.max(r,u),a=void 0!==i.endDTS?Math.max(a,i.endDTS):a}const f=s-i.start;0!==i.start&&i.setStart(s),i.setDuration(r-i.start),i.startPTS=s,i.maxStartPTS=h,i.startDTS=n,i.endPTS=r,i.minEndPTS=d,i.endDTS=a;const g=i.sn;if(!t||g<t.startSN||g>t.endSN)return 0;let m;const p=g-t.startSN,v=t.fragments;for(v[p]=i,m=p;m>0;m--)Bs(v[m],v[m-1]);for(m=p;m<v.length-1;m++)Bs(v[m],v[m+1]);return t.fragmentHint&&Bs(v[v.length-1],t.fragmentHint),t.PTSKnown=t.alignedSliding=!0,f}function Gs(t,i,s){if(t===i)return;let r=null;const n=t.fragments;for(let t=n.length-1;t>=0;t--){const e=n[t].initSegment;if(e){r=e;break}}let a;t.fragmentHint&&delete t.fragmentHint.endPTS,function(t,e,i){var s;const r=e.skippedSegments,n=Math.max(t.startSN,e.startSN)-e.startSN,a=(t.fragmentHint?1:0)+(r?e.endSN:Math.min(t.endSN,e.endSN))-e.startSN,o=e.startSN-t.startSN,l=e.fragmentHint?e.fragments.concat(e.fragmentHint):e.fragments,h=null!=(s=t.fragmentHint)&&s.duration?t.fragments.concat(t.fragmentHint):t.fragments;for(let s=n;s<=a;s++){const n=h[o+s];let a=l[s];if(r&&!a&&n&&(a=e.fragments[s]=n),n&&a){i(n,a,s,l);const r=n.relurl,o=a.relurl;if(r&&zs(r,o))return void(e.playlistParsingError=Ks(`media sequence mismatch ${a.sn}:`,t,e,n,a));if(n.cc!==a.cc)return void(e.playlistParsingError=Ks(`discontinuity sequence mismatch (${n.cc}!=${a.cc})`,t,e,n,a))}}}(t,i,(t,s,n,o)=>{if((!i.startCC||i.skippedSegments)&&s.cc!==t.cc){const e=t.cc-s.cc;for(let t=n;t<o.length;t++)o[t].cc+=e;i.endCC=o[o.length-1].cc}e(t.startPTS)&&e(t.endPTS)&&(s.setStart(s.startPTS=t.startPTS),s.startDTS=t.startDTS,s.maxStartPTS=t.maxStartPTS,s.endPTS=t.endPTS,s.endDTS=t.endDTS,s.minEndPTS=t.minEndPTS,s.setDuration(t.endPTS-t.startPTS),s.duration&&(a=s),i.PTSKnown=i.alignedSliding=!0),t.hasStreams&&(s.elementaryStreams=t.elementaryStreams),s.loader=t.loader,t.hasStats&&(s.stats=t.stats),t.initSegment&&(s.initSegment=t.initSegment,r=t.initSegment)});const o=i.fragments,l=i.fragmentHint?o.concat(i.fragmentHint):o;if(r&&l.forEach(t=>{var e;!t||t.initSegment&&t.initSegment.relurl!==(null==(e=r)?void 0:e.relurl)||(t.initSegment=r)}),i.skippedSegments){if(i.deltaUpdateFailed=o.some(t=>!t),i.deltaUpdateFailed){s.warn("[level-helper] Previous playlist missing segments skipped in delta playlist");for(let t=i.skippedSegments;t--;)o.shift();i.startSN=o[0].sn}else{i.canSkipDateRanges&&(i.dateRanges=function(t,e,i){const{dateRanges:s,recentlyRemovedDateranges:r}=e,n=I({},t);r&&r.forEach(t=>{delete n[t]});const a=Object.keys(n).length;if(!a)return s;return Object.keys(s).forEach(t=>{const e=n[t],r=new Xi(s[t].attr,e);r.isValid?(n[t]=r,e||(r.tagOrder+=a)):i.warn(`Ignoring invalid Playlist Delta Update DATERANGE tag: "${Ue(s[t].attr)}"`)}),n}(t.dateRanges,i,s));const e=t.fragments.filter(t=>t.rawProgramDateTime);if(t.hasProgramDateTime&&!i.hasProgramDateTime)for(let t=1;t<l.length;t++)null===l[t].programDateTime&&Ms(l[t],l[t-1],e);_s(e,i)}i.endCC=o[o.length-1].cc}if(!i.startCC){var h;const e=Hs(t,i.startSN-1);i.startCC=null!=(h=null==e?void 0:e.cc)?h:o[0].cc}if(function(t,e,i){if(t&&e){let s=0;for(let r=0,n=t.length;r<n;r++){const n=t[r],a=e[r+s];n&&a&&n.index===a.index&&n.fragment.sn===a.fragment.sn?i(n,a):s--}}}(t.partList,i.partList,(t,e)=>{e.elementaryStreams=t.elementaryStreams,e.stats=t.stats,e.gap=t.gap||e.gap}),a){i.iframesOnly&&(a.type,f.MAIN);Us(i,a,a.startPTS,a.endPTS,a.startDTS,a.endDTS,0,s)}else Vs(t,i);o.length&&(i.totalduration=i.edge-o[0].start),i.driftStartTime=t.driftStartTime,i.driftStart=t.driftStart;const d=i.advancedDateTime;if(i.advanced&&d){const t=i.edge;i.driftStart||(i.driftStartTime=d,i.driftStart=t),i.driftEndTime=d,i.driftEnd=t}else i.driftEndTime=t.driftEndTime,i.driftEnd=t.driftEnd,i.advancedDateTime=t.advancedDateTime;-1===i.requestScheduled&&(i.requestScheduled=t.requestScheduled)}function Ks(t,e,i,s,r){return new Error(`${t} ${r.url}\nPlaylist starting @${e.startSN}\n${e.m3u8}\n\nPlaylist starting @${i.startSN}\n${i.m3u8}`)}function Vs(t,e,i=!0,s){const r=e.startSN+e.skippedSegments-t.startSN,n=t.fragments,a=r>=0;let o=0;if(a&&r<n.length)o=n[r].start,null==s||s.log(`Aligning playlists based on SN ${e.startSN} (diff: ${o})`);else if(a&&e.startSN===t.endSN+1)o=t.fragmentEnd,null==s||s.log(`Aligning playlists based on first/last SN ${e.startSN} (diff: ${o})`);else if(a&&i)o=t.fragmentStart+r*e.levelTargetDuration;else{if(e.skippedSegments||0!==e.fragmentStart)return o;o=t.fragmentStart,null==s||s.log(`Aligning playlists based on first SN ${e.startSN} (diff: ${o})`)}return function(t,e){if(e){const i=t.fragments;for(let s=t.skippedSegments;s<i.length;s++)i[s].addStart(e);t.fragmentHint&&t.fragmentHint.addStart(e)}}(e,o),o}function js(t,e=1/0){let i=1e3*t.targetduration;if(t.updated){const s=t.fragments,r=4;if(s.length&&i*r>e){const t=1e3*s[s.length-1].duration;t>0&&t<i&&(i=t)}}else i/=2;return Math.round(i)}function Hs(t,e,i){var s;if(!t)return null;let r=t.fragments[e-t.startSN];return r||(r=t.fragmentHint,(null==(s=r)?void 0:s.sn)===e?r:i&&e<t.startSN&&i.sn===e?i:null)}function qs(t,e,i){return t?Ys(t.partList,e,i):null}function Ys(t,e,i){if(t)for(let s=t.length;s--;){const r=t[s];if(r.index===i&&r.fragment.sn===e)return r}return null}function Ws(t){t.forEach((t,e)=>{var i;null==(i=t.details)||i.fragments.forEach(t=>{t.level=e,t.initSegment&&(t.initSegment.level=e)})})}function zs(t,e){return!(t===e||!e)&&Xs(t)!==Xs(e)}function Xs(t){return t.replace(/\?[^?]*$/,"")}function Qs(t,e){for(let s=0,r=t.length;s<r;s++){var i;if((null==(i=t[s])?void 0:i.cc)===e)return t[s]}return null}function Zs(t,e){const i=t.start+e;t.setStart(i)}function Js(t,e){const i=e.fragments;for(let e=0,s=i.length;e<s;e++)Zs(i[e],t);e.fragmentHint&&Zs(e.fragmentHint,t),e.alignedSliding=!0}function tr(t,e,i){t&&(!function(t,e,i){if(!function(t,e){return!!(t&&e.startCC<t.endCC&&e.endCC>t.startCC)}(e,t))return;const s=Math.min(e.endCC,t.endCC),r=Qs(e.fragments,s),n=Qs(t.fragments,s);if(!r||!n)return;const a=r.start-n.start;i.log(`Aligning playlists using dicontinuity sequence ${s} (diff: ${a})`),Js(a,t)}(e,t,i),e.alignedSliding||function(t,e,i){if(!t.hasProgramDateTime||!e.hasProgramDateTime)return;const s=t.fragments,r=e.fragments;if(!s.length||!r.length)return;let n,a;const o=Math.min(e.endCC,t.endCC);e.startCC<o&&t.startCC<o&&(n=Qs(r,o),a=Qs(s,o));n&&a||(n=r[Math.floor(r.length/2)]||r.filter(t=>!!t)[0],a=Qs(s,n.cc)||s[Math.floor(s.length/2)]);const l=n.programDateTime,h=a.programDateTime;if(!l||!h)return;const d=(h-l)/1e3;if(Math.abs(d)>Math.max(60,t.totalduration))return void i.log(`Cannot align playlists using PDT without overlap (${Math.abs(d)} > ${t.totalduration})`);const c=d-(a.start-n.start);i.log(`Aligning playlists using PDT (diff: ${c})`),Js(c,t)}(e,t,i),e.alignedSliding||e.skippedSegments||Vs(t,e,!1,i))}function er(t,e,i){ir(t,e,i),t.addEventListener(e,i)}function ir(t,e,i){t.removeEventListener(e,i)}function sr(t){let e="";const i=t.length;for(let s=0;s<i;s++)e+=`[${t.start(s).toFixed(3)}-${t.end(s).toFixed(3)}]`;return e}const rr="STOPPED",nr="IDLE",ar="KEY_LOADING",or="FRAG_LOADING",lr="FRAG_LOADING_WAITING_RETRY",hr="WAITING_TRACK",dr="PARSING",cr="PARSED",ur="ENDED",fr="ERROR",gr="WAITING_INIT_PTS",mr="WAITING_LEVEL";class pr extends Fi{constructor(t,e,i,s,r){super(s,t.logger),this.hls=void 0,this.fragPrevious=null,this.fragCurrent=null,this.fragPlaying=null,this.fragmentTracker=void 0,this.transmuxer=null,this._state=rr,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=-1,this.startTimeOffset=null,this.retryDate=0,this.levels=null,this.fragmentLoader=void 0,this.initFragmentLoader=void 0,this.keyLoader=void 0,this.levelLastLoaded=null,this.startFragRequested=!1,this.decrypter=void 0,this.initPTS=[],this.buffering=!0,this.loadingParts=!1,this.loopSn=void 0,this.onMediaSeeking=()=>{const{config:t,fragCurrent:e,media:i,mediaBuffer:s,state:r}=this,n=i?i.currentTime:0,a=Bi.bufferInfo(s||i,n,t.maxBufferHole),o=a.len;if(this.log(`Media seeking to ${n}, state: ${r}, ${o?"in":"out of"} buffer`),this.state===ur)this.resetLoadingState();else if(e){const i=t.maxFragLookUpTolerance,s=e.start-i,r=e.start+e.duration+i;if(!o||r<a.start||s>a.end){const t=n<s,i=n>r;(t||i)&&(!e.loader||!i&&this.isFragmentNearlyDownloaded(e)?this.fragPrevious=null:(this.log(`Cancelling fragment load for seek (sn: ${e.sn}) - ${t?"backward":"forward"} seek`),e.abortRequests(),this.resetLoadingState()))}}if(i){this.fragmentTracker.removeFragmentsInRange(n,1/0,this.playlistType,!0);if(n>this.lastCurrentTime&&(this.lastCurrentTime=n),!this.loadingParts){const t=Math.max(a.end,n),e=this.shouldLoadParts(this.getLevelDetails(),t);e&&(this.log(`LL-Part loading ON after seeking to ${n} with buffer @${t}`),this.loadingParts=e)}}const l=!Bi.isBuffered(i,n);this.hls.hasEnoughToStart&&!l||(this.log(`Setting ${l?"startPosition":"nextLoadPosition"} to ${n} for seek without enough to start`),this.nextLoadPosition=n,l&&(this.startPosition=n)),o<1&&this.state===nr&&this.tickImmediate()},this.onMediaEnded=()=>{this.log("setting startPosition to 0 because media ended"),this.startPosition=this.lastCurrentTime=0},this.playlistType=r,this.hls=t,this.fragmentLoader=new Pi(t.config),this.initFragmentLoader=new Pi(t.config),this.keyLoader=i,this.fragmentTracker=e,this.config=t.config,this.decrypter=new Di(t.config)}registerListeners(){const{hls:t}=this;t.on(a.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(a.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(a.MANIFEST_LOADING,this.onManifestLoading,this),t.on(a.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(a.ERROR,this.onError,this)}unregisterListeners(){const{hls:t}=this;t.off(a.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(a.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(a.MANIFEST_LOADING,this.onManifestLoading,this),t.off(a.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(a.ERROR,this.onError,this)}doTick(){this.onTickEnd()}onTickEnd(){}startLoad(t){}stopLoad(){if(this.state===rr)return;this.fragmentLoader.abort(),this.initFragmentLoader.abort(),this.keyLoader.abort(this.playlistType);const t=this.fragCurrent;null!=t&&t.loader&&(t.abortRequests(),this.fragmentTracker.removeFragment(t)),this.resetTransmuxer(),this.fragCurrent=null,this.fragPrevious=null,this.clearInterval(),this.clearNextTick(),this.state=rr}get startPositionValue(){const{nextLoadPosition:t,startPosition:e}=this;if(-1===e&&t){const e=this.getLevelDetails();if(null!=e&&e.live){return(this.hls.liveSyncPosition||e.fragmentStart)+this.timelineOffset}return t}return e}get bufferingEnabled(){return this.buffering}get backtrackFragment(){}set backtrackFragment(t){}get couldBacktrack(){return!1}set couldBacktrack(t){}pauseBuffering(){this.buffering=!1}resumeBuffering(){this.buffering=!0}get inFlightFrag(){return{frag:this.fragCurrent,state:this.state}}_streamEnded(t,e){if(e.live||!this.media)return!1;const i=t.end||0,s=this.config.timelineOffset||0;if(i<=s)return!1;const r=t.buffered;this.config.maxBufferHole&&r&&r.length>1&&(t=Bi.bufferedInfo(r,t.start,0));const n=t.nextStart;if(n&&n>s&&n<e.edge)return!1;if(this.media.currentTime<t.start)return!1;const a=e.partList;if(null!=a&&a.length){const t=a[a.length-1];return Bi.isBuffered(this.media,t.start+t.duration/2)}const o=e.fragments[e.fragments.length-1];return this.fragmentTracker.isEndListAppended(o.type)}getLevelDetails(){if(this.levels&&null!==this.levelLastLoaded)return this.levelLastLoaded.details}get timelineOffset(){const t=this.config.timelineOffset;var e;return t?(null==(e=this.getLevelDetails())?void 0:e.appliedTimelineOffset)||t:0}onMediaAttached(t,e){const i=this.media=this.mediaBuffer=e.media;er(i,"seeking",this.onMediaSeeking),er(i,"ended",this.onMediaEnded);const s=this.config;this.levels&&s.autoStartLoad&&this.state===rr&&this.startLoad(s.startPosition)}onMediaDetaching(t,e){this.fragPlaying=null;const i=!!e.transferMedia,s=this.media;if(null!==s){if(s.ended&&(this.log("MSE detaching and video ended, reset startPosition"),this.startPosition=this.lastCurrentTime=0),ir(s,"seeking",this.onMediaSeeking),ir(s,"ended",this.onMediaEnded),this.media=this.mediaBuffer=null,this.loopSn=void 0,i)return this.resetLoadingState(),void this.resetTransmuxer();this.loadingParts=!1,this.fragmentTracker.removeAllFragments(),this.stopLoad()}}onManifestLoading(){this.initPTS=[],this.fragPlaying=this.levels=this.levelLastLoaded=this.fragCurrent=null,this.lastCurrentTime=0,this.startPosition=-1,this.startFragRequested=!1}onError(t,e){}onManifestLoaded(t,e){this.startTimeOffset=e.startTimeOffset}onHandlerDestroying(){this.stopLoad(),this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null),super.onHandlerDestroying(),this.hls=this.onMediaSeeking=this.onMediaEnded=null}onHandlerDestroyed(){this.state=rr,this.fragmentLoader&&this.fragmentLoader.destroy(),this.initFragmentLoader&&this.initFragmentLoader.destroy(),this.keyLoader&&this.keyLoader.destroy(),this.decrypter&&this.decrypter.destroy(),this.hls=this.decrypter=this.keyLoader=null,this.fragmentLoader=this.initFragmentLoader=this.fragmentTracker=null,super.onHandlerDestroyed()}loadFragment(t,e,i){this.startFragRequested=!0,this._loadFragForPlayback(t,e,i)}_loadFragForPlayback(t,e,i){this._doFragLoad(t,e,i,t=>{const e=t.frag;if(this.fragContextChanged(e))return this.warn(`${e.type} sn: ${e.sn}${t.part?" part: "+t.part.index:""} of ${this.fragInfo(e,!1,t.part)} was dropped during download.`),void this.fragmentTracker.removeFragment(e);const i=++e.stats.chunkCount;this.log(`load progress ${e.type} sn: ${e.sn}${t.part?" part: "+t.part.index:""} of ${this.fragInfo(e,!1,t.part)} chunk: ${i}`),this._handleFragmentLoadProgress(t)}).then(t=>{if(!t)return;const e=this.state,i=t.frag;this.fragContextChanged(i)?(e===or||!this.fragCurrent&&e===dr)&&(this.fragmentTracker.removeFragment(i),this.state=nr):("payload"in t&&(this.log(`Loaded ${i.type} sn: ${i.sn} of ${this.playlistLabel()} ${i.level} (bytes ${i.stats.loaded})`),this.hls.trigger(a.FRAG_LOADED,t)),this._handleFragmentLoadComplete(t))}).catch(e=>{this.state!==rr&&this.state!==fr&&(this.log(`Frag error ${t.type} sn:${t.sn} cc:${t.cc}: ${(null==e?void 0:e.message)||e}`),this.resetFragmentLoading(t))})}clearTrackerIfNeeded(t){var e;const{fragmentTracker:i}=this;if(i.getState(t)===vi){const e=t.type,s=this.getFwdBufferInfo(this.mediaBuffer,e),r=Math.max(t.duration,s?s.len:this.config.maxBufferLength),n=this.backtrackFragment;(1===(n?t.sn-n.sn:0)||this.reduceMaxBufferLength(r,t.duration))&&i.removeFragment(t)}else 0===(null==(e=this.mediaBuffer)?void 0:e.buffered.length)?i.removeAllFragments():i.hasParts(t.type)&&(i.detectPartialFragments({frag:t,part:null,stats:t.stats,id:t.type}),i.getState(t)===yi&&i.removeFragment(t))}checkLiveUpdate(t){if(t.updated&&!t.live){const e=this.fragmentTracker,i=t.fragments[t.fragments.length-1];if(i.endList&&!e.isEndListAppended(this.playlistType)){const t=e.getPartialFragment(i.end);t&&(e.removeFragment(t),e.fragBuffered(i,!0))}e.detectPartialFragments({frag:i,part:null,stats:i.stats,id:i.type})}t.fragments[0]||(t.deltaUpdateFailed=!0)}waitForLive(t){const e=t.details;return(null==e?void 0:e.live)&&"EVENT"!==e.type&&(this.levelLastLoaded!==t||e.expired)}flushMainBuffer(t,e,i=null){if(!(t-e))return;const s={startOffset:t,endOffset:e,type:i};this.hls.trigger(a.BUFFER_FLUSHING,s)}_loadInitSegment(t){const{hls:e}=this;return this.initFragmentLoader.abort(),e.trigger(a.FRAG_LOADING,{frag:t,targetBufferTime:0}),this.initFragmentLoader.load(t).then(t=>{var e;const i=t.frag;if(!this.levels||!T(i,null==(e=this.fragCurrent)?void 0:e.initSegment))throw new Oi({type:r.NETWORK_ERROR,details:n.INTERNAL_ABORTED,error:new Error("init load aborted"),fatal:!1,frag:i,networkDetails:null});return t}).then(t=>{const{frag:i,payload:s}=t,o=i.decryptdata;if(s&&s.byteLength>0&&null!=o&&o.key&&o.iv&&ts(o.method)){const l=self.performance.now(),{decryptRange:h}=xi(i,null,this.iframesOnly);return this.decrypter.decrypt(new Uint8Array(s),o.key.buffer,o.iv.buffer,es(o.method),h).catch(t=>{throw e.trigger(a.ERROR,{type:r.MEDIA_ERROR,details:n.FRAG_DECRYPT_ERROR,fatal:!1,error:t,reason:t.message,frag:i}),this.fragmentLoader.abort(),t}).then(s=>{const r=self.performance.now();return e.trigger(a.FRAG_DECRYPTED,{frag:i,part:null,payload:s,stats:{tstart:l,tdecrypt:r}}),t.payload=s,this.completeInitSegmentLoad(t)})}return this.completeInitSegmentLoad(t)})}completeInitSegmentLoad(t){const e=t.frag.stats;t.frag.data=new Uint8Array(t.payload),e.parsing.start=e.buffering.start=self.performance.now(),e.parsing.end=e.buffering.end=self.performance.now()}loadInitSegmentIfNeeded(t){const{initSegment:e}=t;if(!this.bitrateTest&&y(t)&&e&&!e.data){var i;return(!e.encrypted||null!=(i=e.decryptdata)&&i.key?this._loadInitSegment(e):this.keyLoader.load(e).then(()=>this._loadInitSegment(e))).catch(e=>{if(this.state===rr||this.state===fr)throw e;throw"data"in e&&(e.data.frag=t,this.fragmentLoader.abort(),this.handleFragLoadError(e)),this.resetFragmentLoading(t),e})}}unhandledEncryptionError(t,e){var i,s;const o=t.tracks;if(o&&!e.encrypted&&(null!=(i=o.audio)&&i.encrypted||null!=(s=o.video)&&s.encrypted)&&(!this.config.emeEnabled||!this.keyLoader.emeController)){const t=this.media,i=new Error(`Encrypted track with no key in ${this.fragInfo(e)} (media ${t?"attached mediaKeys: "+t.mediaKeys:"detached"})`);return this.warn(i.message),!t||t.mediaKeys?!1:(this.hls.trigger(a.ERROR,{type:r.KEY_SYSTEM_ERROR,details:n.KEY_SYSTEM_NO_KEYS,fatal:!1,error:i,frag:e}),this.resetTransmuxer(),!0)}return!1}fragContextChanged(t){const{fragCurrent:e}=this;return!t||!T(t,e)}fragBufferedComplete(t,e){const i=this.mediaBuffer?this.mediaBuffer:this.media;if(this.log(`Buffered ${t.type} sn: ${t.sn}${e?" part: "+e.index:""} of ${this.fragInfo(t,!1,e)} > buffer:${i?sr(Bi.getBuffered(i)):"(detached)"})`),y(t)){var s;if(t.type!==f.SUBTITLE){const e=t.elementaryStreams;if(!Object.keys(e).some(t=>!!e[t]))return void(this.state=nr)}const i=null==(s=this.levels)?void 0:s[t.level];null!=i&&i.fragmentError&&(e||this.fragmentTracker.getState(t)!==yi)&&(this.log(`Resetting level fragment error count of ${i.fragmentError} on frag buffered`),i.fragmentError=0,t.stats.retry=0)}this.state=nr}_handleFragmentLoadComplete(t){const{transmuxer:e}=this;if(!e)return;const i=t.frag,{part:s,partsLoaded:r}=t,n=!r||0===r.length||r.some(t=>!t),{decryptRange:a}=xi(i,s),o=new Ni(i.level,i.sn,i.stats.chunkCount+1,0,s?s.index:-1,!n,i.duration,this.iframesOnly,a);this.log(`load complete ${i.type} sn: ${i.sn}${s?" part: "+s.index:""} of ${this.fragInfo(i,!1,s)}`),e.flush(o)}_handleFragmentLoadProgress(t){}loadKeyFor(t,e,i){var s;let r=null;return!t.encrypted||null!=(s=t.decryptdata)&&s.key?t.encrypted||(r=this.keyLoader.loadClear(t,e.encryptedFragments,this.startFragRequested),r&&this.log(`[eme] blocking frag sn: ${t.sn} load until media-keys acquired`)):(this.log(`Loading key for ${t.sn} of [${e.startSN}-${e.endSN}], ${this.playlistLabel()} ${t.level}`),this.state=ar,r=this.keyLoader.load(t,i).then(t=>{if(!this.fragContextChanged(t.frag))return this.hls.trigger(a.KEY_LOADED,t),this.state===ar&&(this.state=nr),t}),this.hls.trigger(a.KEY_LOADING,{frag:t})),r}_doFragLoad(t,i,s=null,r){this.fragCurrent=t;const n=i.details;if(!this.levels||!n)throw new Error(`frag load aborted, missing level${n?"":" detail"}s`);const o=this.fragPrevious;if(!E(t,o)){const e=this.shouldLoadParts(i.details,t.end);e!==this.loadingParts&&(this.log(`LL-Part loading ${e?"ON":"OFF"} loading sn ${null==o?void 0:o.sn}->${t.sn}`),this.loadingParts=e)}if(s=Math.max(t.start,s||0),this.loadingParts){const e=n.partList;if(e&&r){s>n.fragmentEnd&&n.fragmentHint&&(t=n.fragmentHint);const l=this.getNextPart(e,t,s);if(l>-1){const h=e[l];if(!E(t=this.fragCurrent=h.fragment,o)&&!this.shouldLoadParts(i.details,t.end))return this.log(`LL-Part loading OFF @${this.playhead} next part: ${this.fragInfo(t,!1,h)}`),this.loadingParts=!1,Promise.resolve(null);if(!this.filterReplacedPrimary(h,i.details))return Promise.resolve(null);const d=this.loadKeyFor(t,n);if(this.fragContextChanged(t))return Promise.resolve(null);let c;this.log(`Loading ${t.type} sn: ${t.sn} part: ${h.index} (${l}/${e.length-1}) of ${this.fragInfo(t,!1,h)} cc: ${t.cc} [${n.startSN}-${n.endSN}], target: ${s}${h.byteRange.length?` range:${h.byteRange.join("-")}`:""}`),this.nextLoadPosition=h.start+h.duration,this.state=or;const u=this.loadInitSegmentIfNeeded(t);if(d||u){const e=!!d;c=Promise.all([d,u]).then(([s])=>!e||s&&!this.fragContextChanged(s.frag)?this.doFragPartsLoad(t,h,i,r):null).catch(t=>this.handleFragLoadError(t))}else c=this.doFragPartsLoad(t,h,i,r).catch(t=>this.handleFragLoadError(t));return this.hls.trigger(a.FRAG_LOADING,{frag:t,part:h,targetBufferTime:s}),null===this.fragCurrent?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING parts")):c}if(!t.url||this.loadedEndOfParts(e,s))return Promise.resolve(null)}}var l;if(this.loadingParts)this.log(`LL-Part loading OFF after next part miss @${s} Check buffer at sn: ${t.sn} loaded parts: ${null==(l=n.partList)?void 0:l.filter(t=>t.loaded).map(t=>`[${t.start}-${t.end}]`)}`),this.loadingParts=!1;else if(!t.url)return Promise.resolve(null);if(!this.filterReplacedPrimary(t,i.details))return Promise.resolve(null);const h=this.loadInitSegmentIfNeeded(t),d=this.loadKeyFor(t,n,h);var c;if(this.fragContextChanged(t))return this.log(`Context changed in KEY_LOADING sn: ${t.sn} ${t.relurl} > ${null==(c=this.fragCurrent)?void 0:c.relurl}`),null==h||h.catch(()=>null),null==d||d.catch(()=>null),Promise.resolve(null);this.log(`Loading ${t.type} sn: ${t.sn} of ${this.fragInfo(t,!1)} cc: ${t.cc} ${"["+n.startSN+"-"+n.endSN+"]"}, target: ${s}${t.byteRange.length?` range:${t.byteRange.join("-")}`:""}`),e(t.sn)&&!this.bitrateTest&&(this.nextLoadPosition=t.start+t.duration),this.state=or;const u=this.config.progressive&&t.type!==f.SUBTITLE;let g;return g=u&&d?d.then(e=>!e||this.fragContextChanged(e.frag)?null:this.fragmentLoader.load(t,this.iframesOnly,r,h)).catch(t=>this.handleFragLoadError(t)):Promise.all([this.fragmentLoader.load(t,this.iframesOnly,u?r:void 0,u?h:void 0),d,h]).then(([t])=>(!u&&r&&r(t),t)).catch(t=>this.handleFragLoadError(t)),this.hls.trigger(a.FRAG_LOADING,{frag:t,targetBufferTime:s}),null===this.fragCurrent?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING")):Promise.all([g,h]).then(([t])=>t)}doFragPartsLoad(t,e,i,s){return new Promise((r,n)=>{var o;const l=[],h=null==(o=i.details)?void 0:o.partList,d=e=>{this.fragmentLoader.loadPart(t,e,s).then(s=>{l[e.index]=s;const n=s.part;this.hls.trigger(a.FRAG_LOADED,s);const o=qs(i.details,t.sn,e.index+1)||Ys(h,t.sn,e.index+1);if(!o)return r({frag:t,part:n,partsLoaded:l});d(o)}).catch(n)};d(e)})}handleFragLoadError(t){if("data"in t){const e=t.data;e.frag&&e.details===n.INTERNAL_ABORTED?this.handleFragLoadAborted(e.frag,e.part):e.frag&&e.type===r.KEY_SYSTEM_ERROR&&!e.fatal&&(e.frag.abortRequests(),this.resetStartWhenNotLoaded(),this.resetFragmentLoading(e.frag)),this.hls.trigger(a.ERROR,e)}else this.hls.trigger(a.ERROR,{type:r.OTHER_ERROR,details:n.INTERNAL_EXCEPTION,err:t,error:t,fatal:!0});return null}_handleTransmuxerFlush(t){const e=this.getCurrentContext(t);if(!e||this.state!==dr)return void(this.fragCurrent||this.state===rr||this.state===fr||(this.state=nr));const{frag:i,part:s,level:r}=e,n=self.performance.now();i.stats.parsing.end=n,s&&(s.stats.parsing.end=n);const a=this.getLevelDetails(),o=a&&i.sn>a.endSN||this.shouldLoadParts(a,i.end);o!==this.loadingParts&&(this.log(`LL-Part loading ${o?"ON":"OFF"} after parsing segment ending @${i.end}`),this.loadingParts=o),this.updateLevelTiming(i,s,r,t)}shouldLoadParts(t,e){if(this.config.lowLatencyMode){if(!t)return this.loadingParts;if(t.partList&&!this.iframesOnly){var i;const s=t.partList[0];if(e>=s.end+((null==(i=t.fragmentHint)?void 0:i.duration)||0)){if(this.playhead>s.start-s.fragment.duration)return!0}}}return!1}getCurrentContext(t){const{levels:e,fragCurrent:i}=this,{level:s,sn:r,part:n}=t;if(null==e||!e[s])return this.warn(`Levels object was unset while buffering fragment ${r} of ${this.playlistLabel()} ${s}. The current chunk will not be buffered.`),null;const a=e[s],o=a.details,l=n>-1?qs(o,r,n):null,h=l?l.fragment:Hs(o,r,i);return h?(i&&i!==h&&(h.stats=i.stats),{frag:h,part:l,level:a}):null}bufferFragmentData(t,e,i,s,r){if(this.state!==dr)return;y(e)&&!this.fragContextChanged(e)&&(this.fragPrevious=e);const{data1:n,data2:o}=t;let l=n;if(o&&(l=Ht(n,o)),!l.length)return;const h=this.initPTS[e.cc],d=h?-h.baseTime/h.timescale:void 0,c={type:t.type,frag:e,part:i,chunkMeta:s,offset:d,parent:e.type,data:l};if(this.hls.trigger(a.BUFFER_APPENDING,c),t.dropped&&t.independent&&!i){if(r)return;this.flushBufferGap(e)}}flushBufferGap(t){const e=this.media;if(!e)return;if(!Bi.isBuffered(e,e.currentTime))return void this.flushMainBuffer(0,t.start);const i=e.currentTime,s=Bi.bufferInfo(e,i,0),r=t.duration,n=Math.min(2*this.config.maxFragLookUpTolerance,.25*r),a=Math.max(Math.min(t.start-n,s.end-n),i+n);t.start-a>n&&this.flushMainBuffer(a,t.start)}getFwdBufferInfo(t,e){var i;const s=this.playhead,r=this.lastCurrentTime>s||null!=(i=this.media)&&i.paused?0:this.config.maxBufferHole;return this.getFwdBufferInfoAtPos(t,s,e,r)}getFwdBufferInfoAtPos(t,e,i,s){const r=Bi.bufferInfo(t,e,s);if(0===r.len&&void 0!==r.nextStart){const n=this.fragmentTracker.getBufferedFrag(e,i);if(n&&(r.nextStart<=n.end||n.gap)){const i=Math.max(Math.min(r.nextStart,n.end)-e,s);return Bi.bufferInfo(t,e,i)}}return r}getMaxBufferLength(t){const{config:e}=this;let i;return i=t?Math.max(8*e.maxBufferSize/t,e.maxBufferLength):e.maxBufferLength,Math.min(i,e.maxMaxBufferLength)}exceedsMaxBuffer(t,e,i){const s=t.nextStart;if(s&&i.start>s){const s=t.buffered;if(s){let r=t.len;const n=t.bufferedIndex;for(let t=s.length-1;t>n;t--)s[t].start<i.start&&(r+=s[t].end-s[t].start);return r>=e}}return!1}reduceMaxBufferLength(t,e){const i=this.config,s=Math.max(Math.min(t-e,i.maxBufferLength),e/2),r=Math.max(t-3*e,i.maxMaxBufferLength/2,s);return r>=s&&(i.maxMaxBufferLength=r,this.warn(`Reduce max buffer length to ${r}s`),!0)}getAppendedFrag(t){const e=this.fragmentTracker?this.fragmentTracker.getAppendedFrag(t,this.playlistType):null;return e&&"fragment"in e?e.fragment:e}getNextFragment(t,e){const i=e.fragments,s=i.length;if(!s)return null;const{config:r}=this,n=e.fragmentStart,a=r.lowLatencyMode&&!!e.partList;let o=null;if(e.live){const i=r.initialLiveManifestSize;if(s<i)return this.warn(`Not enough fragments to start playback (have: ${s}, need: ${i})`),null;if(this.startFragRequested||!a||this.loadingParts||(this.log("LL-Part loading ON for initial live fragment"),this.loadingParts=!0),!e.PTSKnown&&!this.startFragRequested&&-1===this.startPosition||t<n){var l;o=this.getInitialLiveFragment(e);const i=this.config.startPosition,s=this.hls.startPosition,r=this.hls.liveSyncPosition,a=(null==(l=o)?void 0:l.start)||0;let h,d;if(-1!==s&&s>=n?(h=s,d=s===i?"config":"next load start"):r?(h=r,d="live edge"):(h=t,d="buffer pos"),h<a&&(h=a,d="live frag start"),h<n&&(h=n,d="playlist start"),this.startPosition!=h||this.nextLoadPosition!=h){const l=e.live&&!this.filterReplacedPrimary(o,e)?-1:h;this.log(`Setting startPosition to ${l} next load ${h} ${-1===s?"":`(from ${i}) `}based on ${d}. live edge: ${r} live frag start: ${a} playlist start: ${n} buffer pos: ${t}`),this.startPosition=l,this.nextLoadPosition=h}}}else t<=n&&(o=i[0]);if(!o){const i=this.loadingParts?e.partEnd:e.fragmentEnd;o=this.getFragmentAtPosition(t,i,e)}let h=this.filterReplacedPrimary(o,e);return!h&&o&&(h=ii(e,o.sn),h&&(this.nextLoadPosition=h.start)),h}isLoopLoading(t,e){if(this.nextLoadPosition<=e)return!1;const i=this.fragmentTracker.getState(t);if(i===Ei)return!0;if(i===yi){if(t.gap)return!0;if(t.stats.retry>1)return!0}return!1}getNextFragmentLoopLoading(t,e,i,s,r){let n=null;if(t.gap&&(n=this.getNextFragment(this.nextLoadPosition,e),n&&!n.gap&&i.nextStart)){const t=this.getFwdBufferInfoAtPos(this.mediaBuffer?this.mediaBuffer:this.media,i.nextStart,s,0);if(null!==t&&i.len+t.len>=r){const t=n.sn;return this.loopSn!==t&&(this.log(`buffer full after gaps in "${s}" playlist starting at sn: ${t}`),this.loopSn=t),null}}return this.loopSn=void 0,n}get primaryPrefetch(){if(yr(this.config)){var t;if(null==(t=this.hls.interstitialsManager)||null==(t=t.playingItem)?void 0:t.event)return!0}return!1}filterReplacedPrimary(t,e){if(!t)return t;if(yr(this.config)&&("type"in t?t:t.fragment).type!==f.SUBTITLE){const i=this.hls.interstitialsManager,s=null==i?void 0:i.bufferingItem;if(s){const i=s.event;if(i){if(!i.appendInPlace&&(Math.abs(t.start-s.start)>1||0===s.start))return null}else{if(t.end<=s.start&&!1===(null==e?void 0:e.live))return null;if(t.start>=s.end&&s.nextEvent&&(s.nextEvent.appendInPlace&&!s.nextEvent.hasPlayed||t.start-s.end>1))return null}}if(vr(t,null==i?void 0:i.playerQueue,this.playhead))return null}return t}getNextPart(t,e,i){let s=-1,r=!1,n=!0;for(let a=0,o=t.length;a<o;a++){const o=t[a];if(n=n&&!o.independent,s>-1&&i<o.start)break;const l=o.loaded||o.gap;l?s=-1:(r||(o.independent||n)&&o.fragment===e)&&(s=a),r=l&&!o.gap}const a=t[s];return a&&a.fragment!==e&&this.log(`Need buffer at ${i} but next unloaded part starts at ${a.start} (sn: ${e.sn} -> ${a.fragment.sn})`),s}loadedEndOfParts(t,e){let i;for(let s=t.length;s--;){if(i=t[s],!i.loaded)return!1;if(e>i.start)return!0}return!1}getInitialLiveFragment(t){const i=t.fragments,s=this.fragPrevious;let r=null;if(s){if(t.hasProgramDateTime&&(r=function(t,i,s){if(null===i||!Array.isArray(t)||!t.length||!e(i))return null;if(i<(t[0].programDateTime||0))return null;if(i>=(t[t.length-1].endProgramDateTime||0))return null;for(let e=0;e<t.length;++e){const r=t[e];if(ti(i,s,r))return r}return null}(i,s.endProgramDateTime,this.config.maxFragLookUpTolerance),r&&this.log(`Live playlist, switching playlist, load frag with same PDT: ${s.programDateTime}`)),!r){const e=s.sn+1;if(e>=t.startSN&&e<=t.endSN){const n=i[e-t.startSN];s.cc===n.cc&&(r=n,this.log(`Live playlist, switching playlist, load frag with next SN: ${r.sn}`))}r||(r=ei(t,s.cc,s.end),r&&this.log(`Live playlist, switching playlist, load frag with same CC: ${r.sn}`))}}else{const e=this.hls.liveSyncPosition;null!==e&&(r=this.getFragmentAtPosition(e,this.bitrateTest?t.fragmentEnd:t.edge,t))}return r}getFragmentAtPosition(t,e,i){const{config:s}=this;let{fragPrevious:r}=this,{fragments:n,endSN:a}=i;const{fragmentHint:o}=i,{maxFragLookUpTolerance:l}=s,h=i.partList,d=!!(this.loadingParts&&null!=h&&h.length&&o);let c;if(d&&!this.bitrateTest&&h[h.length-1].fragment.sn===o.sn&&(n=n.concat(o),a=o.sn),r&&this.fragmentTracker.getState(r)===pi&&(r=null),t<e){var u;c=Ze(r,n,t,t<this.lastCurrentTime||t>e-l||null!=(u=this.media)&&u.paused||!this.startFragRequested?0:l)}else c=n[n.length-1];if(c){const t=c.sn-i.startSN,e=this.fragmentTracker.getState(c);if((e===Ei||e===yi&&c.gap)&&(r=c),E(c,r)&&(!d||h[0].fragment.sn>c.sn||!i.live)){const e=n[t+1];c=c.sn<a&&this.fragmentTracker.getState(e)!==Ei?e:null}}return c}alignPlaylists(t,i,s){const r=t.fragments.length;if(!r)return this.warn("No fragments in live playlist"),0;const n=t.fragmentStart,a=!i,o=t.alignedSliding&&e(n);if(a||!o&&!n){tr(s,t,this);const e=t.fragmentStart;return this.log(`Live playlist sliding: ${e} start-sn: ${i?i.startSN:"na"}->${t.startSN} fragments: ${r}`),e}return n}waitForCdnTuneIn(t){return t.live&&t.canBlockReload&&t.partTarget&&t.tuneInGoal>Math.max(t.partHoldBack,3*t.partTarget)}setStartPosition(t,i){let s=this.startPosition;s<i&&(s=-1);const r=this.timelineOffset;if(-1===s){const n=null!==this.startTimeOffset,a=n?this.startTimeOffset:t.startTimeOffset;if(null!==a&&e(a))s=i+a,a<0&&(s+=t.edge),s=Math.min(Math.max(i,s),i+t.totalduration),this.log(`Setting startPosition to ${s} for start time offset ${a} found in ${n?"multivariant":"media"} playlist`),this.startPosition=s;else if(t.live){const t=this.hls.liveSyncPosition;s=t||i,this.log(`Setting startPosition to -1 to start at ${t?"live edge":"playlist start"} ${s}`),this.startPosition=-1}else this.log("setting startPosition to 0 by default"),this.startPosition=s=0;this.lastCurrentTime=s+r}this.nextLoadPosition=s+r}getLoadPosition(){var t;const{media:e}=this;let i=0;return null!=(t=this.hls)&&t.hasEnoughToStart&&e&&!this.iframesOnly?i=e.currentTime:this.nextLoadPosition>=0&&(i=this.nextLoadPosition),i}get playhead(){var t;if(null!=(t=this.hls)&&t.hasEnoughToStart){var i;const t=null==(i=this.media)?void 0:i.currentTime;return e(t)?t:this.lastCurrentTime}return this.getLoadPosition()}get iframesOnly(){var t;if(this.playlistType!==f.MAIN)return!1;const e=this.getLevelDetails();return e?e.iframesOnly:null==(t=this.levelLastLoaded)?void 0:t.iframes}handleFragLoadAborted(t,e){this.transmuxer&&t.type===this.playlistType&&y(t)&&t.stats.aborted&&(this.log(`Fragment ${t.sn}${e?" part "+e.index:""} of ${this.playlistLabel()} ${t.level} was aborted`),this.resetFragmentLoading(t))}resetFragmentLoading(t){this.fragCurrent&&(this.fragContextChanged(t)||this.state===lr)||(this.state=nr)}onFragmentOrKeyLoadError(t,e){if(e.chunkMeta&&!e.frag){const t=this.getCurrentContext(e.chunkMeta);t&&(e.frag=t.frag)}const{frag:i,part:s}=e;if(!i||!this.levels||i.type!==t)return;var r;if(this.fragContextChanged(i))return void this.warn(`Frag load error must match current frag to retry ${i.relurl} > ${null==(r=this.fragCurrent)?void 0:r.relurl}`);const a=e.details===n.FRAG_GAP;a&&this.fragmentTracker.addAsGap(i);const o=e.errorAction;if(!o)return void(this.state=fr);const{action:l,flags:h,retryCount:d=0,retryConfig:c}=o,u=!!c,f=u&&l===ai,g=u&&!o.resolved&&h&li,m=this.hls.latestLevelDetails,p=null==m?void 0:m.live;if(!f&&g&&y(i)&&p&&i.sn<m.endSN&&!P(e))this.resetFragmentErrors(t),s?s.gap=!0:this.treatAsGap(i),o.resolved=!0;else if((f||g)&&d<c.maxNumRetry){var v;const s=F(null==(v=e.response)?void 0:v.code),r=x(c,d);if(this.resetStartWhenNotLoaded(),this.retryDate=self.performance.now()+r,this.state=lr,o.resolved=!0,s)return this.log("Waiting for connection (offline)"),this.retryDate=1/0,void(e.reason="offline");this.warn(`Fragment ${i.sn} of ${t} ${i.level} errored with ${e.details}, retrying loading ${d+1}/${c.maxNumRetry} in ${r}ms`)}else if(c){if(this.resetFragmentErrors(t),!(d<c.maxNumRetry))return void this.warn(`${e.details} reached or exceeded max retry (${d})`);a||l===ni||(o.resolved=!0)}else this.state=l===ri?mr:fr;this.tickImmediate()}checkRetryDate(){const t=self.performance.now(),e=this.retryDate,i=e===1/0;(!e||t>=e||i&&!F(0))&&(i&&this.log("Connection restored (online)"),this.resetStartWhenNotLoaded(),this.state=nr)}reduceLengthAndFlushBuffer(t){if(this.state===dr||this.state===cr){const e=t.frag,i=t.parent,s=this.getFwdBufferInfo(this.mediaBuffer,i),r=s&&s.len>.5;r&&this.reduceMaxBufferLength(s.len,(null==e?void 0:e.duration)||10);const n=!r;return n?this.warn(`Buffer full error while media.currentTime (${this.playhead}) is not buffered, flush ${i} buffer`):s.nextStart&&e&&s.nextStart>e.start&&this.flushMainBuffer(s.nextStart,Number.POSITIVE_INFINITY,i===f.AUDIO?i:void 0),e&&(this.fragmentTracker.removeFragment(e),this.nextLoadPosition=e.start),this.resetLoadingState(),n}return!1}resetFragmentErrors(t){t===f.AUDIO&&(this.fragCurrent=null),this.hls.hasEnoughToStart||(this.startFragRequested=!1),this.state!==rr&&(this.state=nr)}afterBufferFlushed(t,e){if(!t)return;const i=Bi.getBuffered(t);this.fragmentTracker.detectEvictedFragments(e,i,this.playlistType),this.state===ur&&this.resetLoadingState()}resetLoadingState(){this.log("Reset loading state"),this.fragCurrent=null,this.fragPrevious=null,this.state!==rr&&(this.state=nr)}resetStartWhenNotLoaded(){if(!this.hls.hasEnoughToStart){this.startFragRequested=!1;const t=this.getLevelDetails();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(t){this.log(`Loading context changed while buffering sn ${t.sn} of ${this.playlistLabel()} ${-1===t.level?"<removed>":t.level}. This chunk will not be buffered.`),this.removeUnbufferedFrags(),this.resetStartWhenNotLoaded(),this.resetLoadingState()}removeUnbufferedFrags(t=0){this.fragmentTracker.removeFragmentsInRange(t,1/0,this.playlistType,!1,!0)}updateLevelTiming(t,e,i,s){const o=i.details;if(!o)return void this.warn("level.details undefined");this.log(`update level timing ${t.type} sn: ${t.sn}${e?" part: "+e.index:""} of ${this.fragInfo(t,!1,e)}`);if(!Object.keys(t.elementaryStreams).reduce((e,r)=>{const n=t.elementaryStreams[r];if(n){const l=n.endPTS-n.startPTS;if(l<=0)return this.warn(`Could not parse fragment ${t.sn} ${r} duration reliably (${l})`),e||!1;const h=s.partial?0:Us(o,t,n.startPTS,n.endPTS,n.startDTS,n.endDTS,this.iframesOnly,this);return this.hls.trigger(a.LEVEL_PTS_UPDATED,{details:o,level:i,drift:h,type:r,frag:t,start:n.startPTS,end:n.endPTS}),!0}return e},!1)){var l,h,d,c;const s=null===(null==(l=this.transmuxer)?void 0:l.error),o=null!=(null==(h=this.transmuxer)?void 0:h.error),u=(null!=(d=null==(c=this.levels)?void 0:c.length)?d:0)>1;if((0===i.fragmentError||s&&(i.fragmentError<2||t.endList)||o&&u)&&this.treatAsGap(t,i),s){const s=new Error(`Found no media in ${this.playlistLabel()} ${t.level} ${e?`part: ${e.index} of `:""}sn: ${t.sn} at playlist time: ${t.start}. Resetting transmuxer to fallback to playlist timing`);if(this.warn(s.message),this.hls.trigger(a.ERROR,{type:r.MEDIA_ERROR,details:n.FRAG_PARSING_ERROR,fatal:!1,error:s,frag:t,reason:`Found no media in msn ${t.sn} of ${this.playlistLabel()} "${i.url}"`}),!this.hls)return;this.resetTransmuxer()}}this.state=cr,this.log(`Parsed ${t.type} sn: ${t.sn}${e?" part: "+e.index:""} of ${this.fragInfo(t,!1,e)}`),this.hls.trigger(a.FRAG_PARSED,{frag:t,part:e,chunkMeta:s})}playlistLabel(){return`${this.playlistType} playlist`}fragInfo(t,e=!0,i){var s,r;return`${this.playlistLabel()} ${t.level} (${i?"part":"frag"}:[${null!=(s=e&&!i?t.startPTS:(i||t).start)?s:NaN}-${null!=(r=e&&!i?t.endPTS:(i||t).end)?r:NaN}]${i&&"main"===t.type?"INDEPENDENT="+(i.independent?"YES":"NO"):""})`}treatAsGap(t,e){e&&e.fragmentError++,this.fragmentTracker.addAsGap(t)}resetTransmuxer(){var t;null==(t=this.transmuxer)||t.reset()}isFragmentNearlyDownloaded(t){var e;const i=null==(e=t.loader)?void 0:e.stats;if(!i)return!1;const s=i.loading.first>0,r=(i.total-i.loaded)/(this.hls.bandwidthEstimate||this.hls.config.abrEwmaDefaultEstimate);return s&&r<=.15}recoverWorkerError(t){"demuxerWorker"===t.event&&(this.fragmentTracker.removeAllFragments(),this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null),this.resetStartWhenNotLoaded(),this.resetLoadingState())}set state(t){const e=this._state;e!==t&&(this._state=t,this.log(`${e}->${t}`))}get state(){return this._state}calculateOptimalSwitchPoint(t,e){let i=0;const{hls:s,media:r,config:n,levels:a,playlistType:o}=this,l=this.getLevelDetails();if(r&&!r.paused&&a){var h;const e=o===f.AUDIO?ke(t.audioCodec,128e3):t.maxBitrate,r=1+s.ttfbEstimate/1e3,a=s.bandwidthEstimate*n.abrBandWidthUpFactor;i=r+e*(l&&(this.loadingParts?l.partTarget:l.averagetargetduration)||(null==(h=this.fragCurrent)?void 0:h.duration)||6)/a,t.details||(i+=r)}const d=this.playhead;return{fetchdelay:i,okToFlushForwardBuffer:!(null!=l&&l.live)||e.end-d>1.5*i}}scheduleTrackSwitch(t,e,i){const{media:s,playlistType:r}=this;if(!s||!t)return;const n=i?this.getBufferedFrag(this.playhead+e):null;if(n){const t=this.followingBufferedFrag(n);if(t){var a;this.abortCurrentFrag();const e=t.maxStartPTS?t.maxStartPTS:t.start,i=t.duration,s=Math.max(n.end,e+Math.min(Math.max(i-this.config.maxFragLookUpTolerance,i*(this.couldBacktrack?.5:.125)),i*(this.couldBacktrack?.75:.25)));if(((null==(a=this.getLevelDetails())?void 0:a.fragmentStart)||0)>s)return;const o=r===f.MAIN?null:"audio";this.flushMainBuffer(s,Number.POSITIVE_INFINITY,o),this.cleanupBackBuffer()}}}cleanupBackBuffer(){const{media:t,playlistType:e}=this;if(!t)return;const i=this.getAppendedFrag(this.playhead);if(i&&i.start>1){const t=e===f.AUDIO;this.flushMainBuffer(0,i.start-(t?0:1),t?"audio":null)}}getBufferedFrag(t){return this.fragmentTracker.getBufferedFrag(t,this.playlistType)}followingBufferedFrag(t){return t?this.getBufferedFrag(t.end+.5):null}abortCurrentFrag(){const t=this.fragCurrent;switch(this.fragCurrent=null,t&&(t.abortRequests(),this.fragmentTracker.removeFragment(t)),this.state){case ar:case or:case lr:case dr:case cr:this.state=nr}this.nextLoadPosition=this.playhead}checkFragPlaying(){const t=this.media;let e=null;if(t&&t.readyState>1&&!1===t.seeking){const i=t.currentTime;if(Bi.isBuffered(t,i)?e=this.getAppendedFrag(i):Bi.isBuffered(t,i+.1)&&(e=this.getAppendedFrag(i+.1)),e&&(this.backtrackFragment=void 0,!E(e,this.fragPlaying)))return this.fragPlaying=e,!0}return!1}getBufferOutput(){return null}nextLevelSwitch(){const{levels:t,media:e,hls:i,config:s,playlistType:r}=this;if(null!=e&&e.readyState&&t&&i&&s){const e=this.getBufferOutput(),s=this.getFwdBufferInfo(e,r);if(!s)return;const n=t[r===f.AUDIO?i.nextAudioTrack:i.nextLoadLevel],{fetchdelay:a,okToFlushForwardBuffer:o}=this.calculateOptimalSwitchPoint(n,s);this.scheduleTrackSwitch(s,a,o)}this.tickImmediate()}}function vr(t,e,i){if(e)for(let s=e.length;s--;){const r=e[s].interstitial,n=r.startTime,a=Math.min(n+r.duration,r.resumeTime);if(r.appendInPlace){if(t.start>=n&&t.end<=a)return!0;if(i>t.start&&t.end>n&&t.start<a)return!0}}return!1}function yr(t){return!!t.interstitialsController&&!1!==t.enableInterstitialPlayback}class Er{constructor(){this.chunks=[],this.dataLength=0}push(t){this.chunks.push(t),this.dataLength+=t.length}flush(){const{chunks:t,dataLength:e}=this;let i;return t.length?(i=1===t.length?t[0]:function(t,e){const i=new Uint8Array(e);let s=0;for(let e=0;e<t.length;e++){const r=t[e];i.set(r,s),s+=r.length}return i}(t,e),this.reset(),i):new Uint8Array(0)}reset(){this.chunks.length=0,this.dataLength=0}}var Tr,Sr={exports:{}};var br=(Tr||(Tr=1,function(t){var e=Object.prototype.hasOwnProperty,i="~";function s(){}function r(t,e,i){this.fn=t,this.context=e,this.once=i||!1}function n(t,e,s,n,a){if("function"!=typeof s)throw new TypeError("The listener must be a function");var o=new r(s,n||t,a),l=i?i+e:e;return t._events[l]?t._events[l].fn?t._events[l]=[t._events[l],o]:t._events[l].push(o):(t._events[l]=o,t._eventsCount++),t}function a(t,e){0===--t._eventsCount?t._events=new s:delete t._events[e]}function o(){this._events=new s,this._eventsCount=0}Object.create&&(s.prototype=Object.create(null),(new s).__proto__||(i=!1)),o.prototype.eventNames=function(){var t,s,r=[];if(0===this._eventsCount)return r;for(s in t=this._events)e.call(t,s)&&r.push(i?s.slice(1):s);return Object.getOwnPropertySymbols?r.concat(Object.getOwnPropertySymbols(t)):r},o.prototype.listeners=function(t){var e=i?i+t:t,s=this._events[e];if(!s)return[];if(s.fn)return[s.fn];for(var r=0,n=s.length,a=new Array(n);r<n;r++)a[r]=s[r].fn;return a},o.prototype.listenerCount=function(t){var e=i?i+t:t,s=this._events[e];return s?s.fn?1:s.length:0},o.prototype.emit=function(t,e,s,r,n,a){var o=i?i+t:t;if(!this._events[o])return!1;var l,h,d=this._events[o],c=arguments.length;if(d.fn){switch(d.once&&this.removeListener(t,d.fn,void 0,!0),c){case 1:return d.fn.call(d.context),!0;case 2:return d.fn.call(d.context,e),!0;case 3:return d.fn.call(d.context,e,s),!0;case 4:return d.fn.call(d.context,e,s,r),!0;case 5:return d.fn.call(d.context,e,s,r,n),!0;case 6:return d.fn.call(d.context,e,s,r,n,a),!0}for(h=1,l=new Array(c-1);h<c;h++)l[h-1]=arguments[h];d.fn.apply(d.context,l)}else{var u,f=d.length;for(h=0;h<f;h++)switch(d[h].once&&this.removeListener(t,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,e);break;case 3:d[h].fn.call(d[h].context,e,s);break;case 4:d[h].fn.call(d[h].context,e,s,r);break;default:if(!l)for(u=1,l=new Array(c-1);u<c;u++)l[u-1]=arguments[u];d[h].fn.apply(d[h].context,l)}}return!0},o.prototype.on=function(t,e,i){return n(this,t,e,i,!1)},o.prototype.once=function(t,e,i){return n(this,t,e,i,!0)},o.prototype.removeListener=function(t,e,s,r){var n=i?i+t:t;if(!this._events[n])return this;if(!e)return a(this,n),this;var o=this._events[n];if(o.fn)o.fn!==e||r&&!o.once||s&&o.context!==s||a(this,n);else{for(var l=0,h=[],d=o.length;l<d;l++)(o[l].fn!==e||r&&!o[l].once||s&&o[l].context!==s)&&h.push(o[l]);h.length?this._events[n]=1===h.length?h[0]:h:a(this,n)}return this},o.prototype.removeAllListeners=function(t){var e;return t?(e=i?i+t:t,this._events[e]&&a(this,e)):(this._events=new s,this._eventsCount=0),this},o.prototype.off=o.prototype.removeListener,o.prototype.addListener=o.prototype.on,o.prefixed=i,o.EventEmitter=o,t.exports=o}(Sr)),Sr.exports),Ar=o(br);const Lr="1.7.3",Ir={};function Rr(t,e){return 255===t[e]&&240==(246&t[e+1])}function kr(t,e){return 1&t[e+1]?7:9}function _r(t,e){return(3&t[e+3])<<11|t[e+4]<<3|(224&t[e+5])>>>5}function Dr(t,e){return e+1<t.length&&Rr(t,e)}function wr(t,e){if(Dr(t,e)){const i=kr(t,e);if(e+i>=t.length)return!1;const s=_r(t,e);if(s<=i)return!1;const r=e+s;return r===t.length||Dr(t,r)}return!1}function Pr(t,e,i,s,o){if(!t.samplerate){const l=function(t,e,i,s){const o=e[i+2],l=o>>2&15;if(l>12){const e=new Error(`invalid ADTS sampling index:${l}`);return void t.emit(a.ERROR,a.ERROR,{type:r.MEDIA_ERROR,details:n.FRAG_PARSING_ERROR,fatal:!0,error:e,reason:e.message})}const h=1+(o>>6&3),d=e[i+3]>>6&3|(1&o)<<2,c=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350][l];let u,f=l;5!==h&&29!==h||(f-=3);const g=(14&f)>>1,m=(1&f)<<7|d<<3;let p=0;if(1===h&&l>=6){p=5;const t=l-3;u=[p<<3|g,m|(14&t)>>1,(1&t)<<7|8,0]}else u=[h<<3|g,m];const v="mp4a.40."+(p||h);return q.log(`manifest codec:${s}, parsed codec:${v}, channels:${d}, rate:${c} (ADTS object type:${h} sampling index:${l} esds config:[${u.join(",")}])`),{config:u,samplerate:c,channelCount:d,codec:v,parsedCodec:v,manifestCodec:s}}(e,i,s,o);if(!l)return;I(t,l)}}function Cr(t){return 9216e4/t}function xr(t,e,i,s,r){const n=s+r*Cr(t.samplerate),a=function(t,e){const i=kr(t,e);if(e+i<=t.length){const s=_r(t,e)-i;if(s>0)return{headerLength:i,frameLength:s}}}(e,i);let o;if(a){const{frameLength:s,headerLength:r}=a,l=r+s,h=Math.max(0,i+l-e.length);h?(o=new Uint8Array(l-r),o.set(e.subarray(i+r,e.length),0)):o=e.subarray(i+r,i+l);const d={unit:o,pts:n};return h||t.samples.push(d),{sample:d,length:l,missing:h}}const l=e.length-i;o=new Uint8Array(l),o.set(e.subarray(i,e.length),0);return{sample:{unit:o,pts:n},length:l,missing:-1}}let Mr=function(t){return t.audioId3="org.id3",t.dateRange="com.apple.quicktime.HLS",t.emsg="https://aomedia.org/emsg/ID3",t.misbklv="urn:misb:KLV:bin:1910.1",t}({});function Or(t="",e=9e4){return{type:t,id:-1,pid:-1,inputTimeScale:e,sequenceNumber:-1,samples:[],dropped:0}}class Fr{constructor(){this._audioTrack=void 0,this._id3Track=void 0,this.frameIndex=0,this.cachedData=null,this.basePTS=null,this.initPTS=null,this.lastPTS=null}resetInitSegment(t,e,i,s){this._id3Track={type:"id3",id:3,pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0}}resetTimeStamp(t){this.initPTS=t,this.resetContiguity()}resetContiguity(){this.basePTS=null,this.lastPTS=null,this.frameIndex=0}canParse(t,e){return!1}appendFrame(t,e,i){}demux(t,i){this.cachedData&&(t=Ht(this.cachedData,t),this.cachedData=null);let s,r=nt(t,0),n=r?r.length:0;const a=this._audioTrack,o=this._id3Track,l=r?gt(r):void 0,h=t.length;for((null===this.basePTS||0===this.frameIndex&&e(l))&&(this.basePTS=Nr(l,i,this.initPTS),this.lastPTS=this.basePTS),null===this.lastPTS&&(this.lastPTS=this.basePTS),r&&r.length>0&&o.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:r,type:Mr.audioId3,duration:Number.POSITIVE_INFINITY});n<h;){if(this.canParse(t,n)){const e=this.appendFrame(a,t,n);e?(this.frameIndex++,this.lastPTS=e.sample.pts,n+=e.length,s=n):n=h}else st(t,n)?(r=nt(t,n),o.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:r,type:Mr.audioId3,duration:Number.POSITIVE_INFINITY}),n+=r.length,s=n):n++;if(n===h&&s!==h){const e=t.slice(s);this.cachedData?this.cachedData=Ht(this.cachedData,e):this.cachedData=e}}return{audioTrack:a,videoTrack:Or(),id3Track:o,textTrack:Or()}}demuxSampleAes(t,e,i){return Promise.reject(new Error(`[${this}] This demuxer does not support Sample-AES decryption`))}flush(t){const e=this.cachedData;return e&&(this.cachedData=null,this.demux(e,0)),{audioTrack:this._audioTrack,videoTrack:Or(),id3Track:this._id3Track,textTrack:Or()}}destroy(){this.cachedData=null,this._audioTrack=this._id3Track=void 0}}const Nr=(t,i,s)=>{if(e(t))return 90*t;return 9e4*i+(s?9e4*s.baseTime/s.timescale:0)},$r=[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],Br=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],Ur=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],Gr=[0,1,1,4];function Kr(t,e,i,s,r){if(i+24>e.length)return;const n=Vr(e,i);if(n&&i+n.frameLength<=e.length){const a=s+r*(9e4*n.samplesPerFrame/n.sampleRate),o={unit:e.subarray(i,i+n.frameLength),pts:a,dts:a};return t.config=[],t.channelCount=n.channelCount,t.samplerate=n.sampleRate,t.samples.push(o),{sample:o,length:n.frameLength,missing:0}}}function Vr(t,e){const i=t[e+1]>>3&3,s=t[e+1]>>1&3,r=t[e+2]>>4&15,n=t[e+2]>>2&3;if(1!==i&&0!==r&&15!==r&&3!==n){const a=t[e+2]>>1&1,o=t[e+3]>>6,l=1e3*$r[14*(3===i?3-s:3===s?3:4)+r-1],h=Br[3*(3===i?0:2===i?1:2)+n],d=3===o?1:2,c=Ur[i][s],u=Gr[s],f=8*c*u,g=Math.floor(c*l/h+a)*u,m=ne();return!!m&&m<=87&&2===s&&l>=224e3&&0===o&&(t[e+3]=128|t[e+3]),{sampleRate:h,channelCount:d,frameLength:g,samplesPerFrame:f}}}function jr(t,e){return!(255!==t[e]||224&~t[e+1]||!(6&t[e+1]))}function Hr(t,e){return e+1<t.length&&jr(t,e)}function qr(t,e){if(e+1<t.length&&jr(t,e)){const i=4,s=Vr(t,e);let r=i;null!=s&&s.frameLength&&(r=s.frameLength);const n=e+r;return n===t.length||Hr(t,n)}return!1}class Yr{constructor(t,e,i){this.keyData=void 0,this.decrypter=void 0,this.keyData=i,this.decrypter=new Di(e,!0)}decryptBuffer(t){return this.decrypter.decrypt(t,this.keyData.key.buffer,this.keyData.iv.buffer,Li,{start:0,end:t.byteLength})}decryptAacSample(t,e,i){const s=t[e].unit;if(s.length<=16)return;const r=s.subarray(16,s.length-s.length%16),n=r.buffer.slice(r.byteOffset,r.byteOffset+r.length);this.decryptBuffer(n).then(r=>{const n=new Uint8Array(r);s.set(n,16),this.decrypter.isSync()||this.decryptAacSamples(t,e+1,i)}).catch(i)}decryptAacSamples(t,e,i){for(;;e++){if(e>=t.length)return void i();if(!(t[e].unit.length<32)&&(this.decryptAacSample(t,e,i),!this.decrypter.isSync()))return}}getAvcEncryptedData(t){const e=16*Math.floor((t.length-48)/160)+16,i=new Int8Array(e);let s=0;for(let e=32;e<t.length-16;e+=160,s+=16)i.set(t.subarray(e,e+16),s);return i}getAvcDecryptedUnit(t,e){const i=new Uint8Array(e);let s=0;for(let e=32;e<t.length-16;e+=160,s+=16)t.set(i.subarray(s,s+16),e);return t}decryptAvcSample(t,e,i,s,r){const n=zt(r.data),a=this.getAvcEncryptedData(n);this.decryptBuffer(a.buffer).then(a=>{r.data=this.getAvcDecryptedUnit(n,a),this.decrypter.isSync()||this.decryptAvcSamples(t,e,i+1,s)}).catch(s)}decryptAvcSamples(t,e,i,s){if(t instanceof Uint8Array)throw new Error("Cannot decrypt samples of type Uint8Array");for(;;e++,i=0){if(e>=t.length)return void s();const r=t[e].units;for(;!(i>=r.length);i++){const n=r[i];if(!(n.data.length<=48||1!==n.type&&5!==n.type||(this.decryptAvcSample(t,e,i,s,n),this.decrypter.isSync())))return}}}}const Wr=(t,e)=>{let i=0,s=5;e+=s;const r=new Uint32Array(1),n=new Uint32Array(1),a=new Uint8Array(1);for(;s>0;){a[0]=t[e];const o=Math.min(s,8),l=8-o;n[0]=4278190080>>>24+l<<l,r[0]=(a[0]&n[0])>>l,i=i?i<<o|r[0]:r[0],e+=1,s-=o}return i};class zr extends Fr{constructor(t){super(),this.observer=void 0,this.observer=t}resetInitSegment(t,e,i,s){super.resetInitSegment(t,e,i,s),this._audioTrack={container:"audio/ac-3",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"ac3",samples:[],manifestCodec:e,duration:s,inputTimeScale:9e4,dropped:0}}canParse(t,e){return e+64<t.length}appendFrame(t,e,i){const s=Xr(t,e,i,this.basePTS,this.frameIndex);if(-1!==s){return{sample:t.samples[t.samples.length-1],length:s,missing:0}}}static probe(t){if(!t)return!1;const e=nt(t,0);if(!e)return!1;const i=e.length;if(11===t[i]&&119===t[i+1]&&void 0!==gt(e)){if(Wr(t,i)<16)return!0;throw new Error("Containerless ec-3 is not supported")}return!1}}function Xr(t,e,i,s,r){if(i+8>e.length)return-1;if(11!==e[i]||119!==e[i+1])return-1;const n=e[i+4]>>6;if(n>=3)return-1;const a=[48e3,44100,32e3][n],o=63&e[i+4],l=2*[64,69,96,64,70,96,80,87,120,80,88,120,96,104,144,96,105,144,112,121,168,112,122,168,128,139,192,128,140,192,160,174,240,160,175,240,192,208,288,192,209,288,224,243,336,224,244,336,256,278,384,256,279,384,320,348,480,320,349,480,384,417,576,384,418,576,448,487,672,448,488,672,512,557,768,512,558,768,640,696,960,640,697,960,768,835,1152,768,836,1152,896,975,1344,896,976,1344,1024,1114,1536,1024,1115,1536,1152,1253,1728,1152,1254,1728,1280,1393,1920,1280,1394,1920][3*o+n];if(i+l>e.length)return-1;const h=e[i+6]>>5;let d=0;2===h?d+=2:(1&h&&1!==h&&(d+=2),4&h&&(d+=2));const c=(e[i+6]<<8|e[i+7])>>12-d&1,u=[2,1,2,3,3,4,4,5][h]+c,f=e[i+5]>>3,g=7&e[i+5],m=new Uint8Array([n<<6|f<<1|g>>2,(3&g)<<6|h<<3|c<<2|o>>4,o<<4&224]),p=s+r*(1536/a*9e4),v=e.subarray(i,i+l);return t.config=m,t.channelCount=u,t.samplerate=a,t.samples.push({unit:v,pts:p}),l}const Qr=/\/emsg[-/]ID3/i;function Zr(t,i){return e(t.presentationTime)?t.presentationTime/t.timeScale:i+t.presentationTimeDelta/t.timeScale}class Jr{constructor(){this.VideoSample=null}createVideoSample(t,e,i){return{key:t,frame:!1,pts:e,dts:i,units:[],length:0}}getLastNalUnit(t){var e;let i,s=this.VideoSample;if(s&&0!==s.units.length||(s=t[t.length-1]),null!=(e=s)&&e.units){const t=s.units;i=t[t.length-1]}return i}pushAccessUnit(t,e){if(t.units.length&&t.frame){if(void 0===t.pts){const i=e.samples,s=i.length;if(!s)return void e.dropped++;{const e=i[s-1];t.pts=e.pts,t.dts=e.dts}}e.samples.push(t)}}parseNALu(t,e,i){const s=e.byteLength;if(0===s)return[];const r=t.naluState||0,n=-1===r?0:r,a=[];let o=0,l=0,h=-1,d=0;for(-1===r&&(h=0,d=this.getNALuType(e,0),l=1);l<s;){const i=e.indexOf(1,l);if(-1===i)break;l=i+1;let r=i;for(;r>0&&0===e[r-1];)r--;if(!(i-r+(0===r?n:0)<2)){if(h>=0)a.push({data:e.subarray(h,r),type:d});else{const i=this.getLastNalUnit(t.samples);i&&(r>0?i.data=Ht(i.data,e.subarray(0,r)):n>0&&(i.data=i.data.subarray(0,i.data.byteLength-n)),i.state=0)}if(!(l<s)){o=-1,h=-1;break}h=l,d=this.getNALuType(e,l)}}if(-1!==o){let t=s;for(;t>0&&0===e[t-1];)t--;o=s-t+(0===t?n:0)}if(h>=0)a.push({data:e.subarray(h),type:d,state:o});else if(0===a.length&&-1!==o){const i=this.getLastNalUnit(t.samples);i&&(i.data=Ht(i.data,e),i.state=o)}return t.naluState=o,a}}class tn{constructor(t){this.data=void 0,this.bytesAvailable=void 0,this.word=void 0,this.bitsAvailable=void 0,this.data=t,this.bytesAvailable=t.byteLength,this.word=0,this.bitsAvailable=0}loadWord(){const t=this.data,e=this.bytesAvailable,i=t.byteLength-e,s=new Uint8Array(4),r=Math.min(4,e);if(0===r)throw new Error("no bytes available");s.set(t.subarray(i,i+r)),this.word=new DataView(s.buffer).getUint32(0),this.bitsAvailable=8*r,this.bytesAvailable-=r}skipBits(t){let e;t=Math.min(t,8*this.bytesAvailable+this.bitsAvailable),this.bitsAvailable>t?(this.word<<=t,this.bitsAvailable-=t):(e=(t-=this.bitsAvailable)>>3,t-=e<<3,this.bytesAvailable-=e,this.loadWord(),this.word<<=t,this.bitsAvailable-=t)}readBits(t){let e=Math.min(this.bitsAvailable,t);const i=this.word>>>32-e;if(t>32&&q.error("Cannot read more than 32 bits at a time"),this.bitsAvailable-=e,this.bitsAvailable>0)this.word<<=e;else{if(!(this.bytesAvailable>0))throw new Error("no bits available");this.loadWord()}return e=t-e,e>0&&this.bitsAvailable?i<<e|this.readBits(e):i}skipLZ(){let t;for(t=0;t<this.bitsAvailable;++t)if(this.word&2147483648>>>t)return this.word<<=t,this.bitsAvailable-=t,t;return this.loadWord(),t+this.skipLZ()}skipUEG(){this.skipBits(1+this.skipLZ())}skipEG(){this.skipBits(1+this.skipLZ())}readUEG(){const t=this.skipLZ();return this.readBits(t+1)-1}readEG(){const t=this.readUEG();return 1&t?1+t>>>1:-1*(t>>>1)}readBoolean(){return 1===this.readBits(1)}readUByte(){return this.readBits(8)}}class en extends Jr{parsePES(t,e,i,s,r){const n=r.iframe,a=this.parseNALu(t,i.data,s);let o,l=this.VideoSample,h=!1;i.data=null,l&&a.length&&!t.audFound&&(this.pushAccessUnit(l,t),l=this.VideoSample=this.createVideoSample(!1,i.pts,i.dts)),a.forEach(s=>{var r,a;switch(s.type){case 1:{if(n)break;let e=!1;o=!0;const r=s.data;if(h&&r.length>4){const t=this.readSliceType(r);2!==t&&4!==t&&7!==t&&9!==t||(e=!0)}var d;if(e)null!=(d=l)&&d.frame&&!l.key&&(this.pushAccessUnit(l,t),l=this.VideoSample=null);l||(l=this.VideoSample=this.createVideoSample(!0,i.pts,i.dts)),l.frame=!0,l.key=e;break}case 5:o=!0,null!=(r=l)&&r.frame&&!l.key&&(this.pushAccessUnit(l,t),l=this.VideoSample=null),l||(l=this.VideoSample=this.createVideoSample(!0,i.pts,i.dts)),l.key=!0,l.frame=!0;break;case 6:if(n)break;o=!0,Wt(s.data,1,i.pts,e.samples);break;case 7:{var c,u;o=!0,h=!0;const e=s.data,i=this.readSPS(e);if(!t.sps||t.width!==i.width||t.height!==i.height||(null==(c=t.pixelRatio)?void 0:c[0])!==i.pixelRatio[0]||(null==(u=t.pixelRatio)?void 0:u[1])!==i.pixelRatio[1]){t.width=i.width,t.height=i.height,t.pixelRatio=i.pixelRatio,t.sps=[e];const s=e.subarray(1,4);let r="avc1.";for(let t=0;t<3;t++){let e=s[t].toString(16);e.length<2&&(e="0"+e),r+=e}t.codec=r}break}case 8:o=!0,t.pps=[s.data];break;case 9:o=!0,t.audFound=!0,null!=(a=l)&&a.frame&&(this.pushAccessUnit(l,t),l=null),l||(l=this.VideoSample=this.createVideoSample(!1,i.pts,i.dts));break;case 12:o=!0;break;default:o=!1}if(l&&o){l.units.push(s)}}),s&&l&&(this.pushAccessUnit(l,t),this.VideoSample=null)}getNALuType(t,e){return 31&t[e]}readSliceType(t){const e=new tn(t);return e.readUByte(),e.readUEG(),e.readUEG()}skipScalingList(t,e){let i,s=8,r=8;for(let n=0;n<t;n++)0!==r&&(i=e.readEG(),r=(s+i+256)%256),s=0===r?s:r}readSPS(t){const e=new tn(t);let i,s,r,n=0,a=0,o=0,l=0;const h=e.readUByte.bind(e),d=e.readBits.bind(e),c=e.readUEG.bind(e),u=e.readBoolean.bind(e),f=e.skipBits.bind(e),g=e.skipEG.bind(e),m=e.skipUEG.bind(e),p=this.skipScalingList.bind(this);h();const v=h();if(d(5),f(3),h(),m(),100===v||110===v||122===v||244===v||44===v||83===v||86===v||118===v||128===v){const t=c();if(3===t&&f(1),m(),m(),f(1),u())for(s=3!==t?8:12,r=0;r<s;r++)u()&&p(r<6?16:64,e)}m();const y=c();if(0===y)c();else if(1===y)for(f(1),g(),g(),i=c(),r=0;r<i;r++)g();m(),f(1);const E=c(),T=c(),S=d(1);0===S&&f(1),f(1),u()&&(n=c(),a=c(),o=c(),l=c());let b=[1,1];if(u()&&u()){switch(h()){case 1:b=[1,1];break;case 2:b=[12,11];break;case 3:b=[10,11];break;case 4:b=[16,11];break;case 5:b=[40,33];break;case 6:b=[24,11];break;case 7:b=[20,11];break;case 8:b=[32,11];break;case 9:b=[80,33];break;case 10:b=[18,11];break;case 11:b=[15,11];break;case 12:b=[64,33];break;case 13:b=[160,99];break;case 14:b=[4,3];break;case 15:b=[3,2];break;case 16:b=[2,1];break;case 255:b=[h()<<8|h(),h()<<8|h()]}}return{width:Math.ceil(16*(E+1)-2*n-2*a),height:(2-S)*(T+1)*16-(S?2:4)*(o+l),pixelRatio:b}}}class sn extends Jr{constructor(...t){super(...t),this.initVPS=null}parsePES(t,e,i,s){const r=this.parseNALu(t,i.data,s);let n,a=this.VideoSample,o=!1;i.data=null;const l=t=>(a=this.VideoSample=this.createVideoSample(t,i.pts,i.dts),a);r.forEach((s,r)=>{var h,d;if(this.startsNewAccessUnit(a,t,s,r)){this.pushAccessUnit(a,t);const e=s.type>=16&&s.type<=23;a=l(e),o=!1}switch(s.type){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:case 8:case 9:a||(a=l(!1)),a.frame=!0,n=!0;break;case 16:case 17:case 18:case 21:case 22:case 23:var c;if(n=!0,o)null!=(c=a)&&c.frame&&!a.key&&(this.pushAccessUnit(a,t),a=this.VideoSample=null);a||(a=l(!0)),a.key=!0,a.frame=!0;break;case 19:case 20:n=!0,null!=(h=a)&&h.frame&&!a.key&&(this.pushAccessUnit(a,t),a=this.VideoSample=null),a||(a=l(!0)),a.key=!0,a.frame=!0;break;case 39:n=!0,Wt(s.data,2,i.pts,e.samples);break;case 32:n=!0,t.vps||("object"!=typeof t.params&&(t.params={}),t.params=I(t.params,this.readVPS(s.data)),this.initVPS=s.data),t.vps=[s.data];break;case 33:if(n=!0,o=!0,void 0===t.vps||t.vps[0]===this.initVPS||void 0===t.sps||this.matchSPS(t.sps[0],s.data)||(this.initVPS=t.vps[0],t.sps=t.pps=void 0),!t.sps){const e=this.readSPS(s.data);t.width=e.width,t.height=e.height,t.pixelRatio=e.pixelRatio,t.codec=e.codecString,t.sps=[],"object"!=typeof t.params&&(t.params={});for(const i in e.params)t.params[i]=e.params[i]}this.pushParameterSet(t.sps,s.data,t.vps),a||(a=l(!1));break;case 34:if(n=!0,"object"==typeof t.params){if(!t.pps){t.pps=[];const e=this.readPPS(s.data);for(const i in e)t.params[i]=e[i]}this.pushParameterSet(t.pps,s.data,t.vps)}break;case 35:n=!0,t.audFound=!0,null!=(d=a)&&d.frame&&(this.pushAccessUnit(a,t),a=null),a||(a=l(!1));break;default:n=!1}if(a&&n){a.units.push(s)}}),s&&a&&(this.pushAccessUnit(a,t),this.VideoSample=null)}pushParameterSet(t,e,i){(i&&i[0]===this.initVPS||!i&&!t.length)&&t.push(e)}startsNewAccessUnit(t,e,i,s){if(!t)return!1;if(!e.audFound&&0===s)return!0;if(!t.frame)return!1;const{type:r,data:n}=i;return!!(r>=32&&r<=35||39===r||r>=41&&r<=44||r>=48&&r<=55)||r<=31&&n.length>2&&!!(128&n[2])}getNALuType(t,e){return(126&t[e])>>>1}ebsp2rbsp(t){const e=new Uint8Array(t.byteLength);let i=0;for(let s=0;s<t.byteLength;s++)s>=2&&3===t[s]&&0===t[s-1]&&0===t[s-2]||(e[i]=t[s],i++);return new Uint8Array(e.buffer,0,i)}pushAccessUnit(t,e){super.pushAccessUnit(t,e),this.initVPS&&(this.initVPS=null)}readVPS(t){const e=new tn(t);e.readUByte(),e.readUByte(),e.readBits(4),e.skipBits(2),e.readBits(6);return{numTemporalLayers:e.readBits(3)+1,temporalIdNested:e.readBoolean()}}readSPS(t){const e=new tn(this.ebsp2rbsp(t));e.readUByte(),e.readUByte(),e.readBits(4);const i=e.readBits(3);e.readBoolean();const s=e.readBits(2),r=e.readBoolean(),n=e.readBits(5),a=e.readUByte(),o=e.readUByte(),l=e.readUByte(),h=e.readUByte(),d=e.readUByte(),c=e.readUByte(),u=e.readUByte(),f=e.readUByte(),g=e.readUByte(),m=e.readUByte(),p=e.readUByte(),v=[],y=[];for(let t=0;t<i;t++)v.push(e.readBoolean()),y.push(e.readBoolean());if(i>0)for(let t=i;t<8;t++)e.readBits(2);for(let t=0;t<i;t++)v[t]&&(e.readUByte(),e.readUByte(),e.readUByte(),e.readUByte(),e.readUByte(),e.readUByte(),e.readUByte(),e.readUByte(),e.readUByte(),e.readUByte(),e.readUByte()),y[t]&&e.readUByte();e.readUEG();const E=e.readUEG();3==E&&e.skipBits(1);const T=e.readUEG(),S=e.readUEG(),b=e.readBoolean();let A=0,L=0,I=0,R=0;b&&(A+=e.readUEG(),L+=e.readUEG(),I+=e.readUEG(),R+=e.readUEG());const k=e.readUEG(),_=e.readUEG(),D=e.readUEG();for(let t=e.readBoolean()?0:i;t<=i;t++)e.skipUEG(),e.skipUEG(),e.skipUEG();e.skipUEG(),e.skipUEG(),e.skipUEG(),e.skipUEG(),e.skipUEG(),e.skipUEG();if(e.readBoolean()){if(e.readBoolean())for(let t=0;t<4;t++)for(let i=0;i<(3===t?2:6);i++){if(e.readBoolean()){const i=Math.min(64,1<<4+(t<<1));t>1&&e.readEG();for(let t=0;t<i;t++)e.readEG()}else e.readUEG()}}e.readBoolean(),e.readBoolean();e.readBoolean()&&(e.readUByte(),e.skipUEG(),e.skipUEG(),e.readBoolean());const w=e.readUEG();let P=0;for(let t=0;t<w;t++){let i=!1;if(0!==t&&(i=e.readBoolean()),i){t===w&&e.readUEG(),e.readBoolean(),e.readUEG();let i=0;for(let t=0;t<=P;t++){const t=e.readBoolean();let s=!1;t||(s=e.readBoolean()),(t||s)&&i++}P=i}else{const t=e.readUEG(),i=e.readUEG();P=t+i;for(let i=0;i<t;i++)e.readUEG(),e.readBoolean();for(let t=0;t<i;t++)e.readUEG(),e.readBoolean()}}if(e.readBoolean()){const t=e.readUEG();for(let i=0;i<t;i++){for(let t=0;t<D+4;t++)e.readBits(1);e.readBits(1)}}let C=0,x=1,M=1,O=!0,F=1,N=0;e.readBoolean(),e.readBoolean();let $=!1;if(e.readBoolean()){if(e.readBoolean()){const t=e.readUByte();t>0&&t<16?(x=[1,12,10,16,40,24,20,32,80,18,15,64,160,4,3,2][t-1],M=[1,11,11,11,33,11,11,11,33,11,11,33,99,3,2,1][t-1]):255===t&&(x=e.readBits(16),M=e.readBits(16))}e.readBoolean()&&e.readBoolean();if(e.readBoolean()){e.readBits(3),e.readBoolean();e.readBoolean()&&(e.readUByte(),e.readUByte(),e.readUByte())}e.readBoolean()&&(e.readUEG(),e.readUEG()),e.readBoolean(),e.readBoolean(),e.readBoolean(),$=e.readBoolean(),$&&(e.skipUEG(),e.skipUEG(),e.skipUEG(),e.skipUEG());if(e.readBoolean()){F=e.readBits(32),N=e.readBits(32);e.readBoolean()&&e.readUEG();if(e.readBoolean()){const t=e.readBoolean(),s=e.readBoolean();let r=!1;(t||s)&&(r=e.readBoolean(),r&&(e.readUByte(),e.readBits(5),e.readBoolean(),e.readBits(5)),e.readBits(4),e.readBits(4),r&&e.readBits(4),e.readBits(5),e.readBits(5),e.readBits(5));for(let n=0;n<=i;n++){O=e.readBoolean();let i=!1;O||e.readBoolean()?e.readEG():i=e.readBoolean();const n=i?1:e.readUEG()+1;if(t)for(let t=0;t<n;t++)e.readUEG(),e.readUEG(),r&&(e.readUEG(),e.readUEG()),e.skipBits(1);if(s)for(let t=0;t<n;t++)e.readUEG(),e.readUEG(),r&&(e.readUEG(),e.readUEG()),e.skipBits(1)}}}e.readBoolean()&&(e.readBoolean(),e.readBoolean(),e.readBoolean(),C=e.readUEG())}let B=T,U=S;if(b){let t=1,e=1;1===E?t=e=2:2==E&&(t=2),B=T-t*L-t*A,U=S-e*R-e*I}const G=s?["A","B","C"][s]:"",K=a<<24|o<<16|l<<8|h;let V=0;for(let t=0;t<32;t++)V=(V|(K>>t&1)<<31-t)>>>0;let j=V.toString(16);1===n&&"2"===j&&(j="6");return{codecString:`hvc1.${G}${n}.${j}.${r?"H":"L"}${p}.B0`,params:{general_tier_flag:r,general_profile_idc:n,general_profile_space:s,general_profile_compatibility_flags:[a,o,l,h],general_constraint_indicator_flags:[d,c,u,f,g,m],general_level_idc:p,bit_depth:k+8,bit_depth_luma_minus8:k,bit_depth_chroma_minus8:_,min_spatial_segmentation_idc:C,chroma_format_idc:E,frame_rate:{fixed:O,fps:N/F}},width:B,height:U,pixelRatio:[x,M]}}readPPS(t){const e=new tn(this.ebsp2rbsp(t));e.readUByte(),e.readUByte(),e.skipUEG(),e.skipUEG(),e.skipBits(2),e.skipBits(3),e.skipBits(2),e.skipUEG(),e.skipUEG(),e.skipEG(),e.skipBits(2);e.readBoolean()&&e.skipUEG(),e.skipEG(),e.skipEG(),e.skipBits(4);const i=e.readBoolean(),s=e.readBoolean();let r=1;return s&&i?r=0:s?r=3:i&&(r=2),{parallelismType:r}}matchSPS(t,e){return yt(t).substring(3)===yt(e).substring(3)}}const rn=188;class nn{constructor(t,e,i,s){this.logger=void 0,this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.sampleAes=null,this.pmtParsed=!1,this.audioCodec=void 0,this.videoCodec=void 0,this._pmtId=-1,this._videoTrack=void 0,this._audioTrack=void 0,this._id3Track=void 0,this._txtTrack=void 0,this._klvPid=-1,this.aacOverFlow=null,this.remainderData=null,this.videoParser=void 0,this.videoIntegrityChecker=null,this.observer=t,this.config=e,this.typeSupported=i,this.logger=s,this.videoParser=null}static probe(t,e){const i=nn.syncOffset(t);return i>0&&e.warn(`MPEG2-TS detected but first sync word found @ offset ${i}`),-1!==i}static syncOffset(t){const e=t.length;let i=Math.min(940,e-rn)+1,s=0;for(;s<i;){let r=!1,n=-1,a=0;for(let o=s;o<e;o+=rn){if(71!==t[o]||e-o!==rn&&71!==t[o+rn]){if(a)return-1;break}if(a++,-1===n&&(n=o,0!==n&&(i=Math.min(n+18612,t.length-rn)+1)),r||(r=0===an(t,o)),r&&a>1&&(0===n&&a>2||o+rn>i))return n}s++}return-1}static createTrack(t,e){return{container:"video"===t||"audio"===t?"video/mp2t":void 0,type:t,id:St[t],pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0,duration:"audio"===t?e:void 0}}resetInitSegment(t,e,i,s,r,n){this.pmtParsed=!1,this._pmtId=-1,this._videoTrack=nn.createTrack("video"),this._videoTrack.duration=s,this.videoIntegrityChecker="skip"===this.config.handleMpegTsVideoIntegrityErrors?new un(this.logger):null,this._audioTrack=nn.createTrack("audio",s),this._id3Track=nn.createTrack("id3"),this._txtTrack=nn.createTrack("text"),this._audioTrack.segmentCodec="aac",this.videoParser=null,this.aacOverFlow=null,this.remainderData=null,this.audioCodec=e,this.videoCodec=i,t&&this.demux(t,0,n,"SAMPLE-AES"===(null==r?void 0:r.method))}resetTimeStamp(){}resetContiguity(){const{_audioTrack:t,_videoTrack:e,_id3Track:i}=this;t&&(t.pesData=null),e&&(e.pesData=null),i&&(i.pesData=null),this.aacOverFlow=null,this.remainderData=null}demux(t,e,i,s=!1,r=!1){let n;s||(this.sampleAes=null);const a=this._videoTrack,o=this.videoIntegrityChecker,l=this._audioTrack,h=this._id3Track,d=this._txtTrack,c=i.iframe;let u=a.pid,f=a.pesData,g=l.pid,m=h.pid,p=this._klvPid,v=l.pesData,y=h.pesData,E=null,T=null,S=this.pmtParsed,b=this._pmtId,A=t.length;if(this.remainderData&&(A=(t=Ht(this.remainderData,t)).length,this.remainderData=null),A<rn&&!r)return this.remainderData=t,{audioTrack:l,videoTrack:a,id3Track:h,textTrack:d};const L=Math.max(0,nn.syncOffset(t));A-=(A-L)%rn,A<t.byteLength&&!r&&(this.remainderData=new Uint8Array(t.buffer,A,t.buffer.byteLength-A));let I=0;for(let e=L;e<A;e+=rn)if(71===t[e]){const r=!!(64&t[e+1]),A=an(t,e);let I;if((48&t[e+3])>>4>1){if(I=e+5+t[e+4],I===e+rn)continue}else I=e+4;switch(A){case u:r&&(!f||null!=o&&o.isCorrupted||!(n=cn(f,this.logger))||(this.readyVideoParser(a.segmentCodec),null!==this.videoParser&&this.videoParser.parsePES(a,d,n,!1,i)),f={data:[],size:0},null==o||o.reset(u)),null==o||o.handlePacket(t.subarray(e)),f&&(f.data.push(t.subarray(I,e+rn)),f.size+=e+rn-I);break;case g:if(c)break;if(r){if(v&&(n=cn(v,this.logger)))switch(l.segmentCodec){case"aac":this.parseAACPES(l,n,i);break;case"mp3":this.parseMPEGPES(l,n);break;case"ac3":this.parseAC3PES(l,n)}v={data:[],size:0}}v&&(v.data.push(t.subarray(I,e+rn)),v.size+=e+rn-I);break;case m:if(c)break;r&&(y&&(n=cn(y,this.logger))&&this.parseID3PES(h,n),y={data:[],size:0}),y&&(y.data.push(t.subarray(I,e+rn)),y.size+=e+rn-I);break;case p:if(c)break;r&&(E&&(n=cn(E,this.logger))&&this.parseKlvPES(h,n),E={data:[],size:0}),E&&(E.data.push(t.subarray(I,e+rn)),E.size+=e+rn-I);break;case 0:r&&(I+=t[I]+1),b=this._pmtId=on(t,I);break;case b:{r&&(I+=t[I]+1);const n=ln(t,I,this.typeSupported,s,this.observer,this.logger,this.config,i);u=n.videoPid,u>0&&(a.pid=u,a.segmentCodec=n.segmentVideoCodec),g=n.audioPid,g>0&&(l.pid=g,l.segmentCodec=n.segmentAudioCodec),m=n.id3Pid,m>0&&(h.pid=m),p=n.klvPid,p>0&&(this._klvPid=p),null===T||S||(this.logger.warn(`MPEG-TS PMT found at ${e} after unknown PID '${T}'. Backtracking to sync byte @${L} to parse all TS packets.`),T=null,e=L-188),S=this.pmtParsed=!0;break}case 17:case 8191:break;default:T=A}}else I++;I>0&&hn(this.observer,new Error(`Found ${I} TS packet/s that do not start with 0x47`),i,void 0,this.logger),a.pesData=f,l.pesData=v,h.pesData=y;const R={audioTrack:l,videoTrack:a,id3Track:h,textTrack:d};return r&&this.extractRemainingSamples(R,i),R}flush(t,e){const{remainderData:i}=this;let s;return this.remainderData=null,s=i?this.demux(i,0,e,!1,!0):{videoTrack:this._videoTrack,audioTrack:this._audioTrack,id3Track:this._id3Track,textTrack:this._txtTrack},this.extractRemainingSamples(s,e),this.sampleAes?this.decrypt(s,this.sampleAes):s}extractRemainingSamples(t,e){const{audioTrack:i,videoTrack:s,id3Track:r,textTrack:n}=t,a=s.pesData,o=i.pesData,l=r.pesData,h=this.videoIntegrityChecker;let d;if(!a||null!=h&&h.isCorrupted||!(d=cn(a,this.logger))?s.pesData=a:(this.readyVideoParser(s.segmentCodec),null!==this.videoParser&&(this.videoParser.parsePES(s,n,d,!0,e),s.pesData=null)),o&&(d=cn(o,this.logger))){switch(i.segmentCodec){case"aac":this.parseAACPES(i,d,e);break;case"mp3":this.parseMPEGPES(i,d);break;case"ac3":this.parseAC3PES(i,d)}i.pesData=null}else null!=o&&o.size&&this.logger.log("last AAC PES packet truncated,might overlap between fragments"),i.pesData=o;l&&(d=cn(l,this.logger))?(this.parseID3PES(r,d),r.pesData=null):r.pesData=l}demuxSampleAes(t,e,i,s){const r=this.demux(t,i,s,!0,!this.config.progressive),n=this.sampleAes=new Yr(this.observer,this.config,e);return this.decrypt(r,n)}readyVideoParser(t){null===this.videoParser&&("avc"===t?this.videoParser=new en:"hevc"===t&&(this.videoParser=new sn))}decrypt(t,e){return new Promise(i=>{const{audioTrack:s,videoTrack:r}=t;s.samples&&"aac"===s.segmentCodec?e.decryptAacSamples(s.samples,0,()=>{r.samples?e.decryptAvcSamples(r.samples,0,0,()=>{i(t)}):i(t)}):r.samples&&e.decryptAvcSamples(r.samples,0,0,()=>{i(t)})})}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,this.videoIntegrityChecker=null}parseAACPES(t,e,i){let s=0;const r=this.aacOverFlow;let n,a,o,l=e.data;if(r){this.aacOverFlow=null;const e=r.missing,i=r.sample.unit.byteLength;if(-1===e)l=Ht(r.sample.unit,l);else{const n=i-e;r.sample.unit.set(l.subarray(0,e),n),t.samples.push(r.sample),s=r.missing}}for(n=s,a=l.length;n<a-1&&!Dr(l,n);n++);if(n!==s){let t;const e=n<a-1;if(t=e?`AAC PES did not start with ADTS header,offset:${n}`:"No ADTS header found in AAC PES",hn(this.observer,new Error(t),i,e,this.logger),!e)return}if(Pr(t,this.observer,l,n,this.audioCodec),void 0!==e.pts)o=e.pts;else{if(!r)return void this.logger.warn("[tsdemuxer]: AAC PES unknown PTS");{const e=Cr(t.samplerate);o=r.sample.pts+e}}let h,d=0;for(;n<a;){if(h=xr(t,l,n,o,d),n+=h.length,h.missing){this.aacOverFlow=h;break}for(d++;n<a-1&&!Dr(l,n);n++);}}parseMPEGPES(t,e){const i=e.data,s=i.length;let r=0,n=0;const a=e.pts;if(void 0!==a)for(;n<s;)if(Hr(i,n)){const e=Kr(t,i,n,a,r);if(!e)break;n+=e.length,r++}else n++;else this.logger.warn("[tsdemuxer]: MPEG PES unknown PTS")}parseAC3PES(t,e){{const i=e.data,s=e.pts;if(void 0===s)return void this.logger.warn("[tsdemuxer]: AC3 PES unknown PTS");const r=i.length;let n,a=0,o=0;for(;o<r&&(n=Xr(t,i,o,s,a++))>0;)o+=n}}parseID3PES(t,e){if(void 0===e.pts)return void this.logger.warn("[tsdemuxer]: ID3 PES unknown PTS");const i=I({},e,{type:this._videoTrack?Mr.emsg:Mr.audioId3,duration:Number.POSITIVE_INFINITY});t.samples.push(i)}parseKlvPES(t,e){var i;const s=null!=(i=e.pts)?i:e.dts;if(void 0===s)return void this.logger.warn("[tsdemuxer]: KLV PES unknown PTS and DTS");const r=e.data;if(r.length<16)return void this.logger.warn("[tsdemuxer]: KLV PES payload too short");let n=0;for(;n<r.length;){var a;if(n+16>r.length)break;const i=n;if(n+=16,n>=r.length)break;const o=r[n];n+=1;let l=0;if(128&o){const t=127&o;if(0===t||t>4||n+t>r.length){this.logger.warn("[tsdemuxer]: Invalid KLV length encoding");break}for(let e=0;e<t;e++)l=l<<8|r[n+e];n+=t}else l=o;if(n+l>r.length){this.logger.warn("[tsdemuxer]: KLV value extends beyond PES payload");break}const h=n+l,d=r.subarray(i,h),c={data:d,len:d.byteLength,pts:s,dts:null!=(a=e.dts)?a:s,type:Mr.misbklv,duration:Number.POSITIVE_INFINITY};t.samples.push(c),n=h}}}function an(t,e){return((31&t[e+1])<<8)+t[e+2]}function on(t,e){return(31&t[e+10])<<8|t[e+11]}function ln(t,e,i,s,r,n,a,o){const l={audioPid:-1,videoPid:-1,id3Pid:-1,klvPid:-1,segmentVideoCodec:"avc",segmentAudioCodec:"aac"},h=e+3+((15&t[e+1])<<8|t[e+2])-4;for(e+=12+((15&t[e+10])<<8|t[e+11]);e<h;){const h=an(t,e),d=(15&t[e+3])<<8|t[e+4];switch(t[e]){case 207:if(!s){dn("ADTS AAC",n);break}case 15:-1===l.audioPid&&(l.audioPid=h);break;case 21:-1===l.id3Pid&&(l.id3Pid=h);break;case 219:if(!s){dn("H.264",n);break}case 27:-1===l.videoPid&&(l.videoPid=h);break;case 3:case 4:i.mpeg||i.mp3?-1===l.audioPid&&(l.audioPid=h,l.segmentAudioCodec="mp3"):n.log("MPEG audio found, not supported in this browser");break;case 193:if(!s){dn("AC-3",n);break}case 129:i.ac3?-1===l.audioPid&&(l.audioPid=h,l.segmentAudioCodec="ac3"):n.log("AC-3 audio found, not supported in this browser");break;case 6:if(d>0){let s=e+5,r=d;for(;r>2;){switch(t[s]){case 106:-1===l.audioPid&&(!0!==i.ac3?n.log("AC-3 audio found, not supported in this browser for now"):(l.audioPid=h,l.segmentAudioCodec="ac3"));break;case 5:-1===l.klvPid&&a.enableEmsgKLVMetadata&&(l.klvPid=h,n.log(`KLV metadata PID found: ${h}`))}const e=t[s+1]+2;s+=e,r-=e}}break;case 194:case 135:return hn(r,new Error("Unsupported EC-3 in M2TS found"),o,void 0,n),l;case 36:-1===l.videoPid&&(l.videoPid=h,l.segmentVideoCodec="hevc",n.log("HEVC in M2TS found"))}e+=d+5}return l}function hn(t,e,i,s,o){o.warn(`parsing error: ${e.message}`),t.emit(a.ERROR,a.ERROR,{type:r.MEDIA_ERROR,details:n.FRAG_PARSING_ERROR,fatal:!1,levelRetry:s,chunkMeta:i,error:e,reason:e.message})}function dn(t,e){e.log(`${t} with AES-128-CBC encryption found in unencrypted stream`)}function cn(t,e){let i,s,r,n,a,o=0;const l=t.data;if(!t||0===t.size)return null;for(;l[0].length<19&&l.length>1;)l[0]=Ht(l[0],l[1]),l.splice(1,1);i=l[0];if(1===(i[0]<<16)+(i[1]<<8)+i[2]){if(s=(i[4]<<8)+i[5],s&&s>t.size-6)return null;const h=i[7];192&h&&(n=536870912*(14&i[9])+4194304*(255&i[10])+16384*(254&i[11])+128*(255&i[12])+(254&i[13])/2,64&h?(a=536870912*(14&i[14])+4194304*(255&i[15])+16384*(254&i[16])+128*(255&i[17])+(254&i[18])/2,n-a>54e5&&(e.warn(`${Math.round((n-a)/9e4)}s delta between PTS and DTS, align them`),n=a)):a=n),r=i[8];let d=r+9;if(t.size<=d)return null;t.size-=d;const c=new Uint8Array(t.size);for(let t=0,e=l.length;t<e;t++){i=l[t];let e=i.byteLength;if(d){if(d>e){d-=e;continue}i=i.subarray(d),e-=d,d=0}c.set(i,o),o+=e}return s&&(s-=r+3),{data:c,pts:n,dts:a,len:s}}return null}class un{constructor(t){this.logger=void 0,this.pid=0,this.lastContinuityCounter=-1,this.integrityState="ok",this.logger=t}get isCorrupted(){return"ok"!==this.integrityState}reset(t){this.pid=t,this.lastContinuityCounter=-1,this.integrityState="ok"}handlePacket(t){if(t.byteLength<4)return;const e=an(t,0);if(e!==this.pid)return void this.logger.debug(`Packet PID mismatch, expected ${this.pid} got ${e}`);const i=(48&t[3])>>4;if(0===i)return;const s=15&t[3],r=this.lastContinuityCounter;this.lastContinuityCounter=s;const n=!!(1&i);if(!!(2&i)&&0!=t[4]&&!!(128&t[5]))return;if(r<0)return;const a=n?r+1&15:r;return s!==a?(this.logger.warn(`MPEG-TS Continuity Counter check failed for PID='${e}', CC=${s}, Expected-CC=${a} Last-CC=${r}`),void(this.integrityState="cc-failed")):128&t[1]?(this.logger.warn(`MPEG-TS Packet had TEI flag set for PID='${e}'`),void(this.integrityState="tei-bit")):void 0}}class fn{static getSilentFrame(t,e){if("mp4a.40.2"===t){if(1===e)return new Uint8Array([0,200,0,128,35,128]);if(2===e)return new Uint8Array([33,0,73,144,2,25,0,35,128]);if(3===e)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,142]);if(4===e)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,128,44,128,8,2,56]);if(5===e)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,56]);if(6===e)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,0,178,0,32,8,224])}else{if(1===e)return new Uint8Array([1,64,34,128,163,78,230,128,186,8,0,0,0,28,6,241,193,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);if(2===e)return new Uint8Array([1,64,34,128,163,94,230,128,186,8,0,0,0,0,149,0,6,241,161,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);if(3===e)return new Uint8Array([1,64,34,128,163,94,230,128,186,8,0,0,0,0,149,0,6,241,161,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94])}}}var gn;const mn={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])},pn=new Uint8Array([0,0,0,0,0,0,0,0]),vn=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),yn=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0]),En=new Uint8Array([0,0,0,0,0,0,0,0]),Tn=new Uint8Array([0,0,0,0,0,0,0,1]),Sn=new Uint8Array([105,115,111,109]),bn=new Uint8Array([97,118,99,49]),An=new Uint8Array([0,0,0,1]);class Ln{static box(t,...e){let i=8,s=e.length;const r=s;for(;s--;)i+=e[s].byteLength;const n=new Uint8Array(i);for(kt(n,0,i),kt(n,4,t),s=0,i=8;s<r;s++)n.set(e[s],i),i+=e[s].byteLength;return n}static hdlr(t){return Ln.box(Tt.hdlr,mn[t])}static mdat(t){return Ln.box(Tt.mdat,t)}static mdhd(t,e){e*=t;const i=Math.floor(e/(Et+1)),s=Math.floor(e%(Et+1));return Ln.box(Tt.mdhd,new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,t>>24&255,t>>16&255,t>>8&255,255&t,i>>24,i>>16&255,i>>8&255,255&i,s>>24,s>>16&255,s>>8&255,255&s,85,196,0,0]))}static mdia(t){return Ln.box(Tt.mdia,Ln.mdhd(t.timescale||0,t.duration||0),Ln.hdlr(t.type),Ln.minf(t))}static mfhd(t){return Ln.box(Tt.mfhd,new Uint8Array([0,0,0,0,t>>24,t>>16&255,t>>8&255,255&t]))}static minf(t){return"audio"===t.type?Ln.box(Tt.minf,Ln.box(Tt.smhd,En),Ln.DINF,Ln.stbl(t)):Ln.box(Tt.minf,Ln.box(Tt.vmhd,yn),Ln.DINF,Ln.stbl(t))}static moof(t,e,i){return Ln.box(Tt.moof,Ln.mfhd(t),Ln.traf(i,e))}static moov(t){let e=t.length;const i=[];for(;e--;)i[e]=Ln.trak(t[e]);return Ln.box.apply(null,[Tt.moov,Ln.mvhd(t[0].timescale||0,t[0].duration||0)].concat(i).concat(Ln.mvex(t)))}static mvex(t){let e=t.length;const i=[];for(;e--;)i[e]=Ln.trex(t[e]);return Ln.box.apply(null,[Tt.mvex,...i])}static mvhd(t,e){e*=t;const i=Math.floor(e/(Et+1)),s=Math.floor(e%(Et+1)),r=new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,t>>24&255,t>>16&255,t>>8&255,255&t,i>>24,i>>16&255,i>>8&255,255&i,s>>24,s>>16&255,s>>8&255,255&s,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,255,255,255,255]);return Ln.box(Tt.mvhd,r)}static sdtp(t){const e=t.samples||[],i=new Uint8Array(4+e.length);let s,r;for(s=0;s<e.length;s++)r=e[s].flags,i[s+4]=r.dependsOn<<4|r.isDependedOn<<2|r.hasRedundancy;return Ln.box(Tt.sdtp,i)}static stbl(t){return Ln.box(Tt.stbl,Ln.stsd(t),Ln.box(Tt.stts,pn),Ln.box(Tt.stsc,pn),Ln.box(Tt.stsz,vn),Ln.box(Tt.stco,pn))}static avc1(t){let e,i,s,r=[],n=[];for(e=0;e<t.sps.length;e++)i=t.sps[e],s=i.byteLength,r.push(s>>>8&255),r.push(255&s),r=r.concat(Array.prototype.slice.call(i));for(e=0;e<t.pps.length;e++)i=t.pps[e],s=i.byteLength,n.push(s>>>8&255),n.push(255&s),n=n.concat(Array.prototype.slice.call(i));const a=Ln.box(Tt.avcC,new Uint8Array([1,r[3],r[4],r[5],255,224|t.sps.length].concat(r).concat([t.pps.length]).concat(n))),o=t.width,l=t.height,h=t.pixelRatio[0],d=t.pixelRatio[1];return Ln.box(Tt.avc1,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,o>>8&255,255&o,l>>8&255,255&l,0,72,0,0,0,72,0,0,0,0,0,0,0,1,18,100,97,105,108,121,109,111,116,105,111,110,47,104,108,115,46,106,115,0,0,0,0,0,0,0,0,0,0,0,0,0,0,24,17,17]),a,Ln.box(Tt.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),Ln.box(Tt.pasp,new Uint8Array([h>>24,h>>16&255,h>>8&255,255&h,d>>24,d>>16&255,d>>8&255,255&d])))}static esds(t){const e=t.config,i=e.length;return new Uint8Array([0,0,0,0,3,23+i,0,1,0,4,15+i,64,21,0,0,0,0,0,0,0,0,0,0,0,5,i,...e,6,1,2])}static audioStsd(t){const e=t.samplerate||0;return new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,t.channelCount||0,0,16,0,0,0,0,e>>8&255,255&e,0,0])}static mp4a(t){return Ln.box(Tt.mp4a,Ln.audioStsd(t),Ln.box(Tt.esds,Ln.esds(t)))}static mp3(t){return Ln.box(Tt[".mp3"],Ln.audioStsd(t))}static ac3(t){return Ln.box(Tt["ac-3"],Ln.audioStsd(t),Ln.box(Tt.dac3,t.config))}static stsd(t){const{segmentCodec:e}=t;if("audio"===t.type){if("aac"===e)return Ln.box(Tt.stsd,Tn,Ln.mp4a(t));if("ac3"===e&&t.config)return Ln.box(Tt.stsd,Tn,Ln.ac3(t));if("mp3"===e&&"mp3"===t.codec)return Ln.box(Tt.stsd,Tn,Ln.mp3(t))}else{if(!t.pps||!t.sps)throw new Error("video track missing pps or sps");if("avc"===e)return Ln.box(Tt.stsd,Tn,Ln.avc1(t));if("hevc"===e&&t.vps)return Ln.box(Tt.stsd,Tn,Ln.hvc1(t))}throw new Error(`unsupported ${t.type} segment codec (${e}/${t.codec})`)}static tkhd(t){const e=t.id,i=(t.duration||0)*(t.timescale||0),s=t.width||0,r=t.height||0,n=Math.floor(i/(Et+1)),a=Math.floor(i%(Et+1));return Ln.box(Tt.tkhd,new Uint8Array([1,0,0,7,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,e>>24&255,e>>16&255,e>>8&255,255&e,0,0,0,0,n>>24,n>>16&255,n>>8&255,255&n,a>>24,a>>16&255,a>>8&255,255&a,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,s>>8&255,255&s,0,0,r>>8&255,255&r,0,0]))}static traf(t,e){const i=Ln.sdtp(t),s=t.id,r=Math.floor(e/(Et+1)),n=Math.floor(e%(Et+1));return Ln.box(Tt.traf,Ln.box(Tt.tfhd,new Uint8Array([0,0,0,0,s>>24,s>>16&255,s>>8&255,255&s])),Ln.box(Tt.tfdt,new Uint8Array([1,0,0,0,r>>24,r>>16&255,r>>8&255,255&r,n>>24,n>>16&255,n>>8&255,255&n])),Ln.trun(t,i.length+16+20+8+16+8+8),i)}static trak(t){return t.duration=t.duration||4294967295,Ln.box(Tt.trak,Ln.tkhd(t),Ln.mdia(t))}static trex(t){const e=t.id;return Ln.box(Tt.trex,new Uint8Array([0,0,0,0,e>>24,e>>16&255,e>>8&255,255&e,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,1]))}static trun(t,e){const i=t.samples||[],s=i.length,r=12+16*s,n=new Uint8Array(r);let a,o,l,h,d,c;for(e+=8+r,n.set(["video"===t.type?1:0,0,15,1,s>>>24&255,s>>>16&255,s>>>8&255,255&s,e>>>24&255,e>>>16&255,e>>>8&255,255&e],0),a=0;a<s;a++)o=i[a],l=o.duration,h=o.size,d=o.flags,c=o.cts,n.set([l>>>24&255,l>>>16&255,l>>>8&255,255&l,h>>>24&255,h>>>16&255,h>>>8&255,255&h,d.isLeading<<2|d.dependsOn,d.isDependedOn<<6|d.hasRedundancy<<4|d.paddingValue<<1|d.isNonSync,61440&d.degradPrio,15&d.degradPrio,c>>>24&255,c>>>16&255,c>>>8&255,255&c],12+16*a);return Ln.box(Tt.trun,n)}static initSegment(t){const e=Ln.moov(t);return Ht(Ln.FTYP,e)}static hvc1(t){const e=t.params,i=[t.vps,t.sps,t.pps],s=new Uint8Array([1,e.general_profile_space<<6|(e.general_tier_flag?32:0)|e.general_profile_idc,e.general_profile_compatibility_flags[0],e.general_profile_compatibility_flags[1],e.general_profile_compatibility_flags[2],e.general_profile_compatibility_flags[3],e.general_constraint_indicator_flags[0],e.general_constraint_indicator_flags[1],e.general_constraint_indicator_flags[2],e.general_constraint_indicator_flags[3],e.general_constraint_indicator_flags[4],e.general_constraint_indicator_flags[5],e.general_level_idc,240|e.min_spatial_segmentation_idc>>8,255&e.min_spatial_segmentation_idc,252|e.parallelismType,252|e.chroma_format_idc,248|e.bit_depth_luma_minus8,248|e.bit_depth_chroma_minus8,0,parseInt(e.frame_rate.fps),3|e.temporal_id_nested<<2|e.num_temporal_layers<<3|(e.frame_rate.fixed?64:0),i.length]);let r=s.length;for(let t=0;t<i.length;t+=1){r+=3;for(let e=0;e<i[t].length;e+=1)r+=2+i[t][e].length}const n=new Uint8Array(r);n.set(s,0),r=s.length;const a=i.length-1;for(let t=0;t<i.length;t+=1){n.set(new Uint8Array([32+t|(t===a?128:0),0,i[t].length]),r),r+=3;for(let e=0;e<i[t].length;e+=1)n.set(new Uint8Array([i[t][e].length>>8,255&i[t][e].length]),r),r+=2,n.set(i[t][e],r),r+=i[t][e].length}const o=Ln.box(Tt.hvcC,n),l=t.width,h=t.height,d=t.pixelRatio[0],c=t.pixelRatio[1];return Ln.box(Tt.hvc1,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,l>>8&255,255&l,h>>8&255,255&h,0,72,0,0,0,72,0,0,0,0,0,0,0,1,18,100,97,105,108,121,109,111,116,105,111,110,47,104,108,115,46,106,115,0,0,0,0,0,0,0,0,0,0,0,0,0,0,24,17,17]),o,Ln.box(Tt.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),Ln.box(Tt.pasp,new Uint8Array([d>>24,d>>16&255,d>>8&255,255&d,c>>24,c>>16&255,c>>8&255,255&c])))}}gn=Ln,Ln.FTYP=gn.box(Tt.ftyp,Sn,An,Sn,bn),Ln.DINF=gn.box(Tt.dinf,gn.box(Tt.dref,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,12,117,114,108,32,0,0,0,1])));function In(t,e,i=1,s=!1){const r=t*e*i;return s?Math.round(r):r}function Rn(t,e=!1){return In(t,1e3,1/9e4,e)}function kn(t){const{baseTime:e,timescale:i,trackId:s}=t;return`${e/i} (${e}/${i}) trackId: ${s}`}const _n=8589934592;function Dn(t,e,i,s){return{duration:e,size:i,cts:s,flags:{isLeading:0,isDependedOn:0,hasRedundancy:0,degradPrio:0,dependsOn:t?2:1,isNonSync:t?0:1,paddingValue:0}}}class wn extends U{constructor(t,e,i,s){super("mp4-remuxer",s),this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.ISGenerated=!1,this._initPTS=null,this._initDTS=null,this.nextVideoTs=null,this.nextAudioTs=null,this.videoSampleDuration=null,this.isAudioContiguous=!1,this.isVideoContiguous=!1,this.videoTrackConfig=void 0,this.observer=t,this.config=e,this.typeSupported=i,this.ISGenerated=!1}destroy(){this.config=this.videoTrackConfig=this._initPTS=this._initDTS=null}resetTimeStamp(t){const e=this._initPTS;e&&t&&t.trackId===e.trackId&&t.baseTime===e.baseTime&&t.timescale===e.timescale||this.log(`Reset initPTS: ${e?kn(e):e} > ${t?kn(t):t}`),this._initPTS=this._initDTS=t}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(t){let e=!1;const i=t[0].pts,s=t.reduce((t,s)=>{let r=s.pts,n=r-t;return n<-4294967296&&(e=!0,r=Pn(r,i),n=r-t),n>0?t:r},i);return e&&this.debug("PTS rollover detected"),s}remux(t,e,i,s,r,n,a,o,l){let h,d,c,u,g,m,p=r,v=r;const y=!l.iframe&&t.pid>-1,E=e.pid>-1,T=e.samples.length,S=t.samples.length>0,b=a&&T>0||T>1;if((!y||S)&&(!E||b)||this.ISGenerated||a){if(this.ISGenerated){var A,L,I,R;const t=this.videoTrackConfig;(t&&(e.width!==t.width||e.height!==t.height||(null==(A=e.pixelRatio)?void 0:A[0])!==(null==(L=t.pixelRatio)?void 0:L[0])||(null==(I=e.pixelRatio)?void 0:I[1])!==(null==(R=t.pixelRatio)?void 0:R[1]))||!t&&b||null===this.nextAudioTs&&S)&&this.resetInitSegment()}this.ISGenerated||(c=this.generateIS(t,e,r,n));const i=this.isVideoContiguous;let s,a=-1;if(b&&(a=function(t){for(let e=0;e<t.length;e++)if(t[e].key)return e;return-1}(e.samples),!i&&this.config.forceKeyFrameOnDiscontinuity))if(m=!0,a>0){this.warn(`Dropped ${a} out of ${T} video samples due to a missing keyframe`);const t=this.getVideoStartPts(e.samples);e.samples=e.samples.slice(a),e.dropped+=a,v+=(e.samples[0].pts-t)/e.inputTimeScale,s=v}else-1===a&&(this.warn(`No keyframe found out of ${T} video samples`),m=!1);if(this.ISGenerated){if(S&&b&&r){const i=this.getVideoStartPts(e.samples),s=(Pn(t.samples[0].pts,i)-i)/e.inputTimeScale;p+=Math.max(0,s),v+=Math.max(0,-s)}if(S){if(t.samplerate||(this.warn("regenerate InitSegment as audio detected"),c=this.generateIS(t,e,r,n)),d=this.remuxAudio(t,p,this.isAudioContiguous,n,E||b||o===f.AUDIO?v:void 0,l),b){const s=d?d.endPTS-d.startPTS:0;e.inputTimeScale||(this.warn("regenerate InitSegment as video detected"),c=this.generateIS(t,e,r,n)),h=this.remuxVideo(e,v,i,s,l)}}else b&&(h=this.remuxVideo(e,v,i,0,l));h&&(h.firstKeyFrame=a,h.independent=-1!==a,h.firstKeyFramePTS=s)}}return this.ISGenerated&&this._initPTS&&this._initDTS&&(i.samples.length&&(g=Cn(i,r,this._initPTS,this._initDTS)),s.samples.length&&(u=xn(s,r,this._initPTS))),{audio:d,video:h,initSegment:c,independent:m,text:u,id3:g}}computeInitPts(t,e,i,s){const r=Math.round(i*e);let n=Pn(t,r);if(n<r)for(this.log(`Adjusting PTS for rollover in timeline near ${(r-n)/e} ${s}`);n<r;)n+=_n;return n-r}generateIS(t,i,s,r){const n=t.samples,a=i.samples,o=this.typeSupported,l={},h=this._initPTS,d=!h||r;let c,u,f,g="audio/mp4",m=-1;if(d&&(c=u=1/0),t.config&&n.length){switch(t.timescale=t.samplerate,t.segmentCodec){case"mp3":o.mpeg?(g="audio/mpeg",t.codec=""):o.mp3&&(t.codec="mp3");break;case"ac3":t.codec="ac-3"}if(l.audio={id:"audio",container:g,codec:t.codec,initSegment:"mp3"===t.segmentCodec&&o.mpeg?new Uint8Array(0):Ln.initSegment([t]),metadata:{channelCount:t.channelCount}},d){m=t.id,f=t.inputTimeScale;const e=this.computeInitPts(n[0].pts,f,s,"audio");(!h||f!==h.timescale||0===s&&e<h.baseTime)&&(c=u=e)}}if(i.sps&&i.pps&&a.length){if(i.timescale=i.inputTimeScale,l.video={id:"main",container:"video/mp4",codec:i.codec,initSegment:Ln.initSegment([i]),metadata:{width:i.width,height:i.height}},d){m=i.id,f=i.inputTimeScale;const t=this.getVideoStartPts(a),r=Pn(a[0].dts,t),n=this.computeInitPts(r,f,s,"video"),o=this.computeInitPts(t,f,s,"video");(!h||f!==h.timescale||e(c)||0===s&&o<h.baseTime)&&(u=Math.min(u,n),c=Math.min(c,n))}this.videoTrackConfig={width:i.width,height:i.height,pixelRatio:i.pixelRatio}}if(Object.keys(l).length)return this.ISGenerated=!0,d&&e(c)?(h&&this.warn(`Timestamps at playlist time: ${r?"":"~"}${s} ${c/f} != initPTS: ${h.baseTime/h.timescale} (${h.baseTime}/${h.timescale}) trackId: ${h.trackId}`),this.log(`Found initPTS at playlist time: ${s} offset: ${c/f} (${c}/${f}) trackId: ${m}`),this._initPTS={baseTime:c,timescale:f,trackId:m},this._initDTS={baseTime:u,timescale:f,trackId:m}):c=f=void 0,{tracks:l,initPTS:c,timescale:f,trackId:m}}remuxVideo(t,e,i,s,o){const l=t.inputTimeScale,h=t.samples,d=[],c=h.length,u=this._initPTS,f=u.baseTime*l/u.timescale;let g,m,p=this.nextVideoTs,v=8,y=this.videoSampleDuration,E=Number.POSITIVE_INFINITY,T=Number.NEGATIVE_INFINITY,S=!1;if(!i||null===p){const t=f+e*l,s=h[0].pts-Pn(h[0].dts,h[0].pts);ne()&&null!==p&&Math.abs(t-s-(p+f))<15e3?i=!0:p=t-s-f}const b=p+f;for(let t=0;t<c;t++){const e=h[t];e.pts=Pn(e.pts,b),e.dts=Pn(e.dts,b),e.dts<h[t>0?t-1:t].dts&&(S=!0)}S&&h.sort(function(t,e){const i=t.dts-e.dts,s=t.pts-e.pts;return i||s}),g=h[0].dts,m=h[h.length-1].dts;const A=m-g,L=A?Math.round(A/(c-1)):y||t.inputTimeScale/30;if(i){const i=g-b,s=i>L,r=i<-1;if((s||r)&&(s?this.warn(`${(t.segmentCodec||"").toUpperCase()}: ${Rn(i,!0)} ms (${i}dts) hole between fragments detected at ${e.toFixed(3)}`):this.warn(`${(t.segmentCodec||"").toUpperCase()}: ${Rn(-i,!0)} ms (${i}dts) overlapping between fragments detected at ${e.toFixed(3)}`),!r||b>=h[0].pts||ne())){g=b;const t=h[0].pts-i;if(s)h[0].dts=g,h[0].pts=t;else{let e=!0;for(let s=0;s<h.length&&!(h[s].dts>t&&e);s++){const t=h[s].pts;if(h[s].dts-=i,h[s].pts-=i,s<h.length-1){const i=h[s+1].pts;e=i<=h[s].pts==i<=t}}}this.log(`Video: Initial PTS/DTS adjusted: ${Rn(t,!0)}/${Rn(g,!0)}, delta: ${Rn(i,!0)} ms`)}}g=Math.max(0,g);let R=0,k=0,_=g;for(let t=0;t<c;t++){const e=h[t],i=e.units,s=i.length;let r=0;for(let t=0;t<s;t++)r+=i[t].data.length;k+=r,R+=s,e.length=r,e.dts<_?(e.dts=_,_+=L/4|0||1):_=e.dts,E=Math.min(e.pts,E),T=Math.max(e.pts,T)}m=h[c-1].dts;const D=k+4*R+8;let w;try{w=new Uint8Array(D)}catch(t){return void this.observer.emit(a.ERROR,a.ERROR,{type:r.MUX_ERROR,details:n.REMUX_ALLOC_ERROR,fatal:!1,chunkMeta:o,error:t,bytes:D,reason:`fail allocating video mdat ${D}`})}kt(w,0,D),kt(w,4,Tt.mdat);let P=!1,C=Number.POSITIVE_INFINITY,x=Number.POSITIVE_INFINITY,M=Number.NEGATIVE_INFINITY,O=Number.NEGATIVE_INFINITY;for(let t=0;t<c;t++){const e=h[t],r=e.units;let n,a=0;for(let t=0,e=r.length;t<e;t++){const e=r[t],i=e.data,s=e.data.byteLength;kt(w,v,s),v+=4,w.set(i,v),v+=s,a+=4+s}if(t<c-1)y=h[t+1].dts-e.dts,n=h[t+1].pts-e.pts;else{const i=this.config,r=t>0?e.dts-h[t-1].dts:L;if(n=t>0?e.pts-h[t-1].pts:L,i.stretchShortVideoTrack&&null!==this.nextAudioTs){const t=Math.floor(i.maxBufferHole*l),n=(s?E+s*l:this.nextAudioTs+f)-e.pts;n>t?(y=n-r,y<0?y=r:P=!0,this.log(`It is approximately ${n/90} ms to the next segment; using duration ${y/90} ms for the last video frame.`)):y=r}else y=r}let u=Math.round(e.pts-e.dts);if(C=Math.min(C,y),M=Math.max(M,y),x=Math.min(x,n),O=Math.max(O,n),!i&&0===t&&u>y){const t=Math.round(u/L)*L;t-u===1&&(this.log(`pad first CTS ${u} -> ${t} of sn: ${o.sn}`),u=t)}d.push(Dn(e.key,y,a,u))}if(d.length){const t=ne();if(t){if(t<70){const t=d[0].flags;t.dependsOn=2,t.isNonSync=0}}else if(function(){if(void 0===se){const t=Jt.match(/Safari\/(\d+)/i);se=t?parseInt(t[1]):0}return se}()&&O-x<M-C&&L/M<.025&&0===d[0].cts){this.warn("Found irregular gaps in sample duration. Using PTS instead of DTS to determine MP4 sample duration.");let t=g;for(let e=0,i=d.length;e<i;e++){const s=t+d[e].duration,r=t+d[e].cts;if(e<i-1){const t=s+d[e+1].cts;d[e].duration=t-r}else d[e].duration=e?d[e-1].duration:L;d[e].cts=0,t=s}}}y=P||!y?L:y;const F=m+y;this.nextVideoTs=p=F-f,this.videoSampleDuration=y,this.isVideoContiguous=!0,o.iframe&&(1===d.length?(d[0].duration=y=o.duration*l,this.nextVideoTs=p=g+y-f):this.warn(`Not adjusting IFrame duration (sample count ${d.length})`));const N={data1:Ln.moof(o.sn,g,I(t,{samples:d})),data2:w,startPTS:(E-f)/l,endPTS:(T+y-f)/l,startDTS:(g-f)/l,endDTS:p/l,type:"video",hasAudio:!1,hasVideo:!0,nb:d.length,dropped:t.dropped};return t.samples=[],t.dropped=0,N}getSamplesPerFrame(t){switch(t.segmentCodec){case"mp3":return 1152;case"ac3":return 1536;default:return 1024}}remuxAudio(t,e,i,s,o,l){const h=t.inputTimeScale,d=h/(t.samplerate?t.samplerate:h),c=this.getSamplesPerFrame(t),u=c*d,f=this._initPTS,g="mp3"===t.segmentCodec&&this.typeSupported.mpeg,m=[],p=void 0!==o;let v=t.samples,y=g?0:8,E=this.nextAudioTs||-1;const T=f.baseTime*h/f.timescale,S=T+e*h;if(this.isAudioContiguous=i=i||v.length&&E>0&&(s&&Math.abs(S-(E+T))<9e3||Math.abs(Pn(v[0].pts,S)-(E+T))<20*u),v.forEach(function(t){t.pts=Pn(t.pts,S)}),!i||E<0){const t=v.length;if(v=v.filter(t=>t.pts>=0),t!==v.length&&this.warn(`Removed ${v.length-t} of ${t} samples (initPTS ${T} / ${h})`),!v.length)return;E=0===o?0:s&&!p?Math.max(0,S-T):v[0].pts-T}if("aac"===t.segmentCodec){const e=this.config.maxAudioFramesDrift;for(let i=0,s=E+T;i<v.length;i++){const r=v[i],n=r.pts,a=n-s,o=Math.abs(1e3*a/h);if(a<=-e*u&&p)0===i&&(this.warn(`Audio frame @ ${(n/h).toFixed(3)}s overlaps marker by ${Math.round(1e3*a/h)} ms.`),this.nextAudioTs=E=n-T,s=n);else if(a>=e*u&&o<1e4&&p){let e=Math.round(a/u);for(s=n-e*u;s<0&&e&&u;)e--,s+=u;0===i&&(this.nextAudioTs=E=s-T),this.warn(`Injecting ${e} audio frames @ ${((s-T)/h).toFixed(3)}s due to ${Math.round(1e3*a/h)} ms gap.`);for(let n=0;n<e;n++){let e=fn.getSilentFrame(t.parsedCodec||t.manifestCodec||t.codec,t.channelCount);e||(this.log("Unable to get silent frame for given audio codec; duplicating last frame instead."),e=r.unit.subarray()),v.splice(i,0,{unit:e,pts:s}),s+=u,i++}}r.pts=s,s+=u}}let b,A=null,L=null,R=0,k=v.length;for(;k--;)R+=v[k].unit.byteLength;for(let e=0,s=v.length;e<s;e++){const s=v[e],o=s.unit;let h=s.pts;if(null!==L){m[e-1].duration=Math.round((h-L)/d)}else{if(i&&"aac"===t.segmentCodec&&(h=E+T),A=h,!(R>0))return;R+=y;try{b=new Uint8Array(R)}catch(t){return void this.observer.emit(a.ERROR,a.ERROR,{type:r.MUX_ERROR,details:n.REMUX_ALLOC_ERROR,fatal:!1,chunkMeta:l,error:t,bytes:R,reason:`fail allocating audio mdat ${R}`})}g||(kt(b,0,R),kt(b,4,Tt.mdat))}b&&b.set(o,y);const u=o.byteLength;y+=u,m.push(Dn(!0,c,u,0)),L=h}const _=m.length;if(!_)return;const D=m[m.length-1];E=L-T,this.nextAudioTs=E+d*D.duration;const w=g?new Uint8Array(0):Ln.moof(t.sequenceNumber++,A/d,I({},t,{samples:m}));t.samples=[];const P=(A-T)/h,C=this.nextAudioTs/h,x={data1:w,data2:b,startPTS:P,endPTS:C,startDTS:P,endDTS:C,type:"audio",hasAudio:!0,hasVideo:!1,nb:_};return this.isAudioContiguous=!0,x}}function Pn(t,e){let i;if(null===e)return t;for(i=e<t?-8589934592:_n;Math.abs(t-e)>4294967296;)t+=i;return t}function Cn(t,e,i,s){const r=t.samples.length;if(!r)return;const n=t.inputTimeScale;for(let a=0;a<r;a++){const r=t.samples[a];r.pts=Pn(r.pts-i.baseTime*n/i.timescale,e*n)/n,r.dts=Pn(r.dts-s.baseTime*n/s.timescale,e*n)/n}const a=t.samples;return t.samples=[],{samples:a}}function xn(t,e,i){const s=t.samples.length;if(!s)return;const r=t.inputTimeScale;for(let n=0;n<s;n++){const s=t.samples[n];s.pts=Pn(s.pts-i.baseTime*r/i.timescale,e*r)/r}t.samples.sort((t,e)=>t.pts-e.pts);const n=t.samples;return t.samples=[],{samples:n}}function Mn(t,e,i=!1){return void 0!==(null==t?void 0:t.start)?(t.start+(i?t.duration:0))/t.timescale:e}function On(t,e,i){const s=t.codec;if(s&&s.length>4)return s;if(e===g){if("ec-3"===s||"ac-3"===s||"alac"===s)return s;if("fLaC"===s||"Opus"===s){return pe(s,!1)}return i.warn(`Unhandled audio codec "${s}" in mp4 MAP`),s||"mp4a"}return"mjpg"===s?s:(i.warn(`Unhandled video codec "${s}" in mp4 MAP`),s||"avc1")}let Fn;try{Fn=self.performance.now.bind(self.performance)}catch(t){Fn=Date.now}const Nn=[{demux:class{constructor(t,e,i,s=q){this.remainderData=null,this.timeOffset=0,this.config=void 0,this.videoTrack=void 0,this.audioTrack=void 0,this.id3Track=void 0,this.txtTrack=void 0,this.initData=void 0,this.logger=void 0,this.config=e,this.logger=s}resetTimeStamp(){}resetInitSegment(t,e,i,s){const r=this.videoTrack=Or("video",1),n=this.audioTrack=Or("audio",1),a=this.txtTrack=Or("text",1);if(this.id3Track=Or("id3",1),this.initData=void 0,this.timeOffset=0,null==t||!t.byteLength)return;const o=this.initData=Mt(t);if(o.video){const{id:t,timescale:e,codec:i,supplemental:s}=o.video;r.id=t,r.timescale=a.timescale=e,r.codec=i,r.supplemental=s}if(o.audio){const{id:t,timescale:e,codec:i}=o.audio;n.id=t,n.timescale=e,n.codec=i}a.id=St.text,r.sampleDuration=0,r.duration=n.duration=s}resetContiguity(){this.remainderData=null}static probe(t){return function(t,e){const i=t.byteLength;for(let s=0;s<i;){const r=At(t,s);if(r>8&&At(t,s+4)===Tt[e])return!0;s=r>1?s+r:i}return!1}(t,"moof")}demux(t,e,i){this.timeOffset=e;let s=t;const r=this.videoTrack,n=this.txtTrack;if(this.config.progressive){this.remainderData&&(s=Ht(this.remainderData,t));const e=function(t){const e={valid:null,remainder:null},i=Pt(t,["moof"]);if(i.length<2)return e.remainder=t,e;const s=i[i.length-1];return e.valid=t.slice(0,s.byteOffset-8),e.remainder=t.slice(s.byteOffset-8),e}(s);this.remainderData=e.remainder,r.samples=e.valid||new Uint8Array}else r.samples=s;const a=this.extractID3Track(r,e),o=this.parseFragment(r,n,e,i);return{videoTrack:r,audioTrack:this.audioTrack,id3Track:a,textTrack:this.txtTrack,initData:this.initData,sampleData:o}}flush(t,e){const i=this.timeOffset,s=this.videoTrack,r=this.txtTrack;s.samples=this.remainderData||new Uint8Array,this.remainderData=null;const n=this.extractID3Track(s,this.timeOffset),a=this.parseFragment(s,r,i,e);return{videoTrack:s,audioTrack:Or(),id3Track:n,textTrack:Or(),initData:this.initData,sampleData:a}}parseFragment(t,e,i,s){const r=this.initData;if(r&&s){const{samples:n,sampleData:a}=function(t,e,i,s,r=!1){const n=[];return{samples:n,sampleData:{includeSampleDetails:r,tracks:jt(e.samples,i,s,r,{isHEVCFlavor:qt(e.codec),samples:n,timeOffset:t,timescale:e.timescale,trackId:e.id})}}}(i,t,r,this.logger,s.iframe);return e.samples=n,a}e.samples=function(t,e){const i=[],s=e.samples,r=e.timescale,n=e.id;let a=!1;return Pt(s,["moof"]).map(o=>{const l=o.byteOffset-8;Pt(o,["traf"]).map(o=>{const h=Pt(o,["tfdt"]).map(t=>{const e=t[0];let i=At(t,4);return 1===e&&(i*=Math.pow(2,32),i+=At(t,8)),i/r})[0];return void 0!==h&&(t=h),Pt(o,["tfhd"]).map(h=>{const d=At(h,4),c=16777215&At(h,0),u=!!(1&c);let f=0;const g=!!(2&c),p=!!(8&c);let v=0;const y=!!(16&c);let E=0;const T=!!(32&c),S=!u&&!!(131072&c);let b=8;d===n&&(u?(f=At(h,b),b+=4,f*=Math.pow(2,32),f+=At(h,b),b+=4):S&&(f=l),g&&(b+=4),p&&(v=At(h,b),b+=4),y&&(E=At(h,b),b+=4),T&&(b+=4),"video"===e.type&&(a=qt(e.codec)),Pt(o,["trun"]).map(n=>{const o=n[0],l=16777215&At(n,0),h=!!(1&l);let d=0;const c=!!(4&l),u=!!(256&l);let g=0;const p=!!(512&l);let y=0;const T=!!(1024&l),S=!!(2048&l);let b=0;const A=At(n,4);let L=8;h&&(d=At(n,L),L+=4),c&&(L+=4);let I=f+d;for(let l=0;l<A;l++){if(u?(g=At(n,L),L+=4):g=v,p?(y=At(n,L),L+=4):y=E,T&&(L+=4),S&&(b=0===o?At(n,L):Rt(n,L),L+=4),e.type===m){let e=0;for(;e<y;){const n=At(s,I);I+=4,Yt(a,s[I])&&Wt(s.subarray(I,I+n),a?2:1,t+b/r,i),I+=n,e+=n+4}}t+=g/r}}))})})}),i}(i,t)}extractID3Track(t,e){const s=this.id3Track;if(t.samples.length){const r=Pt(t.samples,["emsg"]);r&&r.forEach(t=>{const r=function(t){const e=t[0];let s,r="",n="",a=0,o=0,l=0,h=0,d=4;if(0===e){const e=It(t,d),i=null!==e?It(t,d+e.length):null;null!==e&&null!==i?(r=e,n=i,d+=e.length+i.length,a=At(t,d),d+=4,o=At(t,d),d+=4,l=At(t,d),d+=4,h=At(t,d),d+=4):(q.warn(`Unterminated ${null===e?"scheme_id_uri":"value"} in parsing emsg box: version 0 box ends inside a string, dropping all of its fields`),d=t.length)}else if(1===e){a=At(t,d),d+=4;const e=At(t,d);d+=4;const o=At(t,d);d+=4,s=2**32*e+o,i(s)||(s=Number.MAX_SAFE_INTEGER,q.warn("Presentation time exceeds safe integer limit and wrapped to max safe integer in parsing emsg box")),l=At(t,d),d+=4,h=At(t,d),d+=4;const c=It(t,d),u=null!==c?It(t,d+c.length):null;null!==c&&(r=c,d+=c.length),null!==u?(n=u,d+=u.length):(q.warn(`Unterminated ${null===c?"scheme_id_uri":"value"} in parsing emsg box: version 1 box ends inside a string, dropping its ${null===c?"strings and payload":"value and payload"}`),d=t.length)}return{schemeIdUri:r,value:n,timeScale:a,presentationTime:s,presentationTimeDelta:o,eventDuration:l,id:h,payload:t.subarray(d,t.byteLength)}}(t);if(Qr.test(r.schemeIdUri)){const t=Zr(r,e);let i=4294967295===r.eventDuration?Number.POSITIVE_INFINITY:r.eventDuration/r.timeScale;i<=.001&&(i=Number.POSITIVE_INFINITY);const n=r.payload;s.samples.push({data:n,len:n.byteLength,dts:t,pts:t,type:Mr.emsg,duration:i})}else if(this.config.enableEmsgKLVMetadata){const t=this.config.emsgKLVSchemaUri||Mr.misbklv;if(r.schemeIdUri.startsWith(t)){const t=Zr(r,e);s.samples.push({data:r.payload,len:r.payload.byteLength,dts:t,pts:t,type:Mr.misbklv,duration:Number.POSITIVE_INFINITY})}}})}return s}demuxSampleAes(t,e,i){return Promise.reject(new Error("The MP4 demuxer does not support SAMPLE-AES decryption"))}destroy(){this.config=null,this.remainderData=null,this.videoTrack=this.audioTrack=this.id3Track=this.txtTrack=void 0,this.initData=void 0}},remux:class extends U{constructor(t,e,i,s){super("passthrough-remuxer",s),this.observer=void 0,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,this.videoOnlyRemux=!1,this.decryptdata=null,this.pendingInitSegment=void 0,this.observer=t}destroy(){this.observer&&this.observer.removeAllListeners(),this.observer=null}resetTimeStamp(t){this.lastEndTime=null;const e=this.initPTS;e&&t&&e.baseTime===t.baseTime&&e.timescale===t.timescale||(this.initPTS=t)}resetNextTimestamp(){this.isVideoContiguous=!1,this.lastEndTime=null}resetInitSegment(t,e,i,s){this.audioCodec=e,this.videoCodec=i,this.decryptdata=s,this.pendingInitSegment=t,this.videoOnlyRemux=!1,this.initTracks=void 0,this.initData=void 0,this.emitInitSegment=!0}generateInitSegment(t,e,i){this.videoOnlyRemux=!1;let{audioCodec:s,videoCodec:r}=this;if(null==t||!t.byteLength)return this.initTracks=void 0,void(this.initData=void 0);const{audio:n,video:a}=this.initData=i||Mt(t);if(e)!function(t,e){if(!t||!e)return;const i=e.keyId;16===(null==i?void 0:i.byteLength)&&e.isCommonEncryption&&Ut(t,(t,e)=>{const s=t.subarray(8,24);s.some(t=>0!==t)||(q.log(`[eme] Patching keyId in 'enc${e?"a":"v"}>sinf>>tenc' box: ${mt(s)} -> ${mt(i)}`),t.set(i,8))})}(t,e);else{const t=n||a;null!=t&&t.encrypted&&this.warn(`Init segment with encrypted track with has no key ("${t.codec}")!`)}n&&(s=On(n,g,this)),a&&(r=On(a,m,this));const o={};n&&a?o.audiovideo={container:"video/mp4",codec:s+","+r,supplemental:a.supplemental,encrypted:a.encrypted,initSegment:t,id:"main"}:n?o.audio={container:"audio/mp4",codec:s,encrypted:n.encrypted,initSegment:t,id:"audio"}:a?o.video={container:"video/mp4",codec:r,supplemental:a.supplemental,encrypted:a.encrypted,initSegment:t,id:"main"}:this.warn("initSegment does not contain moov or trak boxes."),this.initTracks=o}remux(t,i,s,r,n,a,o,l,h,d,c){var u,f;let{initPTS:g,lastEndTime:m}=this;const p={audio:void 0,video:void 0,text:void 0,id3:s,initSegment:void 0};e(m)||(m=this.lastEndTime=n||0);const v=i.samples;if(!v.length)return p;const y=this.pendingInitSegment;y&&(this.pendingInitSegment=void 0,this.generateInitSegment(y,this.decryptdata,d));const E={initPTS:void 0,timescale:void 0,trackId:void 0};let T=this.initData;if(null!=(u=T)&&u.length||(this.generateInitSegment(v),T=this.initData),null==(f=T)||!f.length)return this.warn("Failed to generate initSegment."),p;if(h.iframe&&T.audio&&T.video){var S;const t=null==(S=this.initTracks)||null==(S=S.audiovideo)?void 0:S.initSegment,e=t?function(t){const e=Pt(t,["moov"]);if(1!==e.length||Pt(t,["moof"]).length)return null;const i=t.byteOffset,s=[],r=[];let n=!1;const a=Pt(e[0],["trak"]);for(let t=0;t<a.length;t++){const e=a[t],o=Pt(e,["mdia","hdlr"])[0];if("vide"===(o?yt(o.subarray(8,12)):"")){n=!0;continue}const l=Pt(e,["tkhd"])[0];if(!l)return null;const h=l[0];r.push(At(l,0===h?12:20)),s.push(Dt(e,i))}if(!n||!s.length)return null;const o=Pt(e[0],["mvex"])[0];let l=0;if(o){const t=Pt(o,["trex"]);for(let e=0;e<t.length;e++){const n=t[e];-1!==r.indexOf(At(n,4))&&(s.push(Dt(n,i)),l+=n.byteLength+8)}}const{result:h,dropped:d,droppedBefore:c}=wt(t,s);if(kt(h,e[0].byteOffset-i-8,e[0].byteLength+8-d),o&&l){const t=o.byteOffset-i-8;kt(h,t-c(t),o.byteLength+8-l)}return h}(t):null;var b;if(e)this.log("Converted muxed init segment to video-only for I-Frame playback"),this.generateInitSegment(e,this.decryptdata),null!=(b=this.initData)&&b.length&&(T=this.initData,this.emitInitSegment=!0,this.videoOnlyRemux=!0)}this.emitInitSegment&&(E.tracks=this.initTracks,p.initSegment=E,this.emitInitSegment=!1);const A=h.iframe,L=!c||A&&!c.includeSampleDetails?function(t,e,i,s,r=!0){return jt(t,e,s,r)}(v,T,0,this,A):c.tracks,I=T.audio?L[T.audio.id]:null,R=T.video?L[T.video.id]:null,k=!!T.audio,_=!!T.video;let D="";k&&(D+="audio"),_&&(D+="video");const w=Mn(R,1/0),P=Mn(I,1/0),C=Mn(R,0,!0),x=Mn(I,0,!0);let M=n,O=0;R&&I&&T.audio&&(P>C||w>x)&&this.warn(`audio and video track sample timestamps do not overlap. v: ${w}-${C} a: ${P}-${x}}`,R,I);const F=!!I&&(!R||!g&&P<w||!!g&&g.trackId===T.audio.id),N=F?I:R;if(!N)return this.log(`No media samples found in ${l} ${h.level} ${-1===h.part?"":`part: ${h.part} of`} sn: ${h.sn} at playlist time: ${n}`),p;let $,B=v;if(R&&R.sampleCount>=1&&T.video&&h.iframe){const{trun:t,start:e}=R,i=1===t.length,s=t.length?i?t[0].samples:t[0].samples.concat(...t.slice(1).map(t=>t.samples)):[];if(s.length){const r=t[0];let n=r;for(let e=t.length;e--;)if(t[e].samples.length){n=t[e];break}const a=n.lastSampleDurationOffset,{defaultSampleDurationOffset:o}=r,l=Math.abs(h.duration-(C-w))>.05,d=s.length<R.sampleCount;if(l||d||this.videoOnlyRemux||!i){const t=d?n.sampleOffset+n.samples.reduce((t,e)=>t+e.size,0):void 0,i=l?h.duration:C-w,r=function(t,e,i,s){if(void 0!==i){const s=t[t.length-1];let r=e;for(let e=0;e<t.length-1;e++)r-=t[e].duration;return r<=0&&(r=s.duration),s.duration=r,{durationOffset:i,value:r}}if(void 0===s)return;const r=Math.round(e/t.length);for(let e=0;e<t.length;e++)t[e].duration=r;return{durationOffset:s,value:r}}(s,i*T.video.timescale,a,o),c=function(t,e,i,s,r){if(i<1)return null;const n=Pt(t,["moof"]);if(1!==n.length)return null;const a=n[0],o=t.byteOffset,l=[],h=[],d=Pt(a,["traf"]);let c=!0;for(let t=0;t<d.length;t++){const i=d[t],s=Pt(i,["tfhd"])[0];if(!s)return null;At(s,4)===e?(l.push(i),131072&At(s,0)||(c=!1)):h.push(Dt(i,o))}if(!l.length)return null;if(h.length&&!c)return null;if(void 0!==s){let e=i;for(let i=0;i<l.length;i++){const s=l[i];let r=0;const n=Pt(s,["trun"]);for(let i=0;i<n.length;i++){const s=n[i],a=Math.min(e,At(s,4));if(a){kt(t,s.byteOffset-o+4,a);const e=16777215&At(s,0);_t(t,s,8+(1&e?4:0)+(4&e?4:0)+a*((256&e?4:0)+(512&e?4:0)+(1024&e?4:0)+(2048&e?4:0)))}else kt(t,s.byteOffset-o-4,Tt.free);e-=a,r+=a}const a=Pt(s,["senc"])[0];a&&kt(t,a.byteOffset-o+4,r);const h=Pt(s,["saiz"])[0];if(h){let e=4;1&(h[1]<<16|h[2]<<8|h[3])&&(e+=8);const i=h[e];e+=1,kt(t,h.byteOffset-o+e,r),_t(t,h,e+4+(0===i?r:0))}}const r=Pt(t,["mdat"]);if(1===r.length){const e=r[0].byteOffset-o-8;kt(t,e,s-e)}}let u=t,f=0,g=()=>0;if(h.length){({result:u,dropped:f,droppedBefore:g}=wt(t,h)),kt(u,a.byteOffset-o-8,a.byteLength+8-f);for(let t=0;t<l.length;t++){const e=l[t],i=g(e.byteOffset-o),s=Pt(e,["trun"]);for(let t=0;t<s.length;t++){const e=s[t];1&At(e,0)&&kt(u,e.byteOffset-o-i+8,At(e,8)-f)}if(i){const t=Pt(e,["saio"]);for(let e=0;e<t.length;e++){const s=t[e],r=0===s[0]?4:8;let n=1&At(s,0)?12:4,a=At(s,n);for(n+=4;a--;n+=r){const t=n+r-4;kt(u,s.byteOffset-o-i+t,At(s,t)-i)}}}}}if(r){const{durationOffset:t,value:e}=r;kt(u,t-g(t),e)}return void 0!==s?u.subarray(0,s-f):u}(v,T.video.id,s.length,t,r);c?(B=c,$=function(t,e){let i=t,s=t;for(let t=0;t<e.length;t++){const{cts:r,duration:n}=e[t];s=Math.max(s,i+(r||0)+n),i+=n}return s}(e,s)):this.warn(`IFrame remux skipped (sn ${h.sn}); using native sample duration`),O=c&&r?i:C-w}else O=C-w}else this.warn(`Could not remux IFrame track fragment (no samples in range, trun count ${t.length})`),O=C-w}else O=F?x-P:C-w;if(this.videoOnlyRemux&&B===v)return this.warn(`Dropping muxed I-Frame fragment that could not be remuxed to video-only (sn: ${h.sn})`),p;const U=N.timescale,G=N.start-n*U,K=F?T.audio.id:T.video.id;if(M=N.start/U,(a||!g)&&(function(t,e,i,s){if(null===t)return!0;const r=Math.max(s,1),n=e-t.baseTime/t.timescale;return Math.abs(n-i)>=r}(g,M,n,O)||U!==g.timescale)){let t=!1;const e=F?"audio":"video";if(g){const i=0!==n?M/n:1+M/1;t=M>=0&&Math.abs(1-i)<.001,this.log(`${e} timestamps in track ${K} at playlist time: ${a?"":"~"}${n} maps to ${M} with initPTS: ${g.baseTime/g.timescale} (${G/U-g.baseTime/g.timescale}s diff) (${D}) drift estimate: ${i} ${t?"(ignoring drift)":"remapping timestamps (initPTS)"}`)}t||(this.log(`Found initPTS in ${e} track ${K} at playlist time: ${n} offset: ${M-n} (${G}/${U})`),g=null,E.initPTS=G,E.timescale=U,E.trackId=K)}g?(E.initPTS=g.baseTime,E.timescale=g.timescale,E.trackId=g.trackId):(E.timescale&&void 0!==E.trackId&&void 0!==E.initPTS||(this.warn("Could not set initPTS"),E.initPTS=M,E.timescale=1,E.trackId=-1),this.initPTS=g={baseTime:E.initPTS,timescale:E.timescale,trackId:E.trackId});const V=M-g.baseTime/g.timescale,j=V+O,H=_&&void 0!==(null==N?void 0:N.ptsMin)?N.ptsMin/N.timescale-g.baseTime/g.timescale:V,q=void 0!==$&&R?$/R.timescale-g.baseTime/g.timescale:_&&null!=N&&N.ptsMax?N.ptsMax/N.timescale-g.baseTime/g.timescale:j;O>0?this.lastEndTime=j:(this.warn("Duration parsed from mp4 should be greater than zero"),this.resetNextTimestamp());const Y={data1:B,data2:void 0,startPTS:H,startDTS:V,endPTS:q,endDTS:j,type:D,hasAudio:k,hasVideo:_,nb:1,dropped:0,encrypted:!!T.audio&&T.audio.encrypted||!!T.video&&T.video.encrypted};p.audio=k&&!_?Y:void 0,p.video=_?Y:void 0;const W=this.isVideoContiguous,z=null==R?void 0:R.sampleCount;if(z){const t=R.keyFrameIndex,e=-1!==t;Y.nb=z,Y.dropped=0===t||W?0:e?t:z,Y.independent=e,Y.firstKeyFrame=t,e&&R.keyFrameStart&&(Y.firstKeyFramePTS=(R.keyFrameStart-g.baseTime)/g.timescale),W||(p.independent=e),this.isVideoContiguous||(this.isVideoContiguous=e),Y.dropped&&this.warn(`fmp4 does not start with IDR: firstIDR ${t}/${z} dropped: ${Y.dropped} start: ${Y.firstKeyFramePTS||"NA"}`)}return p.initSegment=E,p.id3=Cn(s,n,g,g),r.samples.length&&(p.text=xn(r,n,g)),p}}},{demux:nn,remux:wn},{demux:class extends Fr{constructor(t,e){super(),this.observer=void 0,this.config=void 0,this.sampleAes=null,this.observer=t,this.config=e}resetInitSegment(t,e,i,s){super.resetInitSegment(t,e,i,s),this._audioTrack={container:"audio/adts",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"aac",samples:[],manifestCodec:e,duration:s,inputTimeScale:9e4,dropped:0}}static probe(t,e){if(!t)return!1;const i=nt(t,0);let s=(null==i?void 0:i.length)||0;if(qr(t,s))return!1;for(let i=t.length;s<i;s++)if(wr(t,s))return e.log("ADTS sync word found !"),!0;return!1}canParse(t,e){return function(t,e){return function(t,e){return e+5<t.length}(t,e)&&Rr(t,e)&&_r(t,e)<=t.length-e}(t,e)}appendFrame(t,e,i){Pr(t,this.observer,e,i,t.manifestCodec);const s=xr(t,e,i,this.basePTS,this.frameIndex);if(0===(null==s?void 0:s.missing))return s}demuxSampleAes(t,e,i){const s=this.demux(t,i),r=this.sampleAes=new Yr(this.observer,this.config,e);return new Promise(t=>{r.decryptAacSamples(s.audioTrack.samples,0,()=>{t(s)})})}},remux:wn},{demux:class extends Fr{resetInitSegment(t,e,i,s){super.resetInitSegment(t,e,i,s),this._audioTrack={container:"audio/mpeg",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"mp3",samples:[],manifestCodec:e,duration:s,inputTimeScale:9e4,dropped:0}}static probe(t){if(!t)return!1;const e=nt(t,0);let i=(null==e?void 0:e.length)||0;if(e&&11===t[i]&&119===t[i+1]&&void 0!==gt(e)&&Wr(t,i)<=16)return!1;for(let e=t.length;i<e;i++)if(qr(t,i))return q.log("MPEG Audio sync word found !"),!0;return!1}canParse(t,e){return function(t,e){return jr(t,e)&&4<=t.length-e}(t,e)}appendFrame(t,e,i){if(null!==this.basePTS)return Kr(t,e,i,this.basePTS,this.frameIndex)}},remux:wn}];Nn.splice(2,0,{demux:zr,remux:wn});class $n{constructor(t,e,i,s,r,n){this.asyncResult=!1,this.logger=void 0,this.observer=void 0,this.typeSupported=void 0,this.config=void 0,this.id=void 0,this.demuxer=void 0,this.remuxer=void 0,this.decrypter=void 0,this.probe=void 0,this.decryptionPromise=null,this.transmuxConfig=void 0,this.currentTransmuxState=void 0,this.observer=t,this.typeSupported=e,this.config=i,this.id=r,this.logger=n}configure(t){this.transmuxConfig=t,this.decrypter&&this.decrypter.reset()}push(t,e,i,s){if(!this.observer)return Bn(i);const o=i.transmuxing;o.executeStart=Fn();const l=new Uint8Array(t),{currentTransmuxState:h,transmuxConfig:d}=this;s&&(this.currentTransmuxState=s);const{contiguous:c,discontinuity:u,trackSwitch:f,accurateTimeOffset:g,timeOffset:m,initSegmentChange:p}=s||h,{audioCodec:v,videoCodec:y,defaultInitPts:E,duration:T,initSegmentData:S}=d,b=function(t,e){let i=null;t.byteLength>0&&null!=(null==e?void 0:e.key)&&null!==e.iv&&null!=e.method&&(i=e);return i}(l,e);if(b&&ts(b.method)){const t=this.getDecrypter(),e=es(b.method);return this.asyncResult=!0,this.decryptionPromise=t.decrypt(l,b.key.buffer,b.iv.buffer,e,i.decryptRange).then(t=>{const e=this.push(t,null,i);return this.decryptionPromise=null,e}),this.decryptionPromise}const A=this.needsProbing(u,f);if(A){const t=i.iframe&&S&&nn.probe(S,this.logger)?S:l,e=this.configureTransmuxer(t);if(e)return this.logger.warn(`[transmuxer] ${e.message}`),this.observer.emit(a.ERROR,a.ERROR,{type:r.MEDIA_ERROR,details:n.FRAG_PARSING_ERROR,fatal:!1,error:e,reason:e.message}),o.executeEnd=Fn(),Bn(i)}(u||f||p||A)&&this.resetInitSegment(S,v,y,T,e,i),(u||p||A)&&this.resetInitialTimestamp(E),c||this.resetContiguity();const L=this.transmux(l,b,m,g,i);this.asyncResult=Un(L);const I=this.currentTransmuxState;return I.contiguous=!0,I.discontinuity=!1,I.trackSwitch=!1,o.executeEnd=Fn(),L}flush(t){const e=t.transmuxing;e.executeStart=Fn();const{decrypter:i,currentTransmuxState:s,decryptionPromise:r}=this;if(r)return this.asyncResult=!0,r.then(()=>this.flush(t));const n=[],{timeOffset:a}=s;if(i){const e=i.flush();e&&n.push(this.push(e.buffer,null,t))}const{demuxer:o,remuxer:l}=this;if(!o||!l){e.executeEnd=Fn();const i=[Bn(t)];return this.asyncResult?Promise.resolve(i):i}const h=o.flush(a,t);return Un(h)?(this.asyncResult=!0,h.then(e=>(this.flushRemux(n,e,t),n))):(this.flushRemux(n,h,t),this.asyncResult?Promise.resolve(n):n)}flushRemux(t,e,i){if(!this.remuxer)return;const{audioTrack:s,videoTrack:r,id3Track:n,textTrack:a}=e,{accurateTimeOffset:o,timeOffset:l}=this.currentTransmuxState;this.logger.log(`[transmuxer.ts]: Flushed ${this.id} sn: ${i.sn}${i.part>-1?" part: "+i.part:""} of ${this.id} playlist ${i.level}`);const h=this.remuxer.remux(s,r,n,a,l,o,!0,this.id,i,e.initData,e.sampleData);t.push({remuxResult:h,chunkMeta:i}),i.transmuxing.executeEnd=Fn()}resetInitialTimestamp(t){const{demuxer:e,remuxer:i}=this;e&&i&&(e.resetTimeStamp(t),i.resetTimeStamp(t))}resetContiguity(){const{demuxer:t,remuxer:e}=this;t&&e&&(t.resetContiguity(),e.resetNextTimestamp())}resetInitSegment(t,e,i,s,r,n){const{demuxer:a,remuxer:o}=this;a&&o&&(a.resetInitSegment(t,e,i,s,r,n),o.resetInitSegment(t,e,i,r))}destroy(){this.demuxer&&(this.demuxer.destroy(),this.demuxer=void 0),this.remuxer&&(this.remuxer.destroy(),this.remuxer=void 0),this.observer&&this.observer.removeAllListeners(),this.decryptionPromise=null,this.decrypter=this.observer=void 0,this.logger=this.config=this.probe=void 0}transmux(t,e,i,s,r){let n;return n="SAMPLE-AES"===(null==e?void 0:e.method)?this.transmuxSampleAes(t,e,i,s,r):this.transmuxUnencrypted(t,i,s,r),n}transmuxUnencrypted(t,e,i,s){const{demuxer:r,remuxer:n}=this;if(!r||!n)return Bn(s);const a=r.demux(t,e,s,!1,!this.config.progressive),{audioTrack:o,videoTrack:l,id3Track:h,textTrack:d}=a;return{remuxResult:n.remux(o,l,h,d,e,i,!1,this.id,s,a.initData,a.sampleData),chunkMeta:s}}transmuxSampleAes(t,e,i,s,r){return this.demuxer?this.demuxer.demuxSampleAes(t,e,i,r).then(t=>({remuxResult:this.remuxer.remux(t.audioTrack,t.videoTrack,t.id3Track,t.textTrack,i,s,!1,this.id,r,t.initData,t.sampleData),chunkMeta:r})):Promise.reject(new Error("no demuxer"))}configureTransmuxer(t){const{config:e,observer:i,typeSupported:s}=this;if(!i)return;let r;try{for(let e=0,i=Nn.length;e<i;e++){var n;if(null!=(n=Nn[e].demux)&&n.probe(t,this.logger)){r=Nn[e];break}}}catch(t){return t}if(!r)return new Error("Failed to find demuxer by probing fragment data");const a=this.demuxer,o=this.remuxer,l=r.demux,h=r.remux;a&&a instanceof l||(this.logger.log(`Using ${l.name}`),this.demuxer=new l(i,e,s,this.logger),this.probe=l.probe),o&&o instanceof h||(this.logger.log(`Using ${h.name}`),this.remuxer=new h(i,e,s,this.logger))}needsProbing(t,e){return!this.demuxer||!this.remuxer||t||e}getDecrypter(){let t=this.decrypter;return t||(t=this.decrypter=new Di(this.config)),t}}const Bn=t=>({remuxResult:{},chunkMeta:t});function Un(t){return"then"in t&&t.then instanceof Function}class Gn{constructor(t,e,i,s,r){this.audioCodec=void 0,this.videoCodec=void 0,this.initSegmentData=void 0,this.duration=void 0,this.defaultInitPts=void 0,this.audioCodec=t,this.videoCodec=e,this.initSegmentData=i,this.duration=s,this.defaultInitPts=r||null}}class Kn{constructor(t,e,i,s,r,n){this.discontinuity=void 0,this.contiguous=void 0,this.accurateTimeOffset=void 0,this.trackSwitch=void 0,this.timeOffset=void 0,this.initSegmentChange=void 0,this.discontinuity=t,this.contiguous=e,this.accurateTimeOffset=i,this.trackSwitch=s,this.timeOffset=r,this.initSegmentChange=n}}let Vn=0;class jn{constructor(t,e,i,s){this.error=null,this.hls=void 0,this.id=void 0,this.instanceNo=Vn++,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=t=>{const e=t.data,i=this.hls;if(i&&null!=e&&e.event&&e.instanceNo===this.instanceNo)switch(e.event){case"init":{var s;const t=null==(s=this.workerContext)?void 0:s.objectURL;t&&self.URL.revokeObjectURL(t);break}case"transmuxComplete":this.handleTransmuxComplete(e.data);break;case"flush":this.onFlush(e.data);break;case"workerLog":i.logger[e.data.logType]&&i.logger[e.data.logType](e.data.message);break;default:e.data=e.data||{},e.data.frag=this.frag,e.data.part=this.part,e.data.id=this.id,i.trigger(e.event,e.data)}},this.onWorkerError=t=>{if(!this.hls)return;const e=new Error(`${t.message} (${t.filename}:${t.lineno})`);this.hls.config.enableWorker=!1,this.hls.logger.warn(`Error in "${this.id}" Web Worker, fallback to inline`),this.hls.trigger(a.ERROR,{type:r.OTHER_ERROR,details:n.INTERNAL_EXCEPTION,fatal:!1,event:"demuxerWorker",error:e})};const o=t.config;this.hls=t,this.id=e,this.useWorker=!!o.enableWorker,this.onTransmuxComplete=i,this.onFlush=s;const l=(t,e)=>{(e=e||{}).frag=this.frag||void 0,t===a.ERROR&&(e.parent=this.id,e.part=this.part,this.error=e.error),this.hls.trigger(t,e)};this.observer=new Ar,this.observer.on(a.FRAG_DECRYPTED,l),this.observer.on(a.ERROR,l);const h=Te(o.preferManagedMediaSource);if(this.useWorker&&"undefined"!=typeof Worker){const i=this.hls.logger;if(o.workerPath||"function"==typeof __HLS_WORKER_BUNDLE__){try{o.workerPath?(i.log(`loading Web Worker ${o.workerPath} for "${e}"`),this.workerContext=function(t){const e=Ir[t];if(e)return e.clientCount++,e;const i=new self.URL(t,self.location.href).href,s={worker:new self.Worker(i),scriptURL:i,clientCount:1};return Ir[t]=s,s}(o.workerPath)):(i.log(`injecting Web Worker for "${e}"`),this.workerContext=function(){const t=Ir[Lr];if(t)return t.clientCount++,t;const e=new self.Blob([`var exports={};var module={exports:exports};function define(f){f()};define.amd=true;(${__HLS_WORKER_BUNDLE__.toString()})(true);`],{type:"text/javascript"}),i=self.URL.createObjectURL(e),s={worker:new self.Worker(i),objectURL:i,clientCount:1};return Ir[Lr]=s,s}());const{worker:t}=this.workerContext;t.addEventListener("message",this.onWorkerMessage),t.addEventListener("error",this.onWorkerError),t.postMessage({instanceNo:this.instanceNo,cmd:"init",typeSupported:h,id:e,config:Ue(o)})}catch(s){i.warn(`Error setting up "${e}" Web Worker, fallback to inline`,s),this.terminateWorker(),this.error=null,this.transmuxer=new $n(this.observer,h,o,"",e,t.logger)}return}}this.transmuxer=new $n(this.observer,h,o,"",e,t.logger)}reset(){if(this.frag=null,this.part=null,this.workerContext){const t=this.instanceNo;this.instanceNo=Vn++;const e=this.hls.config,i=Te(e.preferManagedMediaSource);this.workerContext.worker.postMessage({instanceNo:this.instanceNo,cmd:"reset",resetNo:t,typeSupported:i,id:this.id,config:Ue(e)})}}terminateWorker(){if(this.workerContext){const{worker:t}=this.workerContext;this.workerContext=null,t.removeEventListener("message",this.onWorkerMessage),t.removeEventListener("error",this.onWorkerError),function(t){const e=Ir[t||Lr];if(e&&1===e.clientCount--){const{worker:i,objectURL:s}=e;delete Ir[t||Lr],s&&self.URL.revokeObjectURL(s),i.terminate()}}(this.hls.config.workerPath)}}destroy(){if(this.workerContext)this.terminateWorker(),this.onWorkerMessage=this.onWorkerError=null;else{const t=this.transmuxer;t&&(t.destroy(),this.transmuxer=null)}const t=this.observer;t&&t.removeAllListeners(),this.frag=null,this.part=null,this.observer=null,this.hls=null}push(t,e,i,s,r,n,a,o,l,h){var d,c;l.transmuxing.start=self.performance.now();const{instanceNo:u,transmuxer:f}=this,g=n?n.start:r.start,m=r.decryptdata,p=this.frag,v=!p||r.cc!==p.cc,y=!p||l.level!==p.level,E=p?l.sn-p.sn:-1,T=this.part?l.part-this.part.index:-1,S=0===E&&l.id>1&&l.id===(null==p?void 0:p.stats.chunkCount),b=!y&&(1===E||0===E&&(1===T||S&&T<=0)),A=self.performance.now();(y||E||0===r.stats.parsing.start)&&(r.stats.parsing.start=A),!n||!T&&b||(n.stats.parsing.start=A);const L=!(p&&(null==(d=r.initSegment)?void 0:d.url)===(null==(c=p.initSegment)?void 0:c.url)),I=new Kn(v,b,o,y,g,L);if(!b||v||L){this.hls.logger.log(`[transmuxer-interface]: Starting new transmux session for ${r.type} sn: ${l.sn}${l.part>-1?" part: "+l.part:""} ${this.id} playlist: ${l.level} id: ${l.id}\n discontinuity: ${v}\n trackSwitch: ${y}\n contiguous: ${b}\n accurateTimeOffset: ${o}\n timeOffset: ${g}\n initSegmentChange: ${L}`);const t=new Gn(i,s,e,a,h);this.configureTransmuxer(t)}if(this.frag=r,this.part=n,this.workerContext)this.workerContext.worker.postMessage({instanceNo:u,cmd:"demux",data:t,decryptdata:m,chunkMeta:l,state:I},t instanceof ArrayBuffer?[t]:[]);else if(f){const e=f.push(t,m,l,I);Un(e)?e.then(t=>{this.handleTransmuxComplete(t)}).catch(t=>{this.transmuxerError(t,l,"transmuxer-interface push error")}):this.handleTransmuxComplete(e)}}flush(t){t.transmuxing.start=self.performance.now();const{instanceNo:e,transmuxer:i}=this;if(this.workerContext)this.workerContext.worker.postMessage({instanceNo:e,cmd:"flush",chunkMeta:t});else if(i){const e=i.flush(t);Un(e)?e.then(e=>{this.handleFlushResult(e,t)}).catch(e=>{this.transmuxerError(e,t,"transmuxer-interface flush error")}):this.handleFlushResult(e,t)}}transmuxerError(t,e,i){this.hls&&(this.error=t,this.hls.trigger(a.ERROR,{type:r.MEDIA_ERROR,details:n.FRAG_PARSING_ERROR,chunkMeta:e,frag:this.frag||void 0,part:this.part||void 0,fatal:!1,error:t,err:t,reason:i}))}handleFlushResult(t,e){t.forEach(t=>{this.handleTransmuxComplete(t)}),this.onFlush(e)}configureTransmuxer(t){const{instanceNo:e,transmuxer:i}=this;this.workerContext?this.workerContext.worker.postMessage({instanceNo:e,cmd:"configure",config:t}):i&&i.configure(t)}handleTransmuxComplete(t){t.chunkMeta.transmuxing.end=self.performance.now(),this.onTransmuxComplete(t)}}class Hn extends U{constructor(t,e){super(e,t.logger),this.hls=void 0,this.canLoad=!1,this.timer=-1,this.loadingSync=!1,this.hls=t}destroy(){this.clearTimer(),this.hls=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(t,e,i){const s=null==e?void 0:e.renditionReports;if(s){let r=-1;for(let i=0;i<s.length;i++){const n=s[i];let a;try{a=new self.URL(n.URI,e.url).href}catch(t){this.warn(`Could not construct new URL for Rendition Report: ${t}`),a=n.URI||""}if(a===t){r=i;break}a===t.substring(0,a.length)&&(r=i)}if(-1!==r){const t=s[r],n=parseInt(t["LAST-MSN"])||e.lastPartSn;let a=parseInt(t["LAST-PART"])||e.lastPartIndex;if(this.hls.config.lowLatencyMode){const t=Math.min(e.age-e.partTarget,e.targetduration);a>=0&&t>e.partTarget&&(a+=1)}const o=i&&Oe(i);return new Fe(n,a>=0?a:void 0,o)}}}loadPlaylist(t){this.clearTimer()}loadingPlaylist(t,e){this.clearTimer()}shouldLoadPlaylist(t){return this.canLoad&&!!t&&!!t.url&&(!t.details||t.details.live)}getUrlWithDirectives(t,e){if(e)try{return e.addDirectives(t)}catch(t){this.warn(`Could not construct new URL with HLS Delivery Directives: ${t}`)}return t}playlistLoaded(t,e,i){const{details:s,stats:o}=e,l=s.fragments,h=self.performance.now(),d=o.loading.first?Math.max(0,Math.floor(h-o.loading.first)):0;s.advancedDateTime=Date.now()-d;const c=this.hls.config.timelineOffset;if(c!==s.appliedTimelineOffset){const t=Math.max(c||0,0);s.appliedTimelineOffset=t,l.forEach(e=>{null==e||e.setStart(e.playlistOffset+t)})}if(s.live||null!=i&&i.live){var u;const c="levelInfo"in e?e.levelInfo:e.track;s.reloaded(i);const f=null==(u=l[l.length-1])?void 0:u.type;if(s.misses>=this.hls.config.liveMaxUnchangedPlaylistRefresh){const t=new Error(`${f} playlist ${c.id} hit max allowed unchanged reloads.`);this.warn(t);const{networkDetails:i,context:l}=e;return void this.hls.trigger(a.ERROR,{type:r.NETWORK_ERROR,details:n.PLAYLIST_UNCHANGED_ERROR,fatal:!1,url:s.url,error:t,reason:t.message,level:e.level,parent:f,context:l,networkDetails:i,stats:o})}if(i){Gs(i,s,this);const t=s.playlistParsingError;if(t){this.warn(t);const i=this.hls;if(!i.config.ignorePlaylistParsingErrors){const{networkDetails:l}=e;return void i.trigger(a.ERROR,{type:r.NETWORK_ERROR,details:n.LEVEL_PARSING_ERROR,fatal:!1,url:s.url,error:t,reason:t.message,level:e.level,parent:f,networkDetails:l,stats:o})}s.playlistParsingError=null}}-1===s.requestScheduled&&(s.requestScheduled=o.loading.start);const g=this.hls.mainForwardBufferInfo,m=g?g.end-g.len:0,p=js(s,1e3*(s.edge-m));s.requestScheduled+p<h?s.requestScheduled=h:s.requestScheduled<=h&&(s.requestScheduled+=p);const v=e.deliveryDirectives;if(this.log(`live playlist ${t} ${s.advanced?`REFRESHED ${s.lastPartSn} - ${s.lastPartIndex}`:s.updated?"UPDATED":`MISSED (received ${s.lastPartSn} - ${s.lastPartIndex}${v?` | requested ${v.msn} - ${v.part}`:""})`}`),!this.canLoad||!s.live)return;let y,E,T;if(s.canBlockReload&&s.advanced){const t=this.hls.config.lowLatencyMode,r=s.lastPartSn,n=s.endSN,a=s.lastPartIndex,o=r===n;-1!==a?o?(E=n+1,T=t?0:a):(E=r,T=t?a+1:s.maxPartIndex):E=n+1;const l=s.age,d=l+s.ageHeader;let u=Math.min(d-s.partTarget,1.5*s.targetduration);if(u>0){if(d>3*s.targetduration)this.log(`Playlist last advanced ${l.toFixed(2)}s ago. Omitting segment and part directives.`),E=void 0,T=void 0;else if(null!=i&&i.tuneInGoal&&d-s.partTarget>i.tuneInGoal)this.warn(`CDN Tune-in goal increased from: ${i.tuneInGoal} to: ${u} with playlist age: ${s.age}`),u=0;else{const t=Math.floor(u/s.targetduration);if(E+=t,void 0!==T){T+=Math.round(u%s.targetduration/s.partTarget)}this.log(`CDN Tune-in age: ${s.ageHeader}s last advanced ${l.toFixed(2)}s goal: ${u} skip sn ${t} to part ${T}`)}s.tuneInGoal=u}if(y=this.getDeliveryDirectives(s,e.deliveryDirectives,E,T),t||!o)return s.requestScheduled=h,void this.loadingPlaylist(c,y)}else(s.canBlockReload||s.canSkipUntil)&&(y=this.getDeliveryDirectives(s,e.deliveryDirectives,E,T));y&&void 0!==E&&s.canBlockReload&&(s.requestScheduled=o.loading.first+Math.max(p-2*d,p/2)),this.scheduleLoading(c,y,s)}else this.clearTimer()}scheduleLoading(t,e,i){const s=i||t.details;if(!s)return void this.loadingPlaylist(t,e);const r=self.performance.now(),n=s.requestScheduled;if(r>=n&&!this.loadingSync)return this.loadingSync=!0,this.loadingPlaylist(t,e),void(this.loadingSync=!1);const a=Math.max(n-r,0);this.log(`reload live playlist ${t.name||t.bitrate+"bps"} in ${Math.round(a)} ms`),this.clearTimer(),this.timer=self.setTimeout(()=>this.loadingPlaylist(t,e),a)}getDeliveryDirectives(t,e,i,s){let r=Oe(t);return null!=e&&e.skip&&t.deltaUpdateFailed&&(i=e.msn,s=e.part,r=Ce),new Fe(i,s,r)}checkRetry(t){const e=t.details,i=D(t),s=t.errorAction,{action:r,retryCount:n=0,retryConfig:a}=s||{},o=!!s&&!!a&&(r===ai||!s.resolved&&r===ri);if(o){var l;if(n>=a.maxNumRetry)return!1;if(i&&null!=(l=t.context)&&l.deliveryDirectives)this.warn(`Retrying playlist loading ${n+1}/${a.maxNumRetry} after "${e}" without delivery-directives`),this.loadPlaylist();else{var h;const i=F(null==(h=t.response)?void 0:h.code);if(this.clearTimer(),i)this.log("Waiting for connection (offline)"),t.reason="offline",this.timer=self.setTimeout(()=>this.checkOfflineStatus(),1e3);else{const t=x(a,n);this.warn(`Retrying playlist loading ${n+1}/${a.maxNumRetry} after "${e}" in ${t}ms`),this.timer=self.setTimeout(()=>this.loadPlaylist(),t)}}t.levelRetry=!0,s.resolved=!0}return o}checkOfflineStatus(){this.clearTimer(),F(0)?this.timer=self.setTimeout(()=>this.checkOfflineStatus(),1e3):(this.log("Connection restored (online)"),this.loadPlaylist())}}function qn(t,e){if(t.length!==e.length)return!1;for(let i=0;i<t.length;i++)if(!Yn(t[i].attrs,e[i].attrs))return!1;return!0}function Yn(t,e,i){const s=t["STABLE-RENDITION-ID"];return s&&!i?s===e["STABLE-RENDITION-ID"]:!(i||["LANGUAGE","NAME","CHARACTERISTICS","AUTOSELECT","DEFAULT","FORCED","ASSOC-LANGUAGE"]).some(i=>t[i]!==e[i])}class Wn{constructor(t){this.tracks=void 0,this.queues={video:[],audio:[],audiovideo:[]},this.tracks=t}destroy(){this.tracks=this.queues=null}append(t,e,i){if(null===this.queues||null===this.tracks)return;const s=this.queues[e];s.push(t),1!==s.length||i||this.executeNext(e)}appendBlocker(t){return new Promise(e=>{const i={label:"async-blocker",execute:e,onStart:()=>{},onComplete:()=>{},onError:()=>{}};this.append(i,t)})}prependBlocker(t){return new Promise(e=>{if(this.queues){const i={label:"async-blocker-prepend",execute:e,onStart:()=>{},onComplete:()=>{},onError:()=>{}};this.queues[t].unshift(i)}})}removeBlockers(){null!==this.queues&&[this.queues.video,this.queues.audio,this.queues.audiovideo].forEach(t=>{var e;const i=null==(e=t[0])?void 0:e.label;"async-blocker"===i||"async-blocker-prepend"===i?(t[0].execute(),t.splice(0,1)):"block-audio"===i&&t.splice(0,1)})}insertNext(t,e){null!==this.queues&&this.queues[e].splice(1,0,...t)}unblockAudio(){var t;null!==this.queues&&"block-audio"===(null==(t=this.current("audio"))?void 0:t.label)&&this.shiftAndExecuteNext("audio")}audioBlocking(){return null!==this.queues&&this.queues.audio.some(t=>"block-audio"===t.label)}executeNext(t){if(null===this.queues||null===this.tracks)return;const e=this.queues[t];if(e.length){const s=e[0];try{s.execute()}catch(e){var i;if(s.onError(e),null===this.queues||null===this.tracks)return;const r=null==(i=this.tracks[t])?void 0:i.buffer;null!=r&&r.updating||this.shiftAndExecuteNext(t)}}}shiftAndExecuteNext(t){null!==this.queues&&(this.queues[t].shift(),this.executeNext(t))}current(t){var e;return(null==(e=this.queues)?void 0:e[t][0])||null}toString(){const{queues:t,tracks:e}=this;return null===t||null===e?"<destroyed>":`\n${this.list("video")}\n${this.list("audio")}\n${this.list("audiovideo")}}`}list(t){var e,i;return null!=(e=this.queues)&&e[t]||null!=(i=this.tracks)&&i[t]?`${t}: (${this.listSbInfo(t)}) ${this.listOps(t)}`:""}listSbInfo(t){var e;const i=null==(e=this.tracks)?void 0:e[t],s=null==i?void 0:i.buffer;return s?`SourceBuffer${s.updating?" updating":""}${i.ended?" ended":""}${i.ending?" ending":""}`:"none"}listOps(t){var e;return(null==(e=this.queues)?void 0:e[t].map(t=>t.label).join(", "))||""}}const zn=/(avc[1234]|hvc1|hev1|dvh[1e]|vp09|av01)(?:\.[^.,]+)+/,Xn="HlsJsTrackRemovedError";class Qn extends Error{constructor(t){super(t),this.name=Xn}}function Zn(t){const e=t.querySelectorAll("source");[].slice.call(e).forEach(e=>{t.removeChild(e)})}function Jn(t){return"audio"===t?1:0}function ta(t,e){return`${t?"":" - triggering recovery"}${e?" with HTMLMediaElement Error: "+e.message:""}`}function ea(t){return`${t.type}_${t.sn}_${t.level}`}function ia(t,e){const{start:i,end:s}=e;let r=0;for(let e=0;e<t.length;e++){const n=t[e];if(n.start>=s)break;const a=Math.max(i,n.start),o=Math.min(s,n.end);o>a&&(r+=o-a)}return r}function sa(t,e){return e.duration-t<=.05}class ra{constructor(t){this.hls=null,this.autoLevelCapping=void 0,this.media=void 0,this.restrictedLevels=void 0,this.timer=void 0,this.observer=void 0,this.clientRect=void 0,this.streamController=void 0,this.hls=t,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.media=null,this.restrictedLevels=[],this.clientRect=null,this.registerListeners()}setStreamController(t){this.streamController=t}destroy(){this.hls&&this.unregisterListener(),(this.timer||this.observer)&&this.stopCapping(),this.media=this.clientRect=this.hls=null,this.streamController=void 0}registerListeners(){const{hls:t}=this;t&&(t.on(a.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),t.on(a.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(a.MANIFEST_PARSED,this.onManifestParsed,this),t.on(a.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(a.BUFFER_CODECS,this.onBufferCodecs,this),t.on(a.MEDIA_DETACHING,this.onMediaDetaching,this))}unregisterListener(){const{hls:t}=this;t&&(t.off(a.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),t.off(a.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(a.MANIFEST_PARSED,this.onManifestParsed,this),t.off(a.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(a.BUFFER_CODECS,this.onBufferCodecs,this),t.off(a.MEDIA_DETACHING,this.onMediaDetaching,this))}onFpsDropLevelCapping(t,e){if(!this.hls)return;const i=this.hls.levels[e.droppedLevel];this.isLevelAllowed(i)&&this.restrictedLevels.push({bitrate:i.bitrate,height:i.height,width:i.width})}onMediaAttaching(t,e){const i=e.media;this.clientRect=null,this.hls&&(i instanceof HTMLVideoElement?(this.media=i,this.hls.config.capLevelToPlayerSize&&this.observe()):this.media=null,(this.timer||this.observer)&&this.hls.levels.length>1&&this.detectPlayerSize())}onManifestParsed(t,e){this.restrictedLevels=[],e.video&&this.startCapping(),this.onLevelsUpdated()}onLevelsUpdated(){if(this.hls)if((this.timer||this.observer)&&(e(this.autoLevelCapping)||this.clientRect))this.detectPlayerSize();else if(void 0===this.observer&&void 0===this.timer){const t=this.hls.levels;t.length>1&&t.some(t=>!!t.videoCodec)&&this.startCapping()}}onBufferCodecs(t,e){e.video&&this.startCapping()}onMediaDetaching(){this.stopCapping(),this.media=null}detectPlayerSize(){if(this.media){if(this.mediaHeight<=0||this.mediaWidth<=0||!this.hls)return void(this.clientRect=null);const t=this.hls.levels;if(t.length>1){const e=this.hls,i=this.getMaxLevel(t.length-1);i!==this.autoLevelCapping&&e.logger.log(`Setting autoLevelCapping to ${i}: ${t[i].height}p@${t[i].bitrate} for media ${this.mediaWidth}x${this.mediaHeight}`),e.autoLevelCapping=i,e.autoLevelEnabled&&e.autoLevelCapping>this.autoLevelCapping&&this.streamController&&this.streamController.nextLevelSwitch(),this.autoLevelCapping=e.autoLevelCapping}else 1===t.length&&this.stopCapping()}}getMaxLevel(t){if(!this.hls)return-1;const e=this.hls.levels;if(!e.length)return-1;const i=e.filter((e,i)=>this.isLevelAllowed(e)&&i<=t);return this.observer||(this.clientRect=null),ra.getMaxLevelByMediaSize(i,this.mediaWidth,this.mediaHeight)}observe(){const t=self.ResizeObserver;t&&(this.observer=new t(t=>{var e;const i=null==(e=t[0])?void 0:e.contentRect;i&&(this.clientRect=i,this.detectPlayerSize())})),this.observer&&this.media&&this.observer.observe(this.media)}startCapping(){var t;this.timer||this.observer||null==(t=this.hls)||!t.config.capLevelToPlayerSize||(self.clearInterval(this.timer),this.timer=void 0,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.observe(),this.observer||(this.timer=self.setInterval(this.detectPlayerSize.bind(this),1e3)),this.detectPlayerSize())}stopCapping(){this.restrictedLevels=[],this.autoLevelCapping=Number.POSITIVE_INFINITY,this.timer&&(self.clearInterval(this.timer),this.timer=void 0),this.observer&&(this.observer.disconnect(),this.observer=void 0)}getDimensions(){if(this.clientRect)return this.clientRect;const t=this.media,e={width:0,height:0};if(t){const i=t.getBoundingClientRect();e.width=i.width,e.height=i.height,e.width||e.height||(e.width=i.right-i.left||t.width||0,e.height=i.bottom-i.top||t.height||0)}return this.clientRect=e,e}get mediaWidth(){return this.getDimensions().width*this.contentScaleFactor}get mediaHeight(){return this.getDimensions().height*this.contentScaleFactor}get contentScaleFactor(){let t=1;if(!this.hls)return t;const{ignoreDevicePixelRatio:e,maxDevicePixelRatio:i}=this.hls.config;if(!e)try{t=self.devicePixelRatio}catch(t){}return Math.min(t,i)}isLevelAllowed(t){return!this.restrictedLevels.some(e=>t.bitrate===e.bitrate&&t.width===e.width&&t.height===e.height)}static getMaxLevelByMediaSize(t,e,i){if(null==t||!t.length)return-1;const s=(t,e)=>!e||(t.width!==e.width||t.height!==e.height);let r=t.length-1;const n=Math.max(e,i);for(let e=0;e<t.length;e+=1){const i=t[e];if((i.width>=n||i.height>=n)&&s(i,t[e+1])){r=e;break}}return r}}var na=class t{constructor(e,i){Array.isArray(e)&&(e=e.map(e=>e instanceof t?e:new t(e))),this.value=e,this.params=i}};function aa(t,e,i,s){return new Error(`failed to ${t} "${r=e,Array.isArray(r)?JSON.stringify(r):r instanceof Map?"Map{}":r instanceof Set?"Set{}":"object"==typeof r?JSON.stringify(r):String(r)}" as ${i}`,{cause:s});var r}const oa="Bare Item";const la=/[\x00-\x1f\x7f]+/;var ha=class{constructor(t){this.description=t}};function da(t,e,i){return aa("serialize",t,e,i)}function ca(t){if(!1===ArrayBuffer.isView(t))throw da(t,"Byte Sequence");return`:${e=t,btoa(String.fromCharCode(...e))}:`;var e}function ua(t){if(function(t){return t<-999999999999999||999999999999999<t}(t))throw da(t,"Integer");return t.toString()}function fa(t){const e=J(t,3);if(Math.floor(Math.abs(e)).toString().length>12)throw da(t,"Decimal");const i=e.toString();return i.includes(".")?i:`${i}.0`}function ga(t){const e=(i=t).description||i.toString().slice(7,-1);var i;if(!1===/^([a-zA-Z*])([!#$%&'*+\-.^_`|~\w:/]*)$/.test(e))throw da(e,"Token");return e}function ma(t){switch(typeof t){case"number":if(!e(t))throw da(t,oa);return Number.isInteger(t)?ua(t):fa(t);case"string":return function(t){if(la.test(t))throw da(t,"String");return`"${t.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}(t);case"symbol":return ga(t);case"boolean":return function(t){if("boolean"!=typeof t)throw da(t,"Boolean");return t?"?1":"?0"}(t);case"object":if(t instanceof Date)return function(t){return`@${ua(t.getTime()/1e3)}`}(t);if(t instanceof Uint8Array)return ca(t);if(t instanceof ha)return ga(t);default:throw da(t,oa)}}function pa(t){if(!1===/^[a-z*][a-z0-9\-_.*]*$/.test(t))throw da(t,"Key");return t}function va(t){return null==t?"":Object.entries(t).map(([t,e])=>!0===e?`;${pa(t)}`:`;${pa(t)}=${ma(e)}`).join("")}function ya(t){return t instanceof na?`${ma(t.value)}${va(t.params)}`:ma(t)}function Ea(t,e={whitespace:!0}){if("object"!=typeof t||null==t)throw da(t,"Dict");const i=t instanceof Map?t.entries():Object.entries(t),s=null!=e&&e.whitespace?" ":"";return Array.from(i).map(([t,e])=>{e instanceof na==!1&&(e=new na(e));let i=pa(t);var s;return!0===e.value?i+=va(e.params):(i+="=",Array.isArray(e.value)?i+=`(${(s=e).value.map(ya).join(" ")})${va(s.params)}`:i+=ya(e)),i}).join(`,${s}`)}function Ta(t,e){return Ea(t,e)}const Sa=["url"],ba=["version","eventTargets","sid","transmissionMode"],Aa=["customData","headers"],La=t=>t instanceof na?new na(Math.round(t.value),t.params):Math.round(t),Ia=t=>Array.isArray(t)?t.map(La):La(t),Ra=(t,e)=>Array.isArray(t)?t.map(t=>Ra(t,e)):t instanceof na&&"string"==typeof t.value?new na(Ra(t.value,e),t.params):(e.baseUrl&&(t=function(t,e){let i;try{i=new URL(t)}catch(e){return t}const s=new URL(e);if(i.origin!==s.origin)return t;const r=i.pathname.split("/").slice(1),n=s.pathname.split("/").slice(1,-1),a=Math.min(r.length,n.length);for(let t=0;t<a&&r[t]===n[t];t++)r.shift(),n.shift();for(;n.length;)n.shift(),r.unshift("..");return r.join("/")+i.search+i.hash}(t,function(t){const e="string"==typeof t?new URL(t):t;return e.origin+e.pathname.substring(0,e.pathname.lastIndexOf("/")+1)}(e.baseUrl))),1===e.version?encodeURIComponent(t):t),ka=t=>t instanceof na?new na(100*Math.round(t.value/100),t.params):100*Math.round(t/100),_a=t=>Array.isArray(t)?t.map(ka):ka(t),Da={br:Ia,d:Ia,bl:_a,dl:_a,mtp:_a,nor:(t,e)=>{let i=t;return e.version>=2&&(t instanceof na&&"string"==typeof t.value?i=new na([t]):"string"==typeof t&&(i=[t])),Ra(i,e)},rtp:_a,tb:Ia},wa=2,Pa="rr",Ca="bc",xa="e",Ma=Pa,Oa="ce",Fa=new Map([["ps","sta"],["pr","pr"],["c","cid"],["b","bg"],["bc","br"]]),Na="event",$a="request",Ba=["cen","e","h","ts"],Ua=["ab","bg","bl","br","bs","bsa","bsd","bsda","cdn","cid","cs","d","dfa","dl","ec","lab","lb","ltc","msd","mtp","nor","nr","ot","pb","pr","pt","rtp","sf","sid","sn","st","sta","su","tab","tb","tbl","tpb","v"],Ga=/^[a-zA-Z0-9-.]+-[a-zA-Z0-9-.]+$/;function Ka(t){return Ga.test(t)}const Va=new Set(Ua);function ja(t){return Va.has(t)||Ka(t)}const Ha=["cmsdd","cmsds","rc","smrt","ttfb","ttfbb","ttlb","url"],qa=new Set(Ha);function Ya(t){return qa.has(t)}const Wa=new Set(Ba);const za=new Set(["ab","bl","br","bsa","bsd","bsda","lab","lb","mtp","pb","tab","tb","tbl","tpb"]),Xa=["bl","br","bs","cid","d","dl","mtp","nor","nrr","ot","pr","rtp","sf","sid","st","su","tb","v"],Qa=new Set(Xa);function Za(t){return Qa.has(t)||Ka(t)}const Ja=new Set(["ot","sf","st","e","sta"]);function to(t){return Ja.has(t)}function eo(t){return"number"==typeof t?e(t):null!=t&&""!==t&&!1!==t}const io={[Na]:function(t){return ja(t)||Ya(t)||Wa.has(t)},[$a]:ja};function so(t,e){if(Array.isArray(t)){let i;return e&&(i=t.find(t=>{var i;return(null==(i=t.params)?void 0:i.ot)===e})),i||(i=t[0]),so(i)}return t instanceof na?t.value:t}function ro(t,i={}){const s={};if(null==t||"object"!=typeof t)return s;const r=i.version||t.v||wa,n=i.reportingMode||$a,a=1===r?function(t){const e={};for(const[s,r]of Object.entries(t))if(null!=r)if("nor"===s){const t=(Array.isArray(r)?r:[r])[0];var i;t instanceof na?(e.nor=t.value,null!=(i=t.params)&&i.r&&(e.nrr=t.params.r)):e.nor=t}else za.has(s)?e[s]=so(r,t.ot):e[s]=r;else e[s]=r;return e}(t):t,o=1===r?Za:io[n];let l=Object.keys(a).filter(o);a.e&&a.e!==Pa&&(l=l.filter(t=>!Ya(t)));const h=i.filter;"function"==typeof h&&(l=l.filter(h));const d=n===Na;if(d){const t=a.e;l.includes("e")||null==t||l.push("e"),l.includes("ts")||l.push("ts"),l.includes("cen")||null==a.cen||"ce"!==t||l.push("cen");const e=t?Fa.get(t):void 0;e&&null!=a[e]&&!l.includes(e)&&l.push(e)}if(0===l.length)return s;r>1&&!l.includes("v")&&l.push("v");const c={version:r,reportingMode:n,baseUrl:i.baseUrl};l.sort();for(const t of l){var u,f;let n=a[t];const o=null!=(u=null==(f=i.formatters)?void 0:f[t])?u:Da[t];if("function"==typeof o&&(n=o(n,c)),"v"===t){if(1===r)continue;n=r}if("pr"===t&&1===n&&(!d||"pr"!==a.e))continue;d&&"ts"===t&&!e(n)&&(n=Date.now());const l=d&&!1===n&&"bg"===t&&"b"===a.e;(eo(n)||l)&&(to(t)&&"string"==typeof n&&(n=new ha(n)),s[t]=n)}return s}const no="CMCD-Object",ao="CMCD-Request",oo="CMCD-Session",lo="CMCD-Status",ho=ao,co={ab:no,br:no,d:no,lab:no,lb:no,ot:no,tab:no,tb:no,tpb:no,bl:ao,cs:ao,dfa:ao,dl:ao,ltc:ao,mtp:ao,nor:ao,nrr:ao,pb:ao,sn:ao,sta:ao,su:ao,tbl:ao,cid:oo,msd:oo,sf:oo,sid:oo,st:oo,v:oo,bg:lo,bs:lo,bsa:lo,bsd:lo,bsda:lo,cdn:lo,ec:lo,nr:lo,pr:lo,pt:lo,rtp:lo};function uo(t,e){const i={};if(!t)return i;const s=Object.keys(t),r=e?(n=e,Object.keys(n).reduce((t,e)=>{var i;return null==(i=n[e])||i.forEach(i=>t[i]=e),t},{})):{};var n;for(const e of s){var a;const s=co[e]||r[e]||ho;(null!=(a=i[s])?a:i[s]={})[e]=t[e]}return i}const fo="CMCD";function go(t){return Ta(t,{whitespace:!1})}const mo=[...Xa,...Ua,...Ha,...Ba].filter((t,e,i)=>i.indexOf(t)===e),po="m",vo="a",yo="v",Eo="av",To="i",So="tt",bo="s",Ao="p",Lo="k",Io="r",Ro="a",ko="e",_o="f",Do="d",wo="query",Po="headers";function Co(t,e,i){var s;const r=new Set(null!=(s=e.enabledKeys)?s:[]);return{version:e.version||wa,reportingMode:t,filter:t=>r.has(t),baseUrl:i}}const xo=Object.is,Mo=t=>t,Oo=Array.from(Fa,([t,e])=>"br"===e?{event:t,field:e,equal:(t,e)=>void 0===t||void 0===e?t===e:function(t,e){if(t===e)return!0;if(t.length!==e.length)return!1;for(let i=0;i<t.length;i++){const s=t[i],r=e[i];if(s===r)continue;if("number"==typeof s||"number"==typeof r)return!1;if(s.value!==r.value)return!1;const n=s.params,a=r.params,o=n&&Object.keys(n)[0],l=a&&Object.keys(a)[0];if(o!==l)return!1;if(void 0!==o&&void 0!==l&&n&&a&&n[o]!==a[l])return!1}return!0}(t,e),snapshot:t=>t.slice()}:{event:t,field:e,equal:xo,snapshot:Mo}),Fo=new Map(Oo.map(t=>[t.event,t]));function No(t){const{url:e}=t,i=_(t,Sa);return fetch(e,i)}var $o=class{constructor(t,e=No){var i;this.timeOrigin=performance.timeOrigin||(null==(i=performance.timing)?void 0:i.fetchStart)||Date.now()-performance.now(),this.data={},this.msd=NaN,this.eventTargets=new Map,this.lastEmitted={},this.requestTarget={sn:0,msdSent:!1},this.config=function(t){const{version:e=wa,eventTargets:i=[],sid:s=tt(),transmissionMode:r=wo}=t;return k(k({},_(t,ba)),{},{version:e,transmissionMode:r,sid:s,eventTargets:i.reduce((t,e)=>{var i,s,r;return null!=e&&e.url&&null!=(i=e.events)&&i.length&&t.push({version:e.version||wa,enabledKeys:(null==(s=e.enabledKeys)?void 0:s.slice())||[],url:e.url,events:e.events.slice(),interval:null!=(r=e.interval)?r:30,batchSize:e.batchSize||1}),t},[])})}(t),this.data={cid:this.config.cid,sid:this.config.sid,v:this.config.version},this.requester=e;for(const t of this.config.eventTargets)this.eventTargets.set(t,{intervalId:void 0,sn:0,msdSent:!1,queue:[]})}start(){this.eventTargets.forEach((t,e)=>{if(this.disarmInterval(t),0===e.interval||!e.events.includes("t"))return;const i=()=>{this.recordTargetEvent(t,e,"t"),this.processEventTargets()};t.intervalId=setInterval(i,1e3*e.interval),i()})}stop(t=!1){t&&this.flush(),this.eventTargets.forEach(t=>{this.disarmInterval(t)})}flush(){this.processEventTargets(!0)}update(t){t.sid&&t.sid!==this.data.sid&&this.resetSession(),t.msd&&!isNaN(t.msd)&&(this.msd=t.msd),this.data=k(k(k({},this.data),t),{},{msd:void 0});for(const e of Oo)e.field in t&&!e.equal(this.data[e.field],this.lastEmitted[e.field])&&this.recordEvent(e.event)}recordEvent(t,e={}){const i=Fo.get(t);if(i){const t=i.field,s=e[t];void 0!==s&&I(this.data,{[t]:s});const r=this.data[t];if(void 0===r)return;if(i.equal(r,this.lastEmitted[t]))return;I(this.lastEmitted,{[t]:i.snapshot(r)})}this.eventTargets.forEach((i,s)=>{this.recordTargetEvent(i,s,t,e)}),this.processEventTargets()}recordTargetEvent(t,e,i,s={}){var r;if(!e.events.includes(i))return;const n=k(k(k({},this.data),s),{},{e:i,ts:null!=(r=s.ts)?r:Date.now(),sn:t.sn++});isNaN(this.msd)||t.msdSent||(n.msd=this.msd,t.msdSent=!0),t.queue.push(n)}recordResponseReceived(t,e={}){var i,s,r;const{request:n}=t,a=null!=(i=e.url)?i:null==n?void 0:n.url;if(!a)return;const o=new URL(a);o.searchParams.delete(fo);const l={url:o.toString(),rc:t.status},h=t.resourceTiming;h&&(null!=h.startTime&&(l.ts=Math.round(this.timeOrigin+h.startTime),null!=h.responseStart&&(l.ttfb=Math.round(h.responseStart-h.startTime))),null!=h.duration&&(l.ttlb=Math.round(h.duration)));const d=null!=(s=null==(r=n.customData)?void 0:r.cmcd)?s:{};this.recordEvent(Pa,k(k(k({},d),l),e))}applyRequestReport(t){var e;return null!=(e=this.createRequestReport(t))?e:t}isRequestReportingEnabled(){var t;return!(null==(t=this.config.enabledKeys)||!t.length)}createRequestReport(t,e){var i;const{customData:s={},headers:r={}}=t,n=k(k({},_(t,Aa)),{},{headers:k({},r),customData:k(k({},s),{},{cmcd:{}})});if(null==(i=this.config.enabledKeys)||!i.length||!n.url)return n;const a=new URL(n.url),o=k(k(k({},this.data),e),{},{sn:this.requestTarget.sn++}),l=Co($a,this.config,n.url);isNaN(this.msd)||this.requestTarget.msdSent||(o.msd=this.msd,this.requestTarget.msdSent=!0);const h=n.customData.cmcd=ro(o,l);switch(this.config.transmissionMode){case wo:const t=go(h);t&&(a.searchParams.set(fo,t),n.url=a.toString());break;case Po:I(n.headers,function(t,e){const i={},s=uo(t,e);for(const[t,e]of Object.entries(s)){const s=Ta(e,{whitespace:!1});s&&(i[t]=s)}return i}(h,l.customHeaderMap))}return n}processEventTargets(t=!1){let e=!1;this.eventTargets.forEach((i,s)=>{const{queue:r}=i;if(!r.length)return;if(r.length<s.batchSize&&!t)return;const n=t?r.length:s.batchSize,a=r.splice(0,n);this.sendEventReport(s,a).catch(()=>{i.queue.unshift(...a)}),e||(e=r.length>0)}),e&&this.processEventTargets()}async sendEventReport(t,e){const i=Co(Na,t),{status:s}=await this.requester({url:t.url,method:"POST",headers:{"Content-Type":"application/cmcd"},body:e.map(t=>function(t,e={}){return t?go(ro(t,e)):""}(t,i)).join("\n")+"\n"});if(410===s)this.disposeEventTarget(t);else if(429===s||s>499&&s<600)throw new Error(`Event report failed with status ${s}`)}disarmInterval(t){clearInterval(t.intervalId),t.intervalId=void 0}disposeEventTarget(t){const e=this.eventTargets.get(t);e&&(this.disarmInterval(e),this.eventTargets.delete(t))}resetSession(){this.eventTargets.forEach(t=>t.sn=0),this.requestTarget.sn=0,this.lastEmitted={}}};const Bo="h",Uo="v",Go="l",Ko="ll";new Set(Xa),new Set(mo);const Vo=["includeKeys"];function jo(t){return Object.keys(t).every(Ka)}function Ho(t,e,i,s){t&&Object.keys(e).forEach(r=>{const n=t.filter(t=>t.groupId===r).map(t=>{const n=I({},t);return n.details=void 0,n.attrs=new Yi(n.attrs),n.url=n.attrs.URI=qo(t.url,t.attrs["STABLE-RENDITION-ID"],"PER-RENDITION-URIS",i),n.groupId=n.attrs["GROUP-ID"]=e[r],n.attrs["PATHWAY-ID"]=s,n});t.push(...n)})}function qo(t,e,i,s){if(e){const{[i]:t}=s;if(t){const i=t[e];if(i)return i}}const{HOST:r,PARAMS:n}=s,a=new self.URL(t);return r&&(a.hostname=r),n&&Object.keys(n).sort().forEach(t=>{t&&De(a,t,n[t])}),a.href}class Yo{constructor(){this.status="initialized",this.requestErrors=[],this.licenseXhr=void 0,this.onmessage=void 0,this.onkeystatuseschange=void 0,this.emitter=new Ar,this.error=void 0,this.ok=void 0}get errored(){return this.error}set errored(t){this.error=t,this.emitter.eventNames().length&&this.emitter.emit("error",t)}get hasListeners(){return this.emitter.eventNames().length>0}get resolved(){return this.ok}resolve(){this.ok=!0,this.emitter.emit("resolved")}get useable(){return this.ok?Promise.resolve():this.error?Promise.reject(this.error):new Promise((t,e)=>{this.emitter.on("error",e),this.emitter.on("resolved",t)})}reset(){this.emitter.removeAllListeners();const t=this.licenseXhr;t&&(t.readyState!==XMLHttpRequest.DONE&&t.abort(),this.licenseXhr=void 0),this.onmessage=this.onkeystatuseschange=void 0}}class Wo extends Error{constructor(t,e){super(e),this.data=void 0,t.error||(t.error=new Error(e)),this.data=t,t.err=t.error}}class zo extends U{constructor(t){super("eme",t.logger),this.hls=void 0,this.config=void 0,this.media=null,this.mediaResolved=void 0,this.keyFormatPromise=null,this.keySystemAccessPromises={},this.sessionSetupByUri={},this.mediaKeySessions=[],this.activeKeys={},this.mediaKeys=null,this.setMediaKeysQueue=zo.CDMCleanupPromise?[zo.CDMCleanupPromise]:[],this.onMediaEncrypted=t=>{const{initDataType:e,initData:i}=t,s=`"${t.type}" event: init data type: "${e}"`;if(this.log(s),null!==i){if(!this.keyFormatPromise){let t=Object.keys(this.keySystemAccessPromises);t.length||(t=gs(this.config));const e=t.map(fs).filter(t=>!!t);this.keyFormatPromise=this.getKeyFormatPromise(e)}this.keyFormatPromise.then(r=>{let n;const a=cs(r),o=this.activeLevelKeys();if(a===as.FAIRPLAY&&"sinf"===e)try{const t=yt(new Uint8Array(i)),e=Gt(vt(JSON.parse(t).sinf));if(!e)throw new Error("'schm' box missing or not cbcs/cenc with schi > tenc");n=new Uint8Array(e.subarray(8,24))}catch(t){return void this.warn(`${s} Failed to parse sinf: ${t}`)}else if(a===as.PLAYREADY)n=vs(new Uint8Array(i));else if(a===as.WIDEVINE){const t=Qt(i).filter(t=>t.systemId===us);if(t.length){var l;const e=t[0];n=null!=(l=e.kids)&&l.length?e.kids[0]:null}}let h;if(n){const t=mt(n);for(let s=0;s<o.length;s++){const r=o[s];if(r.keyId&&(Zi(n,r.keyId)||-1!==r.uri.replace(/-/g,"").indexOf(t))){r.pssh||(r.scheme=e,r.pssh=new Uint8Array(i),r.keyId=n,Es.setKeyIdForUri(r.uri,n)),h=this.getSessionForKey(r,"encrypted-event-key-match");break}}}if(!h){var d,c;if(o.length)return(d=o[0]).scheme||(d.scheme=e),(c=o[0]).pssh||(c.pssh=new Uint8Array(i)),this.getSessionForKey(o[0],"encrypted-event-no-match");if(n)throw new Error(`Key ID ${mt(n)} not encountered in playlist`);this.log(`Ignoring "${t.type}" event - could not determine keyId`)}return h}).catch(t=>this.handleError(t))}},this.onWaitingForKey=t=>{this.log(`"${t.type}" event`)},this.hls=t,this.config=t.config,this.registerListeners()}destroy(){this.onDestroying(),this.onMediaDetached();const t=this.config;t.requestMediaKeySystemAccessFunc=null,t.licenseXhrSetup=t.licenseResponseCallback=void 0,t.drmSystems=t.drmSystemOptions={},this.hls=this.config=null,this.onMediaEncrypted=this.onWaitingForKey=null}registerListeners(){const{hls:t}=this;t&&(t.on(a.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(a.MEDIA_DETACHED,this.onMediaDetached,this),t.on(a.MANIFEST_LOADING,this.onManifestLoading,this),t.on(a.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(a.DESTROYING,this.onDestroying,this))}unregisterListeners(){const{hls:t}=this;t&&(t.off(a.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(a.MEDIA_DETACHED,this.onMediaDetached,this),t.off(a.MANIFEST_LOADING,this.onManifestLoading,this),t.off(a.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(a.DESTROYING,this.onDestroying,this))}attemptKeySystemAccess(t){if(!this.hls)return Promise.reject(new Error("destroyed"));const e=this.hls.levels,i=(t,e,i)=>!!t&&i.indexOf(t)===e,s=e.map(t=>t.audioCodec).filter(i),a=e.map(t=>t.videoCodec).filter(i);return s.length+a.length===0&&a.push("avc1.42e01e"),new Promise((e,i)=>{const o=t=>{const l=t.shift();this.getMediaKeysPromise(l,s,a).then(t=>e({keySystem:l,mediaKeys:t})).catch(e=>{t.length?o(t):i(e instanceof Wo?e:new Wo({type:r.KEY_SYSTEM_ERROR,details:n.KEY_SYSTEM_NO_ACCESS,error:e,fatal:!0},e.message))})};o(t)})}requestMediaKeySystemAccess(t,e){const{requestMediaKeySystemAccessFunc:i}=this.config;if("function"!=typeof i){let t=`Configured requestMediaKeySystemAccess is not a function ${i}`;return null===ms&&"http:"===self.location.protocol&&(t=`navigator.requestMediaKeySystemAccess is not available over insecure protocol ${location.protocol}`),Promise.reject(new Error(t))}return i(t,e)}getMediaKeysPromise(t,e,i){var s;const r=function(t,e,i,s){let r;switch(t){case as.FAIRPLAY:r=["cenc","sinf"];break;case as.WIDEVINE:case as.PLAYREADY:r=["cenc"];break;case as.CLEARKEY:r=["cenc","keyids"];break;default:throw new Error(`Unknown key-system: ${t}`)}return function(t,e,i,s){return[{initDataTypes:t,persistentState:s.persistentState||"optional",distinctiveIdentifier:s.distinctiveIdentifier||"optional",sessionTypes:s.sessionTypes||[s.sessionType||"temporary"],audioCapabilities:e.map(t=>({contentType:`audio/mp4; codecs=${t}`,robustness:s.audioRobustness||"",encryptionScheme:s.audioEncryptionScheme||null})),videoCapabilities:i.map(t=>({contentType:`video/mp4; codecs=${t}`,robustness:s.videoRobustness||"",encryptionScheme:s.videoEncryptionScheme||null}))}]}(r,e,i,s)}(t,e,i,this.config.drmSystemOptions||{});let n=this.keySystemAccessPromises[t],a=null==(s=n)?void 0:s.keySystemAccess;if(!a){this.log(`Requesting encrypted media "${t}" key-system access with config: ${Ue(r)}`),a=this.requestMediaKeySystemAccess(t,r);const e=n=this.keySystemAccessPromises[t]={keySystemAccess:a};return a.catch(e=>{this.log(`Failed to obtain access to key-system "${t}": ${e}`)}),a.then(i=>{this.throwIfDestroyed(),this.log(`Access for key-system "${i.keySystem}" obtained`);const s=this.fetchServerCertificate(t);this.log(`Create media-keys for "${t}"`);const r=e.mediaKeys=i.createMediaKeys().then(i=>(this.log(`Media-keys created for "${t}"`),e.hasMediaKeys=!0,s.then(e=>e?this.setMediaKeysServerCertificate(i,t,e):i)));return r.catch(e=>{this.error(`Failed to create media-keys for "${t}"}: ${e}`)}),r})}return a.then(()=>n.mediaKeys)}getMediaKeySessionContext(t,e,i,s){const{mediaKeySessions:r}=this,n=` key-session "${t}" keyId: ${mt(i.keyId||[])} keyUri: ${i.uri} for "${s}"`;for(let t=0;t<r.length;t++){const e=r[t];if(!e.initialized&&e.createdFor.levelKey.uri===i.uri)return this.log(`Reusing${n}`),e}this.log(`Creating${n}`);const a=e.createSession(),o={keySystem:t,mediaKeys:e,mediaKeysSession:a,keyRequests:{},keyStatuses:{},createdFor:{levelKey:i,reason:s},initialized:!1};return r.push(o),o}resetMediaKeys(){var t;const e=null==(t=this.mediaKeySessions[0])?void 0:t.keySystem,i=this.keySystemAccessPromises[e];i&&(this.log("reset mediaKeys"),this.mediaKeys=null,i.hasMediaKeys=!1,delete i.mediaKeys,delete this.keySystemAccessPromises[e])}updateKeySession(t,e,i){const s=t.mediaKeysSession;return this.log(`Updating key-session "${s.sessionId}" for keyId ${mt(e.keyId||[])}\n } (data length: ${i.byteLength})`),s.update(i)}getSelectedKeySystemFormats(){return Object.keys(this.keySystemAccessPromises).map(t=>({keySystem:t,hasMediaKeys:this.keySystemAccessPromises[t].hasMediaKeys})).filter(({hasMediaKeys:t})=>!!t).map(({keySystem:t})=>fs(t)).filter(t=>!!t)}getKeySystemAccess(t){return this.getKeySystemSelectionPromise(t).then(({keySystem:t,mediaKeys:e})=>this.attemptSetMediaKeys(t,e))}selectKeySystem(t){return this.getKeySystemSelectionPromise(t).then(({keySystem:t})=>{const e=fs(t);if(!e)throw new Error(`Unable to find format for key-system "${t}"`);return e})}selectKeySystemFormat(t){const e=Object.keys(t.levelkeys||{});return this.keyFormatPromise||(this.log(`Selecting key-system from fragment (sn: ${t.sn} ${t.type}: ${t.level}) key formats ${e.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(e)),this.keyFormatPromise}getKeyFormatPromise(t){const e=gs(this.config),i=t.map(cs).filter(t=>!!t&&-1!==e.indexOf(t));return this.selectKeySystem(i)}loadClear(t,e,i){if(this.config.emeEnabled&&!this.getSelectedKeySystemFormats().length){if(e.length)for(let s=0,r=e.length;s<r;s++){const n=e[s];if(t.cc<=n.cc&&(!y(t)||!y(n)||t.sn<n.sn)||!i&&s==r-1)return this.selectKeySystemFormat(n).then(t=>{if(!this.hls)return;n.setKeyFormat(t);const e=cs(t);return e?this.getKeySystemAccess([e]):void 0})}if(this.config.requireKeySystemAccessOnStart){const t=gs(this.config);if(t.length)return this.getKeySystemAccess(t)}}return null}getKeyStatus(t){const{mediaKeySessions:e}=this;for(let i=0;i<e.length;i++){const s=Xo(t,e[i]);if(s)return s}}loadKey(t){const e=t.decryptdata,i=this.getKeyStatus(e);if("internal-error"===i){const s=Qo(i,e);return s.data.frag=t,this.error(`${s.message} (${mt(e.keyId||[])})`),Promise.reject(s)}const s=t.type,r=this.activeKeys,n=r[s];n&&!e.matches(n.decryptdata)&&(r.previous||(r.previous=[]),r.previous.push(n),delete r[s]),r[s]||(r[s]=t);for(let t=this.mediaKeySessions.length;t--;){const i=this.mediaKeySessions[t];if(e.keyId&&"expired"===i.keyStatuses[mt(e.keyId)])return this.renewKeySession(e,i)}return this.updateUsablePromise(e,"playlist-key",t)}renewKeySession(t,e){return this.resetMediaKeys(),this.removeSession(e).then(()=>(this.throwIfDestroyed(),this.updateUsablePromise(t,"expired")))}updateUsablePromise(t,e,i){const s=this.getSessionForKey(t,e);return s.catch(t=>this.handleError(t,i)),s.then(e=>t)}getSessionForKey(t,e){const i=this.findContextForKey(t);if(void 0!==i)return Promise.resolve(i);const s=t.uri,r=this.sessionSetupByUri[s];let n;n=void 0===r?this.resolveSessionForKey(t,e):r.catch(()=>{}).then(()=>(this.throwIfDestroyed(),this.resolveSessionForKey(t,e))),this.sessionSetupByUri[s]=n;const a=()=>{this.sessionSetupByUri[s]===n&&delete this.sessionSetupByUri[s]};return n.then(a,a),n}findContextForKey(t){const{mediaKeySessions:e}=this;for(let i=e.length;i--;){const s=e[i];if(Xo(t,s))return s}}resolveSessionForKey(t,e){return this.getKeySystemForKeyPromise(t).then(({keySystem:i,mediaKeys:s})=>{this.throwIfDestroyed();for(let i=this.mediaKeySessions.length;i--;){const s=this.mediaKeySessions[i];if(Xo(t,s))return s;const r=this.getUsableKeyPromise(s,t,e);if(r)return r}return this.attemptSetMediaKeys(i,s).then(()=>(this.throwIfDestroyed(),this.getMediaKeySessionContext(i,s,t,e))).then(i=>{this.throwIfDestroyed();const s=t.scheme||"cenc",r=t.pssh?t.pssh.buffer:null;return this.generateRequestWithPreferredKeySession(i,t,s,r,e)})})}getUsableKeyPromise(t,e,i){const s=t.keyRequests[e.uri];if(s)return this.log(`Waiting for usable key (${i} keyId: ${function(t){if(t.keyFormat===ls)return t.uri;if(null===t.keyId)throw new Error("keyId is null");return mt(t.keyId)}(e)} format: "${e.keyFormat}" URI: ${e.uri})`),s.useable.then(()=>t)}throwIfDestroyed(t="Invalid state"){if(!this.hls)throw new Error("invalid state")}handleError(t,e){if(this.hls)if(t instanceof Wo){e&&(t.data.frag=e);const i=t.data.decryptdata;this.error(`${t.message}${i?` (${mt(i.keyId||[])})`:""}`),this.hls.trigger(a.ERROR,t.data)}else this.error(t.message),this.hls.trigger(a.ERROR,{type:r.KEY_SYSTEM_ERROR,details:n.KEY_SYSTEM_NO_KEYS,error:t,fatal:!0})}getKeySystemForKeyPromise(t){const e=cs(t.keyFormat),i=e?[e]:gs(this.config);return this.attemptKeySystemAccess(i)}getKeySystemSelectionPromise(t){if(t.length||(t=gs(this.config)),0===t.length)throw new Wo({type:r.KEY_SYSTEM_ERROR,details:n.KEY_SYSTEM_NO_CONFIGURED_LICENSE,fatal:!0},`Missing key-system license configuration options ${Ue({drmSystems:this.config.drmSystems})}`);return this.attemptKeySystemAccess(t)}activeLevelKeys(){const t=this.activeKeys,e=(t.previous||[]).map(t=>t.decryptdata);return t.audio&&e.unshift(t.audio.decryptdata),t.main&&e.unshift(t.main.decryptdata),e}attemptSetMediaKeys(t,e){if(this.mediaResolved=void 0,this.mediaKeys===e)return Promise.resolve();const i=this.setMediaKeysQueue.slice();this.log(`Setting media-keys for "${t}"`);const s=Promise.all(i).then(()=>this.media?this.media.setMediaKeys(e):new Promise((t,i)=>{this.mediaResolved=()=>{if(this.mediaResolved=void 0,!this.media)return i(new Error("Attempted to set mediaKeys without media element attached"));this.mediaKeys=e,this.media.setMediaKeys(e).then(t).catch(i)}}));return this.mediaKeys=e,this.setMediaKeysQueue.push(s),s.then(()=>{this.log(`Media-keys set for "${t}"`),i.push(s),this.setMediaKeysQueue=this.setMediaKeysQueue.filter(t=>-1===i.indexOf(t))})}filterInitData(t,e,i,s,r){var n;const a=null==(n=this.config.drmSystems)||null==(n=n[t.keySystem])?void 0:n.generateRequest;if(a)try{const n=a.call(this.hls,i,s,I({},t,{decryptdata:e,reason:r}),r);if(!n)throw new Error("Invalid response from configured generateRequest filter");e.scheme=n.initDataType?n.initDataType:"cenc";const o=n.initData?n.initData:null;return e.pssh=o?new Uint8Array(o):null,n}catch(t){var o;if(this.warn(t.message),null!=(o=this.hls)&&o.config.debug)throw t}return{initDataType:i,initData:s}}generateRequestWithPreferredKeySession(t,e,i,s,r){const n=this.getUsableKeyPromise(t,e,r);if(n)return n;const a=this.filterInitData(t,e,i,s,r);if(a&&(s=a.initData?a.initData:null,i=a.initDataType),null===s)return r.startsWith("encrypted-event")?Promise.reject(new Error(`missing initialization data for "${r}"`)):(this.log(`Skipping key-session request for "${r}" (no initData)`),Promise.resolve(t));const o=e.uri,l=new Yo;t.keyRequests[o]=l;const h=i=>{const s=t.mediaKeysSession;if(!s){const t=new Error("invalid state");return void(l.errored=t)}const{messageType:r,message:n}=i;l.status=r,this.log(`"${r}" message event for session "${s.sessionId}" message size: ${n.byteLength}`),"license-request"===r||"license-renewal"===r?this.renewLicense(t,e,n).catch(e=>{l.errored=e,l.hasListeners||this.handleError(e),this.removeSession(t)}):"license-release"===r?t.keySystem===as.FAIRPLAY&&this.updateKeySession(t,e,is("acknowledged")).then(()=>this.removeSession(t)).catch(t=>this.handleError(t)):this.warn(`unhandled media key message type "${r}"`)};l.onmessage=h,er(t.mediaKeysSession,"message",h);return this.generateRequest(t,e,i,s,r,!1)}generateRequest(t,e,i,s,a,o){if(o){const r=this.filterInitData(t,e,i,s,a);r&&(s=r.initData?r.initData:s,i=r.initDataType)}const l=e.uri,h=t.keyRequests[l],d=mt(e.keyId||[]),c=t=>{let i;t.startsWith("usable")?h.resolve():"internal-error"===t||"output-restricted"===t||"output-downscaled"===t?i=Qo(t,e):"expired"===t?i=new Error(`key expired (keyId: ${d})`):"released"===t?i=new Error("key released"):"status-pending"===t||this.warn(`unhandled key status change "${t}" (keyId: ${d})`),i&&(h.errored=i,h.hasListeners||this.handleError(i))},u=i=>{if(!t.mediaKeysSession){const t=new Error("invalid state");return void(h.errored=t)}const s=t.keyStatuses=this.getKeyStatuses(t);if(!Object.keys(s).some(t=>"status-pending"!==s[t]))return;const r=this.activeLevelKeys();for(let i=0;i<r.length;i++){const a=mt(r[i].keyId||[]);if("expired"===s[a]){var n;this.log(`Expired key ${Ue(s)} in key-session "${null==(n=t.mediaKeysSession)?void 0:n.sessionId}"`),this.renewKeySession(e,t).catch(t=>this.handleError(t));break}}let a=s[d];if(a)c(a);else{var o;const i=1e3;t.keyStatusTimeouts||(t.keyStatusTimeouts={}),(o=t.keyStatusTimeouts)[d]||(o[d]=self.setTimeout(()=>{var s;if(!t.mediaKeysSession)return;const r=this.getKeyStatus(e);var n;if(r&&"status-pending"!==r)return this.log(`No status for keyId ${d} in key-session "${null==(n=t.mediaKeysSession)?void 0:n.sessionId}". Using session key-status ${r} from other session.`),c(r);this.log(`key status for ${d} in key-session "${null==(s=t.mediaKeysSession)?void 0:s.sessionId}" timed out after ${i}ms`),a="internal-error",c(a)},i)),this.log(`No status for keyId ${d} (${Ue(s)}).`)}};h.onkeystatuseschange=u,er(t.mediaKeysSession,"keystatuseschange",u);const f=h.useable;return this.log(`Generating key-session request for "${a}" keyId: ${d} URI: ${l} (init data type: ${i} length: ${s.byteLength})`),h.status="started",t.initialized=!0,t.mediaKeysSession.generateRequest(i,s).then(()=>{var e;h.status="generated",this.log(`Request generated for key-session "${null==(e=t.mediaKeysSession)?void 0:e.sessionId}" keyId: ${d} URI: ${l}`)}).catch(t=>{throw this.log(`mediaKeysSession.generateRequest failed: ${t}`),new Wo({type:r.KEY_SYSTEM_ERROR,details:n.KEY_SYSTEM_NO_SESSION,error:t,decryptdata:e,fatal:!1},`Error generating key-session request: ${t}`)}).then(()=>f).catch(e=>{var i;this.log(`mediaKeysSession.generateRequest failed: ${e}`);const s=null==(i=e.data)?void 0:i.details;return s!==n.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED&&s!==n.KEY_SYSTEM_STATUS_INTERNAL_ERROR||!Object.keys(t.keyStatuses).some(e=>"usable"===t.keyStatuses[e])?this.removeSession(t).then(()=>{throw e}):(this.handleError(e),t)}).then(()=>t)}getKeyStatuses(t){const e={},i=t.mediaKeysSession.sessionId;return t.mediaKeysSession.keyStatuses.forEach((s,r)=>{if("string"==typeof r&&"object"==typeof s){const t=r;r=s,s=t}const n="buffer"in r?new Uint8Array(r.buffer,r.byteOffset,r.byteLength):new Uint8Array(r);if(t.keySystem===as.PLAYREADY&&16===n.length){const t=mt(n);e[t]=s,ss(n)}const a=mt(n);this.log(`key status change "${s}" for keyStatuses keyId: ${a} key-session "${i}"`),e[a]=s}),e}fetchServerCertificate(t){const e=this.config,i=new(0,e.loader)(e),s=function(t,e){const{drmSystems:i}=e,s=null==i?void 0:i[t];if(s)return s.serverCertificateUrl}(t,e);return s?(this.log(`Fetching server certificate for "${t}"`),new Promise((a,o)=>{const l={type:u.SERVER_CERTIFICATE,responseType:"arraybuffer",url:s},h=e.certLoadPolicy.default,d={loadPolicy:h,timeout:h.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},c={onSuccess:(t,e,i,s)=>{a(t.data)},onError:(e,i,a,h)=>{o(new Wo({type:r.KEY_SYSTEM_ERROR,details:n.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:a,response:k({url:l.url,data:void 0},e)},`"${t}" certificate request failed (${s}). Status: ${e.code} (${e.text})`))},onTimeout:(e,i,a)=>{o(new Wo({type:r.KEY_SYSTEM_ERROR,details:n.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:a,response:{url:l.url,data:void 0}},`"${t}" certificate request timed out (${s})`))},onAbort:(t,e,i)=>{o(new Error("aborted"))}};i.load(l,d,c)})):(this.log(`No Server Certificate in config.drmSystems["${t}"]`),Promise.resolve())}setMediaKeysServerCertificate(t,e,i){return new Promise((s,a)=>{t.setServerCertificate(i).then(r=>{this.log(`setServerCertificate ${r?"success":"not supported by CDM"} (${i.byteLength}) on "${e}"`),s(t)}).catch(t=>{a(new Wo({type:r.KEY_SYSTEM_ERROR,details:n.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED,error:t,fatal:!0},t.message))})})}renewLicense(t,e,i){return this.requestLicense(t,e,new Uint8Array(i)).then(i=>this.updateKeySession(t,e,new Uint8Array(i)).catch(t=>{throw new Wo({type:r.KEY_SYSTEM_ERROR,details:n.KEY_SYSTEM_SESSION_UPDATE_FAILED,decryptdata:e,error:t,fatal:!1},t.message)}))}unpackPlayReadyKeyMessage(t,e){const i=yt(new Uint16Array(e.buffer));if(!i.includes("PlayReadyKeyMessage"))return t.setRequestHeader("Content-Type","text/xml; charset=utf-8"),e;const s=(new DOMParser).parseFromString(i,"application/xml"),r=s.querySelectorAll("HttpHeader");if(r.length>0){let e;for(let i=0,s=r.length;i<s;i++){var n,a;e=r[i];const s=null==(n=e.querySelector("name"))?void 0:n.textContent,o=null==(a=e.querySelector("value"))?void 0:a.textContent;s&&o&&t.setRequestHeader(s,o)}}const o=s.querySelector("Challenge"),l=null==o?void 0:o.textContent;if(!l)throw new Error("Cannot find <Challenge> in key message");return is(atob(l))}setupLicenseXHR(t,e,i,s,r){const n=this.config.licenseXhrSetup;return n?Promise.resolve().then(()=>(this.throwIfDestroyed(),n.call(this.hls,t,e,k(k({},i),{},{decryptdata:s}),r))).catch(a=>{if(!i.mediaKeysSession)throw a;return t.open("POST",e,!0),n.call(this.hls,t,e,k(k({},i),{},{decryptdata:s}),r)}).then(i=>{t.readyState||t.open("POST",e,!0);return{xhr:t,licenseChallenge:i||r}}):(t.open("POST",e,!0),Promise.resolve({xhr:t,licenseChallenge:r}))}requestLicense(t,e,i){return new Promise((s,a)=>{const o=function(t,e){const{drmSystems:i,widevineLicenseUrl:s}=e,r=null==i?void 0:i[t];if(r)return r.licenseUrl;if(t===as.WIDEVINE&&s)return s}(t.keySystem,this.config);if(!o)return a(new Error(`no license server URL configured for key-system "${t.keySystem}"`));const l=t.keyRequests[e.uri];if(!l)return a(new Error("License emitter removed"));this.log(`Sending license request to URL: ${o}`);const h=this.config.keyLoadPolicy.default,d=new XMLHttpRequest;d.responseType="arraybuffer",d.onreadystatechange=()=>{if(!this.hls||!t.mediaKeysSession)return a(new Error("invalid state"));if(4===d.readyState)if(200===d.status){l.requestErrors=[];let i=d.response;this.log(`License received ${i instanceof ArrayBuffer?i.byteLength:i}`);const r=this.config.licenseResponseCallback;if(r)try{i=r.call(this.hls,d,o,k(k({},t),{},{decryptdata:e}))}catch(t){this.error(t)}s(i)}else{const c=h.errorRetry,u=c?c.maxNumRetry:0;if(l.requestErrors.push({status:d.status,message:d.statusText}),l.requestErrors.length>u||d.status>=400&&d.status<500)a(new Wo({type:r.KEY_SYSTEM_ERROR,details:n.KEY_SYSTEM_LICENSE_REQUEST_FAILED,decryptdata:e,fatal:!0,networkDetails:d,response:{url:o,data:void 0,code:d.status,text:d.statusText}},`License Request XHR failed (${o}). Status: ${d.status} (${d.statusText})`));else{const r=u-l.requestErrors.length;this.warn(`Retrying license request, ${r} attempts left`),this.requestLicense(t,e,i).then(s,a)}}},l.licenseXhr&&l.licenseXhr.readyState!==XMLHttpRequest.DONE&&l.licenseXhr.abort(),l.licenseXhr=d,this.setupLicenseXHR(d,o,t,e,i).then(({xhr:e,licenseChallenge:i})=>{t.keySystem==as.PLAYREADY&&(i=this.unpackPlayReadyKeyMessage(e,i)),e.send(i)}).catch(a)})}onDestroying(){this.unregisterListeners(),this._clear()}onMediaAttached(t,e){if(!this.config.emeEnabled)return;const i=e.media;this.media=i,er(i,"encrypted",this.onMediaEncrypted),er(i,"waitingforkey",this.onWaitingForKey);const s=this.mediaResolved;s?s():this.mediaKeys=i.mediaKeys}onMediaDetached(){const t=this.media;t&&(ir(t,"encrypted",this.onMediaEncrypted),ir(t,"waitingforkey",this.onWaitingForKey),this.media=null,this.mediaKeys=null)}_clear(){var t;this.keyFormatPromise=null,this.keySystemAccessPromises={},this.activeKeys={},this.sessionSetupByUri={};const e=this.mediaResolved;if(e&&e(),!this.mediaKeys&&!this.mediaKeySessions.length)return;const i=this.media,s=this.mediaKeySessions.slice();this.mediaKeySessions=[],this.mediaKeys=null,Es.clearKeyUriToKeyIdMap();const o=s.length;zo.CDMCleanupPromise=Promise.all(s.map(t=>this.removeSession(t)).concat((null==i||null==(t=i.setMediaKeys(null))?void 0:t.catch(t=>{this.log(`Could not clear media keys: ${t}`),this.hls&&this.hls.trigger(a.ERROR,{type:r.OTHER_ERROR,details:n.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR,fatal:!1,error:new Error(`Could not clear media keys: ${t}`)})}))||Promise.resolve())).catch(t=>{this.log(`Could not close sessions and clear media keys: ${t}`),this.hls&&this.hls.trigger(a.ERROR,{type:r.OTHER_ERROR,details:n.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error(`Could not close sessions and clear media keys: ${t}`)})}).then(()=>{o&&this.log("finished closing key sessions and clearing media keys")})}onManifestLoading(){this._clear(),this.keyFormatPromise=null}onManifestLoaded(t,{sessionKeys:e}){if(e&&this.config.emeEnabled&&!this.keyFormatPromise){const t=e.reduce((t,e)=>(-1===t.indexOf(e.keyFormat)&&t.push(e.keyFormat),t),[]);this.log(`Selecting key-system from session-keys ${t.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(t),this.keyFormatPromise.catch(()=>{})}}removeSession(t){const{mediaKeysSession:e}=t;if(e){this.log(`Remove licenses and keys and close session "${e.sessionId}"`),Object.keys(t.keyRequests).forEach(i=>{const s=t.keyRequests[i];s.onmessage&&e.removeEventListener("message",s.onmessage),s.onkeystatuseschange&&e.removeEventListener("keystatuseschange",s.onkeystatuseschange),s.reset(),t.keyRequests[i]=void 0}),t.mediaKeysSession=void 0;const i=this.mediaKeySessions.indexOf(t);i>-1&&this.mediaKeySessions.splice(i,1);const{keyStatusTimeouts:s}=t;s&&Object.keys(s).forEach(t=>self.clearTimeout(s[t]));const{drmSystemOptions:o}=this.config,l=function(t){var e;return!(!t||"persistent-license"!==t.sessionType&&(null==(e=t.sessionTypes)||!e.some(t=>"persistent-license"===t)))}(o)?new Promise((t,i)=>{self.setTimeout(()=>i(new Error("MediaKeySession.remove() timeout")),8e3),e.remove().then(t).catch(i)}):Promise.resolve();return l.catch(t=>{this.log(`Could not remove session: ${t}`),this.hls&&this.hls.trigger(a.ERROR,{type:r.OTHER_ERROR,details:n.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR,fatal:!1,error:new Error(`Could not remove session: ${t}`)})}).then(()=>e.close()).then(()=>e.closed).catch(t=>{this.log(`Could not close session: ${t}`),this.hls&&this.hls.trigger(a.ERROR,{type:r.OTHER_ERROR,details:n.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error(`Could not close session: ${t}`)})})}return Promise.resolve()}}function Xo(t,e){const i=t.keyId,s=e.mediaKeysSession;if(i&&s){const t=e.mediaKeysSession.keyStatuses;if(t.size)return t.has(i)?t.get(i):e.keyStatuses[mt(i)]}}function Qo(t,e){const i="output-restricted"===t,s=i?n.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:n.KEY_SYSTEM_STATUS_INTERNAL_ERROR;return new Wo({type:r.KEY_SYSTEM_ERROR,details:s,fatal:!1,decryptdata:e},i?"HDCP level output restricted":`key status changed to "${t}"`)}zo.CDMCleanupPromise=void 0;var Zo=function(){if(null!=ns&&ns.VTTCue)return self.VTTCue;const t=["","lr","rl"],e=["start","middle","end","left","right"];function i(t,e){if("string"!=typeof e)return!1;if(!Array.isArray(t))return!1;const i=e.toLowerCase();return!!~t.indexOf(i)&&i}function s(t){return i(e,t)}function r(t,...e){let i=1;for(;i<arguments.length;i++){const e=arguments[i];for(const i in e)t[i]=e[i]}return t}function n(e,n,a){const o=this,l={enumerable:!0};o.hasBeenReset=!1;let h="",d=!1,c=e,u=n,f=a,g=null,m="",p=!0,v="auto",y="start",E=50,T="middle",S=50,b="middle";Object.defineProperty(o,"id",r({},l,{get:function(){return h},set:function(t){h=""+t}})),Object.defineProperty(o,"pauseOnExit",r({},l,{get:function(){return d},set:function(t){d=!!t}})),Object.defineProperty(o,"startTime",r({},l,{get:function(){return c},set:function(t){if("number"!=typeof t)throw new TypeError("Start time must be set to a number.");c=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"endTime",r({},l,{get:function(){return u},set:function(t){if("number"!=typeof t)throw new TypeError("End time must be set to a number.");u=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"text",r({},l,{get:function(){return f},set:function(t){f=""+t,this.hasBeenReset=!0}})),Object.defineProperty(o,"region",r({},l,{get:function(){return g},set:function(t){g=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"vertical",r({},l,{get:function(){return m},set:function(e){const s=function(e){return i(t,e)}(e);if(!1===s)throw new SyntaxError("An invalid or illegal string was specified.");m=s,this.hasBeenReset=!0}})),Object.defineProperty(o,"snapToLines",r({},l,{get:function(){return p},set:function(t){p=!!t,this.hasBeenReset=!0}})),Object.defineProperty(o,"line",r({},l,{get:function(){return v},set:function(t){if("number"!=typeof t&&"auto"!==t)throw new SyntaxError("An invalid number or illegal string was specified.");v=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"lineAlign",r({},l,{get:function(){return y},set:function(t){const e=s(t);if(!e)throw new SyntaxError("An invalid or illegal string was specified.");y=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"position",r({},l,{get:function(){return E},set:function(t){if(t<0||t>100)throw new Error("Position must be between 0 and 100.");E=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"positionAlign",r({},l,{get:function(){return T},set:function(t){const e=s(t);if(!e)throw new SyntaxError("An invalid or illegal string was specified.");T=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"size",r({},l,{get:function(){return S},set:function(t){if(t<0||t>100)throw new Error("Size must be between 0 and 100.");S=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"align",r({},l,{get:function(){return b},set:function(t){const e=s(t);if(!e)throw new SyntaxError("An invalid or illegal string was specified.");b=e,this.hasBeenReset=!0}})),o.displayState=void 0}return n.prototype.getCueAsHTML=function(){return self.WebVTT.convertCueToDOMTree(self,this.text)},n}();class Jo{decode(t,e){if(!t)return"";if("string"!=typeof t)throw new Error("Error - expected string data.");return decodeURIComponent(encodeURIComponent(t))}}function tl(t){function e(t,e,i,s){return 3600*(0|t)+60*(0|e)+(0|i)+parseFloat(s||0)}const i=t.match(/^(?:(\d+):)?(\d{2}):(\d{2})(\.\d+)?/);return i?parseFloat(i[2])>59?e(i[2],i[3],0,i[4]):e(i[1],i[2],i[3],i[4]):null}class el{constructor(){this.values=Object.create(null)}set(t,e){this.get(t)||""===e||(this.values[t]=e)}get(t,e,i){return i?this.has(t)?this.values[t]:e[i]:this.has(t)?this.values[t]:e}has(t){return t in this.values}alt(t,e,i){for(let s=0;s<i.length;++s)if(e===i[s]){this.set(t,e);break}}integer(t,e){/^-?\d+$/.test(e)&&this.set(t,parseInt(e,10))}percent(t,e){if(/^([\d]{1,3})(\.[\d]*)?%$/.test(e)){const i=parseFloat(e);if(i>=0&&i<=100)return this.set(t,i),!0}return!1}}function il(t,e,i,s){const r=s?t.split(s):[t];for(const t in r){if("string"!=typeof r[t])continue;const s=r[t].split(i);if(2!==s.length)continue;e(s[0],s[1])}}const sl=new Zo(0,0,""),rl="middle"===sl.align?"middle":"center";function nl(t,e,i){const s=t;function r(){const e=tl(t);if(null===e)throw new Error("Malformed timestamp: "+s);return t=t.replace(/^[^\sa-zA-Z-]+/,""),e}function n(){t=t.replace(/^\s+/,"")}if(n(),e.startTime=r(),n(),"--\x3e"!==t.slice(0,3))throw new Error("Malformed time stamp (time stamps must be separated by '--\x3e'): "+s);t=t.slice(3),n(),e.endTime=r(),n(),function(t,e){const s=new el;il(t,function(t,e){let r;switch(t){case"region":for(let r=i.length-1;r>=0;r--)if(i[r].id===e){s.set(t,i[r].region);break}break;case"vertical":s.alt(t,e,["rl","lr"]);break;case"line":r=e.split(","),s.integer(t,r[0]),s.percent(t,r[0])&&s.set("snapToLines",!1),s.alt(t,r[0],["auto"]),2===r.length&&s.alt("lineAlign",r[1],["start",rl,"end"]);break;case"position":r=e.split(","),s.percent(t,r[0]),2===r.length&&s.alt("positionAlign",r[1],["start",rl,"end","line-left","line-right","auto"]);break;case"size":s.percent(t,e);break;case"align":s.alt(t,e,["start",rl,"end","left","right"])}},/:/,/\s/),e.region=s.get("region",null),e.vertical=s.get("vertical","");let r=s.get("line","auto");"auto"===r&&-1===sl.line&&(r=-1),e.line=r,e.lineAlign=s.get("lineAlign","start"),e.snapToLines=s.get("snapToLines",!0),e.size=s.get("size",100),e.align=s.get("align",rl);let n=s.get("position","auto");"auto"===n&&50===sl.position&&(n="start"===e.align||"left"===e.align?0:"end"===e.align||"right"===e.align?100:50),e.position=n}(t,e)}function al(t){return t.replace(/<br(?: \/)?>/gi,"\n")}class ol{constructor(){this.state="INITIAL",this.buffer="",this.decoder=new Jo,this.regionList=[],this.cue=null,this.oncue=void 0,this.onparsingerror=void 0,this.onflush=void 0}parse(t){const e=this;function i(){let t=e.buffer,i=0;for(t=al(t);i<t.length&&"\r"!==t[i]&&"\n"!==t[i];)++i;const s=t.slice(0,i);return"\r"===t[i]&&++i,"\n"===t[i]&&++i,e.buffer=t.slice(i),s}function s(t){il(t,function(t,e){},/:/)}t&&(e.buffer+=e.decoder.decode(t,{stream:!0}));try{let t="";if("INITIAL"===e.state){if(!/\r\n|\n/.test(e.buffer))return this;t=i();const s=t.match(/^()?WEBVTT([ \t].*)?$/);if(null==s||!s[0])throw new Error("Malformed WebVTT signature.");e.state="HEADER"}let r=!1;for(;e.buffer;){if(!/\r\n|\n/.test(e.buffer))return this;switch(r?r=!1:t=i(),e.state){case"HEADER":/:/.test(t)?s(t):t||(e.state="ID");continue;case"NOTE":t||(e.state="ID");continue;case"ID":if(/^NOTE($|[ \t])/.test(t)){e.state="NOTE";break}if(!t)continue;if(e.cue=new Zo(0,0,""),e.state="CUE",-1===t.indexOf("--\x3e")){e.cue.id=t;continue}case"CUE":if(!e.cue){e.state="BADCUE";continue}try{nl(t,e.cue,e.regionList)}catch(t){e.cue=null,e.state="BADCUE";continue}e.state="CUETEXT";continue;case"CUETEXT":{const i=-1!==t.indexOf("--\x3e");if(!t||i&&(r=!0)){e.oncue&&e.cue&&e.oncue(e.cue),e.cue=null,e.state="ID";continue}if(null===e.cue)continue;e.cue.text&&(e.cue.text+="\n"),e.cue.text+=t}continue;case"BADCUE":t||(e.state="ID")}}}catch(t){"CUETEXT"===e.state&&e.cue&&e.oncue&&e.oncue(e.cue),e.cue=null,e.state="INITIAL"===e.state?"BADWEBVTT":"BADCUE"}return this}flush(){const t=this;try{if((t.cue||"HEADER"===t.state)&&(t.buffer+="\n\n",t.parse()),"INITIAL"===t.state||"BADWEBVTT"===t.state)throw new Error("Malformed WebVTT signature.")}catch(e){t.onparsingerror&&t.onparsingerror(e)}return t.onflush&&t.onflush(),this}}function ll(t){let e=5381,i=t.length;for(;i;)e=33*e^t.charCodeAt(--i);return(e>>>0).toString()}const hl=/\r\n|\n\r|\n|\r/g,dl="Missing initPTS for VTT ";function cl(t,e,i){return ll(t.toString())+ll(e.toString())+ll(i)}function ul(t,i,s,r,n,a,o){const l=new ol,h=ot(new Uint8Array(t)).trim().replace(hl,"\n").split("\n"),d=[],c=i?function(t,e=1){return In(t,9e4,1/e)}(i.baseTime,i.timescale):0;let u,f="00:00.000",g=0,m=0,p=!1,v=!0;l.oncue=function(t){const e=s[r];let a=s.ccOffset;const o=(g-c)/9e4;if(p){if(null!=e&&e.new&&(a=s.ccOffset=e.start),o){if(!i)return void(u=new Error(dl+"MPEGTS"));a=o-s.presentationOffset}}else{if(!i)return void(u=new Error(dl+"without X-TIMESTAMP-MAP"));a=-i.baseTime/i.timescale}const l=t.endTime-t.startTime,h=Pn(9e4*(t.startTime+a-m),9e4*n)/9e4;t.startTime=Math.max(h,0),t.endTime=Math.max(h+l,0);const f=t.text.trim();t.text=decodeURIComponent(encodeURIComponent(f)),t.id?r&&(t.id=`hlsjscc${r}_${t.id}`):t.id=cl(t.startTime,t.endTime,f),t.endTime>0&&d.push(t)},l.onparsingerror=function(t){u=t},l.onflush=function(){u?o(u):a(d)},h.forEach(t=>{if(v){if(t.startsWith("X-TIMESTAMP-MAP=")){v=!1,p=!0,t.slice(16).split(",").forEach(t=>{t.startsWith("LOCAL:")?f=t.slice(6):t.startsWith("MPEGTS:")&&(g=parseInt(t.slice(7)))});try{m=function(t){let i=parseInt(t.slice(-3));const s=parseInt(t.slice(-6,-4)),r=parseInt(t.slice(-9,-7)),n=t.length>9?parseInt(t.substring(0,t.indexOf(":"))):0;if(!(e(i)&&e(s)&&e(r)&&e(n)))throw Error(`Malformed X-TIMESTAMP-MAP: Local:${t}`);return i+=1e3*s,i+=6e4*r,i+=36e5*n,i}(f)/1e3}catch(t){u=t}return}""===t&&(v=!1)}l.parse(t+"\n")}),l.flush()}const fl="stpp.ttml.im1t",gl=/^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/,ml=/^(\d*(?:\.\d*)?)(h|m|s|ms|f|t)$/,pl={left:"start",center:"center",right:"end",start:"start",end:"end"};function vl(t,e,i,s){const r=Pt(new Uint8Array(t),["mdat"]);if(0===r.length)return void s(new Error("Could not parse IMSC1 mdat"));const n=r.map(t=>ot(t)),a=function(t,e,i=1,s=!1){return In(t,e,1/i,s)}(e.baseTime,1,e.timescale);try{n.forEach(t=>i(function(t,e){const i=(new DOMParser).parseFromString(t,"text/xml"),s=i.getElementsByTagName("tt")[0];if(!s)throw new Error("Invalid ttml");const r={frameRate:30,subFrameRate:1,frameRateMultiplier:0,tickRate:1},n=Object.keys(r).reduce((t,e)=>(t[e]=s.getAttribute(`ttp:${e}`)||r[e],t),{});!s.getAttribute("ttp:tickRate")&&s.getAttribute("ttp:frameRate")&&(n.tickRate=Number(n.frameRate)*Number(n.subFrameRate));const a="preserve"!==s.getAttribute("xml:space"),o=El(yl(s,"styling","style")),l=El(yl(s,"layout","region")),h=yl(s,"body","[begin]");return[].map.call(h,t=>{const i=Tl(t,a);if(!i||!t.hasAttribute("begin"))return null;const s=Al(t.getAttribute("begin"),n),r=Al(t.getAttribute("dur"),n);let h=Al(t.getAttribute("end"),n);if(null===s)throw bl(t);if(null===h){if(null===r)throw bl(t);h=s+r}const d=new Zo(s-e,h-e,i);d.id=cl(d.startTime,d.endTime,d.text);const c=function(t,e,i){const s="http://www.w3.org/ns/ttml#styling";let r=null;const n=["displayAlign","textAlign","color","backgroundColor","fontSize","fontFamily"],a=null!=t&&t.hasAttribute("style")?t.getAttribute("style"):null;a&&i.hasOwnProperty(a)&&(r=i[a]);return n.reduce((i,n)=>{const a=Sl(e,s,n)||Sl(t,s,n)||Sl(r,s,n);return a&&(i[n]=a),i},{})}(l[t.getAttribute("region")],o[t.getAttribute("style")],o),{textAlign:u}=c;if(u){const t=pl[u];t&&(d.lineAlign=t),d.align=u}return I(d,c),d}).filter(t=>null!==t)}(t,a)))}catch(t){s(t)}}function yl(t,e,i){const s=t.getElementsByTagName(e)[0];return s?[].slice.call(s.querySelectorAll(i)):[]}function El(t){return t.reduce((t,e)=>{const i=e.getAttribute("xml:id");return i&&(t[i]=e),t},{})}function Tl(t,e){return[].slice.call(t.childNodes).reduce((t,i,s)=>{var r;return"br"===i.nodeName&&s?t+"\n":null!=(r=i.childNodes)&&r.length?Tl(i,e):e?t+i.textContent.trim().replace(/\s+/g," "):t+i.textContent},"")}function Sl(t,e,i){return t&&t.hasAttributeNS(e,i)?t.getAttributeNS(e,i):null}function bl(t){return new Error(`Could not parse ttml timestamp ${t}`)}function Al(t,e){if(!t)return null;let i=tl(t);return null===i&&(gl.test(t)?i=function(t,e){const i=gl.exec(t),s=(0|i[4])+(0|i[5])/e.subFrameRate;return 3600*(0|i[1])+60*(0|i[2])+(0|i[3])+s/e.frameRate}(t,e):ml.test(t)&&(i=function(t,e){const i=ml.exec(t),s=Number(i[1]);switch(i[2]){case"h":return 3600*s;case"m":return 60*s;case"ms":return s/1e3;case"f":return s/e.frameRate;case"t":return s/e.tickRate}return s}(t,e))),i}function Ll(t,e,i,s="",r="disabled"){const n=t.ownerDocument.createElement("track");return n.kind=e,n.label=i,s&&(n.srclang=s),n.src="data:,WEBVTT",n.track.mode=r,t.appendChild(n),n}function Il(t){return t.forced&&(te.indexOf("Apple")>-1||/iPhone|iPad|iPod/.test(Jt))?"forced":t.characteristics&&/transcribes-spoken-dialog/gi.test(t.characteristics)&&/describes-music-and-sound/gi.test(t.characteristics)?"captions":"subtitles"}function Rl(t,e){const i=t.mode;if("disabled"===i&&(t.mode="hidden"),t.cues&&!t.cues.getCueById(e.id))try{if(t.addCue(e),!t.cues.getCueById(e.id))throw new Error(`addCue is failed for: ${e}`)}catch(i){q.debug(`[texttrack-utils]: ${i}`);try{const i=new self.TextTrackCue(e.startTime,e.endTime,e.text);i.id=e.id,t.addCue(i)}catch(t){q.debug(`[texttrack-utils]: Legacy TextTrackCue fallback failed: ${t}`)}}"disabled"===i&&(t.mode=i)}function kl(t,e,i,s){const r=t.mode;if("disabled"===r&&(t.mode="hidden"),t.cues&&t.cues.length>0){const r=function(t,e,i){const s=[],r=function(t,e){if(e<=t[0].startTime)return 0;const i=t.length-1;if(e>t[i].endTime)return-1;let s,r=0,n=i;for(;r<=n;)if(s=Math.floor((n+r)/2),e<t[s].startTime)n=s-1;else{if(!(e>t[s].startTime&&r<i))return s;r=s+1}return t[r].startTime-e<e-t[n].startTime?r:n}(t,e);if(r>-1)for(let n=r,a=t.length;n<a;n++){const r=t[n];if(r.startTime>=e&&r.endTime<=i)s.push(r);else if(r.startTime>i)return s}return s}(t.cues,e,i);for(let e=0;e<r.length;e++)s&&!s(r[e])||t.removeCue(r[e])}"disabled"===r&&(t.mode=r)}function _l(t,e){const i=Dl(t.main);if(i&&i.start<=e)return i;const s=Dl(t.audio);return s&&s.start<=e?s:null}function Dl(t){if(!t)return null;switch(t.state){case nr:case rr:case ur:case fr:return null}return t.frag}function wl(t,e){return e.getAppendedFrag(t,f.MAIN)||e.getPartialFragment(t)}function Pl(t,e,i,s){const r=s.latestLevelDetails,n=wl(e,i);if(yr(s.config)&&!t.nextStart&&r&&n&&s.interstitialsManager){const i="type"in n?n:n.fragment,a=ii(r,i.sn);(null==a?void 0:a.level)===i.level&&vr(a,s.interstitialsManager.playerQueue,e)&&(t.nextStart=a.start)}}function Cl(){if("undefined"!=typeof self)return self.VTTCue||self.TextTrackCue}function xl(t,e,i,s,r){let n=new t(e,i,"");try{n.value=s,r&&(n.type=r)}catch(a){n=new t(e,i,Ue(r?k({type:r},s):s))}return n}const Ml=(()=>{const t=Cl();try{t&&new t(0,Number.POSITIVE_INFINITY,"")}catch(t){return Number.MAX_VALUE}return Number.POSITIVE_INFINITY})();function Ol(){return self.SourceBuffer||self.WebKitSourceBuffer}function Fl(){if(!Y())return!1;const t=Ol();return!t||t.prototype&&"function"==typeof t.prototype.appendBuffer&&"function"==typeof t.prototype.remove}var Nl=0,$l=1,Bl=2;class Ul extends pr{constructor(t,i,s){super(t,i,s,"stream-controller",f.MAIN),this.audioCodecSwap=!1,this.level=-1,this._forceStartLoad=!1,this._hasEnoughToStart=!1,this.altAudio=Nl,this.audioOnly=!1,this._couldBacktrack=!1,this._backtrackFragment=void 0,this.audioCodecSwitch=!1,this.videoBuffer=null,this.onMediaPlaying=()=>{this.tick()},this.onMediaSeeked=()=>{const t=this.media,i=t?t.currentTime:null;if(null===i||!e(i))return;if(this.log(`Media seeked to ${i}`),!this.getBufferedFrag(i))return;const s=this.getFwdBufferInfoAtPos(t,i,f.MAIN,0);s&&0!==s.len?this.tick():this.log(`Main buffer empty at ${i} on "seeked" event: ${s?s.len:s}`)},this.registerListeners()}registerListeners(){super.registerListeners();const{hls:t}=this;t.on(a.MANIFEST_PARSED,this.onManifestParsed,this),t.on(a.LEVEL_LOADING,this.onLevelLoading,this),t.on(a.LEVEL_LOADED,this.onLevelLoaded,this),t.on(a.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),t.on(a.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.on(a.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),t.on(a.BUFFER_CREATED,this.onBufferCreated,this),t.on(a.BUFFER_FLUSHED,this.onBufferFlushed,this),t.on(a.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(a.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){super.unregisterListeners();const{hls:t}=this;t.off(a.MANIFEST_PARSED,this.onManifestParsed,this),t.off(a.LEVEL_LOADED,this.onLevelLoaded,this),t.off(a.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),t.off(a.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.off(a.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),t.off(a.BUFFER_CREATED,this.onBufferCreated,this),t.off(a.BUFFER_FLUSHED,this.onBufferFlushed,this),t.off(a.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(a.FRAG_BUFFERED,this.onFragBuffered,this)}onHandlerDestroying(){this.onMediaPlaying=this.onMediaSeeked=null,this.unregisterListeners(),super.onHandlerDestroying()}startLoad(t,e){if(this.levels){const{lastCurrentTime:i,hls:s}=this;if(this.stopLoad(),this.setInterval(100),this.level=-1,!this.startFragRequested){let t=s.startLevel;-1===t&&(s.config.testBandwidth&&this.levels.length>1?(t=0,this.bitrateTest=!0):t=s.firstAutoLevel),s.nextLoadLevel=t,this.level=s.loadLevel,this._hasEnoughToStart=!!e}i>0&&-1===t&&!e&&this.initPTS.length&&(this.log(`Override startPosition with lastCurrentTime @${i}`),t=i),this.state=nr,this.nextLoadPosition=this.lastCurrentTime=t+this.timelineOffset,this.startPosition=e?-1:t,e||this.fragmentTracker.hasFragments(this.playlistType)||(this._hasEnoughToStart=this.startFragRequested=!1),this.tick()}else this._forceStartLoad=!0,this.state=rr}stopLoad(){this._forceStartLoad=!1,super.stopLoad()}doTick(){switch(this.state){case mr:{const{levels:t,level:e}=this,i=null==t?void 0:t[e],s=null==i?void 0:i.details;if(s&&(!s.live||this.levelLastLoaded===i&&!this.waitForLive(i))){if(this.waitForCdnTuneIn(s))break;this.state=nr;break}if(this.hls.nextLoadLevel!==this.level){this.state=nr;break}break}case lr:this.checkRetryDate()}this.state===nr&&this.doTickIdle(),this.onTickEnd()}onTickEnd(){var t;super.onTickEnd(),null!=(t=this.media)&&t.readyState&&!1===this.media.seeking&&(this.lastCurrentTime=this.media.currentTime),this.checkFragmentChanged()}doTickIdle(){const{hls:t,levelLastLoaded:e,levels:i,media:s}=this;if(null===e||!s&&!this.primaryPrefetch&&(this.startFragRequested||!t.config.startFragPrefetch))return;if(this.altAudio&&this.audioOnly)return;const r=this.buffering?t.nextLoadLevel:t.loadLevel;if(null==i||!i[r])return;const n=i[r],o=this.getMainFwdBufferInfo();if(null===o)return;const l=this.getLevelDetails();if(l&&this._streamEnded(o,l)){const t={type:this.targetBufferType()};return this.hls.trigger(a.BUFFER_EOS,t),void(this.state=ur)}if(!this.buffering)return;t.loadLevel!==r&&-1===t.manualLevel&&this.log(`Adapting to level ${r} from level ${this.level}`),this.level=t.nextLoadLevel=r;const h=n.details;if(!h||this.state===mr||this.waitForLive(n))return this.level=r,this.state=mr,void(this.startFragRequested=!1);const d=o.len,c=this.getMaxBufferLength(n.maxBitrate);if(d>=c)return;this.backtrackFragment&&this.backtrackFragment.start>o.end&&(this.backtrackFragment=void 0);const u=this.backtrackFragment?this.backtrackFragment.start:o.end;let p=this.getNextFragment(u,h);if(this.couldBacktrack&&!this.fragPrevious&&p&&y(p)&&this.fragmentTracker.getState(p)!==Ei){var v;const t=(null!=(v=this.backtrackFragment)?v:p).sn-h.startSN,e=h.fragments[t-1];e&&p.cc===e.cc&&(p=e,this.fragmentTracker.removeFragment(e))}else this.backtrackFragment&&o.len&&(this.backtrackFragment=void 0);if(p&&this.isLoopLoading(p,u)){if(!p.gap){const t=this.audioOnly&&!this.altAudio?g:m,e=(t===m?this.videoBuffer:this.mediaBuffer)||this.media;e&&this.afterBufferFlushed(e,t)}p=this.getNextFragmentLoopLoading(p,h,o,f.MAIN,c)}p&&(this.exceedsMaxBuffer(o,c,p)||this.loadFragment(p,n,u))}loadFragment(t,e,i){const s=this.fragmentTracker.getState(t);s===pi||s===yi?this.bitrateTest?(this.log(`Fragment ${t.sn} of level ${t.level} is being downloaded to test bitrate and will not be buffered`),this._loadBitrateTestFrag(t,e)):super.loadFragment(t,e,i):this.clearTrackerIfNeeded(t)}immediateLevelSwitch(){if(this.abortCurrentFrag(),this.flushMainBuffer(0,Number.POSITIVE_INFINITY),this.altAudio!==Nl){var t;((null==(t=this.getLevelDetails())?void 0:t.fragmentStart)||0)>this.lastCurrentTime&&super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio")}}getBufferOutput(){return this.mediaBuffer&&this.altAudio===Bl?this.mediaBuffer:this.media}checkFragmentChanged(){const t=this.fragPlaying;if(!this.checkFragPlaying())return!1;const e=this.fragPlaying;if(e){const i=e.level;this.hls.trigger(a.FRAG_CHANGED,{frag:e,previousFrag:t}),(null==t?void 0:t.level)!==i&&this.hls.trigger(a.LEVEL_SWITCHED,{level:i})}return!0}get backtrackFragment(){return this._backtrackFragment}set backtrackFragment(t){this._backtrackFragment=t}get couldBacktrack(){return this._couldBacktrack}set couldBacktrack(t){this._couldBacktrack=t}abortCurrentFrag(){this.backtrackFragment=void 0,super.abortCurrentFrag()}flushMainBuffer(t,e){super.flushMainBuffer(t,e,this.targetBufferType())}targetBufferType(){return this.altAudio!==Bl||this.audioOnly?null:"video"}onMediaAttached(t,e){super.onMediaAttached(t,e);const i=e.media;er(i,"playing",this.onMediaPlaying),er(i,"seeked",this.onMediaSeeked)}onMediaDetaching(t,e){const{media:i}=this;i&&(ir(i,"playing",this.onMediaPlaying),ir(i,"seeked",this.onMediaSeeked)),this.videoBuffer=null,super.onMediaDetaching(t,e);!!e.transferMedia||(this._hasEnoughToStart=!1)}onManifestLoading(){super.onManifestLoading(),this.log("Trigger BUFFER_RESET"),this.hls.trigger(a.BUFFER_RESET,void 0),this.couldBacktrack=!1,this.backtrackFragment=void 0,this.altAudio=Nl,this.audioOnly=!1}onManifestParsed(t,e){let i=!1,s=!1;for(let t=0;t<e.levels.length;t++){const r=e.levels[t].audioCodec;r&&(i=i||-1!==r.indexOf("mp4a.40.2"),s=s||-1!==r.indexOf("mp4a.40.5"))}this.audioCodecSwitch=i&&s&&!function(){var t;const e=Ol();return"function"==typeof(null==e||null==(t=e.prototype)?void 0:t.changeType)}(),this.audioCodecSwitch&&this.log("Both AAC/HE-AAC audio found in levels; declaring level codec as HE-AAC"),this.levels=e.levels,this.startFragRequested=!1}onLevelLoading(t,e){const{levels:i}=this;if(!i||this.state!==nr)return;const s=e.levelInfo;(!s.details||s.details.live&&(this.levelLastLoaded!==s||s.details.expired)||this.waitForCdnTuneIn(s.details))&&(this.state=mr)}onLevelLoaded(t,e){var i;const{levels:s,startFragRequested:r}=this,n=e.level,o=e.details,l=o.totalduration;if(!s)return void this.warn(`Levels were reset while loading level ${n}`);this.log(`Level ${n} loaded [${o.startSN},${o.endSN}]${o.lastPartSn?`[part-${o.lastPartSn}-${o.lastPartIndex}]`:""}, cc [${o.startCC}, ${o.endCC}] duration:${l}`);const h=e.levelInfo,d=this.fragCurrent;!d||this.state!==or&&this.state!==lr||d.level!==e.level&&d.loader&&this.abortCurrentFrag();let c=0;if(o.live||null!=(i=h.details)&&i.live){var u;if(this.checkLiveUpdate(o),o.deltaUpdateFailed)return;c=this.alignPlaylists(o,h.details,null==(u=this.levelLastLoaded)?void 0:u.details)}if(h.details=o,this.levelLastLoaded=h,r||this.setStartPosition(o,c),this.hls.trigger(a.LEVEL_UPDATED,{details:o,level:n}),this.state===mr){if(this.waitForCdnTuneIn(o))return;this.state=nr}r&&o.live&&this.synchronizeToLiveEdge(o),this.initPTS.some((t,e)=>{if(e>=o.startCC)return!0;delete this.initPTS[e]}),this.tick()}synchronizeToLiveEdge(t){const{config:e,media:i}=this;if(!i)return;const s=this.hls.liveSyncPosition,r=this.playhead,n=t.fragmentStart,a=t.edge,o=r>=n-e.maxFragLookUpTolerance&&r<=a;if(null!==s&&i.duration>s&&(r<s||!o)){const n=void 0!==e.liveMaxLatencyDuration?e.liveMaxLatencyDuration:e.liveMaxLatencyDurationCount*t.targetduration;if((!o&&i.readyState<4||r<a-n)&&(this._hasEnoughToStart||(this.nextLoadPosition=s),i.readyState))if(this.warn(`Playback: ${r} is located too far from the end of live sliding playlist: ${a}, reset currentTime to : ${s}`),"buffered"===this.config.liveSyncMode){var l;const t=Bi.bufferInfo(i,s,0);if(null==(l=t.buffered)||!l.length)return void(i.currentTime=s);if(t.start<=r)return void(i.currentTime=s);const{nextStart:e}=Bi.bufferedInfo(t.buffered,r,0);e&&(i.currentTime=e)}else i.currentTime=s}}_handleFragmentLoadProgress(t){var e;const i=t.frag,{part:s,payload:r}=t,{levels:n}=this;if(!n)return void this.warn(`Levels were reset while fragment load was in progress. Fragment ${i.sn} of level ${i.level} will not be buffered`);const a=n[i.level];if(!a)return void this.warn(`Level ${i.level} not found on progress`);const o=a.details;if(!o)return this.warn(`Dropping fragment ${i.sn} of level ${i.level} after level details were reset`),void this.fragmentTracker.removeFragment(i);const l=a.videoCodec,h=o.PTSKnown||!o.live,d=null==(e=i.initSegment)?void 0:e.data,c=this._getAudioCodec(a),u=this.transmuxer=this.transmuxer||new jn(this.hls,f.MAIN,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)),g=s?s.index:-1,m=-1!==g,{decryptRange:p,byteRange:v}=xi(i,s,this.iframesOnly),y=new Ni(i.level,i.sn,i.stats.chunkCount,v?v.end-v.start:r.byteLength,g,m,i.duration,this.iframesOnly,p),E=this.initPTS[i.cc];u.push(r,d,c,l,i,s,o.totalduration,h,y,E)}onAudioTrackSwitching(t,e){const i=this.hls,s=this.altAudio!==Nl;if(We(e.url,i))this.altAudio=$l;else{if(this.mediaBuffer!==this.media){this.log("Switching on main audio, use media.buffered to schedule main fragment loading"),this.mediaBuffer=this.media;const t=this.fragCurrent;t&&(this.log("Switching to main audio track, cancel main fragment load"),t.abortRequests(),this.fragmentTracker.removeFragment(t)),this.resetTransmuxer(),this.resetLoadingState()}else this.audioOnly&&this.resetTransmuxer();if(s)return this.altAudio=Nl,this.fragmentTracker.removeAllFragments(),i.once(a.BUFFER_FLUSHED,()=>{this.hls&&this.hls.trigger(a.AUDIO_TRACK_SWITCHED,e)}),void i.trigger(a.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:null});i.trigger(a.AUDIO_TRACK_SWITCHED,e)}}onAudioTrackSwitched(t,e){const i=We(e.url,this.hls);if(i){const t=this.videoBuffer;t&&this.mediaBuffer!==t&&(this.log("Switching on alternate audio, use video.buffered to schedule main fragment loading"),this.mediaBuffer=t)}this.altAudio=i?Bl:Nl,this.tick()}onBufferCreated(t,e){const i=e.tracks;let s,r,n=!1;for(const t in i){const e=i[t];if("main"===e.id){if(r=t,s=e,"video"===t){const e=i[t];e&&(this.videoBuffer=e.buffer)}}else n=!0}n&&s?(this.log(`Alternate track found, use ${r}.buffered to schedule main fragment loading`),this.mediaBuffer=s.buffer):this.mediaBuffer=this.media}onFragBuffered(t,e){const{frag:i,part:s}=e,r=i.type===f.MAIN;if(r){if(this.fragContextChanged(i))return this.warn(`Fragment ${i.sn}${s?" p: "+s.index:""} of level ${i.level} finished buffering, but was aborted. state: ${this.state}`),void(this.state===cr&&(this.state=nr));let t=!1;if(y(i)&&(t=!!i.gap&&!i.tagList.some(t=>"GAP"===t[0])),this.fragBufferedComplete(i,s),t){var n;i.stats.retry++;const t=null==(n=this.levels)?void 0:n[i.level];t&&t.fragmentError++}}const a=this.media;a&&(!this._hasEnoughToStart&&Bi.getBuffered(a).length&&(this._hasEnoughToStart=!0,this.seekToStartPos()),r&&this.tick())}get hasEnoughToStart(){return this._hasEnoughToStart}onError(t,e){var i;if(e.fatal)this.state=fr;else switch(e.details){case n.FRAG_GAP:case n.FRAG_PARSING_ERROR:case n.FRAG_DECRYPT_ERROR:case n.FRAG_LOAD_ERROR:case n.FRAG_LOAD_TIMEOUT:case n.KEY_LOAD_ERROR:case n.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(f.MAIN,e);break;case n.LEVEL_LOAD_ERROR:case n.LEVEL_LOAD_TIMEOUT:case n.LEVEL_PARSING_ERROR:e.levelRetry||this.state!==mr||(null==(i=e.context)?void 0:i.type)!==u.LEVEL||(this.state=nr);break;case n.BUFFER_APPEND_NO_PROGRESS:if("main"!==e.parent)return;e.frag&&(e.appendsWithoutProgress||0)>=this.config.appendErrorMaxRetry&&(this.warn(`Marking fragment ${e.frag.sn} of level ${e.frag.level} as a gap after ${e.appendsWithoutProgress} appends without buffered range growth, to prevent loop loading`),this.fragmentTracker.addAsGap(e.frag));break;case n.BUFFER_ADD_CODEC_ERROR:case n.BUFFER_APPEND_ERROR:if("main"!==e.parent)return;this.reduceLengthAndFlushBuffer(e)&&this.resetLoadingState();break;case n.BUFFER_FULL_ERROR:if("main"!==e.parent)return;if(this.reduceLengthAndFlushBuffer(e)){!this.config.interstitialsController&&this.config.assetPlayerId?this._hasEnoughToStart=!0:this.flushMainBuffer(0,Number.POSITIVE_INFINITY)}break;case n.INTERNAL_EXCEPTION:this.recoverWorkerError(e)}}onFragLoadEmergencyAborted(){this.state=nr,this._hasEnoughToStart||(this.startFragRequested=!1,this.nextLoadPosition=this.lastCurrentTime),this.tickImmediate()}onBufferFlushed(t,{type:e}){if(e!==g||!this.altAudio){const t=(e===m?this.videoBuffer:this.mediaBuffer)||this.media;t&&(this.afterBufferFlushed(t,e),this.tick())}}onLevelsUpdated(t,e){this.level>-1&&this.fragCurrent&&(this.level=this.fragCurrent.level,-1===this.level&&this.resetWhenMissingContext(this.fragCurrent)),this.levels=e.levels}swapAudioCodec(){this.audioCodecSwap=!this.audioCodecSwap}seekToStartPos(){const{media:t}=this;if(!t)return;const e=t.currentTime;let i=this.startPosition;if(i>=0&&e<i){if(t.seeking)return void this.log(`could not seek to ${i}, already seeking at ${e}`);const s=this.timelineOffset;s&&i&&(i+=s);const r=this.getLevelDetails(),n=Bi.getBuffered(t),a=n.length?n.start(0):0,o=a-i,l=Math.max(this.config.maxBufferHole,this.config.maxFragLookUpTolerance);(this.config.startOnSegmentBoundary||o>0&&(o<l||this.loadingParts&&o<2*((null==r?void 0:r.partTarget)||0)))&&(this.log(`adjusting start position by ${o} to match buffer start`),i+=o,this.startPosition=i),e<i&&(this.log(`seek to target start position ${i} from current time ${e} buffer start ${a}`),t.currentTime=i)}}_getAudioCodec(t){let e=this.config.defaultAudioCodec||t.audioCodec;return this.audioCodecSwap&&e&&(this.log("Swapping audio codec"),e=-1!==e.indexOf("mp4a.40.5")?"mp4a.40.2":"mp4a.40.5"),e}_loadBitrateTestFrag(t,e){t.bitrateTest=!0,this._doFragLoad(t,e).then(t=>{const{hls:i}=this,s=null==t?void 0:t.frag;if(!s||this.fragContextChanged(s))return;e.fragmentError=0,this.state=nr,this.startFragRequested=!1,this.bitrateTest=!1;const r=s.stats;r.parsing.start=r.parsing.end=r.buffering.start=r.buffering.end=self.performance.now(),i.trigger(a.FRAG_LOADED,t),s.bitrateTest=!1}).catch(e=>{this.state!==rr&&this.state!==fr&&(this.warn(e),this.resetFragmentLoading(t))})}_handleTransmuxComplete(t){const i=this.playlistType,{hls:s}=this,{remuxResult:r,chunkMeta:n}=t,o=this.getCurrentContext(n);if(!o)return void this.resetWhenMissingContext(n);const{frag:l,part:h,level:d}=o,{video:c,text:u,id3:f,initSegment:m}=r,{details:p}=d,v=this.altAudio?void 0:r.audio;if(this.fragContextChanged(l))this.fragmentTracker.removeFragment(l);else{if(this.state=dr,m){const t=m.tracks;if(t){const e=l.initSegment||l;if(this.unhandledEncryptionError(m,l))return;this._bufferInitSegment(d,t,e,n),s.trigger(a.FRAG_PARSING_INIT_SEGMENT,{frag:e,id:i,tracks:t})}const r=m.initPTS,o=m.timescale,h=this.initPTS[l.cc];if(e(r)&&(!h||h.baseTime!==r||h.timescale!==o)){const t=m.trackId;this.initPTS[l.cc]={baseTime:r,timescale:o,trackId:t};const e=this.initPTS.slice(0);s.trigger(a.INIT_PTS_FOUND,{timestampOffsets:e,frag:l,id:i,initPTS:r,timescale:o,trackId:t})}}if(c&&p){v&&"audiovideo"===c.type&&this.logMuxedErr(l);const t=p.fragments[l.sn-1-p.startSN],e=l.sn===p.startSN,i=!t||l.cc>t.cc;if(!1!==r.independent){const{startPTS:t,endPTS:s,startDTS:r,endDTS:a}=c;if(h)h.elementaryStreams[c.type]={startPTS:t,endPTS:s,startDTS:r,endDTS:a};else if(c.firstKeyFrame&&c.independent&&1===n.id&&!i&&(this.couldBacktrack=!0),c.dropped&&c.independent){const r=this.getMainFwdBufferInfo(),n=(r?r.end:this.getLoadPosition())+this.config.maxBufferHole,o=c.firstKeyFramePTS?c.firstKeyFramePTS:t;if(!e&&n<o-this.config.maxBufferHole&&!i)return void this.backtrack(l);i&&(l.gap=!0),l.setElementaryStreamInfo(c.type,l.start,s,l.start,a,!0)}else e&&t-(p.appliedTimelineOffset||0)>2&&(l.gap=!0);l.setElementaryStreamInfo(c.type,t,s,r,a),this.backtrackFragment&&(this.backtrackFragment=l),this.bufferFragmentData(c,l,h,n,e||i)}else{if(!e&&!i)return void this.backtrack(l);l.gap=!0}}if(v){const{startPTS:t,endPTS:e,startDTS:i,endDTS:s}=v;h&&(h.elementaryStreams[g]={startPTS:t,endPTS:e,startDTS:i,endDTS:s}),l.setElementaryStreamInfo(g,t,e,i,s),this.bufferFragmentData(v,l,h,n)}if(p&&null!=f&&f.samples.length){const t={id:i,frag:l,details:p,samples:f.samples};s.trigger(a.FRAG_PARSING_METADATA,t)}if(p&&u){const t={id:i,frag:l,details:p,samples:u.samples};s.trigger(a.FRAG_PARSING_USERDATA,t)}}}logMuxedErr(t){this.warn(`${y(t)?"Media":"Init"} segment with muxed audiovideo where only video expected: ${t.url}`)}_bufferInitSegment(t,e,i,s){if(this.state!==dr)return;this.audioOnly=!!e.audio&&!e.video,this.altAudio&&!this.audioOnly&&(delete e.audio,e.audiovideo&&this.logMuxedErr(i));const{audio:r,video:n,audiovideo:o}=e;if(r){const i=t.audioCodec;let s=ve(r.codec,i);if("mp4a"===s&&(s="mp4a.40.5"),this.audioCodecSwitch){s&&(s=-1!==s.indexOf("mp4a.40.5")?"mp4a.40.2":"mp4a.40.5");const t=r.metadata;t&&"channelCount"in t&&1!==(t.channelCount||1)&&!function(){if(void 0===ie){const t=Jt.match(/Firefox\/(\d+)/i);ie=t?parseInt(t[1]):0}return ie}()&&(s="mp4a.40.5")}s&&-1!==s.indexOf("mp4a.40.5")&&/Android/.test(Jt)&&"audio/mpeg"!==r.container&&(s="mp4a.40.2",this.log(`Android: force audio codec to ${s}`)),i&&i!==s&&this.log(`Swapping manifest audio codec "${i}" for "${s}"`),r.levelCodec=s,r.id=f.MAIN,this.log(`Init audio buffer, container:${r.container}, codecs[selected/level/parsed]=[${s||""}/${i||""}/${r.codec}]`),delete e.audiovideo}if(n){n.levelCodec=t.videoCodec,n.id=f.MAIN;const i=n.codec;if(4===(null==i?void 0:i.length))switch(i){case"hvc1":case"hev1":n.codec="hvc1.1.6.L120.90";break;case"av01":n.codec="av01.0.04M.08";break;case"avc1":n.codec="avc1.42e01e"}this.log(`Init video buffer, container:${n.container}, codecs[level/parsed]=[${t.videoCodec||""}/${i}]${n.codec!==i?" parsed-corrected="+n.codec:""}${n.supplemental?" supplemental="+n.supplemental:""}`),delete e.audiovideo}o&&(this.iframesOnly&&this.logMuxedErr(i),this.log(`Init audiovideo buffer, container:${o.container}, codecs[level/parsed]=[${t.codecs}/${o.codec}]`),delete e.video,delete e.audio);const l=Object.keys(e);if(l.length){if(this.hls.trigger(a.BUFFER_CODECS,e),!this.hls)return;l.forEach(t=>{const r=e[t].initSegment;null!=r&&r.byteLength&&this.hls.trigger(a.BUFFER_APPENDING,{type:t,data:r,frag:i,part:null,chunkMeta:s,parent:i.type})})}this.tickImmediate()}getMainFwdBufferInfo(){const t=this.getBufferOutput();return this.getFwdBufferInfo(t,f.MAIN)}get maxBufferLength(){const{levels:t,level:e}=this,i=null==t?void 0:t[e];return i?this.getMaxBufferLength(i.maxBitrate):this.config.maxBufferLength}backtrack(t){this.couldBacktrack=!0,this.backtrackFragment=t,this.resetTransmuxer(),this.flushBufferGap(t),this.fragmentTracker.removeFragment(t),this.fragPrevious=null,this.nextLoadPosition=t.start,this.state=nr}get nextLevel(){const t=this.nextBufferedFrag;return t?t.level:-1}get currentFrag(){var t;if(this.fragPlaying)return this.fragPlaying;const i=(null==(t=this.media)?void 0:t.currentTime)||this.lastCurrentTime;return e(i)?this.getAppendedFrag(i):null}get currentProgramDateTime(){var t;const i=(null==(t=this.media)?void 0:t.currentTime)||this.lastCurrentTime;if(e(i)){const t=this.getLevelDetails(),e=this.currentFrag||(t?Ze(null,t.fragments,i):null);if(e){const t=e.programDateTime;if(null!==t){const s=t+1e3*(i-e.start);return new Date(s)}}}return null}get currentLevel(){const t=this.currentFrag;return t?t.level:-1}get nextBufferedFrag(){const t=this.currentFrag;return t?this.followingBufferedFrag(t):null}get forceStartLoad(){return this._forceStartLoad}}class Gl extends Ul{constructor(...t){super(...t),this.currentOp=void 0,this.nextOp=void 0,this.cached=[],this.cachedSize=0,this.cacheFragmentData=!0,this.initDetails=void 0,this.onBufferedToEnd=()=>{const t=this.media;null!=t&&t.seeking&&(t.currentTime=t.currentTime)},this.onMediaSeeking=()=>{}}setInitPts(t){this.initPTS=t.slice()}loadMediaAt(t,e){if(!this.hls)return;const{seekOnAppend:i}=e,s=t+this.timelineOffset;switch(this.nextLoadPosition=this.lastCurrentTime=s,this.startPosition=t,this.state){case rr:case ur:case fr:this.state=nr}this.state===nr?(this.hls.resumeBuffering(),this.tick(),this.currentOp=[s,e]):this.nextOp=[s,e],this.hls.off(a.BUFFERED_TO_END,this.onBufferedToEnd);const r=this.media;if(i&&r){this.seekTo(s)&&(this.currentOp=[s,e],this.nextOp=void 0,this.flushPipeline(s,!0))}}seekTo(t){const e=this.media;if(e){var i;const s=null==(i=this.getLevelDetails())?void 0:i.edge,r=void 0!==s?s:e.duration;t>=r&&(t=r-.01);if(Bi.bufferInfo(e,t,0).len>0&&this.getBufferedAt(t))return e.currentTime=t,!0}return!1}getBufferedAt(t){return this.fragmentTracker.getBufferedFrag(t,f.MAIN)}cacheSet(t,e){if(!this.hls)return;t.data=e;const i=this.cached;i.push(t),this.cachedSize+=e.buffer.byteLength;const s=this.hls.config.iframeCacheLimit;for(;this.cachedSize>s&&i.length>1;){const t=i.shift();if(!t.data){this.cached=i.filter(t=>!!t.data),this.cachedSize=i.reduce((t,{data:e})=>e?e.buffer.byteLength:0,0);break}this.cachedSize-=t.data.byteLength,t.data=void 0}}onHandlerDestroying(){this.cached.length=0,this.cachedSize=0,super.onHandlerDestroying()}_handleFragmentLoadProgress(t){const e=t.frag,{part:i,payload:s}=t;this.cacheFragmentData&&!i&&null!=s&&s.byteLength&&!e.data&&y(e)&&this.cacheSet(e,new Uint8Array(s.slice(0))),super._handleFragmentLoadProgress(t)}loadFragment(t,e,i){const s=this.fragmentTracker.getState(t);s!==pi&&s!==yi||!this.canReplayCached(t)?super.loadFragment(t,e,i):this.replayCachedFragment(t)}canReplayCached(t){var e;if(!this.cacheFragmentData||null==(e=t.data)||!e.byteLength)return!1;const i=t.decryptdata;return"identity"!==(null==i?void 0:i.keyFormat)||!!i.key}replayCachedFragment(t){const e=t.data.slice().buffer;this.log(`Buffering cached ${t.type} sn: ${t.sn} of level ${t.level} (${e.byteLength} bytes)`),this.fragCurrent=t,this.startFragRequested=!0;const i=t.stats=new c;i.loading.start=i.loading.first=i.loading.end=self.performance.now(),i.loaded=i.total=e.byteLength,i.chunkCount=1,this.state=or;const s={frag:t,part:null,payload:e,networkDetails:null};this._handleFragmentLoadProgress(s),this.hls.trigger(a.FRAG_LOADED,s),this._handleFragmentLoadComplete(s)}fragBufferedComplete(t,e){super.fragBufferedComplete(t,e);const{currentOp:i,nextOp:s}=this;this.currentOp=this.nextOp=void 0,this.state=rr,null!=i&&i[1].seekOnAppend&&(this.flushPipeline(i[0],!s),this.seekTo(i[0])||this.log(`Could not seek to ${i[0]} after fragment buffered (superseded or flushed) buffer: ${this.media?sr(Bi.getBuffered(this.media)):"none"}`)),s&&this.loadMediaAt.apply(this,s)}flushPipeline(t,e){if(e){const e=this.media;if(e){const i=Bi.bufferInfo(e,t,0),s=i.len?i.nextStart:0;s&&(this.fragmentTracker.removeFragmentsInRange(s,1/0,f.MAIN),this.flushMainBuffer(s,1/0))}this.hls.once(a.BUFFERED_TO_END,this.onBufferedToEnd)}this.hls.trigger(a.BUFFER_EOS,{type:"video"})}get playhead(){return this.nextLoadPosition}startLoad(){if(!this.startFragRequested){const t=this.hls;t.nextLoadLevel=-1===t.startLevel?0:t.firstAutoLevel}}seekToStartPos(){}setStartPosition(){}alignPlaylists(t,e,i){const s=this.initDetails;return this.initDetails=null,super.alignPlaylists(t,e,i||s||void 0)}getMainFwdBufferInfo(){const t=this.playhead,e=this.getBufferedAt(t);if(e){const i=e.duration;return{len:i,start:t,end:t+i,bufferedIndex:-1}}return{len:0,start:t,end:t,bufferedIndex:-1}}_streamEnded(){const t=this.playhead,e=this.fragmentTracker.getBufferedFrag(t,f.MAIN);return!(null==e||!e.endList)}}class Kl extends Gl{constructor(...t){super(...t),this._img=void 0,this.queued=void 0,this.cacheFragmentData=!1}get image(){return this._img}set image(t){var e;const i=null==(e=this._img)?void 0:e.src;i&&self.URL.revokeObjectURL(i),this._img=t}loadMediaAt(t){if(!this.hls)return;const e=t+this.timelineOffset;switch(this.nextLoadPosition=this.lastCurrentTime=e,this.startPosition=t,this.state){case rr:case ur:case fr:this.state=nr}if(this.state===nr){if(this.hls.resumeBuffering(),this.media||(this.media={}),this.tick(),this.state===nr){const e=this.getBufferedAt(t);e&&(this.fragCurrent=e,this.updateImage(e,null))}}else{const i=this.fragCurrent;(!i||t>=i.start&&t<i.end)&&(this.queued=[e])}}updateImage(t,e,i){const s=t.data;s||this.fragmentTracker.removeFragment(t);const r=this._img;if(r&&s){const n=self.performance.now();(e?e.stats:t.stats).buffering.start=t.stats.buffering.start=n,r.onload=()=>{if(!this.hls)return;const s=this.hls.levels[t.level];null!=s&&s.fragmentError&&(s.fragmentError=0,t.stats.retry=0);const r=self.performance.now(),n=e?e.stats:t.stats;n.buffering.end=t.stats.buffering.end=r,this.hls.trigger(a.FRAG_BUFFERED,{frag:t,part:e,stats:n,id:t.type,chunkMeta:i})},r.onerror=()=>{this.handleError("Image decode error",t,e,i)};const o=r.src;o&&self.URL.revokeObjectURL(o);const l=new Blob([s],{type:"image/jpeg"});r.src=self.URL.createObjectURL(l)}else this.state=rr,this.processQueued()}processQueued(){const t=this.queued;this.queued=void 0,t&&this.loadMediaAt.apply(this,t)}handleError(t,e,i,s){if(!this.hls)return;const o=new Error(t);this.hls.trigger(a.ERROR,{type:r.MEDIA_ERROR,details:n.FRAG_PARSING_ERROR,chunkMeta:s,frag:e,part:i,fatal:!1,error:o,err:o})}_bufferInitSegment(){}bufferFragmentData(t,e,i,s){super.bufferFragmentData(t,e,i,s,!0);const r=Pt(new Uint8Array(t.data1),["mdat"]);if(0===r.length)return void this.handleError("Could not find I-Frame mdat",e,i,s);const n=e;this.cacheSet(n,r[0]),this.updateImage(n,i,s)}fragBufferedComplete(t,e){this.fragmentTracker.fragBuffered(t,!0),super.fragBufferedComplete(t,e),this.processQueued()}checkFragPlaying(){var t;const e=null==(t=this.fragPrevious)?void 0:t.start;if(void 0!==e){const t=this.getAppendedFrag(e);if(t&&!E(t,this.fragPlaying))return this.fragPlaying=t,!0}return!1}getMainFwdBufferInfo(){return{len:0,start:this.playhead,end:this.playhead,bufferedIndex:-1}}}const Vl="Image I-Frame player does not accept HTMLMediaElements",jl={seekOnAppend:!0};let Hl,ql;const Yl=.025;let Wl=function(t){return t[t.Point=0]="Point",t[t.Range=1]="Range",t}({});function zl(t,e,i){return`${t.identifier}-${i+1}-${ll(e)}`}class Xl{constructor(t,e){this.base=void 0,this._duration=null,this._timelineStart=null,this.appendInPlaceDisabled=void 0,this.appendInPlaceStarted=void 0,this.dateRange=void 0,this.hasPlayed=!1,this.cumulativeDuration=0,this.resumeOffset=NaN,this.playoutLimit=NaN,this.restrictions={skip:!1,jump:!1},this.snapOptions={out:!1,in:!1},this.assetList=[],this.assetListLoader=void 0,this.assetListResponse=null,this.resumeAnchor=void 0,this.error=void 0,this.resetOnResume=void 0,this.base=e,this.dateRange=t,this.setDateRange(t)}setDateRange(t){this.dateRange=t,this.resumeOffset=t.attr.optionalFloat("X-RESUME-OFFSET",this.resumeOffset),this.playoutLimit=t.attr.optionalFloat("X-PLAYOUT-LIMIT",this.playoutLimit),this.restrictions=t.attr.enumeratedStringList("X-RESTRICT",this.restrictions),this.snapOptions=t.attr.enumeratedStringList("X-SNAP",this.snapOptions)}reset(){var t;this.appendInPlaceStarted=!1,null==(t=this.assetListLoader)||t.destroy(),this.assetListLoader=void 0,this.supplementsPrimary||(this.assetListResponse=null,this.assetList=[],this._duration=null)}isAssetPastPlayoutLimit(t){var e;if(t>0&&t>=this.assetList.length)return!0;const i=this.playoutLimit;if(t<=0||isNaN(i))return!1;if(0===i)return!0;return((null==(e=this.assetList[t])?void 0:e.startOffset)||0)>i}findAssetIndex(t){return this.assetList.indexOf(t)}get identifier(){return this.dateRange.id}get startDate(){return this.dateRange.startDate}get startTime(){const t=this.dateRange.startTime;if(this.snapOptions.out){const e=this.dateRange.tagAnchor;if(e)return Zl(e,t)?Ql(t,e):t}return t}get startOffset(){return this.cue.pre?0:this.startTime}get startIsAligned(){if(0===this.startTime||this.snapOptions.out)return!0;const t=this.dateRange.tagAnchor;if(t){const e=this.dateRange.startTime;return e-Ql(e,t)<.1}return!1}get resumptionOffset(){const t=this.resumeOffset,i=e(t)?t:this.duration;return this.cumulativeDuration+i}get resumeTime(){const t=this.startOffset+this.resumptionOffset;if(this.snapOptions.in){const e=this.resumeAnchor;if(e)return Zl(e,t)?Ql(t,e):t}return t}get appendInPlace(){return!!this.appendInPlaceStarted||!this.appendInPlaceDisabled&&!(this.cue.once||this.cue.pre||!this.startIsAligned||!(isNaN(this.playoutLimit)&&isNaN(this.resumeOffset)||this.resumeOffset&&this.duration&&Math.abs(this.resumeOffset-this.duration)<Yl))}set appendInPlace(t){this.appendInPlaceStarted?this.resetOnResume=!t:this.appendInPlaceDisabled=!t}get timelineStart(){return null!==this._timelineStart?this._timelineStart:this.startTime}set timelineStart(t){this._timelineStart=t}get duration(){const t=this.playoutLimit;let e;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(t){this._duration=t}get cue(){return this.dateRange.cue}get timelineOccupancy(){return"RANGE"===this.dateRange.attr["X-TIMELINE-OCCUPIES"]?Wl.Range:Wl.Point}get supplementsPrimary(){return"PRIMARY"===this.dateRange.attr["X-TIMELINE-STYLE"]}get contentMayVary(){return"NO"!==this.dateRange.attr["X-CONTENT-MAY-VARY"]}get assetUrl(){return this.dateRange.attr["X-ASSET-URI"]}get assetListUrl(){return this.dateRange.attr["X-ASSET-LIST"]}get baseUrl(){return this.base.url}get assetListLoaded(){return this.assetList.length>0||null!==this.assetListResponse}toString(){return`["${(t=this).identifier}" ${t.cue.pre?"<pre>":t.cue.post?"<post>":""}${t.timelineStart.toFixed(2)}-${t.resumeTime.toFixed(2)}]`;var t}}function Ql(t,e){return t-e.start<e.duration/2&&!(Math.abs(t-(e.start+e.duration))<Yl)?e.start:e.start+e.duration}function Zl(t,e){return e>t.start-Yl&&e<t.start+t.duration+Yl}function Jl(t,e,i){const s=new self.URL(t,i);return"data:"!==s.protocol&&De(s,"_HLS_primary_id",e),s}function th(t,e){for(;null!=(i=t.assetList[++e])&&i.error;)var i;return e}function eh(t){const e=t.timelineStart,i=t.duration||0;return`["${t.identifier}" ${e.toFixed(2)}-${(e+i).toFixed(2)}]`}class ih{constructor(t,e,i,s){this.hls=void 0,this.interstitial=void 0,this.assetItem=void 0,this.tracks=null,this.hasDetails=!1,this.mediaAttached=null,this._currentTime=void 0,this._bufferedEosTime=void 0,this.checkPlayout=()=>{this.reachedPlayout(this.currentTime)&&this.hls&&this.hls.trigger(a.PLAYOUT_LIMIT_REACHED,{})};const r=this.hls=new t(e);this.interstitial=i,this.assetItem=s;const n=()=>{this.hasDetails=!0};r.once(a.LEVEL_LOADED,n),r.once(a.AUDIO_TRACK_LOADED,n),r.once(a.SUBTITLE_TRACK_LOADED,n),r.on(a.MEDIA_ATTACHING,(t,{media:e})=>{this.removeMediaListeners(),this.mediaAttached=e;this.interstitial.playoutLimit&&(e.addEventListener("timeupdate",this.checkPlayout),this.appendInPlace&&r.on(a.BUFFER_APPENDED,()=>{const t=this.bufferedEnd;this.reachedPlayout(t)&&(this._bufferedEosTime=t,r.trigger(a.BUFFERED_TO_END,void 0))}))})}get appendInPlace(){return this.interstitial.appendInPlace}loadSource(){const t=this.hls;if(t)if(t.url)t.levels.length&&!t.started&&t.startLoad(-1,!0);else{let e=this.assetItem.uri;try{e=Jl(e,t.config.primarySessionId||"").href}catch(t){}t.loadSource(e)}}bufferedInPlaceToEnd(t,e){var i;if(!this.appendInPlace)return!1;if(null!=(i=this.hls)&&i.bufferedToEnd)return!0;if(!t)return!1;const s=Math.min(this._bufferedEosTime||1/0,this.duration),r=this.timelineOffset+(e||0),n=Bi.bufferInfo(t,r,.02);return this.getAssetTime(n.end)>=s-.02}reachedPlayout(t){const e=this.interstitial.playoutLimit;return this.startOffset+t>=e}get destroyed(){var t;return!(null!=(t=this.hls)&&t.userConfig)}get assetId(){return this.assetItem.identifier}get interstitialId(){return this.assetItem.parentIdentifier}get media(){var t;return(null==(t=this.hls)?void 0:t.media)||null}get bufferedEnd(){const t=this.media||this.mediaAttached;if(!t)return this._bufferedEosTime?this._bufferedEosTime:this.currentTime;const e=Bi.bufferInfo(t,t.currentTime,.001);return this.getAssetTime(e.end)}get currentTime(){const t=this.media||this.mediaAttached;return t?this.getAssetTime(t.currentTime):this._currentTime||0}get duration(){const t=this.assetItem.duration;if(!t)return 0;const e=this.interstitial.playoutLimit;if(e){const i=e-this.startOffset;if(i>0&&i<t)return i}return t}get remaining(){const t=this.duration;return t?Math.max(0,t-this.currentTime):0}get startOffset(){return this.assetItem.startOffset}get timelineOffset(){var t;return(null==(t=this.hls)?void 0:t.config.timelineOffset)||0}set timelineOffset(t){const e=this.timelineOffset;if(t!==e){const i=t-e;if(Math.abs(i)>1/9e4&&this.hls){if(this.hasDetails)throw new Error("Cannot set timelineOffset after playlists are loaded");this.hls.config.timelineOffset=t}}}getAssetTime(t){const e=this.timelineOffset,i=this.duration;return Math.min(Math.max(0,t-e),i)}removeMediaListeners(){const t=this.mediaAttached;t&&(this._currentTime=t.currentTime,this.bufferSnapShot(),t.removeEventListener("timeupdate",this.checkPlayout))}bufferSnapShot(){var t;this.mediaAttached&&(null!=(t=this.hls)&&t.bufferedToEnd&&(this._bufferedEosTime=this.bufferedEnd))}destroy(){this.removeMediaListeners(),this.hls&&this.hls.destroy(),this.hls=null,this.tracks=this.mediaAttached=this.checkPlayout=null}attachMedia(t){var e;this.loadSource(),null==(e=this.hls)||e.attachMedia(t)}detachMedia(){var t;this.removeMediaListeners(),this.mediaAttached=null,null==(t=this.hls)||t.detachMedia()}resumeBuffering(){var t;null==(t=this.hls)||t.resumeBuffering()}pauseBuffering(){var t;null==(t=this.hls)||t.pauseBuffering()}transferMedia(){var t;return this.bufferSnapShot(),(null==(t=this.hls)?void 0:t.transferMedia())||null}resetDetails(){const t=this.hls;if(t&&this.hasDetails){t.stopLoad();const e=t=>delete t.details;t.levels.forEach(e),t.allAudioTracks.forEach(e),t.allSubtitleTracks.forEach(e),this.hasDetails=!1}}on(t,e,i){var s;null==(s=this.hls)||s.on(t,e)}once(t,e,i){var s;null==(s=this.hls)||s.once(t,e)}off(t,e,i){var s;null==(s=this.hls)||s.off(t,e)}toString(){var t;return`HlsAssetPlayer: ${eh(this.assetItem)} ${null==(t=this.hls)?void 0:t.sessionId} ${this.appendInPlace?"append-in-place":""}`}}const sh=.033;class rh extends U{constructor(t,e){super("interstitials-sched",e),this.onScheduleUpdate=void 0,this.eventMap={},this.events=null,this.items=null,this.durations={primary:0,playout:0,integrated:0},this.onScheduleUpdate=t}destroy(){this.reset(),this.onScheduleUpdate=null}reset(){this.eventMap={},this.setDurations(0,0,0),this.events&&this.events.forEach(t=>t.reset()),this.events=this.items=null}resetErrorsInRange(t,e){return this.events?this.events.reduce((i,s)=>t<=s.startOffset&&e>s.startOffset?(delete s.error,i+1):i,0):0}get duration(){const t=this.items;return t?t[t.length-1].end:0}get length(){return this.items?this.items.length:0}getEvent(t){return t&&this.eventMap[t]||null}hasEvent(t){return t in this.eventMap}findItemIndex(t,e){if(t.event)return this.findEventIndex(t.event.identifier);let i=-1;t.nextEvent?i=this.findEventIndex(t.nextEvent.identifier)-1:t.previousEvent&&(i=this.findEventIndex(t.previousEvent.identifier)+1);const s=this.items;if(s)for(s[i]||(void 0===e&&(e=t.start),i=this.findItemIndexAtTime(e));i>=0&&null!=(r=s[i])&&r.event;){var r;i--}return i}findItemIndexAtTime(t,e){const i=this.items;if(i)for(let s=0;s<i.length;s++){let r=i[s];e&&"primary"!==e&&(r=r[e]);const n=r.start,a=i[s].event,o=null!=a&&a.cue.pre?a.duration:r.end;if(t===n||t>n&&t<o)return s}return-1}findJumpRestrictedIndex(t,e){const i=this.items;if(i)for(let s=t;s<=e&&i[s];s++){const t=i[s].event;if(null!=t&&t.restrictions.jump&&!t.appendInPlace)return s}return-1}findEventIndex(t){const e=this.items;if(e)for(let s=e.length;s--;){var i;if((null==(i=e[s].event)?void 0:i.identifier)===t)return s}return-1}findAssetIndex(t,e){const i=t.assetList,s=i.length;if(s>1)for(let t=0;t<s;t++){const r=i[t];if(!r.error){const i=r.timelineStart;if(e===i||e>i&&(e<i+(r.duration||0)||t===s-1))return t}}return 0}get assetIdAtEnd(){var t;const e=null==(t=this.items)||null==(t=t[this.length-1])?void 0:t.event;if(e){const t=e.assetList,i=t[t.length-1];if(i)return i.identifier}return null}parseInterstitialDateRanges(t,e,i=0){const s=t.main.details,{dateRanges:r}=s,n=this.events,a=this.parseDateRanges(r,{url:s.url},e),o=Object.keys(r),l=n?n.filter(t=>-1===o.indexOf(t.identifier)):[];a.length&&a.sort((t,e)=>{const i=t.cue.pre,s=t.cue.post,r=e.cue.pre,n=e.cue.post;if(i&&!r)return-1;if(r&&!i)return 1;if(s&&!n)return 1;if(n&&!s)return-1;if(!(i||r||s||n)){const i=t.startTime,s=e.startTime;if(i!==s)return i-s}return t.dateRange.tagOrder-e.dateRange.tagOrder}),this.events=a,l.forEach(t=>{this.removeEvent(t)}),this.updateSchedule(t,l,i)}updateSchedule(t,e=[],i=0,s=!1){const r=this.events||[];if(r.length||e.length||this.length<2){const n=this.items,a=this.parseSchedule(r,t,i);(s||e.length||(null==n?void 0:n.length)!==a.length||a.some((t,e)=>Math.abs(t.playout.start-n[e].playout.start)>.005||Math.abs(t.playout.end-n[e].playout.end)>.005))&&(this.items=a,this.onScheduleUpdate(e,n))}}parseDateRanges(t,e,i){const s=[],r=Object.keys(t);for(let n=0;n<r.length;n++){const a=r[n],o=t[a];if(o.isInterstitial){let t=this.eventMap[a];t?t.setDateRange(o):(t=new Xl(o,e),this.eventMap[a]=t,!1===i&&(t.appendInPlace=i)),s.push(t)}}return s}parseSchedule(t,e,i=0){const s=[],r=e.main.details,n=r.live?1/0:r.edge;let a=0;if((t=t.filter(t=>!(t.error||t.cue.once&&t.hasPlayed))).length){this.resolveOffsets(t,e);let l=0,h=0;if(t.forEach((e,o)=>{const d=e.cue.pre,c=e.cue.post,u=t[o-1]||null,f=e.appendInPlace,g=c?n:e.startOffset,m=e.duration,p=e.timelineOccupancy===Wl.Range?m:0,v=d&&r.live?i+(e.resumeOffset||0):0,y=v||e.resumptionOffset,E=(null==u?void 0:u.startTime)===g,T=g+e.cumulativeDuration;let S=f?T+m:g+y;if(d||!c&&g<=0){const t=h;h+=p,e.timelineStart=T;const i=a;a+=m,s.push({event:e,start:T,end:S,playout:{start:i,end:a},integrated:{start:t,end:h}})}else{if(!(g<=n))return;{if(!E){const i=g-l;if(i>sh){const r=l,n=h;h+=i;const d=a;a+=i;const c={previousEvent:t[o-1]||null,nextEvent:e,start:r,end:r+i,playout:{start:d,end:a},integrated:{start:n,end:h}};s.push(c)}else i>0&&u&&(u.cumulativeDuration+=i,s[s.length-1].end=g)}c&&(S=T),e.timelineStart=T;const i=h;h+=p;const r=a;a+=m,s.push({event:e,start:T,end:S,playout:{start:r,end:a},integrated:{start:i,end:h}})}}const b=v||e.resumeTime;l=c||b>n?n:!d&&S&&e.appendInPlaceStarted&&b-S>sh?S:b}),l<n){var o;const t=l,e=h,i=n-l;h+=i;const r=a;a+=i,s.push({previousEvent:(null==(o=s[s.length-1])?void 0:o.event)||null,nextEvent:null,start:l,end:t+i,playout:{start:r,end:a},integrated:{start:e,end:h}})}this.setDurations(n,a,h)}else{const t=0;s.push({previousEvent:null,nextEvent:null,start:t,end:n,playout:{start:t,end:n},integrated:{start:t,end:n}}),this.setDurations(n,n,n)}return s}setDurations(t,e,i){this.durations={primary:t,playout:e,integrated:i}}resolveOffsets(t,i){const s=i.main.details,r=s.live?1/0:s.edge;let n=0,a=-1;t.forEach((o,l)=>{const h=o.cue.pre,d=o.cue.post,c=h?0:d?r:o.startTime;this.updateAssetDurations(o);if(a===c?o.cumulativeDuration=n:(n=0,a=c),!d&&o.snapOptions.in&&(o.resumeAnchor=Ze(null,s.fragments,o.startOffset+o.resumptionOffset,0,0)||void 0),o.appendInPlace&&!o.appendInPlaceStarted){this.primaryCanResumeInPlaceAt(o,i)||(o.appendInPlace=!1)}if(!o.appendInPlace&&l+1<t.length){t[l+1].startTime-t[l].resumeTime<sh&&(t[l+1].appendInPlace=!1,t[l+1].appendInPlace&&this.warn(`Could not change append strategy for abutting event ${o}`))}const u=e(o.resumeOffset)?o.resumeOffset:o.duration;n+=u})}primaryCanResumeInPlaceAt(t,e){const i=t.resumeTime,s=t.startTime+t.resumptionOffset;if(Math.abs(i-s)>Yl)return this.log(`"${t.identifier}" resumption ${i} not aligned with estimated timeline end ${s}`),!1;return!Object.keys(e).some(s=>{const r=e[s].details,n=r.edge;if(i>=n)return this.log(`"${t.identifier}" resumption ${i} past ${s} playlist end ${n}`),!1;const a=Ze(null,r.fragments,i);if(!a)return this.log(`"${t.identifier}" resumption ${i} does not align with any fragments in ${s} playlist (${r.fragStart}-${r.fragmentEnd})`),!0;const o="audio"===s?.175:0;return!(Math.abs(a.start-i)<Yl+o||Math.abs(a.end-i)<Yl+o)&&(this.log(`"${t.identifier}" resumption ${i} not aligned with ${s} fragment bounds (${a.start}-${a.end} sn: ${a.sn} cc: ${a.cc})`),!0)})}updateAssetDurations(t){if(!t.assetListLoaded)return;const e=t.timelineStart;let i=0,s=!1,r=!1;for(let n=0;n<t.assetList.length;n++){const a=t.assetList[n],o=e+i;a.startOffset=i,a.timelineStart=o,s||(s=null===a.duration),r||(r=!!a.error);i+=a.error?0:a.duration||0}t.duration=s&&!r?Math.max(i,t.duration):i}removeEvent(t){t.reset(),delete this.eventMap[t.identifier]}}function nh(t){return`[${t.event?'"'+t.event.identifier+'"':"primary"}: ${t.start.toFixed(2)}-${t.end.toFixed(2)}]`}class ah{constructor(t){this.hls=void 0,this.hls=t}destroy(){this.hls=null}loadAssetList(t,e){const i=t.assetListUrl;let s;try{s=Jl(i,this.hls.sessionId,t.baseUrl)}catch(e){const s=this.assignAssetListError(t,n.ASSET_LIST_LOAD_ERROR,e,i);return void this.hls.trigger(a.ERROR,s)}e&&"data:"!==s.protocol&&De(s,"_HLS_start_offset",""+e);const r=this.hls.config,o=new(0,r.loader)(r),l={type:u.INTERSTITIAL_ASSET_LIST,responseType:"json",url:s.href},h=r.interstitialAssetListLoadPolicy.default,d={loadPolicy:h,timeout:h.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},c={onSuccess:(e,i,s,r)=>{const o=e.data,l=null==o?void 0:o.ASSETS;if(!Array.isArray(l)){const e=this.assignAssetListError(t,n.ASSET_LIST_PARSING_ERROR,new Error("Invalid interstitial asset list"),s.url,i,r);return void this.hls.trigger(a.ERROR,e)}t.assetListResponse=o,this.hls.trigger(a.ASSET_LIST_LOADED,{event:t,assetListResponse:o,networkDetails:r})},onError:(e,i,s,r)=>{const o=this.assignAssetListError(t,n.ASSET_LIST_LOAD_ERROR,new Error(`Error loading X-ASSET-LIST: HTTP status ${e.code} ${e.text} (${i.url})`),i.url,r,s);this.hls.trigger(a.ERROR,o)},onTimeout:(e,i,s)=>{const r=this.assignAssetListError(t,n.ASSET_LIST_LOAD_TIMEOUT,new Error(`Timeout loading X-ASSET-LIST (${i.url})`),i.url,e,s);this.hls.trigger(a.ERROR,r)}};return o.load(l,d,c),this.hls.trigger(a.ASSET_LIST_LOADING,{event:t}),o}assignAssetListError(t,e,i,s,n,a){return t.error=i,{type:r.NETWORK_ERROR,details:e,fatal:!1,interstitial:t,url:s,error:i,networkDetails:a,stats:n}}}function oh(t){var e;null==t||null==(e=t.play())||e.catch(()=>{})}function lh(t,e){return`[${t}] Advancing timeline position to ${e}`}class hh{constructor(t){this.buffered=void 0;const e=(e,i,s)=>{if((i>>>=0)>s-1)throw new DOMException(`Failed to execute '${e}' on 'TimeRanges': The index provided (${i}) is greater than the maximum bound (${s})`);return t[i][e]};this.buffered={get length(){return t.length},end:i=>e("end",i,t.length),start:i=>e("start",i,t.length)}}}const dh={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},ch=t=>String.fromCharCode(dh[t]||t),uh=15,fh=42,gh={17:1,18:3,21:5,22:7,23:9,16:11,19:12,20:14},mh={17:2,18:4,21:6,22:8,23:10,19:13,20:15},ph={25:1,26:3,29:5,30:7,31:9,24:11,27:12,28:14},vh={25:2,26:4,29:6,30:8,31:10,27:13,28:15},yh=["white","green","blue","cyan","red","yellow","magenta","black","transparent"];class Eh{constructor(){this.time=null,this.verboseLevel=0}log(t,e){if(this.verboseLevel>=t){const i="function"==typeof e?e():e;q.log(`${this.time} [${t}] ${i}`)}}}const Th=function(t){const e=[];for(let i=0;i<t.length;i++)e.push(t[i].toString(16));return e},Sh=Object.freeze({foreground:"white",underline:!1,italics:!1,background:"black",flash:!1});class bh{constructor(){this.styles=Sh}get foreground(){return this.styles.foreground}set foreground(t){const e=this.styles;this.styles={foreground:t,underline:e.underline,italics:e.italics,background:e.background,flash:e.flash}}get underline(){return this.styles.underline}set underline(t){const e=this.styles;this.styles={foreground:e.foreground,underline:t,italics:e.italics,background:e.background,flash:e.flash}}get italics(){return this.styles.italics}set italics(t){const e=this.styles;this.styles={foreground:e.foreground,underline:e.underline,italics:t,background:e.background,flash:e.flash}}get background(){return this.styles.background}set background(t){const e=this.styles;this.styles={foreground:e.foreground,underline:e.underline,italics:e.italics,background:t,flash:e.flash}}get flash(){return this.styles.flash}set flash(t){const e=this.styles;this.styles={foreground:e.foreground,underline:e.underline,italics:e.italics,background:e.background,flash:t}}reset(){this.styles=Sh}setStyles(t){const e=this.styles,i=Object.prototype.hasOwnProperty;this.styles={foreground:i.call(t,"foreground")?t.foreground:e.foreground,underline:i.call(t,"underline")?t.underline:e.underline,italics:i.call(t,"italics")?t.italics:e.italics,background:i.call(t,"background")?t.background:e.background,flash:i.call(t,"flash")?t.flash:e.flash}}toString(){return"color="+this.foreground+", underline="+this.underline+", italics="+this.italics+", background="+this.background+", flash="+this.flash}}class Ah{constructor(){this.uchar=" ",this.penState=new bh}reset(){this.uchar=" ",this.penState.reset()}setChar(t,e){this.uchar=t,this.penState.styles=e.styles}setPenState(t){this.penState.styles=t.styles}copy(t){this.uchar=t.uchar,this.penState.styles=t.penState.styles}}class Lh{constructor(t){this.chars=[],this.pos=0,this.currPenState=new bh,this.cueStartTime=null,this.logger=void 0;for(let t=0;t<fh;t++)this.chars.push(new Ah);this.logger=t}equals(t){const e=this.chars,i=t.chars;for(let t=0;t<fh;t++){const s=e[t],r=i[t];if(s.uchar!==r.uchar)return!1;const n=s.penState.styles,a=r.penState.styles;if(n!==a&&(n.foreground!==a.foreground||n.underline!==a.underline||n.italics!==a.italics||n.background!==a.background||n.flash!==a.flash))return!1}return!0}copy(t){for(let e=0;e<fh;e++)this.chars[e].copy(t.chars[e])}isEmpty(){const t=this.chars;for(let e=0;e<fh;e++){const i=t[e];if(" "!==i.uchar)return!1;const s=i.penState.styles;if(s!==Sh&&("white"!==s.foreground||s.underline||s.italics||"black"!==s.background||s.flash))return!1}return!0}setCursor(t){this.pos!==t&&(this.pos=t),this.pos<0?(this.logger.log(3,"Negative cursor position "+this.pos),this.pos=0):this.pos>=fh&&(this.logger.log(3,"Too large cursor position "+this.pos),this.pos=41)}moveCursor(t){const e=Math.min(this.pos+t,fh);if(t>1)for(let t=this.pos+1;t<e;t++)this.chars[t].setPenState(this.currPenState);this.setCursor(e)}backSpace(){this.moveCursor(-1),this.chars[this.pos].setChar(" ",this.currPenState)}insertChar(t){t>=144&&this.backSpace();const e=ch(t);this.pos>=fh?this.logger.log(0,()=>"Cannot insert "+t.toString(16)+" ("+e+") at position "+this.pos+". Skipping it!"):(this.chars[this.pos].setChar(e,this.currPenState),this.moveCursor(1))}clearFromPos(t){let e;for(e=t;e<fh;e++)this.chars[e].reset()}clear(){this.clearFromPos(0),this.pos=0,this.currPenState.reset()}clearToEndOfRow(){this.clearFromPos(this.pos)}getTextString(){const t=[];let e=!0;for(let i=0;i<fh;i++){const s=this.chars[i].uchar;" "!==s&&(e=!1),t.push(s)}return e?"":t.join("")}setPenStyles(t){this.currPenState.setStyles(t);this.chars[this.pos].setPenState(this.currPenState)}}class Ih{constructor(t){this.rows=[],this.currRow=14,this.nrRollUpRows=null,this.lastOutputScreen=null,this.logger=void 0;for(let e=0;e<uh;e++)this.rows.push(new Lh(t));this.logger=t}reset(){for(let t=0;t<uh;t++)this.rows[t].clear();this.currRow=14}equals(t){let e=!0;for(let i=0;i<uh;i++)if(!this.rows[i].equals(t.rows[i])){e=!1;break}return e}copy(t){for(let e=0;e<uh;e++){const i=this.rows[e].chars,s=t.rows[e].chars;for(let t=0;t<fh;t++){const e=i[t],r=s[t];e.uchar=r.uchar,e.penState.styles=r.penState.styles}}}isEmpty(){let t=!0;for(let e=0;e<uh;e++)if(!this.rows[e].isEmpty()){t=!1;break}return t}backSpace(){this.rows[this.currRow].backSpace()}clearToEndOfRow(){this.rows[this.currRow].clearToEndOfRow()}insertChar(t){this.rows[this.currRow].insertChar(t)}setPen(t){this.rows[this.currRow].setPenStyles(t)}moveCursor(t){this.rows[this.currRow].moveCursor(t)}setCursor(t){this.logger.log(2,"setCursor: "+t);this.rows[this.currRow].setCursor(t)}setPAC(t){this.logger.log(2,()=>"pacData = "+Ue(t));let e=t.row-1;if(this.nrRollUpRows&&e<this.nrRollUpRows-1&&(e=this.nrRollUpRows-1),this.nrRollUpRows&&this.currRow!==e){for(let t=0;t<uh;t++)this.rows[t].clear();const t=this.currRow+1-this.nrRollUpRows,i=this.lastOutputScreen;if(i){const s=i.rows[t].cueStartTime,r=this.logger.time;if(null!==s&&null!==r&&s<r)for(let s=0;s<this.nrRollUpRows;s++)this.rows[e-this.nrRollUpRows+s+1].copy(i.rows[t+s])}}this.currRow=e;const i=this.rows[this.currRow];if(null!==t.indent){const e=t.indent,s=Math.max(e-1,0);i.setCursor(t.indent),t.color=i.chars[s].penState.foreground}const s={foreground:t.color,underline:t.underline,italics:t.italics,background:"black",flash:!1};this.setPen(s)}setBkgData(t){this.logger.log(2,()=>"bkgData = "+Ue(t)),this.backSpace(),this.setPen(t),this.insertChar(32)}setRollUpRows(t){this.nrRollUpRows=t}rollUp(){if(null===this.nrRollUpRows)return void this.logger.log(3,"roll_up but nrRollUpRows not set yet");this.logger.log(1,()=>this.getDisplayText());const t=this.currRow+1-this.nrRollUpRows,e=this.rows.splice(t,1)[0];e.clear(),this.rows.splice(this.currRow,0,e),this.logger.log(2,"Rolling up")}getDisplayText(t){t=t||!1;const e=[];let i="",s=-1;for(let i=0;i<uh;i++){const r=this.rows[i].getTextString();r&&(s=i+1,t?e.push("Row "+s+": '"+r+"'"):e.push(r.trim()))}return e.length>0&&(i=t?"["+e.join(" | ")+"]":e.join("\n")),i}getTextAndFormat(){return this.rows}}class Rh{constructor(t,e,i){this.chNr=void 0,this.outputFilter=void 0,this.mode=void 0,this.verbose=void 0,this.displayedMemory=void 0,this.nonDisplayedMemory=void 0,this.lastOutputScreen=void 0,this.currRollUpRow=void 0,this.writeScreen=void 0,this.cueStartTime=void 0,this.logger=void 0,this.chNr=t,this.outputFilter=e,this.mode=null,this.verbose=0,this.displayedMemory=new Ih(i),this.nonDisplayedMemory=new Ih(i),this.lastOutputScreen=new Ih(i),this.currRollUpRow=this.displayedMemory.rows[14],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null,this.logger=i}reset(){this.mode=null,this.displayedMemory.reset(),this.nonDisplayedMemory.reset(),this.lastOutputScreen.reset(),this.outputFilter.reset(),this.currRollUpRow=this.displayedMemory.rows[14],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null}getHandler(){return this.outputFilter}setHandler(t){this.outputFilter=t}setPAC(t){this.writeScreen.setPAC(t)}setBkgData(t){this.writeScreen.setBkgData(t)}setMode(t){t!==this.mode&&(this.mode=t,this.logger.log(2,()=>"MODE="+t),"MODE_POP-ON"===this.mode?this.writeScreen=this.nonDisplayedMemory:(this.writeScreen=this.displayedMemory,this.writeScreen.reset()),"MODE_ROLL-UP"!==this.mode&&(this.displayedMemory.nrRollUpRows=null,this.nonDisplayedMemory.nrRollUpRows=null),this.mode=t)}insertChars(t){for(let e=0;e<t.length;e++)this.writeScreen.insertChar(t[e]);const e=this.writeScreen===this.displayedMemory?"DISP":"NON_DISP";this.logger.log(2,()=>e+": "+this.writeScreen.getDisplayText(!0)),"MODE_PAINT-ON"!==this.mode&&"MODE_ROLL-UP"!==this.mode||(this.logger.log(1,()=>"DISPLAYED: "+this.displayedMemory.getDisplayText(!0)),this.outputDataUpdate())}ccRCL(){this.logger.log(2,"RCL - Resume Caption Loading"),this.setMode("MODE_POP-ON")}ccBS(){this.logger.log(2,"BS - BackSpace"),"MODE_TEXT"!==this.mode&&(this.writeScreen.backSpace(),this.writeScreen===this.displayedMemory&&this.outputDataUpdate())}ccAOF(){}ccAON(){}ccDER(){this.logger.log(2,"DER- Delete to End of Row"),this.writeScreen.clearToEndOfRow(),this.outputDataUpdate()}ccRU(t){this.logger.log(2,"RU("+t+") - Roll Up"),this.writeScreen=this.displayedMemory,this.setMode("MODE_ROLL-UP"),this.writeScreen.setRollUpRows(t)}ccFON(){this.logger.log(2,"FON - Flash On"),this.writeScreen.setPen({flash:!0})}ccRDC(){this.logger.log(2,"RDC - Resume Direct Captioning"),this.setMode("MODE_PAINT-ON")}ccTR(){this.logger.log(2,"TR"),this.setMode("MODE_TEXT")}ccRTD(){this.logger.log(2,"RTD"),this.setMode("MODE_TEXT")}ccEDM(){this.logger.log(2,"EDM - Erase Displayed Memory"),this.displayedMemory.reset(),this.outputDataUpdate(!0)}ccCR(){this.logger.log(2,"CR - Carriage Return"),this.writeScreen.rollUp(),this.outputDataUpdate(!0)}ccENM(){this.logger.log(2,"ENM - Erase Non-displayed Memory"),this.nonDisplayedMemory.reset()}ccEOC(){if(this.logger.log(2,"EOC - End Of Caption"),"MODE_POP-ON"===this.mode){const t=this.displayedMemory;this.displayedMemory=this.nonDisplayedMemory,this.nonDisplayedMemory=t,this.writeScreen=this.nonDisplayedMemory,this.logger.log(1,()=>"DISP: "+this.displayedMemory.getDisplayText())}this.outputDataUpdate(!0)}ccTO(t){this.logger.log(2,"TO("+t+") - Tab Offset"),this.writeScreen.moveCursor(t)}ccMIDROW(t){const e={flash:!1};if(e.underline=t%2==1,e.italics=t>=46,e.italics)e.foreground="white";else{const i=Math.floor(t/2)-16,s=["white","green","blue","cyan","red","yellow","magenta"];e.foreground=s[i]}this.logger.log(2,"MIDROW: "+Ue(e)),this.writeScreen.setPen(e)}outputDataUpdate(t=!1){const e=this.logger.time;null!==e&&this.outputFilter&&(null!==this.cueStartTime||this.displayedMemory.isEmpty()?this.displayedMemory.equals(this.lastOutputScreen)||(this.outputFilter.newCue(this.cueStartTime,e,this.lastOutputScreen),t&&this.outputFilter.dispatchCue&&this.outputFilter.dispatchCue(),this.cueStartTime=this.displayedMemory.isEmpty()?null:e):this.cueStartTime=e,this.lastOutputScreen.copy(this.displayedMemory))}cueSplitAtTime(t){this.outputFilter&&(this.displayedMemory.isEmpty()||(this.outputFilter.newCue&&this.outputFilter.newCue(this.cueStartTime,t,this.displayedMemory),this.cueStartTime=t))}}class kh{constructor(t,e,i){this.channels=[null,null,null],this.currentChannel=0,this.cmdHistory={a:null,b:null},this.logger=void 0,this.field=void 0,this.outputFilters=void 0,this.logger=new Eh,this.field=t,this.outputFilters=[null,e,i]}getHandler(t){return this.outputFilters[t]}setHandler(t,e){var i;this.outputFilters[t]=e,null==(i=this.channels[t])||i.setHandler(e)}getChannel(t){let e=this.channels[t];return e||(e=this.channels[t]=new Rh(this.field+t-1,this.outputFilters[t],this.logger)),e}addData(t,e){this.logger.time=t;for(let t=0;t<e.length;t+=2){const i=127&e[t],s=127&e[t+1];let r=!1,n=null;if(0===i&&0===s)continue;this.logger.log(3,()=>"["+Th([e[t],e[t+1]])+"] -> ("+Th([i,s])+")");const a=this.cmdHistory;if(i>=16&&i<=31){if(Dh(i,s,a)){_h(null,null,a),this.logger.log(3,()=>"Repeated command ("+Th([i,s])+") is dropped");continue}_h(i,s,this.cmdHistory),r=this.parseCmd(i,s),r||(r=this.parseMidrow(i,s)),r||(r=this.parsePAC(i,s)),r||(r=this.parseBackgroundAttributes(i,s))}else _h(null,null,a);if(!r&&(n=this.parseChars(i,s),n)){const t=this.currentChannel;if(t&&t>0){this.getChannel(t).insertChars(n)}else this.logger.log(2,"No channel found yet. TEXT-MODE?")}r||n||this.logger.log(2,()=>"Couldn't parse cleaned data "+Th([i,s])+" orig: "+Th([e[t],e[t+1]]))}}parseCmd(t,e){if(!((20===t||28===t||21===t||29===t)&&e>=32&&e<=47)&&!((23===t||31===t)&&e>=33&&e<=35))return!1;const i=20===t||21===t||23===t?1:2,s=this.getChannel(i);return 20===t||21===t||28===t||29===t?32===e?s.ccRCL():33===e?s.ccBS():34===e?s.ccAOF():35===e?s.ccAON():36===e?s.ccDER():37===e?s.ccRU(2):38===e?s.ccRU(3):39===e?s.ccRU(4):40===e?s.ccFON():41===e?s.ccRDC():42===e?s.ccTR():43===e?s.ccRTD():44===e?s.ccEDM():45===e?s.ccCR():46===e?s.ccENM():47===e&&s.ccEOC():s.ccTO(e-32),this.currentChannel=i,!0}parseMidrow(t,e){let i=0;if((17===t||25===t)&&e>=32&&e<=47){if(i=17===t?1:2,i!==this.currentChannel)return this.logger.log(0,"Mismatch channel in midrow parsing"),!1;const s=this.channels[i];return!!s&&(s.ccMIDROW(e),this.logger.log(3,()=>"MIDROW ("+Th([t,e])+")"),!0)}return!1}parsePAC(t,e){let i;if(!((t>=17&&t<=23||t>=25&&t<=31)&&e>=64&&e<=127)&&!((16===t||24===t)&&e>=64&&e<=95))return!1;const s=t<=23?1:2;i=e>=64&&e<=95?1===s?gh[t]:ph[t]:1===s?mh[t]:vh[t];return this.getChannel(s).setPAC(this.interpretPAC(i,e)),this.currentChannel=s,!0}interpretPAC(t,e){let i;const s={color:null,italics:!1,indent:null,underline:!1,row:t};return i=e>95?e-96:e-64,s.underline=!(1&~i),i<=13?s.color=["white","green","blue","cyan","red","yellow","magenta","white"][Math.floor(i/2)]:i<=15?(s.italics=!0,s.color="white"):s.indent=4*Math.floor((i-16)/2),s}parseChars(t,e){let i,s=null,r=null;if(t>=25?(i=2,r=t-8):(i=1,r=t),r>=17&&r<=19){let t;t=17===r?e+80:18===r?e+112:e+144,this.logger.log(2,()=>"Special char '"+ch(t)+"' in channel "+i),s=[t]}else t>=32&&t<=127&&(s=0===e?[t]:[t,e]);return s&&this.logger.log(3,()=>"Char codes = "+Th(s).join(",")),s}parseBackgroundAttributes(t,e){if(!((16===t||24===t)&&e>=32&&e<=47)&&!((23===t||31===t)&&e>=45&&e<=47))return!1;let i;const s={};16===t||24===t?(i=Math.floor((e-32)/2),s.background=yh[i],e%2==1&&(s.background=s.background+"_semi")):45===e?s.background="transparent":(s.foreground="black",47===e&&(s.underline=!0));const r=t<=23?1:2;return this.getChannel(r).setBkgData(s),!0}reset(){for(let t=0;t<Object.keys(this.channels).length;t++){const e=this.channels[t];e&&e.reset()}_h(null,null,this.cmdHistory)}cueSplitAtTime(t){for(let e=0;e<this.channels.length;e++){const i=this.channels[e];i&&i.cueSplitAtTime(t)}}}function _h(t,e,i){i.a=t,i.b=e}function Dh(t,e,i){return i.a===t&&i.b===e}class wh{constructor(t,e){this.timelineController=void 0,this.cueRanges=[],this.trackName=void 0,this.startTime=null,this.endTime=null,this.screen=null,this.timelineController=t,this.trackName=e}dispatchCue(){null!==this.startTime&&(this.timelineController.addCues(this.trackName,this.startTime,this.endTime,this.screen,this.cueRanges),this.startTime=null)}newCue(t,e,i){(null===this.startTime||this.startTime>t)&&(this.startTime=t),this.endTime=e,this.screen=i,this.timelineController.createCaptionsTrack(this.trackName)}reset(){this.cueRanges=[],this.startTime=null}}function Ph(t,e,i,s){return Math.min(e,s)-Math.max(t,i)}const Ch=/\s/,xh={newCue(t,e,i,s){const r=[];let n,a,o,l,h;const d=self.VTTCue||self.TextTrackCue;for(let u=0;u<s.rows.length;u++)if(n=s.rows[u],o=!0,l=0,h="",!n.isEmpty()){var c;for(let t=0;t<n.chars.length;t++)Ch.test(n.chars[t].uchar)&&o?l++:(h+=n.chars[t].uchar,o=!1);n.cueStartTime=e,e===i&&(i+=1e-4),l>=16?l--:l++;const s=al(h.trim()),f=cl(e,i,s);null!=t&&null!=(c=t.cues)&&c.getCueById(f)||(a=new d(e,i,s),a.id=f,a.line=u+1,a.align="left",a.position=10+Math.min(80,10*Math.floor(8*l/32)),r.push(a))}return t&&r.length&&(r.sort((t,e)=>"auto"===t.line||"auto"===e.line?0:t.line>8&&e.line>8?e.line-t.line:t.line-e.line),r.forEach(e=>Rl(t,e))),r}};class Mh{constructor(){this.requestTimeout=void 0,this.retryTimeout=void 0,this.retryDelay=0,this.config=null,this.callbacks=null,this.context=null,this.stats=new c}destroy(){this.callbacks=this.context=this.config=null,this.abortInternal(),this.stats=null}load(t,e,i){const s=this.stats;if(s.loading.start)throw new Error("Loader can only be used once.");s.loading.start=self.performance.now(),this.context=t,this.config=e,this.callbacks=i,this.loadInternal()}abort(){var t;this.abortInternal(),null!=(t=this.callbacks)&&t.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.getNetworkDetails())}loadtimeout(){if(!this.config)return;const t=this.config.loadPolicy.timeoutRetry;if(O(t,this.stats.retry,!0))this.retry(t);else{var e;q.warn(`timeout while loading ${null==(e=this.context)?void 0:e.url}`);const t=this.callbacks;t&&(this.abortInternal(),t.onTimeout(this.stats,this.context,this.getNetworkDetails()))}}retry(t){const{context:e,stats:i}=this;this.retryDelay=x(t,i.retry),i.retry++,q.warn(`${status?"HTTP Status "+status:"Timeout"} while loading ${null==e?void 0:e.url}, retrying ${i.retry}/${t.maxNumRetry} in ${this.retryDelay}ms`),this.abortInternal(),this.resetInternalLoader(),self.clearTimeout(this.retryTimeout),this.retryTimeout=self.setTimeout(()=>this.loadInternal(),this.retryDelay)}}const Oh=/(\d+)-(\d+)\/(\d+)/;class Fh extends Mh{constructor(t){super(),this.fetchSetup=void 0,this.request=null,this.response=null,this.controller=null,this.fetchSetup=t.fetchSetup||Nh}destroy(){this.request=null,super.destroy(),this.response=null,this.controller=null,this.fetchSetup=null}abortInternal(){self.clearTimeout(this.retryTimeout),this.controller&&!this.stats.loading.end&&(this.stats.aborted=!0,this.controller.abort())}getNetworkDetails(){return this.response}resetInternalLoader(){this.response=null}loadInternal(){const{config:t,context:i,stats:s}=this;if(!t||!i)return;s.loading.first=0,s.loaded=0,s.aborted=!1,this.controller=new self.AbortController;const r=function(t,e){const i={method:"GET",mode:"cors",credentials:"same-origin",signal:e,headers:new self.Headers(I({},t.headers))};t.rangeEnd&&i.headers.set("Range","bytes="+t.rangeStart+"-"+String(t.rangeEnd-1));return i}(i,this.controller.signal),n="arraybuffer"===i.responseType,a=n?"byteLength":"length",{maxTimeToFirstByteMs:o,maxLoadTimeMs:l}=t.loadPolicy;this.request=this.fetchSetup(i,r),self.clearTimeout(this.requestTimeout),t.timeout=o&&e(o)?o:l,this.requestTimeout=self.setTimeout(()=>{this.loadtimeout()},t.timeout);(Un(this.request)?this.request.then(self.fetch):self.fetch(this.request)).then(r=>{var a;this.response=r;const o=Math.max(self.performance.now(),s.loading.start);if(self.clearTimeout(this.requestTimeout),t.timeout=l,this.requestTimeout=self.setTimeout(()=>{this.loadtimeout()},l-(o-s.loading.start)),!r.ok){const{status:t,statusText:e}=r;throw new $h(e||"fetch, bad network response",t,r)}s.loading.first=o,s.total=function(t){const i=t.get("Content-Range");if(i){const t=function(t){const e=Oh.exec(t);if(e)return parseInt(e[2])-parseInt(e[1])+1}(i);if(e(t))return t}const s=t.get("Content-Length");if(s)return parseInt(s)}(r.headers)||s.total;const h=null==(a=this.callbacks)?void 0:a.onProgress;return h&&e(t.highWaterMark)?this.loadProgressively(r,s,i,t.highWaterMark,h):n?r.arrayBuffer():"json"===i.responseType?r.json():r.text()}).then(r=>{var n,o;const l=this.response;if(!l)throw new Error("loader destroyed");self.clearTimeout(this.requestTimeout),s.loading.end=Math.max(self.performance.now(),s.loading.first);const h=r[a];h&&(s.loaded=s.total=h);const d={url:l.url,data:r,code:l.status},c=null==(n=this.callbacks)?void 0:n.onProgress;c&&!e(t.highWaterMark)&&c(s,i,r,l),null==(o=this.callbacks)||o.onSuccess(d,s,i,l)}).catch(e=>{if(self.clearTimeout(this.requestTimeout),s.aborted)return;const r=e&&e.code||0,n=e?e.message:null,a=t.loadPolicy.errorRetry;var o;O(a,s.retry,!1,{url:i.url,data:void 0,code:r})?this.retry(a):(q.error(`${r} while loading ${i.url}`),null==(o=this.callbacks)||o.onError({code:r,text:n},i,e?e.details:null,s))})}getCacheAge(){let t=null;if(this.response){const e=this.response.headers.get("age");t=e?parseFloat(e):null}return t}getResponseHeader(t){return this.response?this.response.headers.get(t):null}loadProgressively(t,e,i,s=0,r){const n=new Er,a=t.body.getReader(),o=()=>a.read().then(a=>{if(a.done)return n.dataLength&&r(e,i,n.flush().buffer,t),Promise.resolve(new ArrayBuffer(0));const l=a.value,h=l.length;return e.loaded+=h,h<s||n.dataLength?(n.push(l),n.dataLength>=s&&r(e,i,n.flush().buffer,t)):r(e,i,l.buffer,t),o()}).catch(()=>Promise.reject());return o()}}function Nh(t,e){return new self.Request(t.url,e)}class $h extends Error{constructor(t,e,i){super(t),this.code=void 0,this.details=void 0,this.code=e,this.details=i}}const Bh=/^age:\s*[\d.]+\s*$/im;class Uh extends Mh{constructor(t){super(),this.xhrSetup=void 0,this.loader=null,this.xhrSetup=t.xhrSetup||null}destroy(){super.destroy(),this.loader=null,this.xhrSetup=null}abortInternal(){const t=this.loader;self.clearTimeout(this.requestTimeout),self.clearTimeout(this.retryTimeout),t&&(t.onreadystatechange=null,t.onprogress=null,4!==t.readyState&&(this.stats.aborted=!0,t.abort()))}getNetworkDetails(){return this.loader}resetInternalLoader(){this.loader=null}loadInternal(){const{config:t,context:e}=this;if(!t||!e)return;const i=this.loader=new self.XMLHttpRequest,s=this.stats;s.loading.first=0,s.loaded=0,s.aborted=!1;const r=this.xhrSetup;r?Promise.resolve().then(()=>{if(this.loader===i&&!this.stats.aborted)return r.call(this,i,e.url,e)}).catch(t=>{if(this.loader===i&&!this.stats.aborted)return i.open("GET",e.url,!0),r.call(this,i,e.url,e)}).then(()=>{this.loader!==i||this.stats.aborted||this.openAndSendXhr(i,e,t)}).catch(t=>{var r;null==(r=this.callbacks)||r.onError({code:i.status,text:t.message},e,i,s)}):this.openAndSendXhr(i,e,t)}openAndSendXhr(t,i,s){t.readyState||t.open("GET",i.url,!0);const r=i.headers,{maxTimeToFirstByteMs:n,maxLoadTimeMs:a}=s.loadPolicy;if(r)for(const e in r)t.setRequestHeader(e,r[e]);i.rangeEnd&&t.setRequestHeader("Range",`bytes=${i.rangeStart}-${i.rangeEnd-1}`),t.onreadystatechange=this.readystatechange.bind(this),t.onprogress=this.loadprogress.bind(this),t.responseType=i.responseType,self.clearTimeout(this.requestTimeout),s.timeout=n&&e(n)?n:a,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),s.timeout),t.send()}readystatechange(){const{context:t,loader:e,stats:i}=this;if(!t||!e)return;const s=e.readyState,r=this.config;if(!i.aborted&&s>=2&&(0===i.loading.first&&(i.loading.first=Math.max(self.performance.now(),i.loading.start),r.timeout!==r.loadPolicy.maxLoadTimeMs&&(self.clearTimeout(this.requestTimeout),r.timeout=r.loadPolicy.maxLoadTimeMs,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),r.loadPolicy.maxLoadTimeMs-(i.loading.first-i.loading.start)))),4===s)){self.clearTimeout(this.requestTimeout),e.onreadystatechange=null,e.onprogress=null;const s=e.status,l="text"===e.responseType?e.responseText:null;if(s>=200&&s<300){const r=null!=l?l:e.response;if(null!=r){var n,a;i.loading.end=Math.max(self.performance.now(),i.loading.first);const o="arraybuffer"===e.responseType?r.byteLength:r.length;i.loaded=i.total=o,i.bwEstimate=8e3*i.total/(i.loading.end-i.loading.first);const l=null==(n=this.callbacks)?void 0:n.onProgress;l&&l(i,t,r,e);const h={url:e.responseURL,data:r,code:s};return t.rangeEnd&&o!==t.rangeEnd-t.rangeStart&&q.warn(`Payload length ${o} does not match requested Range: bytes=${t.rangeStart}-${t.rangeEnd-1}`),void(null==(a=this.callbacks)||a.onSuccess(h,i,t,e))}}const h=r.loadPolicy.errorRetry;var o;if(O(h,i.retry,!1,{url:t.url,data:void 0,code:s}))this.retry(h);else q.error(`${s} while loading ${t.url}`),null==(o=this.callbacks)||o.onError({code:s,text:e.statusText},t,e,i)}}loadprogress(t){const e=this.stats;e.loaded=t.loaded,t.lengthComputable&&(e.total=t.total)}getCacheAge(){let t=null;if(this.loader&&Bh.test(this.loader.getAllResponseHeaders())){const e=this.loader.getResponseHeader("age");t=e?parseFloat(e):null}return t}getResponseHeader(t){return this.loader&&new RegExp(`^${t}:\\s*[\\d.]+\\s*$`,"im").test(this.loader.getAllResponseHeaders())?this.loader.getResponseHeader(t):null}}const Gh=k(k({autoStartLoad:!0,startPosition:-1,defaultAudioCodec:void 0,debug:!1,capLevelOnFPSDrop:!1,capLevelToPlayerSize:!1,ignoreDevicePixelRatio:!1,maxDevicePixelRatio:Number.POSITIVE_INFINITY,preferManagedMediaSource:!1,initialLiveManifestSize:1,maxBufferLength:30,backBufferLength:1/0,frontBufferFlushThreshold:1/0,loopBackBufferFlush:void 0,startOnSegmentBoundary:!1,nextAudioTrackBufferFlushForwardOffset:.25,maxBufferSize:6e7,maxFragLookUpTolerance:.25,maxBufferHole:.1,detectStallWithCurrentTimeMs:1250,highBufferWatchdogPeriod:2,nudgeOffset:.1,nudgeMaxRetry:3,nudgeOnVideoHole:!0,skipBufferHolePadding:.1,liveSyncMode:"edge",liveSyncDurationCount:3,liveSyncOnStallIncrease:1,liveMaxLatencyDurationCount:1/0,liveMaxUnchangedPlaylistRefresh:1/0,liveSyncDuration:void 0,liveMaxLatencyDuration:void 0,maxLiveSyncPlaybackRate:1,liveDurationInfinity:!1,liveBackBufferLength:null,maxMaxBufferLength:600,enableWorker:!0,workerPath:null,enableSoftwareAES:!0,startLevel:void 0,startFragPrefetch:!1,fpsDroppedMonitoringPeriod:5e3,fpsDroppedMonitoringThreshold:.2,appendErrorMaxRetry:3,appendTimeout:1/0,ignorePlaylistParsingErrors:!1,loader:Uh,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,licenseXhrSetup:void 0,licenseResponseCallback:void 0,stretchShortVideoTrack:!1,maxAudioFramesDrift:1,forceKeyFrameOnDiscontinuity:!0,handleMpegTsVideoIntegrityErrors:"process",abrEwmaFastLive:3,abrEwmaSlowLive:9,abrEwmaFastVoD:3,abrEwmaSlowVoD:9,abrEwmaDefaultEstimate:5e5,abrEwmaDefaultEstimateMax:5e6,abrBandWidthFactor:.95,abrBandWidthUpFactor:.7,abrMaxWithRealBitrate:!1,abrSwitchInterval:0,maxStarvationDelay:4,maxLoadingDelay:4,minAutoBitrate:0,emeEnabled:!1,widevineLicenseUrl:void 0,drmSystems:{},drmSystemOptions:{},requestMediaKeySystemAccessFunc:ms,requireKeySystemAccessOnStart:!1,testBandwidth:!0,progressive:!1,lowLatencyMode:!0,cmcd:void 0,enableDateRangeMetadataCues:!0,enableEmsgMetadataCues:!0,enableEmsgKLVMetadata:!1,enableID3MetadataCues:!0,emsgKLVSchemaUri:void 0,enableInterstitialPlayback:!0,interstitialAppendInPlace:!0,interstitialLiveLookAhead:10,iframeCacheLimit:2097152,useMediaCapabilities:!0,preserveManualLevelOnError:!1,errorPenaltyExpireMs:0,certLoadPolicy:{default:{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,streamController:Ul,abrController:class extends U{constructor(t){super("abr",t.logger),this.hls=void 0,this.lastLevelLoadSec=0,this.lastLoadedFragLevel=-1,this.firstSelection=-1,this.firstAutoFloor=-1,this._nextAutoLevel=-1,this.nextAutoLevelKey="",this.audioTracksByGroup=null,this.codecTiers=null,this.timer=-1,this.fragCurrent=null,this.partCurrent=null,this.bitrateTestDelay=0,this.rebufferNotice=-1,this.supportedCache={},this.bwEstimator=void 0,this._abandonRulesCheck=t=>{var i;const{fragCurrent:s,partCurrent:r,hls:n}=this;if(!n)return;const{autoLevelEnabled:o,media:l}=n;if(!s||!l)return;const h=performance.now(),d=r?r.stats:s.stats,c=r?r.duration:s.duration,u=h-d.loading.start,f=n.minAutoLevel,g=s.level,m=this._nextAutoLevel;if(d.aborted||d.loaded&&d.loaded===d.total||g<=f)return this.clearTimer(),void(this._nextAutoLevel=-1);if(!o)return;const p=m>-1&&m!==g,v=!!t||p;if(!v&&(l.paused||!l.playbackRate||!l.readyState))return;const y=n.mainForwardBufferInfo;if(!v&&null===y)return;const E=this.bwEstimator.getEstimateTTFB(),T=Math.abs(l.playbackRate);if(u<=Math.max(E,c/(2*T)*1e3))return;const S=y?y.len/T:0,b=d.loading.first?d.loading.first-d.loading.start:-1,A=d.loaded&&b>-1,L=this.getBwEstimate(),I=n.levels,R=I[g],k=Math.max(d.loaded,Math.round(c*(s.bitrate||R.averageBitrate)/8));let _=A?u-b:u;_<1&&A&&(_=Math.min(u,8*d.loaded/L));const D=A?1e3*d.loaded/_:0,w=E/1e3,P=D?(k-d.loaded)/D:8*k/L+w;if(P<=S)return;const C=D?8*D:L,x=!0===(null==(i=(null==t?void 0:t.details)||n.latestLevelDetails)?void 0:i.live),M=n.config.abrBandWidthUpFactor;let O,F=Number.POSITIVE_INFINITY;for(O=g-1;O>f;O--){const t=I[O].maxBitrate,e=!I[O].details||x;if(F=this.getTimeToLoadFrag(w,C,c*t,e),F<Math.min(S,c+w))break}if(F>=P)return;if(F>10*c)return;A?this.bwEstimator.sample(u-Math.min(E,b),d.loaded):this.bwEstimator.sampleTTFB(u);const N=I[O].maxBitrate;this.getBwEstimate()*M>N&&(this.firstAutoFloor=Math.min(O,n.firstLevel),this.resetEstimator(N));const $=this.findBestLevel(N,f,O,0,S,1,1);$>-1&&(O=$),this.warn(`Fragment ${s.sn}${r?" part "+r.index:""} of level ${g} is loading too slowly;\n Fragment duration: ${s.duration.toFixed(3)}\n Time to underbuffer: ${S.toFixed(3)} s\n Estimated load time for current fragment: ${P.toFixed(3)} s\n Estimated load time for down switch fragment: ${F.toFixed(3)} s\n TTFB estimate: ${0|b} ms\n Current BW estimate: ${e(L)?0|L:"Unknown"} bps\n New BW estimate: ${0|this.getBwEstimate()} bps\n Switching to level ${O} @ ${0|N} bps`),n.nextLoadLevel=n.nextAutoLevel=O,this.clearTimer();const B=()=>{this.clearTimer();const t=this.hls;if(this.fragCurrent===s&&t.loadLevel===O&&O>0){const e=this.getStarvationDelay();if(this.warn(`Aborting inflight request ${O>0?"and switching down":""}\n Fragment duration: ${s.duration.toFixed(3)} s\n Time to underbuffer: ${e.toFixed(3)} s`),s.abortRequests(),this.fragCurrent=this.partCurrent=null,O>f){let i=this.findBestLevel(t.levels[f].bitrate,f,O,0,e,1,1);-1===i&&(i=f),t.nextLoadLevel=t.nextAutoLevel=i,this.firstAutoFloor=Math.min(i,t.firstLevel),this.resetEstimator(t.levels[i].bitrate)}}};p||P>2*F?B():this.timer=self.setInterval(B,1e3*F),n.trigger(a.FRAG_LOAD_EMERGENCY_ABORTED,{frag:s,part:r,stats:d})},this.hls=t,this.bwEstimator=this.initEstimator(),this.registerListeners()}resetEstimator(t){this.hls&&(t&&(this.log(`setting initial bwe to ${t}`),this.hls.config.abrEwmaDefaultEstimate=t),this.firstSelection=-1,this.bwEstimator=this.initEstimator())}initEstimator(){const t=this.hls.config;return new B(t.abrEwmaSlowVoD,t.abrEwmaFastVoD,t.abrEwmaDefaultEstimate)}registerListeners(){const t=this.hls;t.on(a.MANIFEST_LOADING,this.onManifestLoading,this),t.on(a.FRAG_LOADING,this.onFragLoading,this),t.on(a.FRAG_LOADED,this.onFragLoaded,this),t.on(a.FRAG_BUFFERED,this.onFragBuffered,this),t.on(a.LEVEL_SWITCHING,this.onLevelSwitching,this),t.on(a.LEVEL_LOADED,this.onLevelLoaded,this),t.on(a.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(a.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),t.on(a.ERROR,this.onError,this)}unregisterListeners(){const{hls:t}=this;t&&(t.off(a.MANIFEST_LOADING,this.onManifestLoading,this),t.off(a.FRAG_LOADING,this.onFragLoading,this),t.off(a.FRAG_LOADED,this.onFragLoaded,this),t.off(a.FRAG_BUFFERED,this.onFragBuffered,this),t.off(a.LEVEL_SWITCHING,this.onLevelSwitching,this),t.off(a.LEVEL_LOADED,this.onLevelLoaded,this),t.off(a.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(a.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),t.off(a.ERROR,this.onError,this))}destroy(){this.unregisterListeners(),this.clearTimer(),this.hls=this._abandonRulesCheck=this.supportedCache=null,this.audioTracksByGroup=this.codecTiers=this.fragCurrent=this.partCurrent=null}onManifestLoading(t,e){this.lastLoadedFragLevel=-1,this.firstSelection=-1,this.firstAutoFloor=-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(t,e){const i=e.frag;if(!this.ignoreFragment(i)){var s;if(!i.bitrateTest)this.fragCurrent=i,this.partCurrent=null!=(s=e.part)?s:null;this.clearTimer(),this.timer=self.setInterval(this._abandonRulesCheck,100)}}onLevelSwitching(t,e){this.clearTimer()}onError(t,e){if(!e.fatal)switch(e.details){case n.BUFFER_ADD_CODEC_ERROR:case n.BUFFER_APPEND_ERROR:this.lastLoadedFragLevel=-1,this.firstSelection=-1;break;case n.FRAG_LOAD_TIMEOUT:{const t=e.frag,{fragCurrent:i,partCurrent:s}=this;if(t&&T(t,i)){const e=performance.now(),i=s?s.stats:t.stats,r=e-i.loading.start,n=i.loading.first?i.loading.first-i.loading.start:-1;if(i.loaded&&n>-1){const t=this.bwEstimator.getEstimateTTFB();this.bwEstimator.sample(r-Math.min(t,n),i.loaded)}else this.bwEstimator.sampleTTFB(r)}break}}}getTimeToLoadFrag(t,e,i,s){return t+i/e+(s?t+this.lastLevelLoadSec:0)}onLevelLoaded(t,i){const s=this.hls.config,{loading:r}=i.stats,n=r.end-r.first;e(n)&&(this.lastLevelLoadSec=n/1e3),i.details.live?this.bwEstimator.update(s.abrEwmaSlowLive,s.abrEwmaFastLive):this.bwEstimator.update(s.abrEwmaSlowVoD,s.abrEwmaFastVoD),this.timer>-1&&this._abandonRulesCheck(i.levelInfo)}onFragLoaded(t,e){var i;const{frag:s,part:r}=e,n=r?r.stats:s.stats;if(s.type===f.MAIN&&this.bwEstimator.sampleTTFB(n.loading.first-n.loading.start),!this.ignoreFragment(s)){if(this.clearTimer(),s.level===this._nextAutoLevel&&(this._nextAutoLevel=-1),this.firstSelection=-1,null!=(i=this.hls)&&i.config.abrMaxWithRealBitrate){const t=r?r.duration:s.duration,e=this.hls.levels[s.level],i=(e.loaded?e.loaded.bytes:0)+n.loaded,a=(e.loaded?e.loaded.duration:0)+t;e.loaded={bytes:i,duration:a},e.realBitrate=Math.round(8*i/a)}if(s.bitrateTest){const t={stats:n,frag:s,part:r,id:s.type};this.onFragBuffered(a.FRAG_BUFFERED,t),s.bitrateTest=!1}else this.lastLoadedFragLevel=s.level}}onFragBuffered(t,e){const{frag:i,part:s}=e,r=null!=s&&s.stats.loaded?s.stats:i.stats;if(r.aborted)return;if(this.ignoreFragment(i))return;const n=((i.bitrate||0)>=1e5?r.parsing.end:r.loading.end)-r.loading.start-Math.min(r.loading.first-r.loading.start,this.bwEstimator.getEstimateTTFB());this.bwEstimator.sample(n,r.loaded),r.bwEstimate=this.getBwEstimate(),i.bitrateTest?this.bitrateTestDelay=n/1e3:(this.bitrateTestDelay=0,this.firstAutoFloor>-1&&this.bwEstimator.canEstimate()&&(this.firstAutoFloor=-1))}ignoreFragment(t){return t.type!==f.MAIN||"initSegment"===t.sn}clearTimer(){this.timer>-1&&(self.clearInterval(this.timer),this.timer=-1)}get firstAutoLevel(){const{hls:t}=this;if(!t)return 0;const{maxAutoLevel:e,minAutoLevel:i}=t,s=this.getBwEstimate(),r=this.getStarvationDelay(),n=t.config.maxStarvationDelay,a=this.findBestLevel(s,i,e,r/2,n,1,1);if(a>-1)return a;const o=t.firstLevel,l=-1===this.firstAutoFloor?1/0:this.firstAutoFloor,h=Math.min(Math.max(o,i),e,l);return this.warn(`Could not find best starting auto level. Defaulting to first in playlist ${o} clamped to ${h}`),h}get forcedAutoLevel(){return this.nextAutoLevelKey?-1:this._nextAutoLevel}get nextAutoLevel(){if(!this.hls)return-1;const t=this.forcedAutoLevel,e=this.bwEstimator.canEstimate(),i=this.lastLoadedFragLevel>-1;if(!(-1===t||e&&i&&this.nextAutoLevelKey!==this.getAutoLevelKey()))return t;const s=e&&i?this.getNextABRAutoLevel():this.firstAutoLevel;if(-1!==t){const e=this.hls.levels;if(e.length>Math.max(t,s)&&e[t].loadError<=e[s].loadError)return t}return this._nextAutoLevel=s,this.nextAutoLevelKey=this.getAutoLevelKey(),s}getAutoLevelKey(){return`${this.getBwEstimate()}_${this.getStarvationDelay().toFixed(2)}`}getNextABRAutoLevel(){const{fragCurrent:t,partCurrent:e,hls:i}=this;if(!i)return-1;if(i.levels.length<=1)return i.loadLevel;const{maxAutoLevel:s,config:r,minAutoLevel:n}=i,a=e?e.duration:t?t.duration:0,o=this.getBwEstimate(),l=this.getStarvationDelay();let h=r.abrBandWidthFactor,d=r.abrBandWidthUpFactor;if(l){const t=this.findBestLevel(o,n,s,l,0,h,d);if(t>=0)return this.rebufferNotice=-1,t}let c=a?Math.min(a,r.maxStarvationDelay):r.maxStarvationDelay;if(!l){const t=this.bitrateTestDelay;if(t){c=(a?Math.min(a,r.maxLoadingDelay):r.maxLoadingDelay)-t,this.info(`bitrate test took ${Math.round(1e3*t)}ms, set first fragment max fetchDuration to ${Math.round(1e3*c)} ms`),h=d=1}}const u=this.findBestLevel(o,n,s,l,c,h,d);if(this.rebufferNotice!==u&&(this.rebufferNotice=u,this.info(`${l?"rebuffering expected":"buffer is empty"}, optimal quality level ${u}`)),u>-1)return u;const f=i.levels[n],g=i.loadLevelObj;return g&&(null==f?void 0:f.bitrate)<g.bitrate?n:i.loadLevel}getStarvationDelay(){const t=this.hls,e=null==t?void 0:t.media;if(!e)return 1/0;const i=e&&0!==e.playbackRate?Math.abs(e.playbackRate):1,s=t.mainForwardBufferInfo;return(s?s.len:0)/i}getBwEstimate(){return this.bwEstimator.getEstimate()}findBestLevel(t,i,s,r,n,a,o){const{hls:l,lastLoadedFragLevel:h,fragCurrent:d,partCurrent:c}=this;if(!l)return-1;const u=r+n,f=-1===h?l.firstLevel:h,{levels:g,allAudioTracks:m,loadLevel:p,latestLevelDetails:v,config:y}=l;if(1===g.length)return 0;const E=g[f],T=!(null==v||!v.live),S=-1===p||-1===h;let b,A="SDR",L=(null==E?void 0:E.frameRate)||0;const{audioPreference:I,videoPreference:R}=y,k=this.audioTracksByGroup||(this.audioTracksByGroup=Ke(m));let _=-1;if(S){if(-1!==this.firstSelection)return this.firstSelection;const r=this.codecTiers||(this.codecTiers=function(t,e,i,s){return t.slice(i,s+1).reduce((t,i,s)=>{if(!i.codecSet)return t;const r=i.audioGroups;let n=t[i.codecSet];n||(t[i.codecSet]=n={minBitrate:1/0,minHeight:1/0,minFramerate:1/0,minIndex:s,maxScore:0,videoRanges:{SDR:0},channels:{2:0},hasDefaultAudio:!r,fragmentError:0}),n.minBitrate=Math.min(n.minBitrate,i.bitrate);const a=Math.min(i.height,i.width);return n.minHeight=Math.min(n.minHeight,a),n.minFramerate=Math.min(n.minFramerate,i.frameRate),n.minIndex=Math.min(n.minIndex,s),n.maxScore=Math.max(n.maxScore,i.score),n.fragmentError+=i.fragmentError,n.videoRanges[i.videoRange]=(n.videoRanges[i.videoRange]||0)+1,r&&r.forEach(t=>{if(!t)return;const i=e.groups[t];i&&(n.hasDefaultAudio=n.hasDefaultAudio||e.hasDefaultAudio?i.hasDefault:i.hasAutoSelect||!e.hasDefaultAudio&&!e.hasAutoSelectAudio,Object.keys(i.channels).forEach(t=>{n.channels[t]=(n.channels[t]||0)+i.channels[t]}))}),t},{})}(g,k,i,s)),n=function(t,i,s,r,n){const a=Object.keys(t),o=null==r?void 0:r.channels,l=null==r?void 0:r.audioCodec,h=null==n?void 0:n.videoCodec,d=o&&2===parseInt(o);let c=!1,u=!1,f=1/0,g=1/0,m=1/0,p=1/0,v=0,y=[];const{preferHDR:E,allowedVideoRanges:T}=Be(i,n);for(let e=a.length;e--;){const i=t[a[e]];c||(c=i.channels[2]>0),f=Math.min(f,i.minHeight),g=Math.min(g,i.minFramerate),m=Math.min(m,i.minBitrate),T.filter(t=>i.videoRanges[t]>0).length>0&&(u=!0)}f=e(f)?f:0,g=e(g)?g:0;const S=Math.max(1080,f),b=Math.max(30,g);m=e(m)?m:s,s=Math.max(m,s),u||(i=void 0);const A=a.length>1;return{codecSet:a.reduce((e,i)=>{const r=t[i];if(i===e)return e;if(y=u?T.filter(t=>r.videoRanges[t]>0):[],A){if(r.minBitrate>s)return Ge(i,`min bitrate of ${r.minBitrate} > current estimate of ${s}`),e;if(!r.hasDefaultAudio)return Ge(i,"no renditions with default or auto-select sound found"),e;if(l&&i.indexOf(l.substring(0,4))%5!=0)return Ge(i,`audio codec preference "${l}" not found`),e;if(o&&!d){if(!r.channels[o])return Ge(i,`no renditions with ${o} channel sound found (channels options: ${Object.keys(r.channels)})`),e}else if((!l||d)&&c&&0===r.channels[2])return Ge(i,"no renditions with stereo sound found"),e;if(r.minHeight>S)return Ge(i,`min resolution of ${r.minHeight} > maximum of ${S}`),e;if(r.minFramerate>b)return Ge(i,`min framerate of ${r.minFramerate} > maximum of ${b}`),e;if(!y.some(t=>r.videoRanges[t]>0))return Ge(i,`no variants with VIDEO-RANGE of ${Ue(y)} found`),e;if(h&&i.indexOf(h.substring(0,4))%5!=0)return Ge(i,`video codec preference "${h}" not found`),e;if(r.maxScore<v)return Ge(i,`max score of ${r.maxScore} < selected max of ${v}`),e}return e&&(fe(i)>=fe(e)||r.fragmentError>t[e].fragmentError)?e:(p=r.minIndex,v=r.maxScore,i)},void 0),videoRanges:y,preferHDR:E,minFramerate:g,minBitrate:m,minIndex:p}}(r,A,t,I,R),{codecSet:a,videoRanges:o,minFramerate:l,minBitrate:h,minIndex:d,preferHDR:c}=n;_=d,b=a,A=c?o[o.length-1]:o[0],L=l,t=Math.max(t,h),this.log(`picked start tier ${Ue(n)}`)}else b=null==E?void 0:E.codecSet,A=null==E?void 0:E.videoRange;const D=c?c.duration:d?d.duration:0,w=this.bwEstimator.getEstimateTTFB()/1e3,P=[];for(let l=s;l>=i;l--){var C;const i=g[l],d=l>f;if(!i)continue;if(y.useMediaCapabilities&&!i.supportedResult&&!i.supportedPromise){const e=navigator.mediaCapabilities;"function"==typeof(null==e?void 0:e.decodingInfo)&&Ie(i,k,A,L,t,I)?(i.supportedPromise=Re(i,k,e,this.supportedCache),i.supportedPromise.then(t=>{if(!this.hls)return;i.supportedResult=t;const e=this.hls.levels,s=e.indexOf(i);t.error?this.warn(`MediaCapabilities decodingInfo error: "${t.error}" for level ${s} ${Ue(t)}`):t.supported?t.decodingInfoResults.some(t=>!1===t.smooth||!1===t.powerEfficient)&&this.log(`MediaCapabilities decodingInfo for level ${s} not smooth or powerEfficient: ${Ue(t)}`):(this.warn(`Unsupported MediaCapabilities decodingInfo result for level ${s} ${Ue(t)}`),s>-1&&e.length>1&&(this.log(`Removing unsupported level ${s}`),this.hls.removeLevel(s),-1===this.hls.loadLevel&&(this.hls.nextLoadLevel=0)))}).catch(t=>{this.warn(`Error handling MediaCapabilities decodingInfo: ${t}`)})):i.supportedResult=Ae}if((b&&i.codecSet!==b||A&&i.videoRange!==A||d&&L>i.frameRate||!d&&L>0&&L<i.frameRate||null!=(C=i.supportedResult)&&null!=(C=C.decodingInfoResults)&&C.some(t=>!1===t.smooth))&&(!S||l!==_)){P.push(l);continue}const m=i.details,v=(c?null==m?void 0:m.partTarget:null==m?void 0:m.averagetargetduration)||D||1;let E;E=d?o*t:a*t;const R=D&&r>=2*D&&0===n?i.averageBitrate:i.maxBitrate,x=this.getTimeToLoadFrag(w,E,R*v,!m||m.live);if(E>=R&&(l===h||0===i.loadError&&0===i.fragmentError||N(i,y.errorPenaltyExpireMs))&&(x<=w||!e(x)||T&&!this.bitrateTestDelay||x<u)){const t=this.forcedAutoLevel;return l===p||-1!==t&&t===p||(P.length&&this.trace(`Skipped level(s) ${P.join(",")} of ${s} max with CODECS and VIDEO-RANGE:"${g[P[0]].codecs}" ${g[P[0]].videoRange}; not compatible with "${b}" ${A}`),this.info(`switch candidate:${f}->${l} adjustedbw(${Math.round(E)})-bitrate=${Math.round(E-R)} ttfb:${w.toFixed(1)} avgDuration:${v.toFixed(1)} maxFetchDuration:${u.toFixed(1)} fetchDuration:${x.toFixed(1)} firstSelection:${S} codecSet:${i.codecSet} videoRange:${i.videoRange} hls.loadLevel:${p}`)),S&&(this.firstSelection=l),l}}return-1}set nextAutoLevel(t){const e=this.deriveNextAutoLevel(t);this._nextAutoLevel!==e&&(this.nextAutoLevelKey="",this._nextAutoLevel=e)}deriveNextAutoLevel(t){if(!this.hls)return-1;const{maxAutoLevel:e,minAutoLevel:i}=this.hls;return Math.min(Math.max(t,i),e)}},bufferController:class extends U{constructor(t,e){var i;super("buffer-controller",t.logger),this.hls=void 0,this.fragmentTracker=void 0,this.fragmentAppendProgress=Object.create(null),this.appendsWithoutProgress=Object.create(null),this.details=null,this._objectUrl=null,this.operationQueue=null,this.bufferCodecEventsTotal=0,this.media=null,this.mediaSource=null,this.lastMpegAudioChunk=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.appendError=void 0,this._quotaEvictionPending={},this.tracks={},this.sourceBuffers=[[null,null],[null,null]],this._onEndStreaming=t=>{var e;this.hls&&"open"===(null==(e=this.mediaSource)?void 0:e.readyState)&&this.media&&!this.media.seeking&&this.hls.pauseBuffering()},this._onStartStreaming=t=>{this.hls&&this.hls.resumeBuffering()},this._onMediaSourceOpen=t=>{const{media:e,mediaSource:i}=this;t&&this.log("Media source opened"),e&&i&&(ir(i,"sourceopen",this._onMediaSourceOpen),ir(e,"emptied",this._onMediaEmptied),this.updateDuration(),this.hls.trigger(a.MEDIA_ATTACHED,{media:e,mediaSource:i}),null!==this.mediaSource&&this.checkPendingTracks())},this._onMediaSourceClose=()=>{if(this.log("Media source closed"),this.media){const t=this.media.error,{appendError:e,appendErrors:i}=this;let s=!1;if(!e&&t){s=Math.max(++i.audio,++i.video,++i.audiovideo)>=this.hls.config.appendErrorMaxRetry}const o=new Error(`MediaSource closed while media attached${ta(s,t)}`);this.warn(o),this.hls.trigger(a.ERROR,I({fatal:s},e,{type:r.MEDIA_ERROR,details:n.MEDIA_SOURCE_REQUIRES_RESET,error:o}))}},this._onMediaSourceEnded=()=>{this.log("Media source ended")},this._onMediaEmptied=()=>{const{mediaSrc:t,_objectUrl:e}=this;t!==e&&this.error(`Media element src was set while attaching MediaSource (${e} > ${t})`)},this._onMediaError=()=>{const{media:t}=this;var e,i;t&&this.log(`Media error (code: ${null==(e=t.error)?void 0:e.code}): ${null==(i=t.error)?void 0:i.message}`)},this.hls=t,this.fragmentTracker=e,this.appendSource=(i=Y(t.config.preferManagedMediaSource),"undefined"!=typeof self&&i===self.ManagedMediaSource),this.initTracks(),this.registerListeners()}hasSourceTypes(){return Object.keys(this.tracks).length>0}destroy(){this.unregisterListeners(),this.details=null,this.lastMpegAudioChunk=null,this.transferData=this.overrides=void 0,this.operationQueue&&(this.operationQueue.destroy(),this.operationQueue=null),this.hls=this.fragmentTracker=null,this._onMediaSourceOpen=this._onMediaSourceClose=null,this._onMediaSourceEnded=null,this._onStartStreaming=this._onEndStreaming=null,this._onMediaEmptied=this._onMediaError=null}registerListeners(){const{hls:t}=this;t.on(a.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(a.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(a.MANIFEST_LOADING,this.onManifestLoading,this),t.on(a.MANIFEST_PARSED,this.onManifestParsed,this),t.on(a.BUFFER_RESET,this.onBufferReset,this),t.on(a.BUFFER_APPENDING,this.onBufferAppending,this),t.on(a.BUFFER_CODECS,this.onBufferCodecs,this),t.on(a.BUFFER_EOS,this.onBufferEos,this),t.on(a.BUFFER_FLUSHING,this.onBufferFlushing,this),t.on(a.LEVEL_UPDATED,this.onLevelUpdated,this),t.on(a.FRAG_PARSED,this.onFragParsed,this),t.on(a.FRAG_CHANGED,this.onFragChanged,this),t.on(a.ERROR,this.onError,this)}unregisterListeners(){const{hls:t}=this;t.off(a.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(a.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(a.MANIFEST_LOADING,this.onManifestLoading,this),t.off(a.MANIFEST_PARSED,this.onManifestParsed,this),t.off(a.BUFFER_RESET,this.onBufferReset,this),t.off(a.BUFFER_APPENDING,this.onBufferAppending,this),t.off(a.BUFFER_CODECS,this.onBufferCodecs,this),t.off(a.BUFFER_EOS,this.onBufferEos,this),t.off(a.BUFFER_FLUSHING,this.onBufferFlushing,this),t.off(a.LEVEL_UPDATED,this.onLevelUpdated,this),t.off(a.FRAG_PARSED,this.onFragParsed,this),t.off(a.FRAG_CHANGED,this.onFragChanged,this),t.off(a.ERROR,this.onError,this)}transferMedia(){const{media:t,mediaSource:e}=this;if(!t)return null;const i={};if(this.operationQueue){const t=this.isUpdating();t||this.operationQueue.removeBlockers();const e=this.isQueued();(t||e)&&this.warn(`Transfering MediaSource with${e?" operations in queue":""}${t?" updating SourceBuffer(s)":""} ${this.operationQueue}`),this.operationQueue.destroy()}const s=this.transferData;return s&&!this.sourceBufferCount&&s.mediaSource===e?I(i,s.tracks):this.sourceBuffers.forEach(t=>{const[e]=t;e&&(i[e]=I({},this.tracks[e]),this.removeBuffer(e)),t[0]=t[1]=null}),{media:t,mediaSource:e,tracks:i}}initTracks(){this.resetAppendProgress(),this.sourceBuffers=[[null,null],[null,null]],this.tracks={},this.resetQueue(),this.lastMpegAudioChunk=null,this.lastVideoAppendEnd=0}onManifestLoading(){this.bufferCodecEventsTotal=0,this.details=null,this.resetAppendErrors(),this.resetAppendProgress()}onManifestParsed(t,e){var i;let s=2;(e.audio&&!e.video||!e.altAudio)&&(s=1),this.bufferCodecEventsTotal=s,this.log(`${s} bufferCodec event(s) expected.`),null!=(i=this.transferData)&&i.mediaSource&&this.sourceBufferCount&&s&&this.bufferCreated()}onMediaAttaching(t,e){const i=this.media=e.media;this.transferData=this.overrides=void 0;const s=Y(this.appendSource);if(s){const t=!!e.mediaSource;(t||e.overrides)&&(this.transferData=e,this.overrides=e.overrides);const r=this.mediaSource=e.mediaSource||new s;if(this.assignMediaSource(r),t)this._objectUrl=i.src,this.attachTransferred();else{const t=this._objectUrl=self.URL.createObjectURL(r);if(this.appendSource)try{i.removeAttribute("src");const e=self.ManagedMediaSource;i.disableRemotePlayback=i.disableRemotePlayback||e&&r instanceof e,Zn(i),function(t,e){const i=self.document.createElement("source");i.type="video/mp4",i.src=e,t.appendChild(i)}(i,t),i.load()}catch(e){i.src=t}else i.src=t}er(i,"emptied",this._onMediaEmptied),er(i,"error",this._onMediaError),this.appendSource&&er(i,"seeking",this._onStartStreaming)}}assignMediaSource(t){var e,i;this.log(`${(null==(e=this.transferData)?void 0:e.mediaSource)===t?"transferred":"created"} media source: ${null==(i=t.constructor)?void 0:i.name}`),er(t,"sourceopen",this._onMediaSourceOpen),er(t,"sourceended",this._onMediaSourceEnded),er(t,"sourceclose",this._onMediaSourceClose),this.appendSource&&(er(t,"startstreaming",this._onStartStreaming),er(t,"endstreaming",this._onEndStreaming))}attachTransferred(){const t=this.media,e=this.transferData;if(!e||!t)return;const i=this.tracks,s=e.tracks,r=s?Object.keys(s):null,n=r?r.length:0,o=()=>{Promise.resolve().then(()=>{this.media&&this.mediaSourceOpenOrEnded&&this._onMediaSourceOpen()})};if(s&&r&&n){if(!this.tracksReady)return this.hls.config.startFragPrefetch=!0,void this.log("attachTransferred: waiting for SourceBuffer track info");if(this.log(`attachTransferred: (bufferCodecEventsTotal ${this.bufferCodecEventsTotal})\nrequired tracks: ${Ue(i,(t,e)=>"initSegment"===t?void 0:e)};\ntransfer tracks: ${Ue(s,(t,e)=>"initSegment"===t?void 0:e)}}`),!W(s,i)){e.mediaSource=null,e.tracks=void 0;const r=t.currentTime,n=this.details,o=Math.max(r,(null==n?void 0:n.fragments[0].start)||0);return o-r>1?void this.log(`attachTransferred: waiting for playback to reach new tracks start time ${r} -> ${o}`):(this.warn(`attachTransferred: resetting MediaSource for incompatible tracks ("${Object.keys(s)}"->"${Object.keys(i)}") start time: ${o} currentTime: ${r}`),this.onMediaDetaching(a.MEDIA_DETACHING,{}),this.onMediaAttaching(a.MEDIA_ATTACHING,e),void(t.currentTime=o))}this.transferData=void 0,r.forEach(t=>{const e=t,i=s[e];if(i){const t=i.buffer;if(t){const s=this.fragmentTracker,r=i.id;if(s.hasFragments(r)||s.hasParts(r)){const i=Bi.getBuffered(t);s.detectEvictedFragments(e,i,r,null,null,!0)}const n=Jn(e),a=[e,t];this.sourceBuffers[n]=a,t.updating&&this.operationQueue&&this.operationQueue.prependBlocker(e),this.trackSourceBuffer(e,i)}}}),o(),this.bufferCreated()}else this.log("attachTransferred: MediaSource w/o SourceBuffers"),o()}get mediaSourceOpenOrEnded(){var t;const e=null==(t=this.mediaSource)?void 0:t.readyState;return"open"===e||"ended"===e}onMediaDetaching(t,e){const i=!!e.transferMedia;this.transferData=this.overrides=void 0;const{media:s,mediaSource:r,_objectUrl:n}=this;if(r){if(this.log("media source "+(i?"transferring":"detaching")),i)this.sourceBuffers.forEach(([t])=>{t&&this.removeBuffer(t)}),this.resetQueue();else{if(this.mediaSourceOpenOrEnded){const t="open"===r.readyState;try{const e=r.sourceBuffers;for(let i=e.length;i--;)t&&e[i].abort(),r.removeSourceBuffer(e[i]);t&&r.endOfStream()}catch(t){this.warn(`onMediaDetaching: ${t.message} while calling endOfStream`)}}this.sourceBufferCount&&this.onBufferReset()}ir(r,"sourceopen",this._onMediaSourceOpen),ir(r,"sourceended",this._onMediaSourceEnded),ir(r,"sourceclose",this._onMediaSourceClose),this.appendSource&&(ir(r,"startstreaming",this._onStartStreaming),ir(r,"endstreaming",this._onEndStreaming)),this.mediaSource=null,this._objectUrl=null}s&&(ir(s,"emptied",this._onMediaEmptied),ir(s,"error",this._onMediaError),ir(s,"seeking",this._onStartStreaming),i||(n&&self.URL.revokeObjectURL(n),this.mediaSrc===n?(s.removeAttribute("src"),this.appendSource&&Zn(s),s.load()):this.warn("media|source.src was changed by a third party - skip cleanup")),this.media=null)}onBufferReset(){this.sourceBuffers.forEach(([t])=>{t&&this.resetBuffer(t)}),this.initTracks()}resetBuffer(t){var e;const i=null==(e=this.tracks[t])?void 0:e.buffer;if(this.removeBuffer(t),i)try{var s;null!=(s=this.mediaSource)&&s.sourceBuffers.length&&this.mediaSource.removeSourceBuffer(i)}catch(e){this.warn(`onBufferReset ${t}`,e)}delete this.tracks[t]}removeBuffer(t){this.removeBufferListeners(t),this.sourceBuffers[Jn(t)]=[null,null];const e=this.tracks[t];e&&(this.clearBufferAppendTimeoutId(e),e.buffer=void 0)}resetQueue(){this.operationQueue&&this.operationQueue.destroy(),this.operationQueue=new Wn(this.tracks)}onBufferCodecs(t,e){var i;const s=this.tracks,r=Object.keys(e);this.log(`BUFFER_CODECS: "${r}" (current SB count ${this.sourceBufferCount})`);const n="audiovideo"in e&&(s.audio||s.video)||s.audiovideo&&("audio"in e||"video"in e),a=!n&&this.sourceBufferCount&&this.media&&r.some(t=>!s[t]);n||a?this.warn(`Unsupported transition between "${Object.keys(s)}" and "${r}" SourceBuffers`):(r.forEach(t=>{var i,r;const n=e[t],{id:a,codec:o,levelCodec:l,container:h,metadata:d,supplemental:c}=n;let u=s[t];const f=null==(i=this.transferData)||null==(i=i.tracks)?void 0:i[t],g=null!=f&&f.buffer?f:u,m=(null==g?void 0:g.pendingCodec)||(null==g?void 0:g.codec),p=null==g?void 0:g.levelCodec;u||(u=s[t]={buffer:void 0,listeners:[],codec:o,supplemental:c,container:h,levelCodec:l,metadata:d,id:a});const v=ve(m,p),y=null==v?void 0:v.replace(zn,"$1");let E=ve(o,l);const T=null==(r=E)?void 0:r.replace(zn,"$1");E&&v&&y!==T&&("audio"===t.slice(0,5)&&(E=pe(E,this.appendSource)),this.log(`switching codec ${m} to ${E}`),E!==(u.pendingCodec||u.codec)&&(u.pendingCodec=E),u.container=h,this.appendChangeType(t,h,E))}),(this.tracksReady||this.sourceBufferCount)&&(e.tracks=this.sourceBufferTracks),this.sourceBufferCount||(this.bufferCodecEventsTotal>1&&!this.tracks.video&&!e.video&&"main"===(null==(i=e.audio)?void 0:i.id)&&(this.log("Main audio-only"),this.bufferCodecEventsTotal=1),this.mediaSourceOpenOrEnded&&this.checkPendingTracks()))}get sourceBufferTracks(){return Object.keys(this.tracks).reduce((t,e)=>{const i=this.tracks[e];return t[e]={id:i.id,container:i.container,codec:i.codec,levelCodec:i.levelCodec},t},{})}appendChangeType(t,e,i){const s=`${e};codecs=${i}`,r={label:`change-type=${s}`,execute:()=>{const r=this.tracks[t];if(r){const n=r.buffer;null!=n&&n.changeType&&(this.log(`changing ${t} sourceBuffer type to ${s}`),n.changeType(s),r.codec=i,r.container=e)}this.shiftAndExecuteNext(t)},onStart:()=>{},onComplete:()=>{},onError:e=>{this.warn(`Failed to change ${t} SourceBuffer type`,e)}};this.append(r,t,this.isPending(this.tracks[t]))}blockAudio(t){var e;const i=t.start,s=i+.05*t.duration;if(!0===(null==(e=this.fragmentTracker.getAppendedFrag(i,f.MAIN))?void 0:e.gap))return;const r={label:"block-audio",execute:()=>{var t,e;(this.lastVideoAppendEnd>s||Bi.isBuffered(null==(t=this.tracks.video)?void 0:t.buffer,s)||!0===(null==(e=this.fragmentTracker.getAppendedFrag(s,f.MAIN))?void 0:e.gap))&&this.unblockAudio()},onStart:()=>{},onComplete:()=>{},onError:t=>{this.warn("Error executing block-audio operation",t)}};this.append(r,"audio",!0)}unblockAudio(){this.operationQueue&&this.operationQueue.unblockAudio()}onBufferAppending(t,i){const{tracks:s}=this,{data:o,type:l,parent:h,frag:d,part:c,chunkMeta:u,offset:f}=i,g=u.buffering[l],m=y(d)&&!c&&!d.gap&&!u.partial&&!u.iframe;let p=null,v=!1;const{sn:E,cc:T}=d,S=self.performance.now();g.start=S;const b=d.stats.buffering,A=c?c.stats.buffering:null;0===b.start&&(b.start=S),0===(null==A?void 0:A.start)&&(A.start=S);const L=s.audio;let I=!1;"audio"===l&&"audio/mpeg"===(null==L?void 0:L.container)&&(I=!this.lastMpegAudioChunk||1===u.id||this.lastMpegAudioChunk.sn!==u.sn,this.lastMpegAudioChunk=u);const R=s.video,k=null==R?void 0:R.buffer;if(k&&"initSegment"!==E&&void 0!==f){const t=null==L?void 0:L.buffer,e=c||d;if("audio"===l&&"main"!==h&&!R.ending&&!R.ended&&t&&Bi.getBuffered(t).length){const t=e.start+.05*e.duration,i=Bi.getBuffered(k),s=this.currentOp("video");i.length||s?!Bi.isBuffered(k,t)&&this.lastVideoAppendEnd<t&&this.blockAudio(e):this.blockAudio(e)}else if("video"===l){const t=e.end,i=this.lastVideoAppendEnd-t;this.lastVideoAppendEnd=t,i<0||i>e.duration?this.unblockAudio():this.isAudioBlocked()&&this.executeNext("audio")}}const _=(c||d).start,D={label:`append-${l}`,execute:()=>{var t;g.executeStart=self.performance.now();const i=null==(t=this.tracks[l])?void 0:t.buffer;i&&(m&&(p=Bi.timeRangesToArray(Bi.getBuffered(i)),v=sa(ia(p,d),d)),I?this.updateTimestampOffset(i,_,.1,l,E,T):void 0!==f&&e(f)&&this.updateTimestampOffset(i,f,1e-6,l,E,T)),this.appendExecutor(o,l)},onStart:()=>{},onComplete:()=>{this.clearBufferAppendTimeoutId(this.tracks[l]);const t=self.performance.now();g.executeEnd=g.end=t,0===b.first&&(b.first=t),0===(null==A?void 0:A.first)&&(A.first=t);const e={};if(this.sourceBuffers.forEach(([t,i])=>{t&&(e[t]=Bi.getBuffered(i))}),m){const t=this.getFragmentAppendProgress(d),i=e[l];if(i&&p){const e=ia(Bi.timeRangesToArray(i),d);t.progressed||(t.progressed=e-ia(p,d)>.001);const s=v&&sa(e,d);t.fullyBuffered[l]=(void 0===t.fullyBuffered[l]||t.fullyBuffered[l])&&s}}this.hls.trigger(a.BUFFER_APPENDED,{type:l,frag:d,part:c,chunkMeta:u,parent:h,timeRanges:e})},onError:t=>{var e;this.clearBufferAppendTimeoutId(this.tracks[l]);const i=t.code===DOMException.QUOTA_EXCEEDED_ERR||"QuotaExceededError"==t.name||"quota"in t;if(i&&!this._quotaEvictionPending[l]){const t=this.getBackBufferEvictionTarget(l,o.byteLength,d.type);if(t>0){this._quotaEvictionPending[l]=!0,this.log(`QuotaExceededError on "${l}" append sn: ${E} - evicting back buffer to ${t.toFixed(3)}s and retrying`);const e=this.getFlushOp(l,0,t),i=this.getClearEvictionPendingOp(l);return void this.insertNext([e,D,i],l)}this.warn(`QuotaExceededError on "${l}" sn: ${E} - no back buffer available to evict`)}m&&(this.getFragmentAppendProgress(d).errored=!0);const s={type:r.MEDIA_ERROR,parent:h,details:n.BUFFER_APPEND_ERROR,sourceBufferName:l,frag:d,part:c,chunkMeta:u,error:t,err:t,fatal:!1},f=null==(e=this.media)?void 0:e.error;if(t.name!==Xn||0!==this.sourceBufferCount||this.media&&0!==this.pendingTrackCount){var g;i&&(s.details=n.BUFFER_FULL_ERROR);const e=++this.appendErrors[l],r=this.hls.config.appendErrorMaxRetry;this.warn(`Failed ${e}/${r+1} times to append segment in "${l}" sourceBuffer with error: ${t.message}`),e>=r&&(s.fatal=!i);const a=null==(g=this.mediaSource)?void 0:g.readyState;("ended"===a||"closed"===a||f)&&(this.warn(`MediaSource readyState "${a}" during SourceBuffer${ta(s.fatal,f)}`),s.details=n.MEDIA_SOURCE_REQUIRES_RESET)}else s.errorAction=mi(!0);this.appendError=s,this.hls.trigger(a.ERROR,s),i&&this.hls&&this.trimBuffers(d.start,1)}};this.log(`queuing "${l}" append sn: ${E}${c?" p: "+c.index:""} of ${h} playlist ${d.level} cc: ${T} offset: ${f} bytes: ${o.byteLength}`),this.append(D,l,this.isPending(this.tracks[l]))}getClearEvictionPendingOp(t){return{label:"clear",execute:()=>{this._quotaEvictionPending[t]=!1,this.shiftAndExecuteNext(t)},onStart:()=>{},onComplete:()=>{},onError:()=>{}}}getFlushOp(t,e,i){return this.log(`queuing "${t}" remove ${e}-${i}`),{label:"remove",execute:()=>{this.removeExecutor(t,e,i)},onStart:()=>{},onComplete:()=>{var s;const r=null==(s=this.tracks[t])?void 0:s.buffer;this.log(`Remove request ${e}-${i} from ${t} Source Buffer complete > buffer: ${r?sr(Bi.getBuffered(r)):"(detached)"}`),this.hls.trigger(a.BUFFER_FLUSHED,{type:t,start:e,end:i})},onError:s=>{this.warn(`Failed to remove ${e}-${i} from "${t}" SourceBuffer`,s),this.hls.trigger(a.BUFFER_FLUSHED,{type:t,start:0,end:0,error:s})}}}onBufferFlushing(t,e){const{type:i,startOffset:s,endOffset:r}=e;i&&"audio"!==i||this.unblockAudio(),i?this.append(this.getFlushOp(i,s,r),i):this.sourceBuffers.forEach(([t])=>{t&&this.append(this.getFlushOp(t,s,r),t)})}onFragParsed(t,e){const{frag:i,part:s,chunkMeta:r}=e,n=[],o=s?s.elementaryStreams:i.elementaryStreams;o[p]?n.push("audiovideo"):(o[g]&&n.push("audio"),o[m]&&n.push("video"));0===n.length&&this.log(`Fragments must have at least one ElementaryStreamType set. ${i.type} ${i.level} ${s?`part: ${s.index} of `:""}sn: ${i.sn}`),this.blockBuffers(()=>{const t=self.performance.now();i.stats.buffering.end=t,s&&(s.stats.buffering.end=t);const e=s?s.stats:i.stats;this.checkAppendProgress(i,s,r,n),this.hls&&(this.hls.trigger(a.FRAG_BUFFERED,{frag:i,part:s,stats:e,id:i.type,chunkMeta:r}),!s&&i.gap&&e.retry&&this.log(`Nothing buffered for ${i.type} level: ${i.level} sn: ${i.sn} retries ${e.retry}`))},n).catch(t=>{this.warn(`Fragment buffered callback ${t.message}`),this.stepOperationQueue(this.sourceBufferTypes)})}onFragChanged(t,e){var i,s;const r=null==(i=this.hls)?void 0:i.config;if(!r)return;const{backBufferLength:n,frontBufferFlushThreshold:a}=r;this.trimBuffers(a,n,e.frag,e.previousFrag);const o=e.frag.elementaryStreams,{appendErrors:l}=this,h=null==(s=this.appendError)?void 0:s.sourceBufferName;Object.keys(o).forEach(t=>{o[t]&&(l[t]=0,t===h&&(this.appendError=void 0),"audio"===t||"video"===t?(l.audiovideo=0,"audiovideo"===h&&(this.appendError=void 0)):(l.audio=0,l.video=0,"audiovideo"!==h&&(this.appendError=void 0)))})}get bufferedToEnd(){return this.sourceBufferCount>0&&!this.sourceBuffers.some(([t])=>{if(t){const e=this.tracks[t];if(e)return!e.ended||e.ending}return!1})}onBufferEos(t,e){var i;this.sourceBuffers.forEach(([t])=>{if(t){const i=this.tracks[t];e.type&&e.type!==t||(i.ending=!0,i.ended||(i.ended=!0,this.log(`${t} buffer reached EOS`)))}});const s=!1!==(null==(i=this.overrides)?void 0:i.endOfStream);this.sourceBufferCount>0&&!this.sourceBuffers.some(([t])=>{var e;return t&&!(null!=(e=this.tracks[t])&&e.ended)})?(this.unblockAudio(),s?(this.log("Queueing EOS"),this.blockUntilOpen(()=>{this.tracksEnded();const{mediaSource:t}=this;"open"===(null==t?void 0:t.readyState)?(this.log("Calling mediaSource.endOfStream()"),t.endOfStream(),this.hls.trigger(a.BUFFERED_TO_END,void 0)):t&&this.log(`Could not call mediaSource.endOfStream(). mediaSource.readyState: ${t.readyState}`)})):(this.tracksEnded(),this.hls.trigger(a.BUFFERED_TO_END,void 0))):"video"===e.type&&this.unblockAudio()}tracksEnded(){this.sourceBuffers.forEach(([t])=>{if(null!==t){const e=this.tracks[t];e&&(e.ending=!1)}})}onLevelUpdated(t,{details:e}){e.fragments.length&&(this.details=e,this.updateDuration())}updateDuration(){this.blockUntilOpen(()=>{const t=this.getDurationAndRange();t&&this.updateMediaSource(t)})}onError(t,i){if(i.details===n.BUFFER_APPEND_ERROR&&i.frag){var s;const t=null==(s=i.errorAction)?void 0:s.nextAutoLevel;e(t)&&t!==i.frag.level&&this.resetAppendErrors()}}getBackBufferEvictionTarget(t,e,i){const{media:s}=this;return s?this.fragmentTracker.getBackBufferEvictionEnd(s.currentTime,i,e):0}getFragmentAppendProgress(t){var e;const i=ea(t);let s=this.fragmentAppendProgress[i];return(null==(e=s)?void 0:e.stats)!==t.stats&&(s={stats:t.stats,progressed:!1,errored:!1,fullyBuffered:Object.create(null)},this.fragmentAppendProgress[i]=s),s}checkAppendProgress(t,e,i,s){if(e||!y(t)||t.gap||i.iframe||i.partial)return;const o=ea(t),l=this.fragmentAppendProgress[o];delete this.fragmentAppendProgress[o];const h=t.stats.buffering;if(h.start&&!h.first)return;const d=(null==l?void 0:l.stats)===t.stats?l:void 0;if(null!=d&&d.errored)return;const c=s.length>0&&s.every(t=>!0===(null==d?void 0:d.fullyBuffered[t]));if(null!=d&&d.progressed||c)return void delete this.appendsWithoutProgress[o];if(!d&&0===s.length)return;const u=(this.appendsWithoutProgress[o]||0)+1,f=this.hls;u>=f.config.appendErrorMaxRetry?delete this.appendsWithoutProgress[o]:this.appendsWithoutProgress[o]=u,this.warn(`Fragment ${t.sn} of ${t.type} playlist ${t.level} appended ${u} time${u>1?"s":""} without buffered range growth`),f.trigger(a.ERROR,{type:r.MEDIA_ERROR,details:n.BUFFER_APPEND_NO_PROGRESS,fatal:!1,frag:t,chunkMeta:i,parent:t.type,appendsWithoutProgress:u,error:new Error(`Fragment append did not increase buffered coverage (${u})`)})}resetAppendProgress(){this.fragmentAppendProgress=Object.create(null),this.appendsWithoutProgress=Object.create(null)}resetAppendErrors(){this.appendErrors={audio:0,video:0,audiovideo:0},this.appendError=void 0}trimBuffers(t,i,s,r){const{hls:n,details:a,media:o}=this;if(!o||null===a)return;if(!this.sourceBufferCount)return;const l=n.config,h=o.currentTime,d=a.levelTargetDuration;i=a.live&&null!==l.liveBackBufferLength?l.liveBackBufferLength:i;let c=-1/0;if(e(i)&&i>=0){const t=Math.max(i,d);c=Math.floor(h/d)*d-t}if(s){const t=this.getLoopBackBufferFlushEnd(s,null!=r?r:null);t>0&&(c=Math.max(c,t))}if(c>0&&this.flushBackBuffer(h,d,c),e(t)&&t>0){const e=Math.max(l.maxBufferLength,t),i=Math.max(e,d),s=Math.floor(h/d)*d+i;this.flushFrontBuffer(h,d,s)}}getLoopBackBufferFlushEnd(t,e){var i;const{media:s}=this;if(!1===(null==(i=this.hls)?void 0:i.config.loopBackBufferFlush)||null==s||!s.loop||!e||t.level<=e.level)return 0;const{video:r,audiovideo:n}=t.elementaryStreams;if(null!=r&&r.partial||null!=n&&n.partial)return 0;const a=this.getEarliestElementaryStreamStart(t)-.25;return a<=0?0:(this.log(`Flushing lower quality back buffer for loop: level ${t.level}, range [0-${a.toFixed(3)}]`),a)}getEarliestElementaryStreamStart(t){const{audio:e,video:i,audiovideo:s}=t.elementaryStreams;let r=t.start;return s?r=Math.min(r,s.startDTS):(e&&(r=Math.min(r,e.startDTS)),i&&(r=Math.min(r,i.startDTS))),r}flushBackBuffer(t,e,i){this.sourceBuffers.forEach(([t,e])=>{if(e){const o=Bi.getBuffered(e);if(o.length>0&&i>o.start(0)){var s,r,n;this.hls.trigger(a.BACK_BUFFER_REACHED,{bufferEnd:i});const e=this.tracks[t];if(null!=(s=this.details)&&s.live)this.hls.trigger(a.LIVE_BACK_BUFFER_REACHED,{bufferEnd:i});else if(null!=e&&e.ended&&(null==(r=this.media)||!r.loop||!1===(null==(n=this.hls)?void 0:n.config.loopBackBufferFlush)))return void this.log(`Cannot flush ${t} back buffer while SourceBuffer is in ended state`);this.hls.trigger(a.BUFFER_FLUSHING,{startOffset:0,endOffset:i,type:t})}}})}flushFrontBuffer(t,e,i){this.sourceBuffers.forEach(([e,s])=>{if(s){const r=Bi.getBuffered(s),n=r.length;if(n<2)return;const o=r.start(n-1),l=r.end(n-1);if(i>o||t>=o&&t<=l)return;this.hls.trigger(a.BUFFER_FLUSHING,{startOffset:o,endOffset:1/0,type:e})}})}getDurationAndRange(){var t;const{details:i,mediaSource:s}=this;if(!i||!this.media||"open"!==(null==s?void 0:s.readyState))return null;const r=i.edge;if(i.live&&this.hls.config.liveDurationInfinity){if(i.fragments.length&&s.setLiveSeekableRange){const t=Math.max(0,i.fragmentStart);return{duration:1/0,start:t,end:Math.max(t,r)}}return{duration:1/0}}const n=null==(t=this.overrides)?void 0:t.duration;if(n)return e(n)?{duration:n}:null;const a=this.media.duration;return r>(e(s.duration)?s.duration:0)&&r>a||!e(a)?{duration:r}:null}updateMediaSource({duration:t,start:i,end:s}){const r=this.mediaSource;r&&this.media&&"open"===r.readyState&&(r.duration!==t&&(e(t)&&this.log(`Updating MediaSource duration to ${t.toFixed(3)}`),r.duration=t),void 0!==i&&void 0!==s&&(this.log(`MediaSource duration is set to ${r.duration}. Setting seekable range to ${i}-${s}.`),r.setLiveSeekableRange(i,s)))}get tracksReady(){const t=this.pendingTrackCount;return t>0&&(t>=this.bufferCodecEventsTotal||this.isPending(this.tracks.audiovideo))}checkPendingTracks(){const{bufferCodecEventsTotal:t,pendingTrackCount:e,tracks:i}=this;if(this.log(`checkPendingTracks (pending: ${e} codec events expected: ${t}) ${Ue(i)}`),this.tracksReady){var s;const t=null==(s=this.transferData)?void 0:s.tracks;t&&Object.keys(t).length?this.attachTransferred():this.createSourceBuffers()}}bufferCreated(){if(this.sourceBufferCount){const t={};this.sourceBuffers.forEach(([e,i])=>{if(e){const s=this.tracks[e];t[e]={buffer:i,container:s.container,codec:s.codec,supplemental:s.supplemental,levelCodec:s.levelCodec,id:s.id,metadata:s.metadata}}}),this.hls.trigger(a.BUFFER_CREATED,{tracks:t}),this.log(`SourceBuffers created. Running queue: ${this.operationQueue}`),this.sourceBuffers.forEach(([t])=>{this.executeNext(t)})}else{const t=new Error("could not create source buffer for media codec(s)");this.hls.trigger(a.ERROR,{type:r.MEDIA_ERROR,details:n.BUFFER_INCOMPATIBLE_CODECS_ERROR,fatal:!0,error:t,reason:t.message})}}createSourceBuffers(){const{tracks:t,sourceBuffers:e,mediaSource:i}=this;if(!i)throw new Error("createSourceBuffers called when mediaSource was null");for(const o in t){const l=o,h=t[l];if(this.isPending(h)){const t=this.getTrackCodec(h,l),o=`${h.container};codecs=${t}`;h.codec=t,this.log(`creating sourceBuffer(${o})${this.currentOp(l)?" Queued":""} ${Ue(h)}`);try{const t=i.addSourceBuffer(o),s=Jn(l),r=[l,t];e[s]=r,h.buffer=t}catch(t){var s;return this.error(`error while trying to add sourceBuffer: ${t.message}`),this.shiftAndExecuteNext(l),null==(s=this.operationQueue)||s.removeBlockers(),delete this.tracks[l],void this.hls.trigger(a.ERROR,{type:r.MEDIA_ERROR,details:n.BUFFER_ADD_CODEC_ERROR,fatal:!1,error:t,sourceBufferName:l,mimeType:o,parent:h.id})}this.trackSourceBuffer(l,h)}}this.bufferCreated()}clearBufferAppendTimeoutId(t){t&&(self.clearTimeout(t.bufferAppendTimeoutId),t.bufferAppendTimeoutId=void 0)}getTrackCodec(t,e){const i=t.supplemental;let s=t.codec;i&&("video"===e||"audiovideo"===e)&&he(i,"video")&&(s=function(t,e){const i=[];if(t){const e=t.split(",");for(let t=0;t<e.length;t++)le(e[t],"video")||i.push(e[t])}return e&&i.push(e),i.join(",")}(s,i));const r=ve(s,t.levelCodec);return r?"audio"===e.slice(0,5)?pe(r,this.appendSource):r:""}trackSourceBuffer(t,e){const i=e.buffer;if(!i)return;const s=this.getTrackCodec(e,t);this.tracks[t]={buffer:i,codec:s,container:e.container,levelCodec:e.levelCodec,supplemental:e.supplemental,metadata:e.metadata,id:e.id,listeners:[]},this.removeBufferListeners(t),this.addBufferListener(t,"updatestart",this.onSBUpdateStart),this.addBufferListener(t,"updateend",this.onSBUpdateEnd),this.addBufferListener(t,"error",this.onSBUpdateError),this.appendSource&&this.addBufferListener(t,"bufferedchange",(t,e)=>{const i=e.removedRanges;null!=i&&i.length&&(this.log(`${t} buffer removed ${sr(i)}`),this.hls.trigger(a.BUFFER_FLUSHED,{type:t,start:i.start(0),end:i.end(i.length-1)}))})}get mediaSrc(){var t,e;const i=(null==(t=this.media)||null==(e=t.querySelector)?void 0:e.call(t,"source"))||this.media;return null==i?void 0:i.src}onSBUpdateStart(t){const e=this.currentOp(t);e&&e.onStart()}onSBUpdateEnd(t){var e,i;if("closed"===(null==(e=this.mediaSource)?void 0:e.readyState))return void this.resetBuffer(t);const s=this.currentOp(t);if(!s)return;s.onComplete();if(null==(i=this.tracks[t])||null==(i=i.buffer)?void 0:i.updating)return this.log(`${t} SourceBuffer updating on "updateend"`),void this.blockUntilOpen(()=>{this.shiftAndExecuteNext(t)});this.shiftAndExecuteNext(t)}onSBUpdateError(t,e){var i;const s=null==(i=this.mediaSource)?void 0:i.readyState,o=new Error(`${t} SourceBuffer error. MediaSource readyState: ${s}`);this.error(`${o.message}`,e),this.hls.trigger(a.ERROR,{type:r.MEDIA_ERROR,details:n.BUFFER_APPENDING_ERROR,sourceBufferName:t,error:o,fatal:!1});const l=this.currentOp(t);l&&l.onError(o)}updateTimestampOffset(t,e,i,s,r,n){const a=e-t.timestampOffset;Math.abs(a)>=i&&(this.log(`Updating ${s} SourceBuffer timestampOffset to ${e} (sn: ${r} cc: ${n})`),t.timestampOffset=e)}removeExecutor(t,i,s){const{media:r,mediaSource:n}=this,a=this.tracks[t],o=null==a?void 0:a.buffer;if(!r||!n||!o)throw new Error(`Attempting to remove from the ${t} SourceBuffer, but it does not exist`);const l=e(r.duration)?r.duration:1/0,h=e(n.duration)?n.duration:1/0,d=Math.max(0,i);var c;if(d>=h)return null==(c=this.currentOp(t))||c.onComplete(),void this.shiftAndExecuteNext(t);const u=Math.min(s,l,h);if(!(u>d)||a.ending&&!a.ended)throw new Error(`Cannot remove ${u<=d?`invalid range (${d} >= ${u}) `:""}from the ${t} SourceBuffer${a.ending?" while track ending":""}`);a.ended=!1,this.log(`Removing [${d},${u}] from the ${t} SourceBuffer`),o.remove(d,u)}appendExecutor(t,e){const i=this.tracks[e],s=null==i?void 0:i.buffer;if(!s)throw new Qn(`Attempting to append to the ${e} SourceBuffer, but it does not exist`);if(i.ending=!1,i.ended=!1,this.hls.config.appendTimeout!==1/0){const t=this.calculateAppendTimeoutTime(s);i.bufferAppendTimeoutId=self.setTimeout(()=>this.appendTimeoutHandler(e,s,t),t)}s.appendBuffer(t)}appendTimeoutHandler(t,e,i){this.log(`Received timeout after ${i}ms for append on ${t} source buffer. Aborting and triggering error.`);try{e.abort()}catch(e){this.log(`Failed to abort append on ${t} source buffer after timeout.`)}const s=this.currentOp(t);s&&s.onError(new Error(`${t}-append-timeout`))}calculateAppendTimeoutTime(t){let e=10;this.details&&(e=this.details.levelTargetDuration);let i=2*e*1e3;if(null===this.media)return i;const s=Bi.bufferInfo(t,this.media.currentTime,0);return s.len?(i=Math.max(1e3*s.len,i),Math.max(this.hls.config.appendTimeout,i)):i}blockUntilOpen(t){if(this.isUpdating()||this.isQueued())this.blockBuffers(t).catch(t=>{this.warn(`SourceBuffer blocked callback ${t}`),this.stepOperationQueue(this.sourceBufferTypes)});else try{t()}catch(t){this.warn(`Callback run without blocking ${this.operationQueue} ${t}`)}}isUpdating(){return this.sourceBuffers.some(([t,e])=>t&&e.updating)}isQueued(){return this.sourceBuffers.some(([t])=>t&&!!this.currentOp(t))}isPending(t){return!!t&&!t.buffer}isAudioBlocked(){var t;return"block-audio"===(null==(t=this.currentOp("audio"))?void 0:t.label)}isAudioBlocking(){return!!this.operationQueue&&this.operationQueue.audioBlocking()}blockBuffers(t,e=this.sourceBufferTypes){if(!e.length)return this.log("Blocking operation requested, but no SourceBuffers exist"),Promise.resolve().then(t);const{operationQueue:i}=this,s=2===e.length&&this.isAudioBlocking()?[this.appendBlocker("video")]:e.map(t=>this.appendBlocker(t));return Promise.all(s).then(e=>{i===this.operationQueue&&(t(),this.stepOperationQueue(this.sourceBufferTypes))})}stepOperationQueue(t){t.forEach(t=>{var e;const i=null==(e=this.tracks[t])?void 0:e.buffer;!i||i.updating||"audio"===t&&this.isAudioBlocked()||this.shiftAndExecuteNext(t)})}append(t,e,i){this.operationQueue&&this.operationQueue.append(t,e,i)}insertNext(t,e){this.operationQueue&&this.operationQueue.insertNext(t,e)}appendBlocker(t){if(this.operationQueue)return this.operationQueue.appendBlocker(t)}currentOp(t){return this.operationQueue?this.operationQueue.current(t):null}executeNext(t){t&&this.operationQueue&&this.operationQueue.executeNext(t)}shiftAndExecuteNext(t){this.operationQueue&&this.operationQueue.shiftAndExecuteNext(t)}get pendingTrackCount(){return Object.keys(this.tracks).reduce((t,e)=>t+(this.isPending(this.tracks[e])?1:0),0)}get sourceBufferCount(){return this.sourceBuffers.reduce((t,[e])=>t+(e?1:0),0)}get sourceBufferTypes(){return this.sourceBuffers.map(([t])=>t).filter(t=>!!t)}addBufferListener(t,e,i){const s=this.tracks[t];if(!s)return;const r=s.buffer;if(!r)return;const n=i.bind(this,t);s.listeners.push({event:e,listener:n}),er(r,e,n)}removeBufferListeners(t){const e=this.tracks[t];if(!e)return;const i=e.buffer;i&&(e.listeners.forEach(t=>{ir(i,t.event,t.listener)}),e.listeners.length=0)}},capLevelController:ra,errorController:class extends U{constructor(t){super("error-controller",t.logger),this.hls=void 0,this.playlistError=0,this.hls=t,this.registerListeners()}registerListeners(){const t=this.hls;t.on(a.ERROR,this.onError,this),t.on(a.MANIFEST_LOADING,this.onManifestLoading,this),t.on(a.LEVEL_UPDATED,this.onLevelUpdated,this)}unregisterListeners(){const t=this.hls;t&&(t.off(a.ERROR,this.onError,this),t.off(a.ERROR,this.onErrorOut,this),t.off(a.MANIFEST_LOADING,this.onManifestLoading,this),t.off(a.LEVEL_UPDATED,this.onLevelUpdated,this))}destroy(){this.unregisterListeners(),this.hls=null}startLoad(t){}stopLoad(){this.playlistError=0}getVariantLevelIndex(t){return(null==t?void 0:t.type)===f.MAIN?t.level:this.getVariantIndex()}getVariantIndex(){var t;const e=this.hls,i=e.currentLevel;return null!=(t=e.loadLevelObj)&&t.details||-1===i?e.loadLevel:i}variantHasKey(t,e){if(t){var i;if(null!=(i=t.details)&&i.hasKey(e))return!0;const s=t.audioGroups;if(s){return this.hls.allAudioTracks.filter(t=>s.indexOf(t.groupId)>=0).some(t=>{var i;return null==(i=t.details)?void 0:i.hasKey(e)})}}return!1}onManifestLoading(){this.playlistError=0}onLevelUpdated(){this.playlistError=0}onError(t,e){var i;if(e.fatal)return;const s=this.hls,a=e.context;switch(e.details){case n.FRAG_LOAD_ERROR:case n.FRAG_LOAD_TIMEOUT:case n.KEY_LOAD_ERROR:case n.KEY_LOAD_TIMEOUT:return void(e.errorAction=this.getFragRetryOrSwitchAction(e));case n.FRAG_PARSING_ERROR:if(null!=(i=e.frag)&&i.gap)return void(e.errorAction=mi());case n.FRAG_GAP:case n.FRAG_DECRYPT_ERROR:return e.errorAction=this.getFragRetryOrSwitchAction(e),void(e.errorAction.action=ri);case n.PLAYLIST_UNCHANGED_ERROR:case n.LEVEL_EMPTY_ERROR:case n.LEVEL_PARSING_ERROR:{var o;const t=e.parent===f.MAIN?e.level:s.loadLevel;e.details===n.LEVEL_EMPTY_ERROR&&null!=(o=e.context)&&null!=(o=o.levelDetails)&&o.live?e.errorAction=this.getPlaylistRetryOrSwitchAction(e,t):(e.levelRetry=!1,e.errorAction=this.getLevelSwitchAction(e,t))}return;case n.LEVEL_LOAD_ERROR:case n.LEVEL_LOAD_TIMEOUT:return void("number"==typeof(null==a?void 0:a.level)&&(e.errorAction=this.getPlaylistRetryOrSwitchAction(e,a.level)));case n.AUDIO_TRACK_LOAD_ERROR:case n.AUDIO_TRACK_LOAD_TIMEOUT:case n.SUBTITLE_LOAD_ERROR:case n.SUBTITLE_TRACK_LOAD_TIMEOUT:if(a){const t=s.loadLevelObj;if(t&&(a.type===u.AUDIO_TRACK&&t.hasAudioGroup(a.groupId)||a.type===u.SUBTITLE_TRACK&&t.hasSubtitleGroup(a.groupId)))return e.errorAction=this.getPlaylistRetryOrSwitchAction(e,s.loadLevel),e.errorAction.action=ri,void(e.errorAction.flags=li)}return;case n.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:return void(e.errorAction={action:ri,flags:hi});case n.KEY_SYSTEM_SESSION_UPDATE_FAILED:case n.KEY_SYSTEM_STATUS_INTERNAL_ERROR:case n.KEY_SYSTEM_NO_SESSION:return void(e.errorAction={action:ri,flags:di});case n.BUFFER_ADD_CODEC_ERROR:case n.REMUX_ALLOC_ERROR:case n.BUFFER_APPEND_ERROR:return void(e.errorAction||(e.errorAction=this.getLevelSwitchAction(e,e.level)));case n.MEDIA_SOURCE_REQUIRES_RESET:return e.errorAction||(e.errorAction=this.getLevelSwitchAction(e,e.level)),void(e.errorAction.flags|=ui|ci);case n.INTERNAL_EXCEPTION:case n.BUFFER_APPENDING_ERROR:case n.BUFFER_APPEND_NO_PROGRESS:case n.BUFFER_FULL_ERROR:case n.LEVEL_SWITCH_ERROR:case n.BUFFER_STALLED_ERROR:case n.BUFFER_SEEK_OVER_HOLE:case n.BUFFER_NUDGE_ON_STALL:return void(e.errorAction=mi())}e.type===r.KEY_SYSTEM_ERROR&&(e.levelRetry=!1,e.errorAction=mi())}getPlaylistRetryOrSwitchAction(t,e){const i=C(this.hls.config.playlistLoadPolicy,t),s=this.playlistError++;if(O(i,s,D(t),t.response))return{action:ai,flags:oi,retryConfig:i,retryCount:s};const r=this.getLevelSwitchAction(t,e);return i&&(r.retryConfig=i,r.retryCount=s),r}getFragRetryOrSwitchAction(t){const e=this.hls,i=this.getVariantLevelIndex(t.frag),s=e.levels[i],{fragLoadPolicy:r,keyLoadPolicy:a}=e.config,o=C(w(t)?a:r,t),l=e.levels.reduce((t,e)=>t+e.fragmentError,0);if(s&&(t.details!==n.FRAG_GAP&&s.fragmentError++,!P(t))){if(O(o,l,D(t),t.response))return{action:ai,flags:oi,retryConfig:o,retryCount:l}}const h=this.getLevelSwitchAction(t,i);return o&&(h.retryConfig=o,h.retryCount=l),h}getLevelSwitchAction(t,e){const i=this.hls;null==e&&(e=i.loadLevel);const s=this.hls.levels[e];if(s){var r,a;const e=t.details;s.loadError++,s.loadErrorTime=self.performance.now(),e===n.BUFFER_APPEND_ERROR&&s.fragmentError++;let h=-1;const{levels:d,loadLevel:c,minAutoLevel:g,maxAutoLevel:m}=i;i.autoLevelEnabled||i.config.preserveManualLevelOnError||(i.loadLevel=-1);const p=null==(r=t.frag)?void 0:r.type,v=(p===f.AUDIO&&e===n.FRAG_PARSING_ERROR||"audio"===t.sourceBufferName&&fi(t))&&d.some(({audioCodec:t})=>s.audioCodec!==t),y="video"===t.sourceBufferName&&fi(t)&&d.some(({codecSet:t,audioCodec:e})=>s.codecSet!==t&&s.audioCodec===e),{type:E,groupId:T}=null!=(a=t.context)?a:{};for(let r=d.length;r--;){const a=(r+c)%d.length;if(a!==c&&a>=g&&a<=m&&(0===d[a].loadError||N(d[a],i.config.errorPenaltyExpireMs))){var o,l;const i=d[a];if(e===n.FRAG_GAP&&p===f.MAIN&&t.frag){const e=d[a].details;if(e){const i=Ze(t.frag,e.fragments,t.frag.start);if(null!=i&&i.gap)continue}}else{if(E===u.AUDIO_TRACK&&i.hasAudioGroup(T)||E===u.SUBTITLE_TRACK&&i.hasSubtitleGroup(T))continue;if(p===f.AUDIO&&null!=(o=s.audioGroups)&&o.some(t=>i.hasAudioGroup(t))||p===f.SUBTITLE&&null!=(l=s.subtitleGroups)&&l.some(t=>i.hasSubtitleGroup(t))||v&&s.audioCodec===i.audioCodec||y&&s.codecSet===i.codecSet||!v&&s.audioCodec!==i.audioCodec)continue}h=a;break}}if(h>-1&&i.loadLevel!==h)return t.levelRetry=!0,this.playlistError=0,{action:ri,flags:oi,nextAutoLevel:h}}return{action:ri,flags:li}}onErrorOut(t,e){var i,s;switch(null==(i=e.errorAction)?void 0:i.action){case si:break;case ri:this.sendAlternateToPenaltyBox(e),e.errorAction.resolved||e.details===n.FRAG_GAP||e.details===n.PLAYLIST_UNCHANGED_ERROR||gi(e)||(e.fatal=!0)}((null==(s=e.errorAction)?void 0:s.flags)||0)&ui&&this.hls.recoverMediaError(),e.fatal&&this.hls.stopLoad()}sendAlternateToPenaltyBox(t){const e=this.hls,i=t.errorAction;if(!i)return;let s=i.nextAutoLevel;if(i.flags===oi)this.switchLevel(t,s);else if(i.flags&ci){const t=this.hls.levels;for(let e=t.length;e--;)"SDR"!==t[e].videoRange?(t[e].fragmentError++,t[e].loadError++):void 0===s&&(s=e)}else if(i.flags&hi){const s=this.getVariantLevelIndex(t.frag),r=e.levels[s],n=null==r?void 0:r.attrs["HDCP-LEVEL"];i.hdcpLevel=n;const a="NONE"===n;n&&!a?(e.maxHdcpLevel=we[we.indexOf(n)-1],i.resolved=!0,this.warn(`Restricting playback to HDCP-LEVEL of "${e.maxHdcpLevel}" or lower`)):(a&&this.warn("HDCP policy resticted output with HDCP-LEVEL=NONE"),i.flags|=di)}if(i.flags&di){const e=t.decryptdata;if(e){const s=this.hls.levels,a=s.length;for(let i=a;i--;){var r,n;if(this.variantHasKey(s[i],e))this.log(`Banned key found in level ${i} (${s[i].bitrate}bps) or audio group "${null==(r=s[i].audioGroups)?void 0:r.join(",")}" (${null==(n=t.frag)?void 0:n.type} fragment) ${mt(e.keyId||[])}`),s[i].fragmentError++,s[i].loadError++,this.log(`Removing level ${i} with key error (${t.error})`),this.hls.removeLevel(i)}const o=t.frag;if(this.hls.levels.length<a)i.resolved=!0;else if(o&&o.type!==f.MAIN){const t=o.decryptdata;t&&!e.matches(t)&&(i.resolved=!0)}}}i.resolved||this.switchLevel(t,s)}switchLevel(t,e){if(void 0!==e&&t.errorAction&&(this.warn(`switching to level ${e} after ${t.details}`),this.hls.nextAutoLevel=e,t.errorAction.resolved=!0,this.hls.nextLoadLevel=this.hls.nextAutoLevel,t.details===n.BUFFER_ADD_CODEC_ERROR&&t.mimeType&&"audiovideo"!==t.sourceBufferName)){const e=Se(t.mimeType),i=this.hls.levels;for(let s=i.length;s--;)i[s][`${t.sourceBufferName}Codec`]===e&&(this.log(`Removing level ${s} for ${t.details} ("${e}" not supported)`),this.hls.removeLevel(s))}}},fpsController:class{constructor(t){this.hls=void 0,this.isVideoPlaybackQualityAvailable=!1,this.timer=void 0,this.media=null,this.lastTime=void 0,this.lastDroppedFrames=0,this.lastDecodedFrames=0,this.streamController=void 0,this.hls=t,this.registerListeners()}setStreamController(t){this.streamController=t}registerListeners(){this.hls.on(a.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.on(a.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListeners(){this.hls.off(a.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.off(a.MEDIA_DETACHING,this.onMediaDetaching,this)}destroy(){this.timer&&clearInterval(this.timer),this.unregisterListeners(),this.isVideoPlaybackQualityAvailable=!1,this.media=null}onMediaAttaching(t,e){const i=this.hls.config;if(i.capLevelOnFPSDrop){const t=e.media instanceof self.HTMLVideoElement?e.media:null;this.media=t,t&&"function"==typeof t.getVideoPlaybackQuality&&(this.isVideoPlaybackQualityAvailable=!0),self.clearInterval(this.timer),this.timer=self.setInterval(this.checkFPSInterval.bind(this),i.fpsDroppedMonitoringPeriod)}}onMediaDetaching(){this.media=null}checkFPS(t,e,i){const s=performance.now();if(e){if(this.lastTime){const t=s-this.lastTime,r=i-this.lastDroppedFrames,n=e-this.lastDecodedFrames,o=1e3*r/t,l=this.hls;if(l.trigger(a.FPS_DROP,{currentDropped:r,currentDecoded:n,totalDroppedFrames:i}),o>0&&r>l.config.fpsDroppedMonitoringThreshold*n){let t=l.currentLevel;l.logger.warn("drop FPS ratio greater than max allowed value for currentLevel: "+t),t>0&&(-1===l.autoLevelCapping||l.autoLevelCapping>=t)&&(t-=1,l.trigger(a.FPS_DROP_LEVEL_CAPPING,{level:t,droppedLevel:l.currentLevel}),l.autoLevelCapping=t,this.streamController.nextLevelSwitch())}}this.lastTime=s,this.lastDroppedFrames=i,this.lastDecodedFrames=e}}checkFPSInterval(){const t=this.media;if(t)if(this.isVideoPlaybackQualityAvailable){const e=t.getVideoPlaybackQuality();this.checkFPS(t,e.totalVideoFrames,e.droppedVideoFrames)}else this.checkFPS(t,t.webkitDecodedFrameCount,t.webkitDroppedFrameCount)}},id3TrackController:class{constructor(t){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(a.EVENT_CUE_ENTER,{})},this.hls=t,this._registerListeners()}destroy(){this._unregisterListeners(),this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.hls=this.onEventCueEnter=null}_registerListeners(){const{hls:t}=this;t&&(t.on(a.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(a.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(a.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(a.MANIFEST_LOADING,this.onManifestLoading,this),t.on(a.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),t.on(a.BUFFER_FLUSHING,this.onBufferFlushing,this),t.on(a.LEVEL_UPDATED,this.onLevelUpdated,this),t.on(a.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))}_unregisterListeners(){const{hls:t}=this;t&&(t.off(a.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(a.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(a.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(a.MANIFEST_LOADING,this.onManifestLoading,this),t.off(a.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),t.off(a.BUFFER_FLUSHING,this.onBufferFlushing,this),t.off(a.LEVEL_UPDATED,this.onLevelUpdated,this),t.off(a.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))}onMediaAttaching(t,e){this.media=e.media}onMediaAttached(){var t;const e=null==(t=this.hls)?void 0:t.latestLevelDetails;e&&this.updateDateRangeCues(e)}onMediaDetaching(t,e){this.media=null;!!e.transferMedia||(this.id3Track&&(this.id3Track.remove(),this.id3Track=null),this.dateRangeCuesAppended={})}onManifestLoading(){this.dateRangeCuesAppended={}}createTrack(t){return Ll(t,"metadata","id3","","hidden")}onFragParsingMetadata(t,e){if(!this.media||!this.hls)return;const{enableEmsgMetadataCues:i,enableID3MetadataCues:s}=this.hls.config;if(!i&&!s)return;const{samples:r}=e;this.id3Track||(this.id3Track=this.createTrack(this.media));const n=Cl();if(n)for(let t=0;t<r.length;t++){const e=r[t].type;if(e===Mr.emsg&&!i||!s)continue;const a=ct(r[t].data),o=r[t].pts;let l=o+r[t].duration;l>Ml&&(l=Ml);l-o<=0&&(l=o+.25);for(let t=0;t<a.length;t++){const i=a[t];if(!ut(i)){this.updateId3CueEnds(o,e);const t=xl(n,o,l,i,e);t&&this.id3Track.track.addCue(t)}}}}updateId3CueEnds(t,e){var i;const s=null==(i=this.id3Track)?void 0:i.track.cues;if(s)for(let i=s.length;i--;){const r=s[i];r.type===e&&r.startTime<t&&r.endTime===Ml&&(r.endTime=t)}}onBufferFlushing(t,{startOffset:e,endOffset:i,type:s}){const{id3Track:r,hls:n}=this;if(!n)return;const{config:{enableEmsgMetadataCues:a,enableID3MetadataCues:o}}=n;if(r&&(a||o)){let t;t="audio"===s?t=>t.type===Mr.audioId3&&o:"video"===s?t=>t.type===Mr.emsg&&a:t=>t.type===Mr.audioId3&&o||t.type===Mr.emsg&&a,kl(r.track,e,i,t)}}onLevelUpdated(t,{details:e}){this.updateDateRangeCues(e,!0)}onLevelPtsUpdated(t,e){Math.abs(e.drift)>.01&&this.updateDateRangeCues(e.details)}updateDateRangeCues(t,i){if(!this.hls||!this.media)return;const{assetPlayerId:s,timelineOffset:r,enableDateRangeMetadataCues:n,interstitialsController:a}=this.hls.config;if(!n)return;const o=Cl();if(s&&r&&!a){const{fragmentStart:e,fragmentEnd:i}=t;let r=this.assetCue;r?(r.startTime=e,r.endTime=i):o&&(r=this.assetCue=xl(o,e,i,{assetPlayerId:this.hls.config.assetPlayerId},"hlsjs.interstitial.asset"),r&&(r.id=s,this.id3Track||(this.id3Track=this.createTrack(this.media)),this.id3Track.track.addCue(r),r.addEventListener("enter",this.onEventCueEnter)))}if(!t.hasProgramDateTime)return;const{id3Track:l}=this,{dateRanges:h}=t,d=Object.keys(h);let c=this.dateRangeCuesAppended;var u;if(l&&i)if(null!=(u=l.track.cues)&&u.length){const t=Object.keys(c).filter(t=>-1===d.indexOf(t));for(let e=t.length;e--;){var f;const i=t[e],s=null==(f=c[i])?void 0:f.cues;delete c[i],s&&Object.keys(s).forEach(t=>{const e=s[t];if(e){e.removeEventListener("enter",this.onEventCueEnter);try{l.track.removeCue(e)}catch(t){}}})}}else c=this.dateRangeCuesAppended={};const g=t.fragments[t.fragments.length-1];if(0!==d.length&&e(null==g?void 0:g.programDateTime)){this.id3Track||(this.id3Track=this.createTrack(this.media));for(let t=0;t<d.length;t++){const e=d[t],i=h[e],s=i.startTime,r=c[e],n=(null==r?void 0:r.cues)||{};let l=(null==r?void 0:r.durationKnown)||!1,u=Ml;const{duration:f,endDate:g}=i;if(g&&null!==f)u=s+f,l=!0;else if(i.endOnNext&&!l){const t=d.reduce((t,e)=>{if(e!==i.id){const s=h[e];if(s.class===i.class&&s.startDate>i.startDate&&(!t||i.startDate<t.startDate))return s}return t},null);t&&(u=t.startTime,l=!0)}const m=Object.keys(i.attr);for(let t=0;t<m.length;t++){const h=m[t];if(!Wi(h))continue;const d=n[h];if(d)!l||null!=r&&r.durationKnown?Math.abs(d.startTime-s)>.01&&(d.startTime=s,d.endTime=u):d.endTime=u;else if(o){let t=i.attr[h];zi(h)&&(t=pt(t));const r=xl(o,s,u,{key:h,data:t},Mr.dateRange);r&&(r.id=e,this.id3Track.track.addCue(r),n[h]=r,a&&("X-ASSET-LIST"!==h&&"X-ASSET-URL"!==h||r.addEventListener("enter",this.onEventCueEnter)))}}c[e]={cues:n,dateRange:i,durationKnown:l}}}}},gapController:class extends Fi{constructor(t,e){super("gap-controller",t.logger),this.hls=void 0,this.fragmentTracker=void 0,this.media=null,this.mediaSource=void 0,this.nudgeRetry=0,this.skipRetry=0,this.stallReported=!1,this.stalled=null,this.moved=!1,this.seeking=!1,this.buffered={},this.lastCurrentTime=void 0,this.ended=0,this.waiting=0,this.onMediaPlaying=()=>{this.ended=0,this.waiting=0},this.onMediaWaiting=()=>{var t;null!=(t=this.media)&&t.seeking||(this.waiting=self.performance.now(),this.tick())},this.onMediaEnded=()=>{var t;this.hls&&(this.ended=(null==(t=this.media)?void 0:t.currentTime)||1,this.hls.trigger(a.MEDIA_ENDED,{stalled:!1}))},this.hls=t,this.fragmentTracker=e,this.lastCurrentTime=this.getCurrentTime(),this.registerListeners()}registerListeners(){const{hls:t}=this;t&&(t.on(a.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(a.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(a.BUFFER_APPENDED,this.onBufferAppended,this))}unregisterListeners(){const{hls:t}=this;t&&(t.off(a.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(a.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(a.BUFFER_APPENDED,this.onBufferAppended,this))}destroy(){super.destroy(),this.unregisterListeners(),this.media=this.hls=this.fragmentTracker=null,this.mediaSource=void 0}onMediaAttached(t,e){this.setInterval(100),this.mediaSource=e.mediaSource;const i=this.media=e.media;er(i,"playing",this.onMediaPlaying),er(i,"waiting",this.onMediaWaiting),er(i,"ended",this.onMediaEnded)}onMediaDetaching(t,e){this.clearInterval();const{media:i}=this;i&&(ir(i,"playing",this.onMediaPlaying),ir(i,"waiting",this.onMediaWaiting),ir(i,"ended",this.onMediaEnded),this.media=null),this.mediaSource=void 0}onBufferAppended(t,e){this.buffered=e.timeRanges}get hasBuffered(){return Object.keys(this.buffered).length>0}getCurrentTime(){var t;const e=(null==(t=this.hls)?void 0:t.config.timelineOffset)||0;return this.media?Math.max(this.media.currentTime,e):e}tick(){var t;if(null==(t=this.media)||!t.readyState||!this.hasBuffered)return;const e=this.getCurrentTime();this.media.currentTime<e||(this.poll(e,this.lastCurrentTime),this.lastCurrentTime=e)}poll(t,e){var i,s;const r=null==(i=this.hls)?void 0:i.config;if(!r)return;const n=this.media;if(!n)return;const{seeking:o}=n,l=this.seeking&&!o,h=!this.seeking&&o,d=n.paused&&!o||n.ended||0===n.playbackRate;if(this.seeking=o,t!==e)return e&&(this.ended=0),this.moved=!0,o||(this.skipRetry=this.nudgeRetry=0,r.nudgeOnVideoHole&&!d&&t>e&&this.nudgeOnVideoHole(t,e)),void(0===this.waiting&&this.stallResolved(t));if(h||l)return void(l&&this.stallResolved(t));if(d)return this.skipRetry=this.nudgeRetry=0,this.stallResolved(t),void(!this.ended&&n.ended&&this.hls&&(this.ended=t||1,this.hls.trigger(a.MEDIA_ENDED,{stalled:!1})));if(!Bi.getBuffered(n).length)return void(this.skipRetry=this.nudgeRetry=0);const c=Bi.bufferInfo(n,t,0),u=this.fragmentTracker;u&&this.hls&&Pl(c,t,u,this.hls);const f=c.nextStart||0;if(o&&u&&this.hls){const e=_l(this.hls.inFlightFragments,t),i=c.len>2,s=!f||e||f-t>2&&!u.getPartialFragment(t);if(i||s)return;this.moved=!1}const g=null==(s=this.hls)?void 0:s.latestLevelDetails;if(!this.moved&&null!==this.stalled&&u){if(!(c.len>0)&&!f)return;const e=Math.max(f,c.start||0)-t,i=!(null==g||!g.live)?2*g.targetduration:2,s=wl(t,u);if(e>0&&(e<=i||s))return void(n.paused||this._trySkipBufferHole(s))}const m=r.detectStallWithCurrentTimeMs,p=self.performance.now(),v=this.waiting;let y=this.stalled;if(null===y){if(!(v>0&&p-v<m))return void(this.stalled=p);y=this.stalled=v}const E=p-y;if(!o&&(E>=m||v&&this.moved)&&this.hls){var T;if("ended"===(null==(T=this.mediaSource)?void 0:T.readyState)&&(null==g||!g.live)&&Math.abs(t-((null==g?void 0:g.edge)||0))<1){if(this.ended)return;return this.ended=t||1,void this.hls.trigger(a.MEDIA_ENDED,{stalled:!0})}if(this._reportStall(c),!this.media||!this.hls)return;if(n.currentTime!==t){const e=t;return t=n.currentTime,this.moved=!0,void this.log(`currentTime changed ${e} > ${t}`)}}const S=Bi.bufferInfo(n,t,r.maxBufferHole);this._tryFixBufferStall(S,E,t)}stallResolved(t){const e=this.stalled;if(e&&this.hls&&(this.stalled=null,this.stallReported)){const i=self.performance.now()-e;this.log(`playback not stuck anymore @${t}, after ${Math.round(i)}ms`),this.stallReported=!1,this.waiting=0,this.hls.trigger(a.STALL_RESOLVED,{})}}nudgeOnVideoHole(t,e){var i;const s=this.buffered.video;if(this.hls&&this.media&&this.fragmentTracker&&null!=(i=this.buffered.audio)&&i.length&&s&&s.length>1&&t>s.end(0)){const i=Bi.bufferedInfo(Bi.timeRangesToArray(this.buffered.audio),t,0);if(i.len>1&&e>=i.start){const i=Bi.timeRangesToArray(s),o=Bi.bufferedInfo(i,e,0).bufferedIndex;if(o>-1&&o<i.length-1){const e=Bi.bufferedInfo(i,t,0).bufferedIndex,s=i[o].end,l=i[o+1].start;if((-1===e||e>o)&&l-s<1&&t-s<2){const i=new Error(`nudging playhead to flush pipeline after video hole. currentTime: ${t} hole: ${s} -> ${l} buffered index: ${e}`);this.warn(i.message),this.media.currentTime+=1e-6;let o=wl(t,this.fragmentTracker);o&&"fragment"in o?o=o.fragment:o||(o=void 0);const h=Bi.bufferInfo(this.media,t,0);this.hls.trigger(a.ERROR,{type:r.MEDIA_ERROR,details:n.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:i,reason:i.message,frag:o,buffer:h.len,bufferInfo:h})}}}}}_tryFixBufferStall(t,e,i){var s,r;const{fragmentTracker:n,media:a}=this,o=null==(s=this.hls)?void 0:s.config;if(!a||!n||!o)return;const l=null==(r=this.hls)?void 0:r.latestLevelDetails,h=wl(i,n);if(h||null!=l&&l.live&&i<l.fragmentStart){if(this._trySkipBufferHole(h)||!this.media)return}const d=t.buffered,c=this.adjacentTraversal(t,i);(d&&d.length>1&&t.len>o.maxBufferHole||t.nextStart&&(t.nextStart-i<o.maxBufferHole||c))&&(e>1e3*o.highBufferWatchdogPeriod||this.waiting)&&(this.warn("Trying to nudge playhead over buffer-hole"),this._tryNudgeBuffer(t))}adjacentTraversal(t,e){const i=this.fragmentTracker,s=t.nextStart;if(i&&s){const t=i.getFragAtPos(e,f.MAIN),r=i.getFragAtPos(s,f.MAIN);if(t&&r)return r.sn-t.sn<2}return!1}_reportStall(t){const{hls:e,media:i,stallReported:s,stalled:o}=this;if(!s&&null!==o&&i&&e){this.stallReported=!0;const s=new Error(`Playback stalling at @${i.currentTime} due to low buffer (${Ue(t)})`);this.warn(s.message),e.trigger(a.ERROR,{type:r.MEDIA_ERROR,details:n.BUFFER_STALLED_ERROR,fatal:!1,error:s,buffer:t.len,bufferInfo:t,stalled:{start:o}})}}_trySkipBufferHole(t){const{fragmentTracker:e,media:i,hls:s}=this,o=null==s?void 0:s.config;if(!i||!e||!o)return 0;const l=i.currentTime,h=Bi.bufferInfo(i,l,0);Pl(h,l,e,s);const d=l<h.start?h.start:h.nextStart;if(d){const u=h.len<=o.maxBufferHole,g=h.len>0&&h.len<1&&i.readyState<3,m=d-l;if(m>0&&(u||g)){if(m>o.maxBufferHole){let i=!1;if(0===l){const t=e.getAppendedFrag(0,f.MAIN);t&&d<t.end&&(i=!0)}if(!i&&t){var c;if(null==(c=s.loadLevelObj)||!c.details)return 0;if(_l(s.inFlightFragments,d))return 0;let i=!1,r=t.end;for(;r<d;){const t=wl(r,e),s=t?t.duration:0;if(!(s>0)){i=!0;break}r+=s}if(i)return 0}}const{nudgeMaxRetry:u,skipBufferHolePadding:g}=o,p=++this.skipRetry>u,v=Math.max(d,l)+g;if(p||(this.warn(`skipping hole, adjusting currentTime from ${l} to ${v}`),this.moved=!0,i.currentTime=v),null==t||!t.gap||p){const e=new Error(p?`Playhead still not moving after seeking over buffer hole from ${l} to ${v} after ${o.nudgeMaxRetry} attempts.`:`fragment loaded with buffer holes, seeking from ${l} to ${v}`),i={type:r.MEDIA_ERROR,details:n.BUFFER_SEEK_OVER_HOLE,fatal:p,error:e,reason:e.message,buffer:h.len,bufferInfo:h};t&&("fragment"in t?i.part=t:i.frag=t),s.trigger(a.ERROR,i)}return v}}return 0}_tryNudgeBuffer(t){const{hls:e,media:i,nudgeRetry:s}=this,o=null==e?void 0:e.config;if(!i||!o)return 0;const l=i.currentTime;if(this.nudgeRetry++,s<o.nudgeMaxRetry){const h=l+(s+1)*o.nudgeOffset,d=new Error(`Nudging 'currentTime' from ${l} to ${h}`);this.warn(d.message),i.currentTime=h,e.trigger(a.ERROR,{type:r.MEDIA_ERROR,details:n.BUFFER_NUDGE_ON_STALL,error:d,fatal:!1,buffer:t.len,bufferInfo:t})}else{const i=new Error(`Playhead still not moving while enough data buffered @${l} after ${o.nudgeMaxRetry} nudges`);this.error(i.message),e.trigger(a.ERROR,{type:r.MEDIA_ERROR,details:n.BUFFER_STALLED_ERROR,error:i,fatal:!0,buffer:t.len,bufferInfo:t})}}},latencyController:class{constructor(t){this.hls=void 0,this.media=null,this.currentTime=0,this.stallCount=0,this._latency=null,this._targetLatencyUpdated=!1,this.onTimeupdate=()=>{var t;const{media:e}=this,i=this.levelDetails;if(!e||!i||!this.hls)return;this.currentTime=e.currentTime;const s=this.hls.config,r=this.computeLatency();if(null===r)return;this._latency=r;const{lowLatencyMode:n,maxLiveSyncPlaybackRate:a}=s;if(!n||1===a||!i.live)return;const o=this.targetLatency;if(null===o)return;const l=r-o,h=l<Math.min(this.maxLatency,o+i.targetduration),d=yr(s)&&!(null==(t=this.hls.interstitialsManager)||null==(t=t.playingItem)||!t.event);if(h&&l>.05&&this.forwardBufferLength>1&&!d){const t=Math.min(2,Math.max(1,a)),i=Math.round(2/(1+Math.exp(-.75*l-this.edgeStalled))*20)/20,s=Math.min(t,Math.max(1,i));this.changeMediaPlaybackRate(e,s)}else 1!==e.playbackRate&&0!==e.playbackRate&&this.changeMediaPlaybackRate(e,1)},this.hls=t,this.registerListeners()}get levelDetails(){var t;return(null==(t=this.hls)?void 0:t.latestLevelDetails)||null}get latency(){return this._latency||0}get maxLatency(){var t;const e=null==(t=this.hls)?void 0:t.config;if(!e)return 0;if(void 0!==e.liveMaxLatencyDuration)return e.liveMaxLatencyDuration;const i=this.levelDetails;return i?e.liveMaxLatencyDurationCount*i.targetduration:0}get targetLatency(){const t=this.levelDetails;if(null===t||!this.hls)return null;const e=this.hls.config,{holdBack:i,partHoldBack:s,targetduration:r}=t,{liveSyncDuration:n,liveSyncDurationCount:a,lowLatencyMode:o}=e,l=this.hls.userConfig;let h=o&&s||i;(this._targetLatencyUpdated||l.liveSyncDuration||l.liveSyncDurationCount||0===h)&&(h=void 0!==n?n:a*r);const d=r;return h+Math.min(this.stallCount*e.liveSyncOnStallIncrease,d)}set targetLatency(t){this.hls&&(this.stallCount=0,this.hls.config.liveSyncDuration=t,this._targetLatencyUpdated=!0)}get liveSyncPosition(){const t=this.estimateLiveEdge(),e=this.targetLatency;if(null===t||null===e||!this.hls)return null;const i=this.levelDetails;if(null===i)return null;const s=i.edge,r=t-e-this.edgeStalled,n=s-i.totalduration,a=s-(this.hls.config.lowLatencyMode&&i.partTarget||i.targetduration);return Math.min(Math.max(n,r),a)}get drift(){const t=this.levelDetails;return null===t?1:t.drift}get edgeStalled(){const t=this.levelDetails;if(null===t||!this.hls)return 0;const e=3*(this.hls.config.lowLatencyMode&&t.partTarget||t.targetduration);return Math.max(t.age-e,0)}get forwardBufferLength(){const{media:t}=this,e=this.levelDetails;if(!t||!e)return 0;const i=t.buffered.length;return(i?t.buffered.end(i-1):e.edge)-this.currentTime}destroy(){this.unregisterListeners(),this.onMediaDetaching(),this.hls=null}registerListeners(){const{hls:t}=this;t&&(t.on(a.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(a.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(a.MANIFEST_LOADING,this.onManifestLoading,this),t.on(a.LEVEL_UPDATED,this.onLevelUpdated,this),t.on(a.ERROR,this.onError,this),t.on(a.INTERSTITIAL_ASSET_STARTED,this.onAssetStarted,this))}unregisterListeners(){const{hls:t}=this;t&&(t.off(a.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(a.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(a.MANIFEST_LOADING,this.onManifestLoading,this),t.off(a.LEVEL_UPDATED,this.onLevelUpdated,this),t.off(a.ERROR,this.onError,this),t.off(a.INTERSTITIAL_ASSET_STARTED,this.onAssetStarted,this))}onMediaAttached(t,e){this.media=e.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(t,{details:e}){e.advanced&&this.onTimeupdate(),!e.live&&this.media&&this.media.removeEventListener("timeupdate",this.onTimeupdate)}onAssetStarted(t,e){var i;const s=this.hls,r=this.media||e.event.appendInPlace&&(null==s||null==(i=s.interstitialsManager)?void 0:i.playerQueue.reduce((t,e)=>t||e.media,null));s&&r&&r.playbackRate>1&&r.playbackRate<=s.config.maxLiveSyncPlaybackRate&&this.changeMediaPlaybackRate(r,1)}onError(t,e){var i;e.details===n.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(t,e){var i,s;t.playbackRate!==e&&(null==(i=this.hls)||i.logger.debug(`[latency-controller]: latency=${this.latency.toFixed(3)}, targetLatency=${null==(s=this.targetLatency)?void 0:s.toFixed(3)}, forwardBufferLength=${this.forwardBufferLength.toFixed(3)}: adjusting playback rate from ${t.playbackRate} to ${e}`),t.playbackRate=e)}estimateLiveEdge(){const t=this.levelDetails;return null===t?null:t.edge+t.age}computeLatency(){const t=this.estimateLiveEdge();return null===t?null:t-this.currentTime}}},{cueHandler:xh,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 pr{constructor(t,e,i){super(t,e,i,"subtitle-stream-controller",f.SUBTITLE),this.currentTrackId=-1,this.tracksBuffered=[],this.mainDetails=null,this.registerListeners()}onHandlerDestroying(){this.unregisterListeners(),super.onHandlerDestroying(),this.mainDetails=null}registerListeners(){super.registerListeners();const{hls:t}=this;t.on(a.LEVEL_LOADED,this.onLevelLoaded,this),t.on(a.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.on(a.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),t.on(a.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.on(a.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),t.on(a.BUFFER_FLUSHING,this.onBufferFlushing,this)}unregisterListeners(){super.unregisterListeners();const{hls:t}=this;t.off(a.LEVEL_LOADED,this.onLevelLoaded,this),t.off(a.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.off(a.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),t.off(a.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.off(a.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),t.off(a.BUFFER_FLUSHING,this.onBufferFlushing,this)}startLoad(t,e){this.stopLoad(),this.state=nr,this.setInterval(500),this.nextLoadPosition=this.lastCurrentTime=t+this.timelineOffset,this.startPosition=e?-1:t,this.tick()}onManifestLoading(){super.onManifestLoading(),this.mainDetails=null}onMediaDetaching(t,e){this.tracksBuffered=[],super.onMediaDetaching(t,e)}onLevelLoaded(t,e){this.mainDetails=e.details}onSubtitleFragProcessed(t,e){const{frag:i,part:s,success:r}=e;if(!r)return;const n=this.tracksBuffered[this.currentTrackId];if(!n)return;let a;const o=(s||i).start;for(let t=0;t<n.length;t++)if(o>=n[t].start&&o<=n[t].end){a=n[t];break}const l=o+(s||i).duration;if(a?a.end=l:(a={start:o,end:l},n.push(a)),!s||l>=i.end){const t=this.fragmentTracker.fragBuffered(i);s&&t&&(t.range.subs={time:[{startPTS:i.start,endPTS:l}],partial:!0}),y(i)&&!this.fragContextChanged(i)&&(this.fragPrevious=i),this.fragBufferedComplete(i,s),this.media&&this.tickImmediate()}}onBufferFlushing(t,e){const{startOffset:i,endOffset:s}=e;if(0===i&&s!==Number.POSITIVE_INFINITY){const t=s-1;if(t<=0)return;e.endOffsetSubtitles=Math.max(0,t),this.tracksBuffered.forEach(e=>{if(e)for(let i=0;i<e.length;)if(e[i].end<=t)e.shift();else{if(!(e[i].start<t))break;e[i].start=t,i++}}),this.fragmentTracker.removeFragmentsInRange(i,t,f.SUBTITLE)}}onError(t,e){const i=e.frag;(null==i?void 0:i.type)===f.SUBTITLE&&(e.details===n.FRAG_GAP&&this.fragmentTracker.addAsGap(i),this.fragCurrent&&this.fragCurrent.abortRequests(),this.state!==rr&&(this.state=nr))}onSubtitleTracksUpdated(t,{subtitleTracks:e}){this.levels&&qn(this.levels,e)?this.levels=e.map(t=>new Ne(t)):(this.tracksBuffered=[],this.levels=e.map(t=>{const e=new Ne(t);return this.tracksBuffered[e.id]=[],e}),this.fragmentTracker.removeFragmentsInRange(0,Number.POSITIVE_INFINITY,f.SUBTITLE),this.fragPrevious=null,this.mediaBuffer=null)}onSubtitleTrackSwitch(t,e){var i;if(this.currentTrackId=e.id,this.abortCurrentFrag(),null==(i=this.levels)||!i.length||-1===this.currentTrackId)return void this.clearInterval();const s=this.levels[this.currentTrackId];null!=s&&s.details?(this.mediaBuffer=this.mediaBufferTimeRanges,this.state!==rr&&this.setInterval(500)):this.mediaBuffer=null}onSubtitleTrackLoaded(t,e){var i;const{currentTrackId:s,levels:r}=this,{details:n,id:o}=e;if(!r)return void this.warn(`Subtitle tracks were reset while loading level ${o}`);const l=r[o];if(o>=r.length||!l)return;this.log(`Subtitle track ${o} loaded [${n.startSN},${n.endSN}]${n.lastPartSn?`[part-${n.lastPartSn}-${n.lastPartIndex}]`:""},duration:${n.totalduration}`),this.mediaBuffer=this.mediaBufferTimeRanges;const h=this.mainDetails;let d=0;if(n.live||null!=(i=l.details)&&i.live){if(n.deltaUpdateFailed)return;if(!h)return void(this.startFragRequested=!1);var c;if(l.details)d=this.alignPlaylists(n,l.details,null==(c=this.levelLastLoaded)?void 0:c.details);n.alignedSliding||(tr(h,n,this),d=n.fragmentStart)}l.details=n,this.levelLastLoaded=l,h&&!this.startFragRequested&&this.setStartPosition(h,d),o===s&&(this.hls.trigger(a.SUBTITLE_TRACK_UPDATED,{details:n,id:o,groupId:e.groupId}),this.tickImmediate())}_handleFragmentLoadProgress(t){const{frag:e,part:i,payload:s}=t;i&&null!=s&&s.byteLength&&this.shouldDecrypt(e)&&this.decryptPayload(s,e,i)}_handleFragmentLoadComplete(t){const{frag:e,payload:i}=t;!this.fragContextChanged(e)&&null!=i&&i.byteLength&&this.shouldDecrypt(e)&&this.decryptPayload(i,e,null)}shouldDecrypt(t){const e=t.decryptdata;return!!(null!=e&&e.key&&e.iv&&ts(e.method))}decryptPayload(t,e,i){const s=e.decryptdata,o=performance.now();this.decrypter.decrypt(new Uint8Array(t),s.key.buffer,s.iv.buffer,es(s.method)).then(t=>{this.fragContextChanged(e)||this.hls.trigger(a.FRAG_DECRYPTED,{frag:e,part:i,payload:t,stats:{tstart:o,tdecrypt:performance.now()}})}).catch(t=>{this.hls.trigger(a.ERROR,{type:r.MEDIA_ERROR,details:n.FRAG_DECRYPT_ERROR,fatal:!1,error:t,reason:t.message,frag:e,part:i}),i||(this.warn(`${t.name}: ${t.message}`),this.state=nr)})}doTick(){if(this.state===nr&&this.levels){var t;if(!this.media&&!this.primaryPrefetch&&(this.startFragRequested||!this.config.startFragPrefetch))return;const{currentTrackId:i,levels:s}=this,r=s[i],n=null==r?void 0:r.details;if(!n||this.waitForLive(r)||this.waitForCdnTuneIn(n))return void(this.startFragRequested=!1);const{config:a}=this,o=this.playhead,l=Bi.bufferedInfo(this.tracksBuffered[this.currentTrackId]||[],o,a.maxBufferHole),{end:h,len:d}=l;if(d>Math.max(this.hls.maxBufferLength+n.levelTargetDuration,(null==(t=this.hls.mainForwardBufferInfo)?void 0:t.len)||0)||d&&!this.buffering)return;let c=this.getNextFragment(h,n);if(!c)return;if(y(c)){var e;const t=c.sn-n.startSN,i=n.fragments[t-1];c.cc!==(null==i?void 0:i.cc)||null!=(e=n.partList)&&e.length||this.fragmentTracker.getState(i)!==pi||(c=i)}this.loadFragment(c,r,h)}}loadFragment(t,e,i){const s=this.fragmentTracker.getState(t);s!==pi&&s!==yi||super.loadFragment(t,e,i)}get mediaBufferTimeRanges(){return new hh(this.tracksBuffered[this.currentTrackId]||[])}},subtitleTrackController:class extends Hn{constructor(t){super(t,"subtitle-track-controller"),this.media=null,this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0,this.queuedDefaultTrack=-1,this.useTextTrackPolling=!1,this.subtitlePollingInterval=-1,this._subtitleDisplay=!0,this.asyncPollTrackChange=()=>this.pollTrackChange(0),this.onTextTracksChanged=()=>{if(this.useTextTrackPolling||self.clearInterval(this.subtitlePollingInterval),!this.media||!this.hls.config.renderTextTracksNatively)return;let t=-1,e=!1;if(this.currentTrack){var i;const s=null==(i=this.currentTrack.trackNode)?void 0:i.track.mode;"showing"===s?(t=this.trackId,e=!0):"hidden"===s&&(t=this.trackId)}if(!e)for(let e=0;e<this.tracksInGroup.length;e++){var s;const i=null==(s=this.tracksInGroup[e].trackNode)?void 0:s.track.mode;if("showing"===i){t=e;break}t<0&&"hidden"===i&&(t=e)}var r;t>-1&&(this._subtitleDisplay="showing"===(null==(r=this.tracksInGroup[t].trackNode)?void 0:r.track.mode));this.setSubtitleTrack(t,!0)},this.registerListeners()}destroy(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.currentTrack=null,this.onTextTracksChanged=this.asyncPollTrackChange=null,super.destroy()}get subtitleDisplay(){return this._subtitleDisplay}set subtitleDisplay(t){this._subtitleDisplay=t,this.trackId>-1&&this.toggleTrackModes()}registerListeners(){const{hls:t}=this;t.on(a.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(a.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(a.MANIFEST_LOADING,this.onManifestLoading,this),t.on(a.MANIFEST_PARSED,this.onManifestParsed,this),t.on(a.LEVEL_LOADING,this.onLevelLoading,this),t.on(a.LEVEL_SWITCHING,this.onLevelSwitching,this),t.on(a.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.on(a.ERROR,this.onError,this)}unregisterListeners(){const{hls:t}=this;t.off(a.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(a.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(a.MANIFEST_LOADING,this.onManifestLoading,this),t.off(a.MANIFEST_PARSED,this.onManifestParsed,this),t.off(a.LEVEL_LOADING,this.onLevelLoading,this),t.off(a.LEVEL_SWITCHING,this.onLevelSwitching,this),t.off(a.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.off(a.ERROR,this.onError,this)}createTracksInGroup(){var t;if(!this.media||!this.hls.config.renderTextTracksNatively)return;this.tracksInGroup.forEach(t=>{t.trackNode||(t.trackNode=Ll(this.media,Il(t),t.name,t.lang))});const e=null==(t=this.currentTrack)||null==(t=t.trackNode)?void 0:t.track;"disabled"===(null==e?void 0:e.mode)&&(e.mode=this._subtitleDisplay?"showing":"hidden")}onMediaAttached(t,e){const i=e.media;this.media=i;let s=this.trackId;this.queuedDefaultTrack>-1&&(s=this.queuedDefaultTrack,this.queuedDefaultTrack=-1),this.setSubtitleTrack(s),this.createTracksInGroup(),this.useTextTrackPolling=!(i.textTracks&&"onchange"in i.textTracks),this.useTextTrackPolling?this.pollTrackChange(500):i.textTracks.addEventListener("change",this.asyncPollTrackChange)}pollTrackChange(t){self.clearInterval(this.subtitlePollingInterval),this.subtitlePollingInterval=self.setInterval(this.onTextTracksChanged,t)}onMediaDetaching(t,e){const i=this.media;if(!i)return;const s=!!e.transferMedia;self.clearInterval(this.subtitlePollingInterval),this.useTextTrackPolling||i.textTracks.removeEventListener("change",this.asyncPollTrackChange),this.trackId>-1&&(this.queuedDefaultTrack=this.trackId,this.setSubtitleTrack(-1)),this.media=null,s||this.hls.config.renderTextTracksNatively&&this.tracksInGroup.forEach(t=>{const e=t.trackNode;e&&(e.track.mode="hidden",e.remove(),t.trackNode=void 0)})}onManifestLoading(){this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0}onManifestParsed(t,e){this.tracks=e.subtitleTracks}onSubtitleTrackLoaded(t,e){const{id:i,groupId:s,details:r}=e,n=this.tracksInGroup[i];if(!n||n.groupId!==s)return void this.warn(`Subtitle track with id:${i} and group:${s} not found in active group ${null==n?void 0:n.groupId}`);const a=n.details;n.details=e.details,this.log(`Subtitle track ${i} "${n.name}" lang:${n.lang} group:${s} loaded [${r.startSN}-${r.endSN}]`),i===this.trackId&&this.playlistLoaded(i,e,a)}onLevelLoading(t,e){this.switchLevel(e.level)}onLevelSwitching(t,e){this.switchLevel(e.level)}switchLevel(t){const e=this.hls.levels[t];if(!e)return;const i=e.subtitleGroups||null,s=this.groupIds;let r=this.currentTrack;if(!i||(null==s?void 0:s.length)!==(null==i?void 0:i.length)||null!=i&&i.some(t=>-1===(null==s?void 0:s.indexOf(t)))){this.groupIds=i;const t=[];if(this.tracks.forEach(e=>{(e.textCodec===fl?this.hls.config.enableIMSC1:this.hls.config.enableWebVTT)&&(!i||i.indexOf(e.groupId)>-1?(e.id=t.length,t.push(e)):e.trackNode&&(e.trackNode.remove(),e.trackNode=void 0))}),t.length===this.tracksInGroup.length){let e=!1;for(let i=0;i<t.length;i++)if(t[i]!==this.tracksInGroup[i]){e=!0;break}if(!e)return}t.length&&this.selectDefaultTrack&&!t.some(t=>t.default)&&(this.selectDefaultTrack=!1),this.tracksInGroup=t,this.trackId=-1,this.currentTrack=null;const e=this.hls.config.subtitlePreference;if(!r&&e){this.selectDefaultTrack=!1;const i=je(e,t);if(i>-1)r=t[i];else{const t=je(e,this.tracks);r=this.tracks[t]}}let s=this.findTrackId(r);-1===s&&r&&(s=this.findTrackId(null));const n={subtitleTracks:t};this.log(`Updating subtitle tracks, ${t.length} track(s) found in "${null==i?void 0:i.join(",")}" group-id`),this.hls.trigger(a.SUBTITLE_TRACKS_UPDATED,n),this.setSubtitleTrack(s),this.createTracksInGroup()}}findTrackId(t){const e=this.tracksInGroup,i=this.selectDefaultTrack;for(let s=0;s<e.length;s++){const r=e[s];if((!i||r.default)&&(i||t)&&(!t||He(r,t)))return s}if(t){for(let i=0;i<e.length;i++){const s=e[i];if(Yn(t.attrs,s.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return i}for(let i=0;i<e.length;i++){const s=e[i];if(Yn(t.attrs,s.attrs,["LANGUAGE"]))return i}}return-1}onError(t,e){!e.fatal&&e.context&&e.context.type===u.SUBTITLE_TRACK&&e.context.id===this.trackId&&ze(e.context.groupId,this.groupIds)&&this.checkRetry(e)}get allSubtitleTracks(){return this.tracks}get subtitleTracks(){return this.tracksInGroup}get subtitleTrack(){return this.trackId}set subtitleTrack(t){this.selectDefaultTrack=!1,this.setSubtitleTrack(t,!0)}setSubtitleOption(t){if(this.hls.config.subtitlePreference=t,t){if(-1===t.id)return this.setSubtitleTrack(-1,!0),null;const e=this.allSubtitleTracks;if(this.selectDefaultTrack=!1,e.length){const i=this.currentTrack;if(i&&He(t,i))return i;const s=je(t,this.tracksInGroup);if(s>-1){const t=this.tracksInGroup[s];return this.setSubtitleTrack(s,!0),t}if(i)return null;{const i=je(t,e);if(i>-1)return e[i]}}}return null}loadPlaylist(t){super.loadPlaylist(),this.shouldLoadPlaylist(this.currentTrack)&&this.scheduleLoading(this.currentTrack,t)}loadingPlaylist(t,e){super.loadingPlaylist(t,e);const i=t.id,s=t.groupId,r=this.getUrlWithDirectives(t.url,e),n=t.details,o=null==n?void 0:n.age;this.log(`Loading subtitle ${i} "${t.name}" lang:${t.lang} group:${s}${void 0!==(null==e?void 0:e.msn)?" at sn "+e.msn+" part "+e.part:""}${o&&n.live?" age "+o.toFixed(1)+(n.type&&" "+n.type||""):""} ${r}`),this.hls.trigger(a.SUBTITLE_TRACK_LOADING,{url:r,id:i,groupId:s,deliveryDirectives:e||null,track:t})}toggleTrackModes(){if(!this.media||!this.hls.config.renderTextTracksNatively)return;const t=this.currentTrack;this.tracksInGroup.forEach(e=>{if(e.trackNode){const i=e===t?this._subtitleDisplay?"showing":"hidden":"disabled",s=e.trackNode.track;s.mode!==i&&(s.mode=i)}})}setSubtitleTrack(t,i=!1){const s=this.tracksInGroup;if(this.media||(this.queuedDefaultTrack=t),t<-1||t>=s.length||!e(t))return void this.warn(`Invalid subtitle track id: ${t}`);const r=this.currentTrack,n=s[t]||null;if(this.trackId=t,this.currentTrack=n,i&&this.toggleTrackModes(),!n)return void(r&&this.hls.trigger(a.SUBTITLE_TRACK_SWITCH,{id:t}));const o=!!n.details&&!n.details.live;if(n===r&&o)return;this.log(`Switching to subtitle-track ${t}`+(n?` "${n.name}" lang:${n.lang} group:${n.groupId}`:""));const{id:l,groupId:h="",name:d,type:c,url:u}=n;this.hls.trigger(a.SUBTITLE_TRACK_SWITCH,{id:l,groupId:h,name:d,type:c,url:u});const f=this.switchParams(n.url,null==r?void 0:r.details,n.details);this.loadPlaylist(f)}},timelineController:class{constructor(t){this.hls=void 0,this.media=null,this.config=void 0,this.enabled=!0,this.Cues=void 0,this.tracks=[],this.initPTS=[],this.unparsedVttFrags=[],this.captionsTracks={},this.cueCache={},this.nonNativeCaptionsTracks={},this.cea608Parser1=void 0,this.cea608Parser2=void 0,this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs={ccOffset:0,presentationOffset:0,0:{start:0,prevCC:-1,new:!0}},this.captionsProperties=void 0,this.hls=t,this.config=t.config,this.Cues=t.config.cueHandler,this.cueCache={},this.captionsProperties={textTrack1:{label:this.config.captionsTextTrack1Label,languageCode:this.config.captionsTextTrack1LanguageCode},textTrack2:{label:this.config.captionsTextTrack2Label,languageCode:this.config.captionsTextTrack2LanguageCode},textTrack3:{label:this.config.captionsTextTrack3Label,languageCode:this.config.captionsTextTrack3LanguageCode},textTrack4:{label:this.config.captionsTextTrack4Label,languageCode:this.config.captionsTextTrack4LanguageCode}},t.on(a.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(a.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(a.MANIFEST_LOADING,this.onManifestLoading,this),t.on(a.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(a.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.on(a.FRAG_LOADING,this.onFragLoading,this),t.on(a.FRAG_LOADED,this.onFragLoaded,this),t.on(a.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),t.on(a.FRAG_DECRYPTED,this.onFragDecrypted,this),t.on(a.INIT_PTS_FOUND,this.onInitPtsFound,this),t.on(a.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),t.on(a.BUFFER_APPENDED,this.onBufferAppended,this),t.on(a.BUFFER_FLUSHING,this.onBufferFlushing,this)}destroy(){const{hls:t}=this;t.off(a.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(a.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(a.MANIFEST_LOADING,this.onManifestLoading,this),t.off(a.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(a.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.off(a.FRAG_LOADING,this.onFragLoading,this),t.off(a.FRAG_LOADED,this.onFragLoaded,this),t.off(a.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),t.off(a.FRAG_DECRYPTED,this.onFragDecrypted,this),t.off(a.INIT_PTS_FOUND,this.onInitPtsFound,this),t.off(a.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),t.off(a.BUFFER_APPENDED,this.onBufferAppended,this),t.off(a.BUFFER_FLUSHING,this.onBufferFlushing,this),this.hls=this.config=this.media=null,this.cea608Parser1=this.cea608Parser2=void 0}initCea608Parsers(){const t=new wh(this,"textTrack1"),e=new wh(this,"textTrack2"),i=new wh(this,"textTrack3"),s=new wh(this,"textTrack4");this.cea608Parser1=new kh(1,t,e),this.cea608Parser2=new kh(3,i,s)}addCues(t,e,i,s,r){let n=!1;for(let t=r.length;t--;){const s=r[t],a=Ph(s[0],s[1],e,i);if(a>=0&&(s[0]=Math.min(s[0],e),s[1]=Math.max(s[1],i),n=!0,a/(i-e)>.5))return}if(n||r.push([e,i]),this.config.renderTextTracksNatively){const r=this.cueCache[t];if(r){const t=this.Cues.newCue(null,e,i,s);t.length&&r.push.apply(r,t)}else{const r=this.captionsTracks[t].track;this.Cues.newCue(r,e,i,s)}}else{var o;const r=this.Cues.newCue(null,e,i,s),n=null==(o=this.captionsProperties[t])?void 0:o.media;this.hls.trigger(a.CUES_PARSED,{type:"captions",cues:r,track:t,closedCaptions:n})}}onInitPtsFound(t,{id:e,timestampOffsets:i}){const{unparsedVttFrags:s}=this;e===f.MAIN&&(this.initPTS=i),s.length&&(this.unparsedVttFrags=[],s.forEach(t=>{this.initPTS[t.frag.cc]?this.onFragLoaded(a.FRAG_LOADED,t):this.hls.trigger(a.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:t.frag,part:null,error:new Error("Subtitle discontinuity domain does not match main")})}))}createCaptionsTrack(t){this.config.renderTextTracksNatively?this.createNativeTrack(t):this.createNonNativeTrack(t)}createNativeTrack(t){if(this.captionsTracks[t])return;const{captionsProperties:e,captionsTracks:i,cueCache:s,media:r}=this,{label:n,languageCode:a}=e[t];r&&(s[t]=[],i[t]=Ll(r,"captions",n,a,"hidden"))}createNonNativeTrack(t){if(this.nonNativeCaptionsTracks[t])return;const e=this.captionsProperties[t];if(!e)return;const i={_id:t,label:e.label,kind:"captions",default:!!e.media&&!!e.media.default,closedCaptions:e.media};this.nonNativeCaptionsTracks[t]=i,this.hls.trigger(a.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:[i]})}onMediaAttaching(t,e){this.media=e.media}onMediaDetaching(t,e){const i=!!e.transferMedia;if(this.media=null,!i){if(this.config.renderTextTracksNatively){const{captionsTracks:t,cueCache:e}=this;for(const i in t)t[i].remove(),delete e[i]}this.cueCache={},this.captionsTracks={},this.nonNativeCaptionsTracks={}}}onManifestLoading(){this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs={ccOffset:0,presentationOffset:0,0:{start:0,prevCC:-1,new:!0}},this.tracks=[],this.captionsTracks={},this.nonNativeCaptionsTracks={},this.unparsedVttFrags=[],this.initPTS=[],this.cea608Parser1&&this.cea608Parser2&&(this.cea608Parser1.reset(),this.cea608Parser2.reset())}onSubtitleTracksUpdated(t,e){const i=e.subtitleTracks||[];if(i.length&&!this.config.renderTextTracksNatively&&!qn(this.tracks,i)){const t=i.map(t=>({label:t.name,kind:t.type.toLowerCase(),default:t.default,subtitleTrack:t}));this.hls.trigger(a.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:t})}this.tracks=i}onManifestLoaded(t,e){this.config.enableCEA708Captions&&e.captions&&e.captions.forEach(t=>{const e=/(?:CC|SERVICE)([1-4])/.exec(t.instreamId);if(!e)return;const i=`textTrack${e[1]}`,s=this.captionsProperties[i];s&&(s.label=t.name,t.lang&&(s.languageCode=t.lang),s.media=t)})}closedCaptionsForLevel(t){const e=this.hls.levels[t.level];return null==e?void 0:e.attrs["CLOSED-CAPTIONS"]}onFragLoading(t,e){if(this.enabled&&e.frag.type===f.MAIN){var i,s;const{cea608Parser1:t,cea608Parser2:r,lastSn:n}=this,{cc:a,sn:o}=e.frag,l=null!=(i=null==(s=e.part)?void 0:s.index)?i:-1;t&&r&&(o!==n+1||o===n&&l!==this.lastPartIndex+1||a!==this.lastCc)&&(t.reset(),r.reset()),this.lastCc=a,this.lastSn=o,this.lastPartIndex=l}}onFragLoaded(t,e){const{frag:i,payload:s}=e;var r;if(i.level<this.tracks.length&&i.type===f.SUBTITLE)if(s.byteLength||null!=(r=i.initSegment)&&null!=(r=r.data)&&r.byteLength){const t=i.decryptdata,s="stats"in e;if(null==t||!t.encrypted||s){const t=this.tracks[i.level],s=this.vttCCs;s[i.cc]||(s[i.cc]={start:i.start,prevCC:this.prevCC,new:!0},this.prevCC=i.cc),(null==t?void 0:t.textCodec)===fl?this._parseIMSC1(e):this._parseVTTs(e)}}else{const t="part"in e?e.part:null;this.hls.trigger(a.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:i,part:t,error:new Error("Empty subtitle payload")})}}_parseIMSC1(t){const{frag:e,payload:i}=t,s="part"in t?t.part:null,r=this.hls;vl(i,this.initPTS[e.cc],t=>{this._appendCues(t,e.level),r.trigger(a.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:e,part:s})},t=>{r.logger.log(`Cannot parse IMSC1 (sn: ${e.sn} @${e.start}): ${t}`),r.trigger(a.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:e,part:s,error:t})})}_parseVTTs(t){var e;const{frag:i,payload:s}=t,r="part"in t?t.part:null,{initPTS:n,unparsedVttFrags:o}=this,l=n.length-1;if(!n[i.cc]&&-1===l)return void o.push(t);const h=this.hls,d=null==(e=i.initSegment)?void 0:e.data;ul(d?Ht(d,new Uint8Array(s)).buffer:s,this.initPTS[i.cc],this.vttCCs,i.cc,(r&&!d?r:i).start,t=>{this._appendCues(t,i.level),h.trigger(a.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:i,part:r})},e=>{const s=e.message.startsWith("Missing initPTS");h.logger.log(`${s?"Deferred parsing of":"Cannot parse"} VTT cue (sn: ${i.sn} @${i.start}): ${e}`),s?o.push(t):(this.config.enableIMSC1&&this._fallbackToIMSC1(t),h.trigger(a.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:i,part:r,error:e}))})}_fallbackToIMSC1(t){const{frag:e,payload:i}=t,s=this.tracks[e.level];s.textCodec||vl(i,this.initPTS[e.cc],()=>{s.textCodec=fl,this._parseIMSC1(t)},()=>{s.textCodec="wvtt"})}_appendCues(t,e){const i=this.hls;if(this.config.renderTextTracksNatively){var s;const i=null==(s=this.tracks[e].trackNode)?void 0:s.track;if(!i||"disabled"===i.mode)return;t.forEach(t=>Rl(i,t))}else{const s=this.tracks[e];if(!s)return;const r=s.default?"default":"subtitles"+e;i.trigger(a.CUES_PARSED,{type:"subtitles",cues:t,track:r,subtitleTrack:s})}}onFragDecrypted(t,e){const{frag:i}=e;i.type===f.SUBTITLE&&this.onFragLoaded(a.FRAG_LOADED,e)}onSubtitleTracksCleared(){this.tracks=[],this.captionsTracks={}}onFragParsingUserdata(t,e){if(!this.enabled||!this.config.enableCEA708Captions)return;const{frag:i,samples:s}=e;if(i.type!==f.MAIN||"NONE"!==this.closedCaptionsForLevel(i))for(let t=0;t<s.length;t++){const e=s[t].bytes;if(e){this.cea608Parser1||this.initCea608Parsers();const i=this.extractCea608Data(e);this.cea608Parser1.addData(s[t].pts,i[0]),this.cea608Parser2.addData(s[t].pts,i[1])}}}onBufferAppended(t,e){if(this.config.renderTextTracksNatively){var i;const{type:t,timeRanges:s}=e;if("video"===t&&null!=(i=s[t])&&i.length){const{captionsTracks:t,cueCache:e}=this;Object.keys(e).forEach(i=>{var s;const r=null==(s=t[i])?void 0:s.track;if(r){const t=e[i];for(let e=0;e<t.length;e++)Rl(r,t[e])}delete e[i]})}}}onBufferFlushing(t,e){const{startOffset:i,endOffset:s,endOffsetSubtitles:r,type:n}=e,{media:a}=this;if(a&&!(a.currentTime<s)){if(!n||"video"===n){const{captionsTracks:t,cueCache:e}=this;Object.keys(t).forEach(e=>kl(t[e].track,i,s)),Object.keys(e).forEach(t=>{const r=e[t];for(let t=r.length;t--;){const e=r[t];e.startTime>=i&&e.endTime<=s&&r.splice(t,1)}})}this.config.renderTextTracksNatively&&0===i&&void 0!==r&&this.tracks.forEach(t=>{var e;const s=null==(e=t.trackNode)?void 0:e.track;s&&kl(s,i,r)})}}extractCea608Data(t){const e=[[],[]],i=31&t[0];let s=2;for(let r=0;r<i;r++){const i=t[s++],r=127&t[s++],n=127&t[s++];if(0===r&&0===n)continue;if(!!(4&i)){const t=3&i;0!==t&&1!==t||(e[t].push(r),e[t].push(n))}}return e}},audioStreamController:class extends pr{constructor(t,e,i){super(t,e,i,"audio-stream-controller",f.AUDIO),this.mainAnchor=null,this.mainFragLoading=null,this.audioOnly=!1,this.bufferedTrack=null,this.switchingTrack=null,this.trackId=-1,this.nextTrackId=-1,this.waitingData=null,this.mainDetails=null,this.flushing=!1,this.bufferFlushed=!1,this.cachedTrackLoadedData=null,this.registerListeners()}onHandlerDestroying(){this.unregisterListeners(),super.onHandlerDestroying(),this.resetItem()}resetItem(){this.mainDetails=this.mainAnchor=this.mainFragLoading=this.bufferedTrack=this.switchingTrack=this.waitingData=this.cachedTrackLoadedData=null}registerListeners(){super.registerListeners();const{hls:t}=this;t.on(a.LEVEL_LOADED,this.onLevelLoaded,this),t.on(a.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),t.on(a.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.on(a.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),t.on(a.BUFFER_RESET,this.onBufferReset,this),t.on(a.BUFFER_CREATED,this.onBufferCreated,this),t.on(a.BUFFER_FLUSHING,this.onBufferFlushing,this),t.on(a.BUFFER_FLUSHED,this.onBufferFlushed,this),t.on(a.INIT_PTS_FOUND,this.onInitPtsFound,this),t.on(a.FRAG_LOADING,this.onFragLoading,this),t.on(a.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){const{hls:t}=this;t&&(super.unregisterListeners(),t.off(a.LEVEL_LOADED,this.onLevelLoaded,this),t.off(a.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),t.off(a.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.off(a.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),t.off(a.BUFFER_RESET,this.onBufferReset,this),t.off(a.BUFFER_CREATED,this.onBufferCreated,this),t.off(a.BUFFER_FLUSHING,this.onBufferFlushing,this),t.off(a.BUFFER_FLUSHED,this.onBufferFlushed,this),t.off(a.INIT_PTS_FOUND,this.onInitPtsFound,this),t.off(a.FRAG_LOADING,this.onFragLoading,this),t.off(a.FRAG_BUFFERED,this.onFragBuffered,this))}onInitPtsFound(t,e){const{frag:i,id:s,initPTS:r,timescale:n,trackId:a,timestampOffsets:o}=e;if(s===f.MAIN){const t=i.cc,e=this.fragCurrent;if(this.initPTS=o,this.log(`InitPTS for cc: ${t} found from main: ${r/n} (${r}/${n}) trackId: ${a}`),this.mainAnchor=i,this.state===gr){const e=this.waitingData;(!e&&!this.loadingParts||e&&e.frag.cc!==t)&&this.syncWithAnchor(i,null==e?void 0:e.frag)}else!this.hls.hasEnoughToStart&&e&&e.cc!==t?(e.abortRequests(),this.syncWithAnchor(i,e)):this.state===nr&&this.tick()}}getLoadPosition(){var t;return!this.startFragRequested&&this.nextLoadPosition>=0&&!1!==(null==(t=this.switchingTrack)?void 0:t.flushImmediate)?this.nextLoadPosition:super.getLoadPosition()}syncWithAnchor(t,e){var i;const s=(null==(i=this.mainFragLoading)?void 0:i.frag)||null;if(e&&(null==s?void 0:s.cc)===e.cc)return;const r=(s||t).cc,n=ei(this.getLevelDetails(),r,this.getLoadPosition());n&&(this.log(`Syncing with main frag at ${n.start} cc ${n.cc}`),this.startFragRequested=!1,this.nextLoadPosition=n.start,this.resetLoadingState(),this.state===nr&&this.doTickIdle())}startLoad(t,e){if(!this.levels)return this.startPosition=t,void(this.state=rr);const i=this.lastCurrentTime;this.stopLoad(),this.setInterval(100),i>0&&-1===t&&!e&&this.initPTS.length&&(this.log(`Override startPosition with lastCurrentTime @${i.toFixed(3)}`),t=i),this.state=nr,this.nextLoadPosition=this.lastCurrentTime=t+this.timelineOffset,this.startPosition=e?-1:t,e||this.fragmentTracker.hasFragments(this.playlistType)||(this.startFragRequested=!1),this.tick()}doTick(){switch(this.state){case nr:this.doTickIdle();break;case hr:{const{levels:t,trackId:e}=this,i=null==t?void 0:t[e],s=null==i?void 0:i.details;if(s&&!this.waitForLive(i)){if(this.waitForCdnTuneIn(s))break;this.state=gr}break}case lr:this.checkRetryDate();break;case gr:{const t=this.waitingData;if(t){const{frag:e,part:i,cache:s,complete:r}=t,n=this.mainAnchor;if(void 0!==this.initPTS[e.cc]){this.waitingData=null,this.state=or;const t={frag:e,part:i,payload:s.flush().buffer,networkDetails:null};this._handleFragmentLoadProgress(t),r&&super._handleFragmentLoadComplete(t)}else n&&n.cc!==t.frag.cc&&this.syncWithAnchor(n,t.frag)}else this.state=nr}}this.onTickEnd()}resetLoadingState(){const t=this.waitingData;t&&(this.fragmentTracker.removeFragment(t.frag),this.waitingData=null),super.resetLoadingState()}onTickEnd(){const{media:t}=this;null!=t&&t.readyState&&(this.lastCurrentTime=t.currentTime,this.checkFragmentChanged())}doTickIdle(){var t;const{hls:e,levels:i,media:s,trackId:r}=this,n=e.config;if(!this.buffering||!s&&!this.primaryPrefetch&&(this.startFragRequested||!n.startFragPrefetch)||null==i||!i[r])return;const o=i[r],l=o.details;if(!l||this.waitForLive(o)||this.waitForCdnTuneIn(l))return this.state=hr,void(this.startFragRequested=!1);const h=this.getBufferOutput();this.bufferFlushed&&h&&(this.bufferFlushed=!1,this.afterBufferFlushed(h,g));const d=this.getFwdBufferInfo();if(null===d)return;if(!this.switchingTrack&&this._streamEnded(d,l))return e.trigger(a.BUFFER_EOS,{type:"audio"}),void(this.state=ur);const c=d.len,u=e.maxBufferLength,m=l.fragments,p=m[0].start,v=this.getLoadPosition(),E=this.flushing||this.switchingTrack&&!this.switchingTrack.flushImmediate?v:d.end;if(this.switchingTrack&&s){const t=v;l.PTSKnown&&t<p&&t>=this.timelineOffset&&(d.end>p||d.nextStart)&&(this.log(`Alt audio track ahead of main track, seek to start of alt audio track ${t} -> ${p} + 0.05`),s.currentTime=p+.05)}if(c>=u&&!this.switchingTrack&&E<m[m.length-1].start)return;let T=this.getNextFragment(E,l);if(T&&this.isLoopLoading(T,E)&&(T=this.getNextFragmentLoopLoading(T,l,d,f.MAIN,u)),!T)return void(this.bufferFlushed=!0);if(this.exceedsMaxBuffer(d,u,T))return;let S=(null==(t=this.mainFragLoading)?void 0:t.frag)||null;if(!this.audioOnly&&this.startFragRequested&&S&&y(T)&&!T.endList&&(!l.live||!this.loadingParts&&E<this.hls.liveSyncPosition)&&(this.fragmentTracker.getState(S)===Ei&&(this.mainFragLoading=S=null),S&&y(S))){if(T.start>S.end){const t=this.fragmentTracker.getFragAtPos(E,f.MAIN);t&&t.end>S.end&&(S=t,this.mainFragLoading={frag:t,targetBufferTime:null})}if(T.start>S.end)return}this.loadFragment(T,o,E)}onMediaDetaching(t,e){this.bufferFlushed=this.flushing=!1,super.onMediaDetaching(t,e)}onAudioTracksUpdated(t,{audioTracks:e}){this.resetTransmuxer(),this.levels=e.map(t=>new Ne(t))}onAudioTrackSwitching(t,e){const i=!!e.url;this.trackId=e.id;const{fragCurrent:s}=this;s&&(s.abortRequests(),this.removeUnbufferedFrags(s.start)),this.resetLoadingState(),i?(this.switchingTrack=e,e.flushImmediate||(this.nextTrackId=e.id,this.nextLevelSwitch()),this.flushAudioIfNeeded(e),this.state!==rr&&(this.setInterval(100),this.state=nr,this.tick())):(this.resetTransmuxer(),this.switchingTrack=null,this.bufferedTrack=e,this.clearInterval())}onManifestLoading(){super.onManifestLoading(),this.bufferFlushed=this.flushing=this.audioOnly=!1,this.resetItem(),this.trackId=-1}onLevelLoaded(t,e){this.mainDetails=e.details;const i=this.cachedTrackLoadedData;i&&(this.cachedTrackLoadedData=null,this.onAudioTrackLoaded(a.AUDIO_TRACK_LOADED,i))}onAudioTrackLoaded(t,e){var i;const{levels:s}=this,{details:r,id:n,groupId:o,track:l}=e;if(!s)return void this.warn(`Audio tracks reset while loading track ${n} "${l.name}" of "${o}"`);const h=this.mainDetails;if(!h||r.endCC>h.endCC||h.expired)return this.cachedTrackLoadedData=e,void(this.state!==rr&&(this.state=hr));this.cachedTrackLoadedData=null,this.log(`Audio track ${n} "${l.name}" of "${o}" loaded [${r.startSN},${r.endSN}]${r.lastPartSn?`[part-${r.lastPartSn}-${r.lastPartIndex}]`:""},duration:${r.totalduration}`);const d=s[n];let c=0;if(r.live||null!=(i=d.details)&&i.live){if(this.checkLiveUpdate(r),r.deltaUpdateFailed)return;var u;if(d.details)c=this.alignPlaylists(r,d.details,null==(u=this.levelLastLoaded)?void 0:u.details);r.alignedSliding||(tr(h,r,this),c=r.fragmentStart)}d.details=r,this.levelLastLoaded=d,this.startFragRequested||this.setStartPosition(h,c),this.hls.trigger(a.AUDIO_TRACK_UPDATED,{details:r,id:n,groupId:e.groupId}),this.state!==hr||this.waitForCdnTuneIn(r)||(this.state=nr),this.tick()}_handleFragmentLoadProgress(t){var e;const i=t.frag,{part:s,payload:r}=t,{config:n,trackId:a,levels:o}=this;if(!o)return void this.warn(`Audio tracks were reset while fragment load was in progress. Fragment ${i.sn} of level ${i.level} will not be buffered`);const l=o[a];if(!l)return void this.warn("Audio track is undefined on fragment load progress");const h=l.details;if(!h)return this.warn("Audio track details undefined on fragment load progress"),void this.removeUnbufferedFrags(i.start);const d=n.defaultAudioCodec||l.audioCodec||"mp4a.40.2";let c=this.transmuxer;c||(c=this.transmuxer=new jn(this.hls,f.AUDIO,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)));const u=this.initPTS[i.cc],g=null==(e=i.initSegment)?void 0:e.data;if(void 0!==u){const t=!1,e=s?s.index:-1,n=-1!==e,a=new Ni(i.level,i.sn,i.stats.chunkCount,r.byteLength,e,n,i.duration);c.push(r,g,d,"",i,s,h.totalduration,t,a,u)}else{this.log(`Unknown video PTS for cc ${i.cc}, waiting for video PTS before demuxing audio frag ${i.sn} of [${h.startSN} ,${h.endSN}],track ${a}`);const{cache:t}=this.waitingData=this.waitingData||{frag:i,part:s,cache:new Er,complete:!1};t.push(new Uint8Array(r)),this.state!==rr&&(this.state=gr)}}_handleFragmentLoadComplete(t){this.waitingData?this.waitingData.complete=!0:super._handleFragmentLoadComplete(t)}onBufferReset(){this.mediaBuffer=null}onBufferCreated(t,e){this.bufferFlushed=this.flushing=!1;const i=e.tracks.audio;i&&(this.mediaBuffer=i.buffer||null)}onFragLoading(t,e){!this.audioOnly&&e.frag.type===f.MAIN&&y(e.frag)&&(this.mainFragLoading=e,this.state===nr&&this.tick())}onFragBuffered(t,e){const{frag:i,part:s}=e;if(i.type===f.AUDIO)if(this.fragContextChanged(i))this.warn(`Fragment ${i.sn}${s?" p: "+s.index:""} of level ${i.level} finished buffering, but was aborted. state: ${this.state}, audioSwitch: ${this.switchingTrack?this.switchingTrack.name:"false"}`);else{if(y(i)){const t=this.switchingTrack;t&&(this.bufferedTrack=t)}this.fragBufferedComplete(i,s),this.media&&this.tick()}else this.audioOnly||i.type!==f.MAIN||i.elementaryStreams.video||i.elementaryStreams.audiovideo||(this.audioOnly=!0,this.mainFragLoading=null)}getFwdBufferInfo(){const t=this.getBufferOutput();return super.getFwdBufferInfo(t,f.AUDIO)}getBufferOutput(){return this.mediaBuffer?this.mediaBuffer:this.media}checkFragmentChanged(){const t=this.fragPlaying;if(!this.checkFragPlaying())return!1;const e=this.fragPlaying,i=null==t?void 0:t.level;return e&&e.level===i||(t&&this.cleanupBackBuffer(),this.switchingTrack&&this.completeAudioSwitch(this.switchingTrack)),!0}onError(t,e){var i;if(e.fatal)this.state=fr;else switch(e.details){case n.FRAG_GAP:case n.FRAG_PARSING_ERROR:case n.FRAG_DECRYPT_ERROR:case n.FRAG_LOAD_ERROR:case n.FRAG_LOAD_TIMEOUT:case n.KEY_LOAD_ERROR:case n.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(f.AUDIO,e);break;case n.AUDIO_TRACK_LOAD_ERROR:case n.AUDIO_TRACK_LOAD_TIMEOUT:case n.LEVEL_PARSING_ERROR:e.levelRetry||this.state!==hr||(null==(i=e.context)?void 0:i.type)!==u.AUDIO_TRACK||(this.state=nr);break;case n.BUFFER_APPEND_NO_PROGRESS:if("audio"!==e.parent)return;e.frag&&(e.appendsWithoutProgress||0)>=this.config.appendErrorMaxRetry&&(this.warn(`Marking fragment ${e.frag.sn} of track ${e.frag.level} as a gap after ${e.appendsWithoutProgress} appends without buffered range growth, to prevent loop loading`),this.fragmentTracker.addAsGap(e.frag));break;case n.BUFFER_ADD_CODEC_ERROR:case n.BUFFER_APPEND_ERROR:if("audio"!==e.parent)return;this.reduceLengthAndFlushBuffer(e)||this.resetLoadingState();break;case n.BUFFER_FULL_ERROR:if("audio"!==e.parent)return;this.reduceLengthAndFlushBuffer(e)&&(this.bufferedTrack=null,super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"));break;case n.INTERNAL_EXCEPTION:this.recoverWorkerError(e)}}onBufferFlushing(t,{type:e}){e!==m&&(this.flushing=!0)}onBufferFlushed(t,{type:e}){if(e!==m){this.flushing=!1,this.bufferFlushed=!0,this.state===ur&&(this.state=nr);const t=this.getBufferOutput();t&&(this.afterBufferFlushed(t,e),this.tick())}}_handleTransmuxComplete(t){var e;const i="audio",{hls:s}=this,{remuxResult:r,chunkMeta:n}=t,o=this.getCurrentContext(n);if(!o)return void this.resetWhenMissingContext(n);const{frag:l,part:h,level:d}=o,{details:c}=d,{audio:u,text:m,id3:p,initSegment:v}=r;if(this.fragContextChanged(l)||!c)return this.fragmentTracker.removeFragment(l),void(null!=v&&v.tracks&&this.resetTransmuxer());if(this.state=dr,u&&this.switchingTrack&&!this.switchingTrack.flushImmediate){const{config:t}=this,e=t.nextAudioTrackBufferFlushForwardOffset,i=Math.max(this.getLoadPosition()+e,l.start);super.flushMainBuffer(i,Number.POSITIVE_INFINITY,f.AUDIO)}if(null!=v&&v.tracks){const t=l.initSegment||l;if(this.unhandledEncryptionError(v,l))return;this._bufferInitSegment(d,v.tracks,t,n),s.trigger(a.FRAG_PARSING_INIT_SEGMENT,{frag:t,id:i,tracks:v.tracks})}if(u){const{startPTS:t,endPTS:e,startDTS:i,endDTS:s}=u;h&&(h.elementaryStreams[g]={startPTS:t,endPTS:e,startDTS:i,endDTS:s}),l.setElementaryStreamInfo(g,t,e,i,s),this.bufferFragmentData(u,l,h,n)}if(null!=p&&null!=(e=p.samples)&&e.length){const t=I({id:i,frag:l,details:c},p);s.trigger(a.FRAG_PARSING_METADATA,t)}if(m){const t=I({id:i,frag:l,details:c},m);s.trigger(a.FRAG_PARSING_USERDATA,t)}}_bufferInitSegment(t,e,i,s){if(this.state!==dr)return;if(e.video&&delete e.video,e.audiovideo&&delete e.audiovideo,!e.audio)return;const r=e.audio;r.id=f.AUDIO;const n=t.audioCodec;this.log(`Init audio buffer, container:${r.container}, codecs[level/parsed]=[${n}/${r.codec}]`),1===(null==n?void 0:n.split(",").length)&&(r.levelCodec=n),this.hls.trigger(a.BUFFER_CODECS,e);const o=r.initSegment;if(null!=o&&o.byteLength){const t={type:"audio",frag:i,part:null,chunkMeta:s,parent:i.type,data:o};this.hls.trigger(a.BUFFER_APPENDING,t)}this.tickImmediate()}loadFragment(t,e,i){const s=this.fragmentTracker.getState(t);var r;if(this.switchingTrack||s===pi||s===yi)if(null!=(r=e.details)&&r.live&&!this.initPTS[t.cc]){this.log(`Waiting for video PTS in continuity counter ${t.cc} of live stream before loading audio fragment ${t.sn} of level ${this.trackId}`),this.state=gr;const i=this.mainDetails;i&&i.fragmentStart!==e.details.fragmentStart&&tr(i,e.details,this)}else super.loadFragment(t,e,i);else this.clearTrackerIfNeeded(t)}flushAudioIfNeeded(t){if(this.media&&this.bufferedTrack&&t.flushImmediate){const{name:e,lang:i,assocLang:s,characteristics:r,audioCodec:n,channels:a}=this.bufferedTrack;He({name:e,lang:i,assocLang:s,characteristics:r,audioCodec:n,channels:a},t,qe)||(We(t.url,this.hls)?(this.log("Switching audio track : flushing all audio"),super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"),this.bufferedTrack=null):this.bufferedTrack=t)}}completeAudioSwitch(t){const{hls:e}=this;this.bufferedTrack=t,this.switchingTrack=null,e.trigger(a.AUDIO_TRACK_SWITCHED,k({},t))}get nextAudioTrack(){return this.nextTrackId}},audioTrackController:class extends Hn{constructor(t){super(t,"audio-track-controller"),this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0,this.registerListeners()}registerListeners(){const{hls:t}=this;t.on(a.MANIFEST_LOADING,this.onManifestLoading,this),t.on(a.MANIFEST_PARSED,this.onManifestParsed,this),t.on(a.LEVEL_LOADING,this.onLevelLoading,this),t.on(a.LEVEL_SWITCHING,this.onLevelSwitching,this),t.on(a.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),t.on(a.ERROR,this.onError,this)}unregisterListeners(){const{hls:t}=this;t.off(a.MANIFEST_LOADING,this.onManifestLoading,this),t.off(a.MANIFEST_PARSED,this.onManifestParsed,this),t.off(a.LEVEL_LOADING,this.onLevelLoading,this),t.off(a.LEVEL_SWITCHING,this.onLevelSwitching,this),t.off(a.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),t.off(a.ERROR,this.onError,this)}destroy(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.currentTrack=null,super.destroy()}onManifestLoading(){this.tracks=[],this.tracksInGroup=[],this.groupIds=null,this.currentTrack=null,this.trackId=-1,this.selectDefaultTrack=!0}onManifestParsed(t,e){this.tracks=e.audioTracks||[]}onAudioTrackLoaded(t,e){const{id:i,groupId:s,details:r}=e,n=this.tracksInGroup[i];if(!n||n.groupId!==s)return void this.warn(`Audio track with id:${i} and group:${s} not found in active group ${null==n?void 0:n.groupId}`);const a=n.details;n.details=e.details,this.log(`Audio track ${i} "${n.name}" lang:${n.lang} group:${s} loaded [${r.startSN}-${r.endSN}]`),i===this.trackId&&this.playlistLoaded(i,e,a)}onLevelLoading(t,e){this.switchLevel(e.level)}onLevelSwitching(t,e){this.switchLevel(e.level)}switchLevel(t){const e=this.hls.levels[t];if(!e)return;const i=e.audioGroups||null,s=this.groupIds;let o=this.currentTrack;if(!i||(null==s?void 0:s.length)!==(null==i?void 0:i.length)||null!=i&&i.some(t=>-1===(null==s?void 0:s.indexOf(t)))){this.groupIds=i,this.trackId=-1,this.currentTrack=null;const t=this.tracks.filter(t=>ze(t.groupId,i));if(t.length)this.selectDefaultTrack&&!t.some(t=>t.default)&&(this.selectDefaultTrack=!1),t.forEach((t,e)=>{t.id=e});else if(!o&&!this.tracksInGroup.length)return;this.tracksInGroup=t;const e=this.hls.config.audioPreference;if(!o&&e){const i=je(e,t,qe);if(i>-1)o=t[i];else{const t=je(e,this.tracks);o=this.tracks[t]}}let s=this.findTrackId(o);-1===s&&o&&(s=this.findTrackId(null));const h={audioTracks:t};this.log(`Updating audio tracks, ${t.length} track(s) found in group(s): ${null==i?void 0:i.join(",")}`),this.hls.trigger(a.AUDIO_TRACKS_UPDATED,h);const d=this.trackId;if(-1!==s&&-1===d)this.setAudioTrack(s);else if(t.length&&-1===d){var l;const e=new Error(`No audio track selected for current audio group-ID(s): ${null==(l=this.groupIds)?void 0:l.join(",")} track count: ${t.length}`);this.warn(e.message),this.hls.trigger(a.ERROR,{type:r.MEDIA_ERROR,details:n.AUDIO_TRACK_LOAD_ERROR,fatal:!0,error:e})}}}onError(t,e){!e.fatal&&e.context&&e.context.type===u.AUDIO_TRACK&&e.context.id===this.trackId&&ze(e.context.groupId,this.groupIds)&&this.checkRetry(e)}get allAudioTracks(){return this.tracks}get audioTracks(){return this.tracksInGroup}get audioTrack(){return this.trackId}set audioTrack(t){this.selectDefaultTrack=!1,this.setAudioTrack(t)}get nextAudioTrack(){return this.trackId}set nextAudioTrack(t){this.selectDefaultTrack=!1,this.setAudioTrack(t,!1)}setAudioOption(t){const e=this.hls;if(e.config.audioPreference=t,t){const i=this.allAudioTracks;if(this.selectDefaultTrack=!1,i.length){const s=this.currentTrack;if(s&&He(t,s,qe))return s;const r=je(t,this.tracksInGroup,qe);if(r>-1){const e=this.tracksInGroup[r];return this.setAudioTrack(r,"flushImmediate"in t&&t.flushImmediate),e}if(s){let s=e.loadLevel;-1===s&&(s=e.firstAutoLevel);const r=function(t,e,i,s,r){const n=e[s],a=e.reduce((t,e,i)=>{const s=e.uri;return(t[s]||(t[s]=[])).push(i),t},{})[n.uri];a.length>1&&(s=Math.max.apply(Math,a));const o=n.videoRange,l=n.frameRate,h=n.codecSet.substring(0,4),d=Ye(e,s,e=>{if(e.videoRange!==o||e.frameRate!==l||e.codecSet.substring(0,4)!==h)return!1;const s=e.audioGroups,n=i.filter(t=>ze(t.groupId,s));return je(t,n,r)>-1});return d>-1?d:Ye(e,s,e=>{const s=e.audioGroups,n=i.filter(t=>ze(t.groupId,s));return je(t,n,r)>-1})}(t,e.levels,i,s,qe);if(-1===r)return null;e.nextLoadLevel=r}if(t.channels||t.audioCodec){const e=je(t,i);if(e>-1)return i[e]}}}return null}setAudioTrack(t,e=!0){const i=this.tracksInGroup;if(t<0||t>=i.length)return void this.warn(`Invalid audio track id: ${t}`);this.selectDefaultTrack=!1;const s=this.currentTrack,r=i[t],n=r.details&&!r.details.live;if(t===this.trackId&&r===s&&n)return;if(this.log(`Switching to audio-track ${t} "${r.name}" lang:${r.lang} group:${r.groupId} channels:${r.channels}`),this.trackId=t,this.currentTrack=r,this.hls.trigger(a.AUDIO_TRACK_SWITCHING,k(k({},r),{},{flushImmediate:e})),n)return;const o=this.switchParams(r.url,null==s?void 0:s.details,r.details);this.loadPlaylist(o)}findTrackId(t){const e=this.tracksInGroup;for(let i=0;i<e.length;i++){const s=e[i];if((!this.selectDefaultTrack||s.default)&&(!t||He(t,s,qe)))return i}if(t){const{name:i,lang:s,assocLang:r,characteristics:n,audioCodec:a,channels:o}=t;for(let t=0;t<e.length;t++){if(He({name:i,lang:s,assocLang:r,characteristics:n,audioCodec:a,channels:o},e[t],qe))return t}for(let i=0;i<e.length;i++){const s=e[i];if(Yn(t.attrs,s.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return i}for(let i=0;i<e.length;i++){const s=e[i];if(Yn(t.attrs,s.attrs,["LANGUAGE"]))return i}}return-1}loadPlaylist(t){super.loadPlaylist();const e=this.currentTrack;this.shouldLoadPlaylist(e)&&We(e.url,this.hls)&&this.scheduleLoading(e,t)}loadingPlaylist(t,e){super.loadingPlaylist(t,e);const i=t.id,s=t.groupId,r=this.getUrlWithDirectives(t.url,e),n=t.details,o=null==n?void 0:n.age;this.log(`Loading audio-track ${i} "${t.name}" lang:${t.lang} group:${s}${void 0!==(null==e?void 0:e.msn)?" at sn "+e.msn+" part "+e.part:""}${o&&n.live?" age "+o.toFixed(1)+(n.type&&" "+n.type||""):""} ${r}`),this.hls.trigger(a.AUDIO_TRACK_LOADING,{url:r,id:i,groupId:s,deliveryDirectives:e||null,track:t})}},emeController:zo,cmcdController:class{constructor(t){this.hls=void 0,this.config=void 0,this.media=void 0,this.initialized=!1,this.starved=!1,this.buffering=!0,this.playerState=void 0,this.reporter=void 0,this.playheadLevel=void 0,this.onWaiting=()=>{this.initialized&&(this.starved=!0,this.setPlayerState(Io)),this.buffering=!0},this.onPlay=()=>{this.initialized||this.setPlayerState(bo)},this.onPlaying=()=>{this.initialized||(this.initialized=!0),this.buffering=!1,this.setPlayerState(Ao)},this.onPause=()=>{this.media&&!this.media.ended&&this.setPlayerState(Ro)},this.onSeeking=()=>{this.initialized&&this.setPlayerState(Lo)},this.onSeeked=()=>{var t;this.initialized&&null!=(t=this.media)&&t.paused&&this.setPlayerState(Ro)},this.onRateChange=()=>{this.reporter&&this.media&&this.reporter.update({pr:this.media.playbackRate})},this.applyPlaylistData=t=>{try{this.apply(t,{ot:po,su:!this.initialized})}catch(t){this.hls.logger.warn("Could not generate manifest CMCD data.",t)}},this.applyFragmentData=t=>{try{const{frag:a,part:o}=t,l=this.hls.levels[a.level],h=this.getObjectType(a,l),d={d:1e3*(o||a).duration,ot:h};if(h===yo||h===vo||h===Eo||null==h&&("main"===a.type||"audio"===a.type)){var i;const t=l.bitrate/1e3;d.br=[t];const{cmcd:r}=this.config,n=null!=(i=null==r?void 0:r.rtpSafetyFactor)?i:5;if(d.rtp=100*Math.round(t*n/100),h===Eo||null==h&&"main"===a.type){const t=this.getTopBandwidth()/1e3;e(t)&&(d.tb=[t]);const i=this.getLowestBandwidth()/1e3;e(i)&&(d.lb=[i])}const o=this.getBufferLength(a);if(e(o)){var s;d.bl=[o];const t=(null==(s=this.media)?void 0:s.playbackRate)||1;d.dl=100*Math.round(o/t/100)}this.playheadLevel&&(d.pb=[this.playheadLevel.bitrate/1e3]);const c=this.hls.maxAutoLevel;if(c>=0){const t=this.hls.levels[c];t&&(d.tpb=[t.bitrate/1e3])}}const c=o?this.getNextPart(o):this.getNextFrag(a);null!=c&&c.url&&c.url!==a.url&&(c.byteRange.length>0?d.nor=[(r=c.url,n={r:`${c.byteRange[0]}-${c.byteRange[1]}`},new na(r,n))]:d.nor=[c.url]),this.apply(t,d)}catch(t){this.hls.logger.warn("Could not generate segment CMCD data.",t)}var r,n},this.recordFragmentResponse=(t,e,i)=>{var s;const{cmcd:r}=this.config,n=null==r||null==(s=r.eventTargets)?void 0:s.some(t=>{var e;return null==(e=t.events)?void 0:e.includes(Ma)});if(this.reporter&&i.loading.first>0&&n)try{this.reporter.recordResponseReceived({request:{url:t},status:e.code,resourceTiming:{startTime:i.loading.start,responseStart:i.loading.first,duration:i.loading.end-i.loading.start,encodedBodySize:i.total}})}catch(t){this.hls.logger.warn("Could not record fragment response CMCD data.",t)}},this.hls=t;const i=this.config=t.config,{cmcd:s}=i;null!=s&&(i.pLoader=this.createPlaylistLoader(),i.fLoader=this.createFragmentLoader(),this.registerListeners())}createReporter(){var t,e;const{cmcd:i}=this.config;if(null==i)return;const s=i.version||1;if(this.reporter=new $o({sid:i.sessionId||this.hls.sessionId,cid:i.contentId,version:s,transmissionMode:!0===i.useHeaders?Po:wo,enabledKeys:null!=(t=i.includeKeys)?t:[...s>=wa?mo:Xa],eventTargets:(null!=(e=i.eventTargets)?e:[]).map(t=>{let{includeKeys:e}=t;return k(k({},_(t,Vo)),{},{enabledKeys:null!=e?e:mo})})},i.loader),this.reporter.update({sf:Bo,sta:this.playerState}),i.reporterCallback){const t=this.reporter,e={updateCustomData:e=>{jo(e)&&t.update(e)},recordCustomEvent:(e,i={})=>{jo(i)&&t.recordEvent(Oa,k({cen:e},i))}};i.reporterCallback(e)}this.reporter.start()}registerListeners(){const t=this.hls;t.on(a.MANIFEST_LOADING,this.onManifestLoading,this),t.on(a.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(a.MEDIA_DETACHED,this.onMediaDetached,this),t.on(a.MEDIA_ENDED,this.onMediaEnded,this),t.on(a.ERROR,this.onError,this),t.on(a.LEVEL_SWITCHING,this.onLevelSwitching,this),t.on(a.LEVEL_SWITCHED,this.onLevelSwitched,this),t.on(a.BUFFER_APPENDED,this.onBufferInfoChange,this),t.on(a.BUFFER_FLUSHED,this.onBufferInfoChange,this)}unregisterListeners(){const t=this.hls;t.off(a.MANIFEST_LOADING,this.onManifestLoading,this),t.off(a.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(a.MEDIA_DETACHED,this.onMediaDetached,this),t.off(a.MEDIA_ENDED,this.onMediaEnded,this),t.off(a.ERROR,this.onError,this),t.off(a.LEVEL_SWITCHING,this.onLevelSwitching,this),t.off(a.LEVEL_SWITCHED,this.onLevelSwitched,this),t.off(a.BUFFER_APPENDED,this.onBufferInfoChange,this),t.off(a.BUFFER_FLUSHED,this.onBufferInfoChange,this)}destroy(){this.unregisterListeners(),this.onMediaDetached(),this.reporter&&(this.reporter.stop(!0),this.reporter=void 0),this.hls=this.config=null,this.onWaiting=this.onPlay=this.onPlaying=this.onPause=null,this.onSeeking=this.onSeeked=this.onRateChange=this.media=null}onMediaAttaching(t,e){const i=this.media=e.media;this.setPlayerState(this.media.autoplay?bo:Do),er(i,"waiting",this.onWaiting),er(i,"play",this.onPlay),er(i,"playing",this.onPlaying),er(i,"pause",this.onPause),er(i,"seeking",this.onSeeking),er(i,"seeked",this.onSeeked),er(i,"ratechange",this.onRateChange)}onMediaDetached(){const t=this.media;t&&(ir(t,"waiting",this.onWaiting),ir(t,"play",this.onPlay),ir(t,"playing",this.onPlaying),ir(t,"pause",this.onPause),ir(t,"seeking",this.onSeeking),ir(t,"seeked",this.onSeeked),ir(t,"ratechange",this.onRateChange),this.media=null)}onMediaEnded(t,e){this.setPlayerState(ko)}onManifestLoading(t,e){this.initialized=!1,this.starved=!1,this.buffering=!0,this.reporter&&(this.reporter.stop(!0),this.reporter=void 0),this.createReporter(),this.media||this.setPlayerState(Do)}onError(t,e){e.fatal&&(this.setPlayerState(_o),this.reporter&&this.reporter.recordEvent(xa,{ec:[e.details]}))}onLevelSwitching(t,e){var i;if(!this.reporter)return;const s={br:[e.bitrate/1e3]},r=null==(i=e.details)?void 0:i.fragments[0];r&&(s.ot=this.getObjectType(r,e)),this.reporter.recordEvent(Ca,s)}onLevelSwitched(t,e){const i=this.hls.levels[e.level];i&&(this.playheadLevel=i)}setPlayerState(t){this.playerState=t,this.reporter&&this.reporter.update({sta:t})}getStreamType(){const t=this.hls.latestLevelDetails;if(t)return t.live?t.partList&&t.canBlockReload?Ko:Go:Uo}apply(t,e={}){var i;if(!this.reporter)return;this.reporter.update({mtp:[this.hls.bandwidthEstimate/1e3],pr:null==(i=this.media)?void 0:i.playbackRate,st:this.getStreamType()});const s=e.ot===To||e.ot===yo||e.ot===Eo;this.starved&&s&&(e.bs=!0,e.su=!0,this.starved=!1),null==e.su&&(e.su=this.buffering);const r=this.reporter.createRequestReport({url:t.url,headers:t.headers},e);t.url=r.url,t.headers=r.headers}getNextFrag(t){var e;const i=null==(e=this.hls.levels[t.level])?void 0:e.details;if(i){const e=t.sn-i.startSN;return i.fragments[e+1]}}getNextPart(t){var e;const{index:i,fragment:s}=t,r=null==(e=this.hls.levels[s.level])||null==(e=e.details)?void 0:e.partList;if(r){const{sn:t}=s;for(let e=r.length-1;e>=0;e--){const s=r[e];if(s.index===i&&s.fragment.sn===t)return r[e+1]}}}getObjectType(t,e){const{type:i}=t;if("subtitle"===i)return So;if("initSegment"===t.sn)return To;if("audio"===i)return vo;if("main"===i){if(t.hasStreams){const e=t.elementaryStreams;if(e.audiovideo)return Eo;if(e.video)return yo;if(e.audio)return vo}if(e){const{audioCodec:t,videoCodec:i}=e;if(!this.hls.audioTracks.length){if(t&&i)return Eo;if(t)return vo}if(i)return yo}}}getTopBandwidth(){let t=0;const e=this.hls,i=e.maxAutoLevel,s=i>-1?i+1:e.levels.length;return e.levels.slice(0,s).forEach(e=>{e.bitrate>t&&(t=e.bitrate)}),t>0?t:NaN}getLowestBandwidth(){let t=1/0;const i=this.hls,s=i.maxAutoLevel,r=s>-1?s+1:i.levels.length;return i.levels.slice(0,r).forEach(e=>{e.bitrate<t&&(t=e.bitrate)}),e(t)?t:NaN}getBufferLength(t){if(!this.media)return NaN;const e="audio"===t.type?this.hls.audioForwardBufferInfo:this.hls.mainForwardBufferInfo;return e?1e3*e.len:NaN}getEventBufferLength(){if(!this.media)return NaN;const t=this.hls.mainForwardBufferInfo,e=this.hls.audioForwardBufferInfo;if(t&&e)return 1e3*Math.min(t.len,e.len);const i=t||e;return i?1e3*i.len:NaN}onBufferInfoChange(t,i){if(!this.reporter)return;const s=this.getEventBufferLength();e(s)&&this.reporter.update({bl:[s]})}createPlaylistLoader(){const{pLoader:t}=this.config,e=this.applyPlaylistData,i=t||this.config.loader;return class{constructor(t){this.loader=void 0,this.loader=new i(t)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(t,i,s){e(t),this.loader.load(t,i,s)}}}createFragmentLoader(){const{fLoader:t}=this.config,e=this.applyFragmentData,i=this.recordFragmentResponse,s=t||this.config.loader;return class{constructor(t){this.loader=void 0,this.loader=new s(t)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(t,s,r){e(t);const{onSuccess:n}=r;this.loader.load(t,s,k(k({},r),{},{onSuccess:(e,s,r,a)=>{n(e,s,r,a),i(t.url,e,s)}}))}}}},contentSteeringController:class extends U{constructor(t){super("content-steering",t.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=t,this.registerListeners()}registerListeners(){const t=this.hls;t.on(a.MANIFEST_LOADING,this.onManifestLoading,this),t.on(a.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(a.MANIFEST_PARSED,this.onManifestParsed,this),t.on(a.ERROR,this.onError,this)}unregisterListeners(){const t=this.hls;t&&(t.off(a.MANIFEST_LOADING,this.onManifestLoading,this),t.off(a.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(a.MANIFEST_PARSED,this.onManifestParsed,this),t.off(a.ERROR,this.onError,this))}pathways(){return(this.levels||[]).reduce((t,e)=>(-1===t.indexOf(e.pathwayId)&&t.push(e.pathwayId),t),[])}get pathwayPriority(){return this._pathwayPriority}set pathwayPriority(t){this.updatePathwayPriority(t)}startLoad(){if(this.started=!0,this.clearTimeout(),this.enabled&&this.uri){if(this.updated){const t=1e3*this.timeToLoad-(performance.now()-this.updated);if(t>0)return void this.scheduleRefresh(this.uri,t)}this.loadSteeringManifest(this.uri)}}stopLoad(){this.started=!1,this.loader&&(this.loader.destroy(),this.loader=null),this.clearTimeout()}clearTimeout(){-1!==this.reloadTimer&&(self.clearTimeout(this.reloadTimer),this.reloadTimer=-1)}destroy(){this.unregisterListeners(),this.stopLoad(),this.hls=null,this.levels=this.audioTracks=this.subtitleTracks=null}removeLevel(t){const e=this.levels;e&&(this.levels=e.filter(e=>e!==t))}onManifestLoading(){this.stopLoad(),this.enabled=!0,this.timeToLoad=300,this.updated=0,this.uri=null,this.pathwayId=".",this.levels=this.audioTracks=this.subtitleTracks=null}onManifestLoaded(t,e){const{contentSteering:i}=e;null!==i&&(this.pathwayId=i.pathwayId,this.uri=i.uri,this.started&&this.startLoad())}onManifestParsed(t,e){this.audioTracks=e.audioTracks,this.subtitleTracks=e.subtitleTracks}onError(t,e){const{errorAction:i}=e;if((null==i?void 0:i.action)===ri&&i.flags&li){const t=this.levels;let s=this._pathwayPriority,r=this.pathwayId;if(e.context){const{groupId:i,pathwayId:s,type:n}=e.context;i&&t?r=this.getPathwayForGroupId(i,n,r):s&&(r=s)}r in this.penalizedPathways||(this.penalizedPathways[r]=performance.now()),!s&&t&&(s=this.pathways()),s&&s.length>1&&(this.updatePathwayPriority(s),i.resolved=this.pathwayId!==r,i.resolved||e.details===n.BUFFER_APPEND_ERROR&&!e.fatal||this.warn(`Could not resolve ${e.details} ("${e.error.message}") with content-steering for Pathway: ${r} levels: ${t?t.length:t} priorities: ${Ue(s)} penalized: ${Ue(this.penalizedPathways)}`))}}filterParsedLevels(t){this.levels=t;let e=this.getLevelsForPathway(this.pathwayId);if(0===e.length){const i=t[0].pathwayId;this.log(`No levels found in Pathway ${this.pathwayId}. Setting initial Pathway to "${i}"`),e=this.getLevelsForPathway(i),this.pathwayId=i}return e.length!==t.length&&this.log(`Found ${e.length}/${t.length} levels in Pathway "${this.pathwayId}"`),e}getLevelsForPathway(t){return null===this.levels?[]:this.levels.filter(e=>t===e.pathwayId)}updatePathwayPriority(t){let e;this._pathwayPriority=t;const i=this.penalizedPathways,s=performance.now();Object.keys(i).forEach(t=>{s-i[t]>3e5&&delete i[t]});for(let s=0;s<t.length;s++){const r=t[s];if(r in i)continue;if(r===this.pathwayId)return;const n=this.hls.nextLoadLevel,o=this.hls.levels[n];if(e=this.getLevelsForPathway(r),e.length>0){this.log(`Setting Pathway to "${r}"`),this.pathwayId=r,Ws(e),this.hls.trigger(a.LEVELS_UPDATED,{levels:e});const t=this.hls.levels[n];o&&t&&this.levels&&(t.attrs["STABLE-VARIANT-ID"]!==o.attrs["STABLE-VARIANT-ID"]&&t.bitrate!==o.bitrate&&this.log(`Unstable Pathways change from bitrate ${o.bitrate} to ${t.bitrate}`),this.hls.nextLoadLevel=n);break}}}getPathwayForGroupId(t,e,i){const s=this.getLevelsForPathway(i).concat(this.levels||[]);for(let i=0;i<s.length;i++)if(e===u.AUDIO_TRACK&&s[i].hasAudioGroup(t)||e===u.SUBTITLE_TRACK&&s[i].hasSubtitleGroup(t))return s[i].pathwayId;return i}clonePathways(t){const e=this.levels;if(!e)return;const i={},s={};t.forEach(t=>{const{ID:r,"BASE-ID":n,"URI-REPLACEMENT":a}=t;if(e.some(t=>t.pathwayId===r))return;const o=this.getLevelsForPathway(n).map(t=>{const e=new Yi(t.attrs);e["PATHWAY-ID"]=r;const n=e.AUDIO&&`${e.AUDIO}_clone_${r}`,o=e.SUBTITLES&&`${e.SUBTITLES}_clone_${r}`;n&&(i[e.AUDIO]=n,e.AUDIO=n),o&&(s[e.SUBTITLES]=o,e.SUBTITLES=o);const l=qo(t.uri,e["STABLE-VARIANT-ID"],"PER-VARIANT-URIS",a),h=new Ne({attrs:e,audioCodec:t.audioCodec,bitrate:t.bitrate,height:t.height,name:t.name,url:l,videoCodec:t.videoCodec,width:t.width});if(t.audioGroups)for(let e=1;e<t.audioGroups.length;e++)h.addGroupId("audio",`${t.audioGroups[e]}_clone_${r}`);if(t.subtitleGroups)for(let e=1;e<t.subtitleGroups.length;e++)h.addGroupId("text",`${t.subtitleGroups[e]}_clone_${r}`);return h});e.push(...o),Ho(this.audioTracks,i,a,r),Ho(this.subtitleTracks,s,a,r)})}loadSteeringManifest(t){const e=this.hls.config,i=e.loader;let s;this.loader&&this.loader.destroy(),this.loader=new i(e);try{s=new self.URL(t)}catch(e){return this.enabled=!1,void this.log(`Failed to parse Steering Manifest URI: ${t}`)}if("data:"!==s.protocol){const t=0|(this.hls.bandwidthEstimate||e.abrEwmaDefaultEstimate);De(s,"_HLS_pathway",this.pathwayId),De(s,"_HLS_throughput",""+t)}const r={type:u.STEERING_MANIFEST,responseType:"json",url:s.href},n=e.steeringManifestLoadPolicy.default,o=n.errorRetry||n.timeoutRetry||{},l={loadPolicy:n,timeout:n.maxLoadTimeMs,maxRetry:o.maxNumRetry||0,retryDelay:o.retryDelayMs||0,maxRetryDelay:o.maxRetryDelayMs||0},h={onSuccess:(t,e,i,r)=>{this.log(`Loaded steering manifest: "${s}"`);const n=t.data;if(1!==(null==n?void 0:n.VERSION))return void this.log(`Steering VERSION ${n.VERSION} not supported!`);this.updated=performance.now(),this.timeToLoad=n.TTL;const{"RELOAD-URI":o,"PATHWAY-CLONES":l,"PATHWAY-PRIORITY":h}=n;if(o)try{this.uri=new self.URL(o,s).href}catch(t){return this.enabled=!1,void this.log(`Failed to parse Steering Manifest RELOAD-URI: ${o}`)}this.scheduleRefresh(this.uri||i.url),l&&this.clonePathways(l);const d={steeringManifest:n,url:s.toString()};this.hls.trigger(a.STEERING_MANIFEST_LOADED,d),h&&this.updatePathwayPriority(h)},onError:(t,e,i,s)=>{if(this.log(`Error loading steering manifest: ${t.code} ${t.text} (${e.url})`),this.stopLoad(),410===t.code)return this.enabled=!1,void this.log(`Steering manifest ${e.url} no longer available`);let r=1e3*this.timeToLoad;if(429===t.code){const t=this.loader;if("function"==typeof(null==t?void 0:t.getResponseHeader)){const e=t.getResponseHeader("Retry-After");e&&(r=1e3*parseFloat(e))}return void this.log(`Steering manifest ${e.url} rate limited`)}this.scheduleRefresh(this.uri||e.url,r)},onTimeout:(t,e,i)=>{this.log(`Timeout loading steering manifest (${e.url})`),this.scheduleRefresh(this.uri||e.url)}};this.log(`Requesting steering manifest: ${s}`),this.loader.load(r,l,h)}scheduleRefresh(t,e=1e3*this.timeToLoad){this.clearTimeout(),this.reloadTimer=self.setTimeout(()=>{var e;const i=null==(e=this.hls)?void 0:e.media;!i||i.ended?this.scheduleRefresh(t,1e3*this.timeToLoad):this.loadSteeringManifest(t)},e)}},iframeController:class extends U{constructor(t,e){var i;super("iframes",t.logger),this.hls=void 0,this.stats=void 0,this.variableList=null,this.initPTS=[],this.iframeInstances=void 0,this.instanceCounter=0,Hl||(i=e,Hl=class extends i{constructor(t,e,i,s){t.streamController||(t.streamController=Gl),super(t),this._url=e,this.streamController.setInitPts(i),this.streamController.initDetails=s}loadSource(){}loadMediaAt(t,e=jl){if(t<0)return;const i=k(k({},jl),e);this.loadingEnabled||this.startLoad(t),this.streamController.loadMediaAt(t,i)}}),ql||(ql=function(t){return class extends t{constructor(t,e,i,s){t.cmcdController=void 0,t.emeController=void 0,t.streamController||(t.streamController=Kl),t.capLevelController=void 0,t.bufferController=void 0,super(t,e,i,s)}attachImage(t){this.streamController.image=t}detachImage(){this.streamController.image=void 0}loadSource(){}attachMedia(){throw new Error(Vl)}detachMedia(){}recoverMediaError(){}transferMedia(){return null}loadMediaAt(t){if(t<0)return null;this.loadingEnabled||this.startLoad(t),this.streamController.loadMediaAt(t)}}}(Hl)),this.hls=t,this.iframeInstances=[],this.registerListeners()}registerListeners(){const t=this.hls;t&&(t.on(a.MANIFEST_LOADING,this.clearAsset,this),t.on(a.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(a.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(a.INIT_PTS_FOUND,this.onInitPtsFound,this),t.on(a.FRAG_BUFFERED,this.onFragBuffered,this),t.on(a.DESTROYING,this.onDestroying,this))}unregisterListeners(){const t=this.hls;t&&(t.off(a.MANIFEST_LOADING,this.clearAsset,this),t.off(a.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(a.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(a.INIT_PTS_FOUND,this.onInitPtsFound,this),t.off(a.FRAG_BUFFERED,this.onFragBuffered,this),t.off(a.DESTROYING,this.onDestroying,this))}clearAsset(){this.stats=void 0,this.variableList=null,this.initPTS=[],this.iframeInstances.forEach(t=>t.destroy()),this.iframeInstances.length=0}onDestroying(){this.unregisterListeners(),this.clearAsset(),this.hls=void 0}onManifestLoaded(t,e){this.stats=e.stats,this.variableList=e.variableList}onLevelsUpdated(t,{levels:e}){var i;const s=null==(i=this.hls)?void 0:i.pathwayPriority;e.length&&s&&this.iframeInstances.forEach(t=>{t.pathwayPriority=s})}onInitPtsFound(t,{id:e,timestampOffsets:i}){e===f.MAIN&&(this.initPTS=i)}onFragBuffered(t,e){var i;const s=this.hls;s&&s.hasEnoughToStart&&((null==(i=s.mainForwardBufferInfo)?void 0:i.len)||0)>10&&this.iframeInstances.forEach(t=>{var e;t.loadingEnabled||t.startLoad((null==(e=this.hls)||null==(e=e.media)?void 0:e.currentTime)||0)})}createIFramePlayer(t){var e;return this.createInstance(Hl,null==(e=this.hls)?void 0:e.iframeVariants,t)}createImageIFramePlayer(t){var e;const i=null==(e=this.hls)?void 0:e.iframeVariants.filter(t=>t.imageCodec);return this.createInstance(ql,i,t,"image-")}createInstance(t,e,i,s){const{hls:r}=this;if(!r)return null;const{url:n,userConfig:o,latestLevelDetails:l,loadLevelObj:h,loadLevel:d,bandwidthEstimate:c,sessionId:u}=r,{stats:f,variableList:g}=this;if(null==e||!e.length||!f||!n)return null;const m=`${s||""}iframe-player-${this.instanceCounter++}`,p=r.levels,v=h||p[d],y=Xe(v,o.videoPreference),E=(null==v?void 0:v.pathwayId)||".",T=new t(k(k({},o),{},{loggerId:m,primarySessionId:u,videoPreference:y,abrEwmaDefaultEstimate:c,streamController:void 0,audioStreamController:void 0,audioTrackController:void 0,subtitleStreamController:void 0,subtitleTrackController:void 0,timelineController:void 0,id3TrackController:void 0,fpsController:void 0,gapController:void 0,iframeController:void 0,cmcd:void 0,interstitialsController:void 0,backBufferLength:1/0,maxMaxBufferLength:1,capLevelToPlayerSize:!0,enableWorker:!1,autoStartLoad:!1,startFragPrefetch:!1,testBandwidth:!1,progressive:!1},i),n,this.initPTS,l);return this.iframeInstances=this.iframeInstances.filter(t=>!t.url),this.iframeInstances.push(T),T.trigger(a.MANIFEST_LOADED,{levels:e,contentSteering:{uri:"",pathwayId:E},sessionKeys:null,audioTracks:[],iframeVariants:[],sessionData:null,startTimeOffset:null,stats:f,networkDetails:null,url:n,variableList:g}),T}},interstitialsController:class extends U{constructor(t,e){super("interstitials",t.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.bufferPastEdge=!1,this.shouldPlay=!1,this.onPlay=()=>{this.shouldPlay=!0},this.onPause=()=>{this.shouldPlay=!1},this.onSeeking=()=>{const t=this.currentTime;if(void 0===t||this.playbackDisabled||!this.schedule)return;const e=t-this.timelinePos;if(Math.abs(e)<1/7056e5)return;const i=e<=-.01;-1!==this.timelinePos||this.effectivePlayingItem||this.checkStart(),this.timelinePos=t,this.bufferedPos=t;const s=this.playingItem;if(!s)return void this.checkBuffer();if(i){this.schedule.resetErrorsInRange(t,t-e)&&this.updateSchedule(!0)}if(this.checkBuffer(),i&&t<s.start||t>=s.end){var r;const e=this.findItemIndex(s);let n=this.schedule.findItemIndexAtTime(t);if(-1===n&&(n=e+(i?-1:1),this.log(`seeked ${i?"back ":""}to position not covered by schedule ${t} (resolving from ${e} to ${n})`)),!this.isInterstitial(s)&&null!=(r=this.media)&&r.paused&&(this.shouldPlay=!1),!i&&n>e){const t=this.schedule.findJumpRestrictedIndex(e+1,n);if(t>e)return void this.setSchedulePosition(t)}return void this.setSchedulePosition(n)}const n=this.playingAsset;if(!n){if(this.playingLastItem&&this.isInterstitial(s)){const e=s.event.assetList[0];e&&(this.endedItem=this.playingItem,this.playingItem=null,this.setScheduleToAssetAtTime(t,e))}return}const a=n.timelineStart,o=n.duration||0;var l;(i&&t<a||t>=a+o)&&(null!=(l=s.event)&&l.appendInPlace&&(this.clearAssetPlayers(s.event,s),this.flushFrontBuffer(t)),this.setScheduleToAssetAtTime(t,n))},this.onTimeupdate=()=>{const t=this.currentTime;if(void 0===t||this.playbackDisabled)return;if(-1!==this.timelinePos||this.effectivePlayingItem||this.checkStart(),!(t>this.timelinePos))return;this.timelinePos=t,t>this.bufferedPos&&this.checkBuffer();const e=this.playingItem;if(!e||this.playingLastItem)return;if(t>=e.end){this.timelinePos=e.end;const t=this.findItemIndex(e);this.setSchedulePosition(t+1)}const i=this.playingAsset;if(!i)return;t>=i.timelineStart+(i.duration||0)&&this.setScheduleToAssetAtTime(t,i)},this.onScheduleUpdate=(t,e)=>{const i=this.schedule;if(!i)return;const s=this.playingItem,r=i.events||[],n=i.items||[],o=i.durations,l=t.map(t=>t.identifier),h=!(!r.length&&!l.length);(h||e)&&this.log(`INTERSTITIALS_UPDATED (${r.length}): ${r}\nSchedule: ${n.map(t=>nh(t))} pos: ${this.timelinePos}`),l.length&&this.log(`Removed events ${l}`);let d=null,c=null;s&&(d=this.updateItem(s,this.timelinePos),this.itemsMatch(s,d)?this.playingItem=d:this.waitingItem=null),this.waitingItem=this.updateItem(this.waitingItem);const u=this.bufferingItem;if(u&&(c=this.updateItem(u,this.bufferedPos),this.itemsMatch(u,c)?this.bufferingItem=c:u.event&&(this.bufferingItem=this.playingItem,this.clearInterstitial(u.event,null))),t.forEach(t=>{t.assetList.forEach(t=>{this.clearAssetPlayer(t.identifier,null)})}),this.playerQueue.forEach(t=>{if(t.interstitial.appendInPlace){const e=t.assetItem.timelineStart,i=t.timelineOffset-e;if(i)try{t.timelineOffset=e}catch(s){Math.abs(i)>Yl&&this.warn(`${s} ("${t.assetId}" ${t.timelineOffset}->${e})`)}}}),h||e){if(this.hls.trigger(a.INTERSTITIALS_UPDATED,{events:r.slice(0),schedule:n.slice(0),durations:o,removedIds:l}),this.isInterstitial(s)&&l.indexOf(s.event.identifier)>-1)return this.warn(`Interstitial "${s.event.identifier}" removed while playing`),void this.primaryFallback(s.event);s&&this.trimInPlace(d,s),u&&c!==d&&this.trimInPlace(c,u),this.checkBuffer()}},this.hls=t,this.HlsPlayerClass=e,this.assetListLoader=new ah(t),this.schedule=new rh(this.onScheduleUpdate,t.logger),this.registerListeners()}registerListeners(){const t=this.hls;t&&(t.on(a.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(a.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(a.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(a.MANIFEST_LOADING,this.onManifestLoading,this),t.on(a.LEVEL_UPDATED,this.onLevelUpdated,this),t.on(a.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.on(a.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),t.on(a.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),t.on(a.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),t.on(a.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),t.on(a.ASSET_LIST_LOADED,this.onAssetListLoaded,this),t.on(a.BUFFER_APPENDED,this.onBufferAppended,this),t.on(a.BUFFER_FLUSHED,this.onBufferFlushed,this),t.on(a.BUFFERED_TO_END,this.onBufferedToEnd,this),t.on(a.MEDIA_ENDED,this.onMediaEnded,this),t.on(a.ERROR,this.onError,this),t.on(a.DESTROYING,this.onDestroying,this))}unregisterListeners(){const t=this.hls;t&&(t.off(a.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(a.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(a.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(a.MANIFEST_LOADING,this.onManifestLoading,this),t.off(a.LEVEL_UPDATED,this.onLevelUpdated,this),t.off(a.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.off(a.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),t.off(a.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),t.off(a.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),t.off(a.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),t.off(a.ASSET_LIST_LOADED,this.onAssetListLoaded,this),t.off(a.BUFFER_CODECS,this.onBufferCodecs,this),t.off(a.BUFFER_APPENDED,this.onBufferAppended,this),t.off(a.BUFFER_FLUSHED,this.onBufferFlushed,this),t.off(a.BUFFERED_TO_END,this.onBufferedToEnd,this),t.off(a.MEDIA_ENDED,this.onMediaEnded,this),t.off(a.ERROR,this.onError,this),t.off(a.DESTROYING,this.onDestroying,this))}startLoad(){this.resumeBuffering()}stopLoad(){this.pauseBuffering()}resumeBuffering(){var t;null==(t=this.getBufferingPlayer())||t.resumeBuffering()}pauseBuffering(){var t;null==(t=this.getBufferingPlayer())||t.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=null,this.assetListLoader=null,this.onPlay=this.onPause=this.onSeeking=this.onTimeupdate=null,this.onScheduleUpdate=null}onDestroying(){const t=this.primaryMedia||this.media;t&&this.removeMediaListeners(t)}removeMediaListeners(t){ir(t,"play",this.onPlay),ir(t,"pause",this.onPause),ir(t,"seeking",this.onSeeking),ir(t,"timeupdate",this.onTimeupdate)}onMediaAttaching(t,e){const i=this.media=e.media;er(i,"seeking",this.onSeeking),er(i,"timeupdate",this.onTimeupdate),er(i,"play",this.onPlay),er(i,"pause",this.onPause)}onMediaAttached(t,e){const i=this.effectivePlayingItem,s=this.detachedData;if(this.detachedData=null,null===i)this.checkStart();else if(!s){this.clearScheduleState();const t=this.findItemIndex(i);this.setSchedulePosition(t)}}clearScheduleState(){this.log("clear schedule state"),this.playingItem=this.bufferingItem=this.waitingItem=this.endedItem=this.playingAsset=this.endedAsset=this.bufferingAsset=null}onMediaDetaching(t,e){const i=!!e.transferMedia,s=this.media;if(this.media=null,!i&&(s&&this.removeMediaListeners(s),this.detachedData)){const t=this.getBufferingPlayer();t&&(this.log(`Removing schedule state for detachedData and ${t}`),this.playingAsset=this.endedAsset=this.bufferingAsset=this.bufferingItem=this.waitingItem=this.detachedData=null,t.detachMedia()),this.shouldPlay=!1}}get interstitialsManager(){if(!this.hls)return null;if(this.manager)return this.manager;const t=this,e=()=>t.bufferingItem||t.waitingItem,i=e=>e?t.getAssetPlayer(e.identifier):e,s=(e,s,n,a,o)=>{if(e){let l=e[s].start;const h=e.event;if(h){if("playout"===s||h.timelineOccupancy!==Wl.Point){const t=i(n);(null==t?void 0:t.interstitial)===h&&(l+=t.assetItem.startOffset+t[o])}}else{l+=("bufferedPos"===a?r():t[a])-e.start}return l}return 0},r=()=>{const e=t.bufferedPos;return e===Number.MAX_VALUE?n("primary"):Math.max(e,0)},n=e=>{var i,s;return null!=(i=t.primaryDetails)&&i.live?t.primaryDetails.edge:(null==(s=t.schedule)?void 0:s.durations[e])||0},a=(e,r)=>{var n,a;const o=t.effectivePlayingItem;if(null!=o&&null!=(n=o.event)&&n.restrictions.skip||!t.schedule)return;t.log(`seek to ${e} "${r}"`);const l=t.effectivePlayingItem,h=t.schedule.findItemIndexAtTime(e,r),d=null==(a=t.schedule.items)?void 0:a[h],c=t.getBufferingPlayer(),u=null==c?void 0:c.interstitial,f=null==u?void 0:u.appendInPlace,g=l&&t.itemsMatch(l,d);if(l&&(f||g)){const n=i(t.playingAsset),a=(null==n?void 0:n.media)||t.primaryMedia;if(a){const i="primary"===r?a.currentTime:s(l,r,t.playingAsset,"timelinePos","currentTime"),o=e-i,h=(f?i:a.currentTime)+o;if(h>=0&&(!n||f||h<=n.duration))return void(a.currentTime=h)}}if(d){let i=e;if("primary"!==r){const t=e-d[r].start;i=d.start+t}const s=!t.isInterstitial(d);if(t.isInterstitial(l)&&!l.event.appendInPlace||!s&&!d.event.appendInPlace){if(l){const n=t.findItemIndex(l);if(h>n){const e=t.schedule.findJumpRestrictedIndex(n+1,h);if(e>n)return void t.setSchedulePosition(e)}let a=0;if(s)t.timelinePos=i,t.checkBuffer();else{const t=d.event.assetList,i=e-(d[r]||d).start;for(let e=t.length;e--;){const s=t[e];if(s.duration&&i>=s.startOffset&&i<s.startOffset+s.duration){a=e;break}}}t.setSchedulePosition(h,a)}}else{const e=t.media||(f?null==c?void 0:c.media:null);e&&(e.currentTime=i)}}},o=()=>{const i=t.effectivePlayingItem;if(t.isInterstitial(i))return i;const s=e();return t.isInterstitial(s)?s:null},l={get bufferedEnd(){const i=e(),r=t.bufferingItem;var n;return r&&r===i&&(s(r,"playout",t.bufferingAsset,"bufferedPos","bufferedEnd")-r.playout.start||(null==(n=t.bufferingAsset)?void 0:n.startOffset))||0},get currentTime(){const e=o(),i=t.effectivePlayingItem;return i&&i===e?s(i,"playout",t.effectivePlayingAsset,"timelinePos","currentTime")-i.playout.start:0},set currentTime(e){const i=o(),s=t.effectivePlayingItem;s&&s===i&&a(e+s.playout.start,"playout")},get duration(){const t=o();return t?t.playout.end-t.playout.start:0},get assetPlayers(){var e;const i=null==(e=o())?void 0:e.event.assetList;return i?i.map(e=>t.getAssetPlayer(e.identifier)):[]},get playingIndex(){var e;const i=null==(e=o())?void 0:e.event;return i&&t.effectivePlayingAsset?i.findAssetIndex(t.effectivePlayingAsset):-1},get scheduleItem(){return o()}};return this.manager={get events(){var e;return(null==(e=t.schedule)||null==(e=e.events)?void 0:e.slice(0))||[]},get schedule(){var e;return(null==(e=t.schedule)||null==(e=e.items)?void 0:e.slice(0))||[]},get interstitialPlayer(){return o()?l:null},get playerQueue(){return t.playerQueue.slice(0)},get bufferingAsset(){return t.bufferingAsset},get bufferingItem(){return e()},get bufferingIndex(){const i=e();return t.findItemIndex(i)},get playingAsset(){return t.effectivePlayingAsset},get playingItem(){return t.effectivePlayingItem},get playingIndex(){const e=t.effectivePlayingItem;return t.findItemIndex(e)},primary:{get bufferedEnd(){return r()},get currentTime(){const e=t.timelinePos;return e>0?e:0},set currentTime(t){a(t,"primary")},get duration(){return n("primary")},get seekableStart(){return t.seekableStart}},integrated:{get bufferedEnd(){return s(e(),"integrated",t.bufferingAsset,"bufferedPos","bufferedEnd")},get currentTime(){return s(t.effectivePlayingItem,"integrated",t.effectivePlayingAsset,"timelinePos","currentTime")},set currentTime(t){a(t,"integrated")},get duration(){return n("integrated")},get seekableStart(){return((e,i)=>{var s;if(0!==e&&"primary"!==i&&null!=(s=t.schedule)&&s.length){var r;const s=t.schedule.findItemIndexAtTime(e),n=null==(r=t.schedule.items)?void 0:r[s];if(n)return e+(n[i].start-n.start)}return e})(t.seekableStart,"integrated")}},skip:()=>{const e=t.effectivePlayingItem,i=null==e?void 0:e.event;if(i&&!i.restrictions.skip){const s=t.findItemIndex(e);if(i.appendInPlace){const t=e.playout.start+e.event.duration;a(t+.001,"playout")}else t.advanceAfterAssetEnded(i,s,1/0)}}}}get effectivePlayingItem(){return this.waitingItem||this.playingItem||this.endedItem}get effectivePlayingAsset(){return this.playingAsset||this.endedAsset}get playingLastItem(){var t;const e=this.playingItem,i=null==(t=this.schedule)?void 0:t.items;return!!(this.playbackStarted&&e&&i)&&this.findItemIndex(e)===i.length-1}get playbackStarted(){return null!==this.effectivePlayingItem}get currentTime(){var t,i;if(null===this.mediaSelection)return;const s=this.waitingItem||this.playingItem;if(this.isInterstitial(s)&&!s.event.appendInPlace)return;let r=this.media;!r&&null!=(t=this.bufferingItem)&&null!=(t=t.event)&&t.appendInPlace&&(r=this.primaryMedia);const n=null==(i=r)?void 0:i.currentTime;return void 0!==n&&e(n)?n:void 0}get primaryMedia(){var t;return this.media||(null==(t=this.detachedData)?void 0:t.media)||null}isInterstitial(t){return!(null==t||!t.event)}retreiveMediaSource(t,e){const i=this.getAssetPlayer(t);i&&this.transferMediaFromPlayer(i,e)}transferMediaFromPlayer(t,e){const i=t.interstitial.appendInPlace,s=t.media;if(i&&s===this.primaryMedia){if(this.bufferingAsset=null,(!e||this.isInterstitial(e)&&!e.event.appendInPlace)&&e&&s)return void(this.detachedData={media:s});const i=t.transferMedia();this.log(`transfer MediaSource from ${t} ${Ue(i)}`),this.detachedData=i}else e&&s&&(this.shouldPlay||(this.shouldPlay=!s.paused))}transferMediaTo(t,e){var i,s;if(t.media===e)return;let r=null;const n=this.hls,a=t!==n,o=a&&t.interstitial.appendInPlace,l=null==(i=this.detachedData)?void 0:i.mediaSource;let h;if(n.media)o&&(r=n.transferMedia(),this.detachedData=r),h="Primary";else{const t=this.getBufferingPlayer();t?(r=t.transferMedia(),this.detachedData=r,h=`${t}`):h=l?"detached MediaSource":"detached media"}if(!r)if(l)r=this.detachedData,this.log(`using detachedData: MediaSource ${Ue(r)}`);else if(!this.detachedData||n.media===e){const t=this.playerQueue;t.length>1&&t.forEach(t=>{if(a&&t.interstitial.appendInPlace!==o){const e=t.interstitial;this.clearInterstitial(t.interstitial,null),e.appendInPlace=!1,e.appendInPlace&&this.warn(`Could not change append strategy for queued assets ${e}`)}}),this.hls.detachMedia(),this.detachedData={media:e}}const d=r&&"mediaSource"in r&&"closed"!==(null==(s=r.mediaSource)?void 0:s.readyState);if(this.log(`${d?"transfering MediaSource":"attaching media"} to ${a?t:"Primary"} from ${h} (media.currentTime: ${e.currentTime})`),!d&&!a)return void t.attachMedia(e);const c=d&&r?k({},r):{media:e},u=this.schedule;if(u&&a){const e=t.assetId===u.assetIdAtEnd;c.overrides={duration:u.duration,endOfStream:e||!1===t.appendInPlace}}if(!d&&o){const e=t,i=e.assetItem.timelineStart;if(i){const t=e.hls,s=Math.max(this.timelinePos-i,Number.EPSILON);t.startPosition!==s&&(this.log(`Set ${e} startPosition: ${s}`),t.config.startPosition=s,t.loadingEnabled&&t.startLoad(s))}}t.attachMedia(c)}onInterstitialCueEnter(){this.onTimeupdate()}checkStart(){const t=this.schedule,e=null==t?void 0:t.events,i=this.hls;if(!e||this.playbackDisabled||!this.media||!i)return;-1===this.bufferedPos&&(this.bufferedPos=0);const s=this.timelinePos,r=this.effectivePlayingItem;if(-1===s){if(!i.loadingEnabled)return void this.log("waiting for startLoad( <startPosition> )");const s=i.startPosition;if(this.timelinePos=s,0===e.length)this.setSchedulePosition(0);else if(e[0].cue.pre){this.log(lh("checkStart (preroll)",s));const i=t.findEventIndex(e[0].identifier);this.setSchedulePosition(i)}else if(s>=0||!this.primaryLive){this.log(lh("checkStart",s));const e=this.timelinePos=s>0?s:0,i=t.findItemIndexAtTime(e);this.setSchedulePosition(i)}else 0===i.liveSyncPosition?this.setSchedulePosition(0):this.log("[checkStart] waiting for live start")}else if(r&&!this.playingItem){this.log(lh("checkStart (playing item)",r.start));const e=t.findItemIndex(r);this.setSchedulePosition(e)}}advanceAssetBuffering(t,e){const i=t.event,s=i.findAssetIndex(e),r=th(i,s);if(i.isAssetPastPlayoutLimit(r)){if(this.schedule){var n;const e=this.getNextItemIndex(t,!0),i=null==(n=this.schedule.items)?void 0:n[e];i&&this.bufferedToItem(i)}}else this.bufferedToEvent(t,r)}livePrerollResumption(t,i){if(t.cue.pre&&this.primaryLive&&!e(t.resumeOffset)&&this.hls){const t=this.getLiveStartPos();if(i){const e=this.getBufferingPlayer();return t+(null!=e&&e.interstitial.cue.pre?e.remaining:0)}return t}}getNextItemIndex(t,e){if(this.schedule){const i=this.livePrerollResumption(t.event,e);if(void 0!==i)return this.log(`find next item index @${i}`),this.schedule.findItemIndexAtTime(i)}return this.findItemIndex(t)+1}advanceAfterAssetEnded(t,e,i){const s=th(t,i);if(t.isAssetPastPlayoutLimit(s)){if(this.schedule){const i=this.schedule.items;if(i){const s=i[e],r=s.event?this.getNextItemIndex(s):e+1;if(r>=i.length)return void this.setSchedulePosition(-1);const n=t.resumeTime;this.timelinePos<n&&(this.log(lh("advanceAfterAssetEnded",n)),this.timelinePos=n,t.appendInPlace&&!i[r].event&&this.hls.startLoad(n+.01),this.checkBuffer(this.bufferedPos<n)),this.setSchedulePosition(r)}}}else{if(t.appendInPlace){const e=t.assetList[s];e&&this.advanceInPlace(e.timelineStart)}this.setSchedulePosition(e,s)}}setScheduleToAssetAtTime(t,e){const i=this.schedule;if(!i)return;const s=e.parentIdentifier,r=i.getEvent(s);if(r){const e=i.findEventIndex(s),n=i.findAssetIndex(r,t);this.advanceAfterAssetEnded(r,e,n-1)}}setSchedulePosition(t,e){var i;const s=null==(i=this.schedule)?void 0:i.items;if(!s||this.playbackDisabled)return;const r=t>=0?s[t]:null;this.log(`setSchedulePosition ${t}, ${e} (${r?nh(r):r}) pos: ${this.timelinePos}`);const n=this.waitingItem||this.playingItem,o=this.playingLastItem;if(this.isInterstitial(n)){const i=n.event,c=this.playingAsset,u=null==c?void 0:c.identifier,f=u?this.getAssetPlayer(u):null;if(f&&u&&(!this.eventItemsMatch(n,r)||void 0!==e&&u!==i.assetList[e].identifier)){var l;const e=i.findAssetIndex(c);if(this.log(`INTERSTITIAL_ASSET_ENDED ${e+1}/${i.assetList.length} ${eh(c)}`),this.endedAsset=c,this.playingAsset=null,this.hls.trigger(a.INTERSTITIAL_ASSET_ENDED,{asset:c,assetListIndex:e,event:i,schedule:s.slice(0),scheduleIndex:t,player:f}),n!==this.playingItem)return void(this.itemsMatch(n,this.playingItem)&&!this.playingAsset&&this.advanceAfterAssetEnded(i,this.findItemIndex(this.playingItem),e));this.retreiveMediaSource(u,r),!f.media||null!=(l=this.detachedData)&&l.mediaSource||f.detachMedia()}if(!this.eventItemsMatch(n,r)&&(this.endedItem=n,this.playingItem=this.waitingItem=null,this.log(`INTERSTITIAL_ENDED ${i} ${nh(n)}`),i.hasPlayed=!0,this.hls.trigger(a.INTERSTITIAL_ENDED,{event:i,schedule:s.slice(0),scheduleIndex:t}),i.cue.once&&this.hls)){var h;this.updateSchedule();const t=null==(h=this.schedule)?void 0:h.items;if(r&&t){const a=this.findItemIndex(r),l=this.livePrerollResumption(i);if(void 0!==l){let e=l;const r=this.getNextItemIndex(n);if(!this.isInterstitial(s[r])){var d;const t=null==(d=this.primaryDetails)?void 0:d.fragments;if(i.snapOptions.in&&t){const i=Ze(null,t,l);i&&(e=Math.min(Math.max(s[r].start,Ql(e,i)),s[r].end))}}if(this.log(lh("live join (preroll)",e)),this.timelinePos=e,r!==a&&(r||0===r))return void this.advanceSchedule(r,t,void 0,n,o)}this.advanceSchedule(a,t,e,n,o)}return}}this.advanceSchedule(t,s,e,n,o)}advanceSchedule(t,e,i,s,r){const n=this.schedule;if(!n)return;const o=e[t]||null,l=this.primaryMedia,h=this.playerQueue;if(h.length&&h.forEach(e=>{const i=e.interstitial,s=n.findEventIndex(i.identifier);(s<t||s>t+1)&&this.clearInterstitial(i,o)}),this.isInterstitial(o)){this.timelinePos=Math.min(Math.max(this.timelinePos,o.start),o.end);const r=o.event;if(void 0===i){const e=th(r,(i=r.cue.pre?0:n.findAssetIndex(r,this.timelinePos))-1);if(r.isAssetPastPlayoutLimit(e)||r.appendInPlace&&this.timelinePos===o.end)return void this.advanceAfterAssetEnded(r,t,i);i=e}const h=this.waitingItem;this.assetsBuffered(o,l)||this.setBufferingItem(o);let d=this.preloadAssets(r,i);if(this.eventItemsMatch(o,h||s)||(this.waitingItem=o,this.log(`INTERSTITIAL_STARTED ${nh(o)} ${r.appendInPlace?"append in place":""}`),r.hasPlayed=!1,this.hls.trigger(a.INTERSTITIAL_STARTED,{event:r,schedule:e.slice(0),scheduleIndex:t})),!r.assetListLoaded)return void this.log(`Waiting for ASSET-LIST to complete loading ${r}`);if(r.assetListLoader&&(r.assetListLoader.destroy(),r.assetListLoader=void 0),!l)return void this.log(`Waiting for attachMedia to start Interstitial ${r}`);this.waitingItem=this.endedItem=null,this.playingItem=o;const c=r.assetList[i];if(!c)return void this.advanceAfterAssetEnded(r,t,i||0);if(d||(d=this.getAssetPlayer(c.identifier)),null===d||d.destroyed){const t=r.assetList.length;this.warn(`asset ${i+1}/${t} player destroyed ${r}`),d=this.createAssetPlayer(r,c,i),d.loadSource()}if(!this.eventItemsMatch(o,this.bufferingItem)&&r.appendInPlace&&this.isAssetBuffered(c))return;this.startAssetPlayer(d,i,e,t,l),this.shouldPlay&&oh(d.media)}else o?(this.resumePrimary(o,t,s),this.shouldPlay&&oh(this.hls.media)):r&&this.isInterstitial(s)&&(this.endedItem=null,this.playingItem=s,s.event.appendInPlace||this.attachPrimary(n.durations.primary,null))}get playbackDisabled(){return!1===this.hls.config.enableInterstitialPlayback}get primaryDetails(){var t;return null==(t=this.mediaSelection)?void 0:t.main.details}get primaryLive(){var t;return!(null==(t=this.primaryDetails)||!t.live)}resumePrimary(t,e,i){var s,r;this.playingItem=t,this.playingAsset=this.endedAsset=null,this.waitingItem=null,this.bufferedToItem(t),this.endedItem=null,this.log(`resuming ${nh(t)}`);let n=this.timelinePos;if(null!=(s=this.detachedData)&&s.mediaSource?this.primaryLive&&this.startLoadingPrimaryAt(n):((n<t.start||n>=t.end||n<this.seekableStart)&&(n=this.getPrimaryResumption(t,e),this.log(lh("resumePrimary",n)),this.timelinePos=n),this.attachPrimary(n,t)),!i)return;const o=null==(r=this.schedule)?void 0:r.items;o&&(this.log(`INTERSTITIALS_PRIMARY_RESUMED ${nh(t)}`),this.hls.trigger(a.INTERSTITIALS_PRIMARY_RESUMED,{schedule:o.slice(0),scheduleIndex:e}),this.checkBuffer())}get seekableStart(){var t;return this.primaryLive&&(null==(t=this.primaryDetails)?void 0:t.fragmentStart)||0}getPrimaryResumption(t,e,i){const s=t.start;if(this.primaryLive){if(0===e)return this.hls.startPosition;const t=this.endedItem||this.playingItem,r=null!=t&&t.event?this.livePrerollResumption(t.event,i):void 0;if(void 0!==r)return r;const n=this.primaryDetails;if(n){const{fragmentStart:t,edge:e}=n;if(s<t||s>e&&!i){const i=this.hls.liveSyncPosition;return this.log(`primary resumption out of bounds (${s} [${t}-${e}]) snapping to liveSync ${i}`),i||t}}}return this.log(`primary resumption itemStart: ${s}`),s}getLiveStartPos(){var t;const e=this.hls.startPosition,i=this.hls.liveSyncPosition||0,s=3*((null==(t=this.primaryDetails)?void 0:t.targetduration)||10);return-1===e||i&&i-e<s?i||0:e}isAssetBuffered(t){const e=this.getAssetPlayer(t.identifier);if(null!=e&&e.hls)return e.hls.bufferedToEnd;return Bi.bufferInfo(this.primaryMedia,this.timelinePos,0).end+1>=t.timelineStart+(t.duration||0)}attachPrimary(t,e,i){e?this.setBufferingItem(e):this.bufferingItem=this.playingItem,this.bufferingAsset=null;const s=this.primaryMedia;if(!s)return;const r=this.hls;r.media?this.checkBuffer():(this.transferMediaTo(r,s),i&&this.startLoadingPrimaryAt(t,i)),i||(this.log(lh("attachPrimary",t)),this.timelinePos=t,this.startLoadingPrimaryAt(t,i))}startLoadingPrimaryAt(t,e){const i=this.hls,{loadingEnabled:s,bufferingEnabled:r,startPosition:n}=i,a=i.hasEnoughToStart;if(this.log(`Start loading primary @${t} bufferedPos: ${this.bufferedPos} startPosition: ${n} skip seek: ${e} has enough ${a} loadingEnabled: ${s} bufferingEnabled: ${r}`),!e&&a||!s||Math.abs(n-t)>.1){const s=this.primaryDetails;if(null!=s&&s.live&&t+.5>=s.edge){const e=this.bufferingItem;return this.log(`Resume primary loading when live passes ${t} buffering item: ${e?nh(e):null}`),i.pauseBuffering(),void(this.bufferPastEdge=!0)}i.startLoad(t,e)}else r||i.resumeBuffering()}onManifestLoading(){var t;this.stopLoad(),null==(t=this.schedule)||t.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(a.BUFFER_CODECS,this.onBufferCodecs,this),this.hls.on(a.BUFFER_CODECS,this.onBufferCodecs,this)}onLevelUpdated(t,e){if(-1===e.level||!this.schedule)return;const i=this.hls.levels[e.level];if(!i.details)return;const s=k(k({},this.mediaSelection||this.altSelection),{},{main:i});this.mediaSelection=s;const r=this.hls.startPosition;this.schedule.parseInterstitialDateRanges(s,this.hls.config.interstitialAppendInPlace,-1===r?0:r);if(this.schedule.items)if(this.effectivePlayingItem){if(this.bufferPastEdge){const t=this.primaryDetails,e=this.bufferedPos;if(null!=t&&t.live&&e+.5<t.edge){this.bufferPastEdge=!1;const i=this.bufferingItem;this.log(`Live edge ${t.edge} passed buffer: ${e} buffering item: ${i?nh(i):null}`);if((null==i?void 0:i.end)===1/0){const t=this.playingItem,s=this.isInterstitial(t)&&t.event.appendInPlace;this.hls.startLoad(Math.max(e,i.start),s)}else{const t=this.getBufferingPlayer();if(t){t.bufferedInPlaceToEnd(this.primaryMedia,t.currentTime)&&t.hls&&t.hls.trigger(a.BUFFERED_TO_END,void 0)}}}}}else this.checkStart()}onAudioTrackUpdated(t,e){const i=this.hls.audioTracks[e.id],s=this.mediaSelection;if(!s)return void(this.altSelection=k(k({},this.altSelection),{},{audio:i}));const r=k(k({},s),{},{audio:i});this.mediaSelection=r}onSubtitleTrackUpdated(t,e){const i=this.hls.subtitleTracks[e.id],s=this.mediaSelection;if(!s)return void(this.altSelection=k(k({},this.altSelection),{},{subtitles:i}));const r=k(k({},s),{},{subtitles:i});this.mediaSelection=r}onAudioTrackSwitching(t,e){const i=Ve(e);this.playerQueue.forEach(({hls:t})=>t&&(t.setAudioOption(e)||t.setAudioOption(i)))}onSubtitleTrackSwitch(t,e){const i=Ve(e);this.playerQueue.forEach(({hls:t})=>t&&(t.setSubtitleOption(e)||-1!==e.id&&t.setSubtitleOption(i)))}onBufferCodecs(t,e){const i=e.tracks;i&&(this.requiredTracks=i)}onBufferAppended(t,e){this.checkBuffer()}onBufferFlushed(t,e){const i=this.playingItem;if(i&&!this.itemsMatch(i,this.bufferingItem)&&!this.isInterstitial(i)){const t=this.timelinePos;this.bufferedPos=t,this.checkBuffer()}}onBufferedToEnd(t){if(!this.schedule)return;const e=this.schedule.events;if(this.bufferedPos<Number.MAX_VALUE&&e){for(let t=0;t<e.length;t++){const i=e[t];if(i.cue.post){const t=this.getEventItem(i.identifier);t&&this.eventItemsMatch(t,this.bufferingItem)&&this.bufferedToItem(t,0);break}}this.bufferedPos=Number.MAX_VALUE}}onMediaEnded(t){const e=this.playingItem;if(!this.playingLastItem&&e){const t=this.findItemIndex(e);this.setSchedulePosition(t+1)}else this.shouldPlay=!1}updateItem(t,e){var i;const s=null==(i=this.schedule)?void 0:i.items;if(t&&s){return s[this.findItemIndex(t,e)]||null}return null}trimInPlace(t,e){if(this.isInterstitial(t)&&t.event.appendInPlace&&e.end-t.end>.25){t.event.assetList.forEach((e,i)=>{t.event.isAssetPastPlayoutLimit(i)&&this.clearAssetPlayer(e.identifier,null)});const i=t.end+.25,s=Bi.bufferInfo(this.primaryMedia,i,0);if(s.end>i||(s.nextStart||0)>i){this.log(`trim buffered interstitial ${nh(t)} (was ${nh(e)})`);const s=!0;this.attachPrimary(i,null,s),this.flushFrontBuffer(i)}}}itemsMatch(t,e){return!!e&&(t===e||t.event&&e.event&&this.eventItemsMatch(t,e)||!t.event&&!e.event&&this.findItemIndex(t)===this.findItemIndex(e))}eventItemsMatch(t,e){var i;return!!e&&(t===e||t.event.identifier===(null==(i=e.event)?void 0:i.identifier))}findEventIndex(t){return this.schedule?this.schedule.findEventIndex(t):-1}getEventItem(t){if(this.schedule){var e;const i=null==(e=this.schedule.items)?void 0:e[this.findEventIndex(t)];if(this.isInterstitial(i)&&i.event.identifier===t)return i}}findItemIndex(t,e){return t&&this.schedule?this.schedule.findItemIndex(t,e):-1}updateSchedule(t=!1){var e,i;const s=this.mediaSelection;if(!s)return;const r=(null==(e=this.hls)?void 0:e.liveSyncPosition)||0;null==(i=this.schedule)||i.updateSchedule(s,[],r,t)}checkBuffer(t){var e;const i=null==(e=this.schedule)?void 0:e.items;if(!i)return;const s=Bi.bufferInfo(this.primaryMedia,this.timelinePos,0);t&&(this.bufferedPos=this.timelinePos),t||(t=s.len<1),this.updateBufferedPos(s.end,i,t)}updateBufferedPos(t,e,i){const s=this.schedule,r=this.bufferingItem;if(this.bufferedPos>t||!s)return;if(1===e.length&&this.itemsMatch(e[0],r))return void(this.bufferedPos=t);const n=this.playingItem,a=this.findItemIndex(n);let o=s.findItemIndexAtTime(t);if(this.bufferedPos<t){var l;const i=this.findItemIndex(r),s=Math.min(i+1,e.length-1),n=e[s];if((-1===o&&r&&t>=r.end||null!=(l=n.event)&&l.appendInPlace&&t+.01>=n.start)&&(o=s),this.isInterstitial(r)){const t=r.event;if(s-a>1&&!1===t.appendInPlace)return;if(0===t.assetList.length&&t.assetListLoader)return}if(this.bufferedPos=t,o>i&&o>a)this.bufferedToItem(n);else{const e=this.primaryDetails;this.primaryLive&&e&&t>e.edge-e.targetduration&&n.start<e.edge+this.hls.config.interstitialLiveLookAhead&&this.isInterstitial(n)&&this.preloadAssets(n.event,0)}}else i&&n&&!this.itemsMatch(n,r)&&(o===a?this.bufferedToItem(n):o===a+1&&this.bufferedToItem(e[o]))}assetsBuffered(t,e){return 0!==t.event.assetList.length&&!t.event.assetList.some(t=>{const i=this.getAssetPlayer(t.identifier);return!(null!=i&&i.bufferedInPlaceToEnd(e))})}setBufferingItem(t){const e=this.bufferingItem,i=this.schedule;if(!this.itemsMatch(t,e)&&i){const{items:s,events:r}=i;if(!s||!r)return e;const n=this.isInterstitial(t),o=this.getBufferingPlayer();this.bufferingItem=t,this.bufferedPos=Math.max(t.start,Math.min(t.end,this.timelinePos));const l=o?o.remaining:e?e.end-this.timelinePos:0;if(this.log(`INTERSTITIALS_BUFFERED_TO_BOUNDARY ${nh(t)}`+(e?` (${l.toFixed(2)} remaining)`:"")),!this.playbackDisabled)if(n){const e=i.findAssetIndex(t.event,this.bufferedPos);t.event.assetList.forEach((t,i)=>{const s=this.getAssetPlayer(t.identifier);s&&(i===e&&s.loadSource(),s.resumeBuffering())})}else this.hls.resumeBuffering(),this.playerQueue.forEach(t=>t.pauseBuffering());this.hls.trigger(a.INTERSTITIALS_BUFFERED_TO_BOUNDARY,{events:r.slice(0),schedule:s.slice(0),bufferingIndex:this.findItemIndex(t),playingIndex:this.findItemIndex(this.playingItem)})}else this.bufferingItem!==t&&(this.bufferingItem=t);return e}bufferedToItem(t,e=0){const i=this.setBufferingItem(t);if(!this.playbackDisabled)if(this.isInterstitial(t))this.bufferedToEvent(t,e);else if(null!==i){this.bufferingAsset=null;const e=this.getPrimaryResumption(t,this.findItemIndex(t),!0),i=this.bufferedPos=Math.max(e,Math.min(this.bufferedPos,t.end),this.timelinePos,t.start),s=this.detachedData;if(s)if(s.mediaSource){const e=!0;this.attachPrimary(i,t,e)}else this.startLoadingPrimaryAt(i);else{const t=this.playingItem,e=this.isInterstitial(t)&&t.event.appendInPlace;this.startLoadingPrimaryAt(i,e)}}}bufferedToEvent(t,e){const i=t.event,s=0===i.assetList.length&&!i.assetListLoader,r=i.cue.once;if(s||!r){const t=this.preloadAssets(i,e);if(null!=t&&t.interstitial.appendInPlace){const e=this.primaryMedia;e&&this.bufferAssetPlayer(t,e)}}}preloadAssets(t,e){const i=t.assetUrl,s=t.assetList.length,r=0===s&&!t.assetListLoader,n=t.cue.once;if(r){const r=t.timelineStart,n=this.playingItem,o=this.getBufferingPlayer();var a;if(t.appendInPlace)this.isInterstitial(n)||(null==n||null==(a=n.nextEvent)?void 0:a.identifier)!==t.identifier||this.flushFrontBuffer(r+.25);let l,h=0;if(o&&!o.interstitial.cue.pre||!this.primaryLive||(h=this.getLiveStartPos(),o&&(h+=o.remaining)),h&&!t.cue.pre&&!t.cue.post){const t=h-r;t>0&&(l=Math.round(1e3*t)/1e3)}if(this.log(`Load interstitial asset ${e+1}/${i?1:s} ${t}${h?` live-start: ${h} start-offset: ${l} (timeline-start: ${r})`:""}`),i)return this.createAsset(t,0,0,r,t.duration,i);const d=this.assetListLoader.loadAssetList(t,l);d&&(t.assetListLoader=d)}else if(!n&&s){for(let i=e;i<s;i++){const e=t.assetList[i],s=this.getAssetPlayerQueueIndex(e.identifier);-1!==s&&!this.playerQueue[s].destroyed||e.error||this.createAssetPlayer(t,e,i)}const i=t.assetList[e];if(i){const t=this.getAssetPlayer(i.identifier);return t&&t.loadSource(),t}}return null}flushFrontBuffer(t){const e=this.requiredTracks;if(!e)return;const i=this.primaryDetails;if(i&&t>=i.edge)return;this.log(`Removing front buffer starting at ${t}`);Object.keys(e).forEach(e=>{this.hls.trigger(a.BUFFER_FLUSHING,{startOffset:t,endOffset:1/0,type:e})})}getAssetPlayerQueueIndex(t){const e=this.playerQueue;for(let i=0;i<e.length;i++)if(t===e[i].assetId)return i;return-1}getAssetPlayer(t){const e=this.getAssetPlayerQueueIndex(t);return this.playerQueue[e]||null}getBufferingPlayer(){const{playerQueue:t,primaryMedia:e}=this;if(e)for(let i=0;i<t.length;i++)if(t[i].media===e)return t[i];return null}createAsset(t,e,i,s,r,n){const a={parentIdentifier:t.identifier,identifier:zl(t,n,e),duration:r,startOffset:i,timelineStart:s,uri:n};return this.createAssetPlayer(t,a,e)}createAssetPlayer(t,e,i){const s=this.hls,o=s.userConfig,l=Xe(s.loadLevelObj||s.levels[s.currentLevel],o.videoPreference),h=s.audioTracks[s.audioTrack],d=s.subtitleTracks[s.subtitleTrack];let c=0;if(this.primaryLive||t.appendInPlace){const t=this.timelinePos-e.timelineStart;if(t>=0){const i=e.duration;i&&t<i&&(c=t)}}const u=e.identifier,f=k(k({},o),{},{maxMaxBufferLength:Math.min(15,s.config.maxMaxBufferLength),autoStartLoad:!0,startFragPrefetch:!0,primarySessionId:s.sessionId,assetPlayerId:u,abrEwmaDefaultEstimate:s.bandwidthEstimate,interstitialsController:void 0,startPosition:c,liveDurationInfinity:!1,testBandwidth:!1,videoPreference:l,audioPreference:h||o.audioPreference,subtitlePreference:d||o.subtitlePreference});t.appendInPlace&&(t.appendInPlaceStarted=!0,e.timelineStart&&(f.timelineOffset=e.timelineStart));const g=f.cmcd;null!=g&&g.sessionId&&g.contentId&&(f.cmcd=I({},g,{contentId:ll(e.uri)})),this.getAssetPlayer(u)&&this.warn(`Duplicate date range identifier ${t} and asset ${u}`);const m=new ih(this.HlsPlayerClass,f,t,e);this.playerQueue.push(m),t.assetList[i]=e;let p=!0;const v=s=>{if(s.live){const e=new Error(`Interstitials MUST be VOD assets ${t}`),s={fatal:!0,type:r.OTHER_ERROR,details:n.INTERSTITIAL_ASSET_ITEM_ERROR,error:e},a=this.findEventIndex(t.identifier);return void this.handleAssetItemError(s,t,a,i,e.message)}const a=s.edge-s.fragmentStart,o=e.duration;(p||null===o||a>o)&&(p=!1,this.log(`Interstitial asset "${u}" duration change ${o} > ${a}`),e.duration=a,this.updateSchedule())};m.on(a.LEVEL_UPDATED,(t,{details:e})=>v(e)),m.on(a.LEVEL_PTS_UPDATED,(t,{details:e})=>v(e)),m.on(a.EVENT_CUE_ENTER,()=>this.onInterstitialCueEnter());const y=(t,e)=>{const i=this.getAssetPlayer(u);if(i&&e.tracks){i.off(a.BUFFER_CODECS,y),i.tracks=e.tracks;const t=this.primaryMedia;this.bufferingAsset===i.assetItem&&t&&!i.media&&this.bufferAssetPlayer(i,t)}};m.on(a.BUFFER_CODECS,y);m.on(a.BUFFERED_TO_END,()=>{const e=this.getAssetPlayer(u);if(this.log(`buffered to end of asset ${e}`),!e||!this.schedule)return;const i=this.getEventItem(t.identifier);i&&this.advanceAssetBuffering(i,e.assetItem)});const E=e=>()=>{if(!this.getAssetPlayer(u)||!this.schedule)return;this.shouldPlay=!0;const i=this.findEventIndex(t.identifier);this.advanceAfterAssetEnded(t,i,e)};return m.once(a.MEDIA_ENDED,E(i)),m.once(a.PLAYOUT_LIMIT_REACHED,E(1/0)),m.on(a.ERROR,(e,s)=>{if(!this.schedule)return;const r=this.getAssetPlayer(u);if(s.details===n.BUFFER_STALLED_ERROR)return null!=r&&r.appendInPlace?void this.handleInPlaceStall(t):(this.onTimeupdate(),void this.checkBuffer(!0));s.details!==n.BUFFER_SEEK_OVER_HOLE&&this.handleAssetItemError(s,t,this.findEventIndex(t.identifier),i,`Asset player error ${s.error} ${t}`)}),m.on(a.DESTROYING,()=>{if(!this.getAssetPlayer(u)||!this.schedule)return;const e=new Error(`Asset player destroyed unexpectedly ${u}`),s={fatal:!0,type:r.OTHER_ERROR,details:n.INTERSTITIAL_ASSET_ITEM_ERROR,error:e};this.handleAssetItemError(s,t,this.findEventIndex(t.identifier),i,e.message)}),this.log(`INTERSTITIAL_ASSET_PLAYER_CREATED ${eh(e)}`),this.hls.trigger(a.INTERSTITIAL_ASSET_PLAYER_CREATED,{asset:e,assetListIndex:i,event:t,player:m}),m}clearInterstitial(t,e){this.clearAssetPlayers(t,e),t.reset()}clearAssetPlayers(t,e){t.assetList.forEach(t=>{this.clearAssetPlayer(t.identifier,e)})}resetAssetPlayer(t){const e=this.getAssetPlayerQueueIndex(t);if(-1!==e){this.log(`reset asset player "${t}" after error`);const i=this.playerQueue[e];this.transferMediaFromPlayer(i,null),i.resetDetails()}}clearAssetPlayer(t,e){const i=this.getAssetPlayerQueueIndex(t);if(-1!==i){const t=this.playerQueue[i];this.log(`clear ${t} toSegment: ${e?nh(e):e}`),this.transferMediaFromPlayer(t,e),this.playerQueue.splice(i,1),t.destroy()}}emptyPlayerQueue(){let t;for(;t=this.playerQueue.pop();)t.destroy();this.playerQueue=[]}startAssetPlayer(t,e,i,s,r){const{interstitial:n,assetItem:o,assetId:l}=t,h=n.assetList.length,d=this.playingAsset;this.endedAsset=null,this.playingAsset=o,(null==d?void 0:d.identifier)!==l&&(d&&(this.clearAssetPlayer(d.identifier,i[s]),delete d.error),this.log(`INTERSTITIAL_ASSET_STARTED ${e+1}/${h} ${eh(o)}`),this.hls.trigger(a.INTERSTITIAL_ASSET_STARTED,{asset:o,assetListIndex:e,event:n,schedule:i.slice(0),scheduleIndex:s,player:t})),this.bufferAssetPlayer(t,r)}bufferAssetPlayer(t,e){var i;if(!this.schedule)return;const{interstitial:s,assetItem:a}=t,o=this.getEventItem(s.identifier);if(!o)return;if(t.loadSource(),this.setBufferingItem(o),this.bufferingAsset=a,t.bufferedInPlaceToEnd(this.primaryMedia,t.currentTime))return void this.advanceAssetBuffering(o,a);const l=this.getBufferingPlayer();if(l===t)return;const h=s.appendInPlace;if(h&&!1===(null==l?void 0:l.interstitial.appendInPlace))return;const d=(null==l?void 0:l.tracks)||(null==(i=this.detachedData)?void 0:i.tracks)||this.requiredTracks;if(h&&a!==this.playingAsset){if(!t.tracks)return void this.log(`Waiting for track info before buffering ${t}`);if(d&&!W(d,t.tracks)){const e=new Error(`Asset ${eh(a)} SourceBuffer tracks ('${Object.keys(t.tracks)}') are not compatible with primary content tracks ('${Object.keys(d)}')`),i={fatal:!0,type:r.OTHER_ERROR,details:n.INTERSTITIAL_ASSET_ITEM_ERROR,error:e},o=s.findAssetIndex(a);return void this.handleAssetItemError(i,s,this.findEventIndex(s.identifier),o,e.message)}}this.transferMediaTo(t,e)}handleInPlaceStall(t){const e=this.schedule,i=this.primaryMedia;if(!e||!i)return;const s=i.currentTime,r=e.findAssetIndex(t,s),n=t.assetList[r];if(n){const a=this.getAssetPlayer(n.identifier);if(a){const o=a.currentTime||s-n.timelineStart,l=a.duration-o;if(this.warn(`Stalled at ${o} of ${o+l} in ${a} ${t} (media.currentTime: ${s})`),o&&(l/i.playbackRate<.5||a.bufferedInPlaceToEnd(i,a.currentTime))&&a.hls){const i=e.findEventIndex(t.identifier);this.advanceAfterAssetEnded(t,i,r)}}}}advanceInPlace(t){const e=this.primaryMedia;if(e&&e.currentTime<t){const i=`advance currentTime to ${t}, duration: ${e.duration}`;e.duration>t?(this.log(i),e.currentTime=t):this.log(`Cannot ${i}`)}}handleAssetItemError(t,e,i,s,r){if(t.details===n.BUFFER_STALLED_ERROR)return;const o=e.assetList[s]||null;if(this.warn(`INTERSTITIAL_ASSET_ERROR ${o?eh(o):o} ${t.error}`),!this.schedule)return;const l=(null==o?void 0:o.identifier)||"",h=this.getAssetPlayerQueueIndex(l),d=this.playerQueue[h]||null,c=this.schedule.items,u=I({},t,{fatal:!1,errorAction:mi(!0),asset:o,assetListIndex:s,event:e,schedule:c,scheduleIndex:i,player:d});if(this.hls.trigger(a.INTERSTITIAL_ASSET_ERROR,u),!t.fatal)return;const f=this.playingAsset,g=this.bufferingAsset,m=new Error(r);if(o&&(this.clearAssetPlayer(l,null),o.error=m),e.assetList.some(t=>!t.error))for(let t=s;t<e.assetList.length;t++)this.resetAssetPlayer(e.assetList[t].identifier);else e.error=m;this.updateSchedule(!0),e.error?this.primaryFallback(e):(null==f?void 0:f.identifier)===l?this.advanceAfterAssetEnded(e,i,s):(null==g?void 0:g.identifier)===l&&this.isInterstitial(this.bufferingItem)&&this.advanceAssetBuffering(this.bufferingItem,g)}primaryFallback(t){const e=t.timelineStart,i=this.effectivePlayingItem,s=this.playingItem,r=this.seekableStart,n=this.hls.startPosition;let a=this.timelinePos;if(this.isInterstitial(i)){this.log(`Fallback to primary from event "${t.identifier}" start: ${e} pos: ${a} playing: ${nh(i)} startPosition: ${n} seekableStart: ${r} error: ${t.error}`),-1===a&&(a=n),a=Math.max(a,r);const s=this.updateItem(i,a);this.itemsMatch(i,s)&&this.clearInterstitial(t,null),t.appendInPlace&&(this.attachPrimary(e,null),this.flushFrontBuffer(e))}else if(-1===a)return void this.checkStart();if(!this.schedule)return;if(!this.isInterstitial(s))return;const o=this.schedule.findItemIndexAtTime(a);this.setSchedulePosition(o)}onAssetListLoaded(t,e){var i,s;const r=e.event,n=r.identifier,a=e.assetListResponse.ASSETS;if(null==(i=this.schedule)||!i.hasEvent(n))return;const o=r.timelineStart,l=r.duration;let h=0;a.forEach((t,e)=>{const i=parseFloat(t.DURATION);this.createAsset(r,e,h,o+h,i,t.URI),h+=i}),r.duration=h,this.log(`Loaded asset-list with duration: ${h} (was: ${l}) ${r}`);const d=this.waitingItem,c=(null==d?void 0:d.event.identifier)===n;this.updateSchedule();const u=null==(s=this.bufferingItem)?void 0:s.event;if(c){const t=this.findEventIndex(n),e=this.getEventItem(n);if(e){if(!this.playingItem&&this.timelinePos>e.end){if(this.schedule.findItemIndexAtTime(this.timelinePos)!==t)return r.error=new Error(`Interstitial ${a.length?"no longer within playback range":"asset-list is empty"} ${this.timelinePos} ${r}`),this.log(r.error.message),this.updateSchedule(!0),void this.primaryFallback(r)}this.setBufferingItem(e)}this.setSchedulePosition(t)}else if((null==u?void 0:u.identifier)===n){const t=r.assetList[0];if(t){const e=this.getAssetPlayer(t.identifier);if(u.appendInPlace){const t=this.primaryMedia;e&&t&&this.bufferAssetPlayer(e,t)}else e&&e.loadSource()}}}onError(t,e){if(this.schedule)switch(e.details){case n.ASSET_LIST_PARSING_ERROR:case n.ASSET_LIST_LOAD_ERROR:case n.ASSET_LIST_LOAD_TIMEOUT:{const t=e.interstitial;t&&(this.updateSchedule(!0),this.primaryFallback(t));break}case n.BUFFER_STALLED_ERROR:{const t=this.endedItem||this.waitingItem||this.playingItem;if(this.isInterstitial(t)&&t.event.appendInPlace)return void this.handleInPlaceStall(t.event);const e=this.primaryMedia;this.log(`Primary player stall @${this.timelinePos} currentTime: ${null==e?void 0:e.currentTime} bufferedPos: ${this.bufferedPos}`),this.onTimeupdate(),this.checkBuffer(!0);break}}}}});function Kh(t,e,i){if((e.liveSyncDurationCount||e.liveMaxLatencyDurationCount)&&(e.liveSyncDuration||e.liveMaxLatencyDuration))throw new Error("Illegal hls.js config: don't mix up liveSyncDurationCount/liveMaxLatencyDurationCount and liveSyncDuration/liveMaxLatencyDuration");if(void 0!==e.liveMaxLatencyDurationCount&&(void 0===e.liveSyncDurationCount||e.liveMaxLatencyDurationCount<=e.liveSyncDurationCount))throw new Error('Illegal hls.js config: "liveMaxLatencyDurationCount" must be greater than "liveSyncDurationCount"');if(void 0!==e.liveMaxLatencyDuration&&(void 0===e.liveSyncDuration||e.liveMaxLatencyDuration<=e.liveSyncDuration))throw new Error('Illegal hls.js config: "liveMaxLatencyDuration" must be greater than "liveSyncDuration"');if(void 0!==e.liveMaxUnchangedPlaylistRefresh){const t=e.liveMaxUnchangedPlaylistRefresh,s=((t,e,i)=>Math.max(e,Math.min(t,i)))(t,2,1/0);s!==t&&i.warn(`hls.js config: "liveMaxUnchangedPlaylistRefresh" clamped from ${t} to ${s}.`),e.liveMaxUnchangedPlaylistRefresh=s}const s=Vh(t),r=["TimeOut","MaxRetry","RetryDelay","MaxRetryTimeout"];return["manifest","level","frag"].forEach(t=>{const n=`${"level"===t?"playlist":t}LoadPolicy`,a=void 0===e[n],o=[];r.forEach(i=>{const r=`${t}Loading${i}`,l=e[r];if(void 0!==l&&a){o.push(r);const t=s[n].default;switch(e[n]={default:t},i){case"TimeOut":t.maxLoadTimeMs=l,t.maxTimeToFirstByteMs=l;break;case"MaxRetry":t.errorRetry.maxNumRetry=l,t.timeoutRetry.maxNumRetry=l;break;case"RetryDelay":t.errorRetry.retryDelayMs=l,t.timeoutRetry.retryDelayMs=l;break;case"MaxRetryTimeout":t.errorRetry.maxRetryDelayMs=l,t.timeoutRetry.maxRetryDelayMs=l}}}),o.length&&i.warn(`hls.js config: "${o.join('", "')}" setting(s) are deprecated, use "${n}": ${Ue(e[n])}`)}),k(k({},s),e)}function Vh(t){return t&&"object"==typeof t?Array.isArray(t)?t.map(Vh):Object.keys(t).reduce((e,i)=>(e[i]=Vh(t[i]),e),{}):t}function jh(t,e){const i=t.loader;if(i!==Fh&&i!==Uh)e.log("[config]: Custom loader detected, cannot enable progressive streaming"),t.progressive=!1;else{(function(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch(t){}return!1})()&&(t.loader=Fh,t.progressive=!0,t.enableSoftwareAES=!0,e.log("[config]: Progressive streaming enabled, using FetchLoader"))}}class Hh extends Hn{constructor(t,e){super(t,"level-controller"),this._levels=[],this._firstLevel=-1,this._maxAutoLevel=-1,this._startLevel=void 0,this.currentLevel=null,this.currentLevelIndex=-1,this.manualLevelIndex=-1,this.steering=void 0,this.lastABRSwitchTime=-1,this._iframeVariants=[],this.onParsedComplete=void 0,this.steering=e,this._registerListeners()}_registerListeners(){const{hls:t}=this;t.on(a.MANIFEST_LOADING,this.onManifestLoading,this),t.on(a.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(a.LEVEL_LOADED,this.onLevelLoaded,this),t.on(a.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(a.FRAG_BUFFERED,this.onFragBuffered,this),t.on(a.ERROR,this.onError,this)}_unregisterListeners(){const{hls:t}=this;t.off(a.MANIFEST_LOADING,this.onManifestLoading,this),t.off(a.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(a.LEVEL_LOADED,this.onLevelLoaded,this),t.off(a.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(a.FRAG_BUFFERED,this.onFragBuffered,this),t.off(a.ERROR,this.onError,this)}destroy(){this._unregisterListeners(),this.steering=null,this.resetLevels(),super.destroy()}stopLoad(){this._levels.forEach(t=>{t.loadError=0,t.fragmentError=0}),super.stopLoad()}resetLevels(){this._startLevel=void 0,this.manualLevelIndex=-1,this.currentLevelIndex=-1,this.currentLevel=null,this._levels=[],this._maxAutoLevel=-1,this._iframeVariants=[]}onManifestLoading(t,e){this.resetLevels()}onManifestLoaded(t,e){const i=this.hls.config.preferManagedMediaSource,s=[],r={},n={};let a=!1,o=!1,l=!1,h=!1;e.levels.forEach(t=>{const e=t.attrs,d=Wh(t,i),{audioCodec:c,videoCodec:u,imageCodec:f,width:g,height:m}=t;if(!d)return void this.log(`Some or all CODECS not supported "${e.CODECS}"`);a||(a=!(!g||!m)),o||(o=!!u),l||(l=!!c),h||(h=!!f);const{CODECS:p,"FRAME-RATE":v,"HDCP-LEVEL":y,"PATHWAY-ID":E,RESOLUTION:T,"VIDEO-RANGE":S}=e,b=`${`${E||"."}-`}${t.bitrate}-${T}-${v}-${p}-${S}-${y}`;if(r[b])if(r[b].uri===t.url||t.attrs["PATHWAY-ID"])t.iframes||(r[b].addGroupId("audio",e.AUDIO),r[b].addGroupId("text",e.SUBTITLES));else{const e=n[b]+=1;t.attrs["PATHWAY-ID"]=new Array(e+1).join(".");const i=this.createLevel(t);r[b]=i,s.push(i)}else{const e=this.createLevel(t);r[b]=e,n[b]=1,s.push(e)}}),this.filterAndSortMediaOptions(s,e,a,o,l,h)}createLevel(t){const e=new Ne(t),i=t.supplemental;if(null!=i&&i.videoCodec&&!Yh(i.videoCodec,this.hls.config.preferManagedMediaSource)){const t=new Error(`SUPPLEMENTAL-CODECS not supported "${i.videoCodec}"`);this.log(t.message),e.supportedResult=Le(t,[])}return e}filterAndSortMediaOptions(t,e,i,s,o,l){var h;let d=[],c=[],u=t;const f=(null==(h=e.stats)?void 0:h.parsing)||{},g=this.hls.config.preferManagedMediaSource;if((i||s)&&o&&(u=u.filter(({videoCodec:t,videoRange:e,width:i,height:s})=>{return(!!t||!(!i||!s))&&(!!(r=e)&&Pe.indexOf(r)>-1);var r})),s&&l&&(u=u.filter(t=>!t.imageCodec)),0===u.length)return Promise.resolve().then(()=>{if(this.hls){let t="no level with compatible codecs found in manifest",i=t;e.levels.length&&(i=`one or more CODECS in variant not supported: ${Ue(e.levels.map(t=>t.attrs.CODECS).filter((t,e,i)=>i.indexOf(t)===e))}`,this.warn(i),t+=` (${i})`);const s=new Error(t);this.hls.trigger(a.ERROR,{type:r.MEDIA_ERROR,details:n.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:e.url,error:s,reason:i})}}),void(f.end=performance.now());e.audioTracks&&(d=e.audioTracks.filter(t=>!t.audioCodec||qh(t.audioCodec,g)),zh(d)),e.subtitles&&(c=e.subtitles,zh(c));const m=u.slice(0);u.sort((t,e)=>{if(t.attrs["HDCP-LEVEL"]!==e.attrs["HDCP-LEVEL"])return(t.attrs["HDCP-LEVEL"]||"")>(e.attrs["HDCP-LEVEL"]||"")?1:-1;if(i&&t.height!==e.height)return t.height-e.height;if(t.frameRate!==e.frameRate)return t.frameRate-e.frameRate;if(t.videoRange!==e.videoRange)return Pe.indexOf(t.videoRange)-Pe.indexOf(e.videoRange);if(t.videoCodec!==e.videoCodec){const i=ue(t.videoCodec),s=ue(e.videoCodec);if(i!==s)return s-i}if(t.uri===e.uri&&t.codecSet!==e.codecSet){const i=fe(t.codecSet),s=fe(e.codecSet);if(i!==s)return s-i}return t.averageBitrate!==e.averageBitrate?t.averageBitrate-e.averageBitrate:0});let p=m[0];if(this.steering&&(u=this.steering.filterParsedLevels(u),u.length!==m.length))for(let t=0;t<m.length;t++)if(m[t].pathwayId===u[0].pathwayId){p=m[t];break}this._levels=u;for(let t=0;t<u.length;t++)if(u[t]===p){var v;this._firstLevel=t;const e=p.bitrate,i=this.hls.bandwidthEstimate;if(this.log(`manifest loaded, ${u.length} level(s) found, first bitrate: ${e}`),void 0===(null==(v=this.hls.userConfig)?void 0:v.abrEwmaDefaultEstimate)){const t=Math.min(e,this.hls.config.abrEwmaDefaultEstimateMax);t>i&&i===this.hls.abrEwmaDefaultEstimate&&(this.hls.bandwidthEstimate=t)}break}const y=e.iframeVariants.filter(t=>Wh(t,g));this._iframeVariants=y;const E=o&&!s,T=this.hls.config,S=!(!T.audioStreamController||!T.audioTrackController),b={levels:u,audioTracks:d,subtitleTracks:c,iframeVariants:y,sessionData:e.sessionData,sessionKeys:e.sessionKeys,firstLevel:this._firstLevel,stats:e.stats,audio:o,video:s,altAudio:S&&!E&&d.some(t=>!!t.url)};f.end=performance.now(),this.hls.trigger(a.MANIFEST_PARSED,b)}get iframeVariants(){return 0===this._iframeVariants.length?null:this._iframeVariants}get levels(){return 0===this._levels.length?null:this._levels}get loadLevelObj(){return this.currentLevel}get level(){return this.currentLevelIndex}set level(t){const e=this._levels;if(0===e.length)return;if(t<0||t>=e.length){const i=new Error("invalid level idx"),s=t<0;if(this.hls.trigger(a.ERROR,{type:r.OTHER_ERROR,details:n.LEVEL_SWITCH_ERROR,level:t,fatal:s,error:i,reason:i.message}),s)return;t=Math.min(t,e.length-1)}const i=this.currentLevelIndex,s=this.currentLevel,o=s?s.attrs["PATHWAY-ID"]:void 0,l=e[t],h=l.attrs["PATHWAY-ID"];if(this.currentLevelIndex=t,this.currentLevel=l,i===t&&s&&o===h)return;this.log(`Switching to level ${t} (${l.height?l.height+"p ":""}${l.videoRange?l.videoRange+" ":""}${l.codecSet?l.codecSet+" ":""}@${l.bitrate})${h?" with Pathway "+h:""} from level ${i}${o?" with Pathway "+o:""}`);const d={level:t,attrs:l.attrs,details:l.details,bitrate:l.bitrate,averageBitrate:l.averageBitrate,maxBitrate:l.maxBitrate,realBitrate:l.realBitrate,width:l.width,height:l.height,codecSet:l.codecSet,audioCodec:l.audioCodec,videoCodec:l.videoCodec,audioGroups:l.audioGroups,subtitleGroups:l.subtitleGroups,loaded:l.loaded,loadError:l.loadError,fragmentError:l.fragmentError,name:l.name,id:l.id,uri:l.uri,url:l.url,urlId:0,audioGroupIds:l.audioGroupIds,textGroupIds:l.textGroupIds};this.hls.trigger(a.LEVEL_SWITCHING,d);const c=l.details;if(!c||c.live){const t=this.switchParams(l.uri,null==s?void 0:s.details,c);this.loadPlaylist(t)}}get manualLevel(){return this.manualLevelIndex}set manualLevel(t){this.manualLevelIndex=t,void 0===this._startLevel&&(this._startLevel=t),-1!==t&&(this.level=t)}get firstLevel(){return this._firstLevel}set firstLevel(t){this._firstLevel=t}get startLevel(){if(void 0===this._startLevel){const t=this.hls.config.startLevel;return void 0!==t?t:this.hls.firstAutoLevel}return this._startLevel}set startLevel(t){this._startLevel=t}get pathways(){return this.steering?this.steering.pathways():[]}get pathwayPriority(){return this.steering?this.steering.pathwayPriority:null}set pathwayPriority(t){if(this.steering){const e=this.steering.pathways(),i=t.filter(t=>-1!==e.indexOf(t));if(t.length<1)return void this.warn(`pathwayPriority ${t} should contain at least one pathway from list: ${e}`);this.steering.pathwayPriority=i}}onError(t,e){!e.fatal&&e.context&&e.context.type===u.LEVEL&&e.context.level===this.level&&this.checkRetry(e)}onFragBuffered(t,{frag:e}){if(e.type===f.MAIN){const t=e.elementaryStreams;if(!Object.keys(t).some(e=>!!t[e]))return;const i=this._levels[e.level];null!=i&&i.loadError&&(this.log(`Resetting level error count of ${i.loadError} on frag buffered`),i.loadError=0)}}onLevelLoaded(t,e){var i;const{level:s,details:r}=e,n=e.levelInfo;var a;if(!n)return this.warn(`Invalid level index ${s}`),void(null!=(a=e.deliveryDirectives)&&a.skip&&(r.deltaUpdateFailed=!0));if(n===this.currentLevel||e.withoutMultiVariant){0===n.fragmentError&&(n.loadError=0);let t=n.details;t===e.details&&t.advanced&&(t=void 0),this.playlistLoaded(s,e,t)}else null!=(i=e.deliveryDirectives)&&i.skip&&(r.deltaUpdateFailed=!0)}loadPlaylist(t){super.loadPlaylist(),this.shouldLoadPlaylist(this.currentLevel)&&this.scheduleLoading(this.currentLevel,t)}loadingPlaylist(t,e){super.loadingPlaylist(t,e);const i=this.getUrlWithDirectives(t.uri,e),s=this.currentLevelIndex,r=t.attrs["PATHWAY-ID"],n=t.details,o=null==n?void 0:n.age;this.log(`Loading level index ${s}${void 0!==(null==e?void 0:e.msn)?" at sn "+e.msn+" part "+e.part:""}${r?" Pathway "+r:""}${o&&n.live?" age "+o.toFixed(1)+(n.type&&" "+n.type||""):""} ${i}`),this.hls.trigger(a.LEVEL_LOADING,{url:i,level:s,levelInfo:t,pathwayId:t.attrs["PATHWAY-ID"],id:0,deliveryDirectives:e||null})}get nextLoadLevel(){return-1!==this.manualLevelIndex?this.manualLevelIndex:this.hls.nextAutoLevel}set nextLoadLevel(t){const e=this.currentLevelIndex;if(-1===this.manualLevelIndex&&t!==e&&-1!==t){const i=this.hls.config.abrSwitchInterval;if(i>0){const s=performance.now(),r=s-this.lastABRSwitchTime,n=1e3*i;if(this.lastABRSwitchTime>-1&&r<n)return void this.warn(`Preventing ABR level switch: ${e} -> ${t} (${Math.round(r)}ms < ${n}ms / ${i}s)`);this.lastABRSwitchTime=s,this.log(`Allowing ABR level switch: ${e} -> ${t} (${Math.round(r)}ms >= ${n}ms / ${i}s)`)}}this.level=t,-1===this.manualLevelIndex&&(this.hls.nextAutoLevel=t)}removeLevel(t){var e;if(1===this._levels.length)return;const i=this._levels.filter((e,i)=>i!==t||(this.steering&&this.steering.removeLevel(e),e===this.currentLevel&&(this.currentLevel=null,this.currentLevelIndex=-1,e.details&&e.details.fragments.forEach(t=>t.level=-1)),!1));Ws(i),this._levels=i,this.currentLevelIndex>-1&&null!=(e=this.currentLevel)&&e.details&&(this.currentLevelIndex=this.currentLevel.details.fragments[0].level),this.manualLevelIndex>-1&&(this.manualLevelIndex=this.currentLevelIndex);const s=i.length-1;this._firstLevel=Math.min(this._firstLevel,s),this._startLevel&&(this._startLevel=Math.min(this._startLevel,s)),this.hls.trigger(a.LEVELS_UPDATED,{levels:i})}onLevelsUpdated(t,{levels:e}){this._levels=e}checkMaxAutoUpdated(){const{autoLevelCapping:t,maxAutoLevel:e,maxHdcpLevel:i}=this.hls;this._maxAutoLevel!==e&&(this._maxAutoLevel=e,this.hls.trigger(a.MAX_AUTO_LEVEL_UPDATED,{autoLevelCapping:t,levels:this.levels,maxAutoLevel:e,minAutoLevel:this.hls.minAutoLevel,maxHdcpLevel:i}))}}function qh(t,e){return he(t,"audio",e)}function Yh(t,e){return he(t,"video",e)}function Wh(t,e){let{audioCodec:i,videoCodec:s}=t;i&&(t.audioCodec=i=pe(i,e)||void 0),s&&(s=t.videoCodec=function(t){const e=t.split(",");for(let t=0;t<e.length;t++){const i=e[t].split(".");i.length>2&&"avc1"===i[0]&&(e[t]=`avc1.${parseInt(i[1]).toString(16)}${("000"+parseInt(i[2]).toString(16)).slice(-4)}`)}return e.join(",")}(s));const{unknownCodecs:r}=t;return!((null==r?void 0:r.length)||0||i&&!qh(i,e)||s&&!Yh(s,e))}function zh(t){const e={};t.forEach(t=>{const i=t.groupId||"";t.id=e[i]=e[i]||0,e[i]++})}class Xh extends U{constructor(t,e){super("key-loader",e),this.config=void 0,this.keyLoaderInfo={},this.emeController=null,this.config=t}abort(t){for(const i in this.keyLoaderInfo){const s=this.keyLoaderInfo[i].loader;if(s){var e;if(t&&t!==(null==(e=s.context)?void 0:e.frag.type))return;s.abort()}}}destroy(){for(const t in this.keyLoaderInfo){const e=this.keyLoaderInfo[t].loader;e&&e.destroy()}this.emeController=null,this.keyLoaderInfo={}}loadClear(t,e,i){return this.emeController?this.emeController.loadClear(t,e,i):null}load(t,e){return!t.decryptdata&&t.encrypted&&this.emeController&&this.config.emeEnabled?this.emeController.selectKeySystemFormat(t).then(i=>this.loadInternal(t,e,i)):this.loadInternal(t,e)}loadInternal(t,e,i){i&&t.setKeyFormat(i);const s=t.decryptdata;if(!s){const e=new Error(i?`Expected frag.decryptdata to be defined after setting format ${i}`:`Missing decryption data on fragment in onKeyLoading (emeEnabled with controller: ${this.emeController&&this.config.emeEnabled})`);return Promise.reject(Qh(t,n.KEY_LOAD_ERROR,e))}const r=t;switch(s.method){case"SAMPLE-AES":case"SAMPLE-AES-CENC":case"SAMPLE-AES-CTR":return"identity"===s.keyFormat?this.loadKeyHTTP(r):e?e.then(()=>this.loadKeyEME(r)):this.loadKeyEME(r);case"AES-128":case"AES-256":case"AES-256-CTR":return this.loadKeyHTTP(r);default:return Promise.reject(Qh(t,n.KEY_LOAD_ERROR,new Error(`Key supplied with unsupported METHOD: "${s.method}"`)))}}loadKeyEME(t){if(this.emeController&&this.config.emeEnabled){var e;if(!t.decryptdata.keyId&&null!=(e=t.initSegment)&&e.data){const e=function(t){const e=[];return Ut(t,t=>e.push(t.subarray(8,24))),e}(t.initSegment.data);if(e.length){let i=e[0];const s=t.decryptdata.uri;if(i.some(t=>0!==t))this.log(`Using keyId found in init segment ${mt(i)} keyUri: ${s}`),Es.setKeyIdForUri(s,i);else{const t=Es.addKeyIdForUri(s);this.log(`Patching empty keyId with ${mt(t)} keyUri: ${s}`),i=t}t.decryptdata.keyId=i}}return this.emeController.loadKey(t).then(()=>({frag:t,keyInfo:{decryptdata:t.decryptdata}}))}return Promise.reject(Qh(t,n.KEY_LOAD_ERROR,new Error(`emeEnabled with controller: ${this.emeController&&this.config.emeEnabled})`)))}loadKeyHTTP(t){const e=t.decryptdata,i=e.uri;if(!i)return Promise.reject(Qh(t,n.KEY_LOAD_ERROR,new Error(`Invalid key URI: "${i}"`)));const s=this.keyLoaderInfo[i];if(s){if(s.decryptdata.key)return e.key=s.decryptdata.key,s.keyLoadPromise=null,Promise.resolve({frag:t,keyInfo:s});if(s.keyLoadPromise)return s.keyLoadPromise.then(i=>(e.key=s.decryptdata.key,k(k({},i),{},{frag:t})))}this.log(`Loading${e.keyId?" keyId: "+mt(e.keyId):""} URI: ${e.uri} from ${t.type} ${t.level}`);const r=this.config,a=new(0,r.loader)(r);t.keyLoader=a;const o=this.keyLoaderInfo[i]={decryptdata:e,keyLoadPromise:null,loader:a};return o.keyLoadPromise=new Promise((e,s)=>{const l={type:u.KEY,keyInfo:o,frag:t,responseType:"arraybuffer",url:i},h=r.keyLoadPolicy.default,d={loadPolicy:h,timeout:h.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},c={onSuccess:(t,i,r,a)=>{const{frag:o,keyInfo:l,url:h}=r;if(!o.decryptdata||l!==this.keyLoaderInfo[h])return s(Qh(o,n.KEY_LOAD_ERROR,new Error("after key load, decryptdata unset or changed"),a));l.decryptdata.key=o.decryptdata.key=new Uint8Array(t.data),o.keyLoader=l.loader=l.keyLoadPromise=null,e({frag:o,keyInfo:l})},onError:(e,r,a,o)=>{this.resetLoader(r),s(Qh(t,n.KEY_LOAD_ERROR,new Error(`HTTP Error ${e.code} loading key ${e.text}`),a,k({url:i,data:void 0},e)))},onTimeout:(e,i,r)=>{this.resetLoader(i),s(Qh(t,n.KEY_LOAD_TIMEOUT,new Error("key loading timed out"),r))},onAbort:(e,i,r)=>{this.resetLoader(i),s(Qh(t,n.INTERNAL_ABORTED,new Error("key loading aborted"),r))}};a.load(l,d,c)})}resetLoader(t){const{frag:e,keyInfo:i,url:s}=t,r=i.loader;e.keyLoader===r&&(e.keyLoader=i.loader=i.keyLoadPromise=null),delete this.keyLoaderInfo[s],r&&r.destroy()}}function Qh(t,e=n.KEY_LOAD_ERROR,i,s,a){return new Oi({type:r.NETWORK_ERROR,details:e,fatal:!1,frag:t,response:a,error:i,networkDetails:s||null})}function Zh(t){const{type:e}=t;switch(e){case u.AUDIO_TRACK:return f.AUDIO;case u.SUBTITLE_TRACK:return f.SUBTITLE;default:return f.MAIN}}function Jh(t,e){let i=t.url;return void 0!==i&&0!==i.indexOf("data:")||(i=e.url),i}class td{constructor(t){this.hls=void 0,this.loaders=Object.create(null),this.variableList=null,this.onManifestLoaded=this.checkAutostartLoad,this.hls=t,this.registerListeners()}startLoad(t){}stopLoad(){this.destroyInternalLoaders()}registerListeners(){const{hls:t}=this;t.on(a.MANIFEST_LOADING,this.onManifestLoading,this),t.on(a.LEVEL_LOADING,this.onLevelLoading,this),t.on(a.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),t.on(a.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),t.on(a.LEVELS_UPDATED,this.onLevelsUpdated,this)}unregisterListeners(){const{hls:t}=this;t.off(a.MANIFEST_LOADING,this.onManifestLoading,this),t.off(a.LEVEL_LOADING,this.onLevelLoading,this),t.off(a.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),t.off(a.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),t.off(a.LEVELS_UPDATED,this.onLevelsUpdated,this)}createInternalLoader(t){const e=this.hls.config,i=e.pLoader,s=e.loader,r=new(i||s)(e);return this.loaders[t.type]=r,r}getInternalLoader(t){return this.loaders[t.type]}resetInternalLoader(t){this.loaders[t]&&delete this.loaders[t]}destroyInternalLoaders(){for(const t in this.loaders){const e=this.loaders[t];e&&e.destroy(),this.resetInternalLoader(t)}}destroy(){this.variableList=null,this.unregisterListeners(),this.destroyInternalLoaders()}onManifestLoading(t,e){const{url:i}=e;this.variableList=null,this.load({id:null,level:0,responseType:"text",type:u.MANIFEST,url:i,deliveryDirectives:null,levelOrTrack:null})}onLevelLoading(t,e){const{id:i,level:s,pathwayId:r,url:n,deliveryDirectives:a,levelInfo:o}=e;this.load({id:i,level:s,pathwayId:r,responseType:"text",type:u.LEVEL,url:n,deliveryDirectives:a,levelOrTrack:o})}onAudioTrackLoading(t,e){const{id:i,groupId:s,url:r,deliveryDirectives:n,track:a}=e;this.load({id:i,groupId:s,level:null,responseType:"text",type:u.AUDIO_TRACK,url:r,deliveryDirectives:n,levelOrTrack:a})}onSubtitleTrackLoading(t,e){const{id:i,groupId:s,url:r,deliveryDirectives:n,track:a}=e;this.load({id:i,groupId:s,level:null,responseType:"text",type:u.SUBTITLE_TRACK,url:r,deliveryDirectives:n,levelOrTrack:a})}onLevelsUpdated(t,e){const i=this.loaders[u.LEVEL];if(i){const t=i.context;t&&!e.levels.some(e=>e===t.levelOrTrack)&&(i.abort(),delete this.loaders[u.LEVEL])}}load(t){var i;const s=this.hls.config;let r,n=this.getInternalLoader(t);if(n){const e=this.hls.logger,i=n.context;if((null==i?void 0:i.levelOrTrack)===t.levelOrTrack&&(i.url===t.url||i.deliveryDirectives&&!t.deliveryDirectives))return void(i.url===t.url?e.log(`[playlist-loader]: ignore ${t.url} ongoing request`):e.log(`[playlist-loader]: ignore ${t.url} in favor of ${i.url}`));e.log(`[playlist-loader]: aborting previous loader for type: ${t.type}`),n.abort()}if(r=t.type===u.MANIFEST?s.manifestLoadPolicy.default:I({},s.playlistLoadPolicy.default,{timeoutRetry:null,errorRetry:null}),n=this.createInternalLoader(t),e(null==(i=t.deliveryDirectives)?void 0:i.part)){let e;if(t.type===u.LEVEL&&null!==t.level?e=this.hls.levels[t.level].details:t.type===u.AUDIO_TRACK&&null!==t.id?e=this.hls.audioTracks[t.id].details:t.type===u.SUBTITLE_TRACK&&null!==t.id&&(e=this.hls.subtitleTracks[t.id].details),e){const t=e.partTarget,i=e.targetduration;if(t&&i){const e=1e3*Math.max(3*t,.8*i);r=I({},r,{maxTimeToFirstByteMs:Math.min(e,r.maxTimeToFirstByteMs),maxLoadTimeMs:Math.min(e,r.maxTimeToFirstByteMs)})}}}const a=r.errorRetry||r.timeoutRetry||{},o={loadPolicy:r,timeout:r.maxLoadTimeMs,maxRetry:a.maxNumRetry||0,retryDelay:a.retryDelayMs||0,maxRetryDelay:a.maxRetryDelayMs||0},l={onSuccess:(t,e,i,s)=>{const r=this.getInternalLoader(i);this.resetInternalLoader(i.type);const n=t.data;e.parsing.start=performance.now(),Rs.isMediaPlaylist(n)||i.type!==u.MANIFEST?this.handleTrackOrLevelPlaylist(t,e,i,s||null,r):this.handleMasterPlaylist(t,e,i,s)},onError:(t,e,i,s)=>{this.handleNetworkError(e,i,!1,t,s)},onTimeout:(t,e,i)=>{this.handleNetworkError(e,i,!0,void 0,t)}};n.load(t,o,l)}checkAutostartLoad(){if(!this.hls)return;const{config:{autoStartLoad:t,startPosition:e},forceStartLoad:i}=this.hls;(t||i)&&(this.hls.logger.log(`${t?"auto":"force"} startLoad with configured startPosition ${e}`),this.hls.startLoad(e))}handleMasterPlaylist(t,e,i,s){const r=this.hls,n=t.data,o=Jh(t,i),l=Rs.parseMasterPlaylist(n,o);if(l.playlistParsingError)return e.parsing.end=performance.now(),void this.handleManifestParsingError(t,i,l.playlistParsingError,s,e);const{contentSteering:h,levels:d,iframeVariants:c,sessionData:u,sessionKeys:f,startTimeOffset:g,variableList:m}=l;this.variableList=m,d.forEach(t=>{const{unknownCodecs:e}=t;if(e){const{preferManagedMediaSource:i}=this.hls.config;let{audioCodec:s,videoCodec:r}=t;for(let n=e.length;n--;){const a=e[n];he(a,"audio",i)?(t.audioCodec=s=s?`${s},${a}`:a,oe.audio[s.substring(0,4)]=2,e.splice(n,1)):he(a,"video",i)&&(t.videoCodec=r=r?`${r},${a}`:a,oe.video[r.substring(0,4)]=2,e.splice(n,1))}}});const{AUDIO:p=[],SUBTITLES:v,"CLOSED-CAPTIONS":y}=Rs.parseMasterPlaylistMedia(n,o,l);if(p.length){p.some(t=>!t.url)||!d[0].audioCodec||d[0].attrs.AUDIO||(this.hls.logger.log("[playlist-loader]: audio codec signaled in quality level, but no embedded audio track signaled, create one"),p.unshift({type:"main",name:"main",groupId:"main",default:!1,autoselect:!1,forced:!1,id:-1,attrs:new Yi({}),bitrate:0,url:""}))}r.trigger(a.MANIFEST_LOADED,{levels:d,audioTracks:p,subtitles:v,iframeVariants:c,captions:y,contentSteering:h,url:o,stats:e,networkDetails:s,sessionData:u,sessionKeys:f,startTimeOffset:g,variableList:m})}handleTrackOrLevelPlaylist(t,i,s,r,n){const o=this.hls,{id:l,level:h,type:d}=s,c=Jh(t,s),f=e(h)?h:e(l)?l:0,g=Zh(s),m=Rs.parseLevelPlaylist(t.data,c,f,g,0,this.variableList);if(d===u.MANIFEST){const t={attrs:new Yi({}),bitrate:0,details:m,name:"",url:c};m.requestScheduled=i.loading.start+js(m,0),o.trigger(a.MANIFEST_LOADED,{levels:[t],audioTracks:[],iframeVariants:[],url:c,stats:i,networkDetails:r,sessionData:null,sessionKeys:null,contentSteering:null,startTimeOffset:null,variableList:null})}i.parsing.end=performance.now(),s.levelDetails=m,this.handlePlaylistLoaded(m,t,i,s,r,n)}handleManifestParsingError(t,e,i,s,o){this.hls.trigger(a.ERROR,{type:r.NETWORK_ERROR,details:n.MANIFEST_PARSING_ERROR,fatal:e.type===u.MANIFEST,url:t.url,err:i,error:i,reason:i.message,response:t,context:e,networkDetails:s,stats:o})}handleNetworkError(t,e,i=!1,s,o){let l=`A network ${i?"timeout":"error"+(s?" (status "+s.code+")":"")} occurred while loading ${t.type}`;t.type===u.LEVEL?l+=`: ${t.level} id: ${t.id}`:t.type!==u.AUDIO_TRACK&&t.type!==u.SUBTITLE_TRACK||(l+=` id: ${t.id} group-id: "${t.groupId}"`);const h=new Error(l);this.hls.logger.warn(`[playlist-loader]: ${l}`);let d=n.UNKNOWN,c=!1;const f=this.getInternalLoader(t);switch(t.type){case u.MANIFEST:d=i?n.MANIFEST_LOAD_TIMEOUT:n.MANIFEST_LOAD_ERROR,c=!0;break;case u.LEVEL:d=i?n.LEVEL_LOAD_TIMEOUT:n.LEVEL_LOAD_ERROR,c=!1;break;case u.AUDIO_TRACK:d=i?n.AUDIO_TRACK_LOAD_TIMEOUT:n.AUDIO_TRACK_LOAD_ERROR,c=!1;break;case u.SUBTITLE_TRACK:d=i?n.SUBTITLE_TRACK_LOAD_TIMEOUT:n.SUBTITLE_LOAD_ERROR,c=!1}f&&this.resetInternalLoader(t.type);const g={type:r.NETWORK_ERROR,details:d,fatal:c,url:t.url,loader:f,context:t,error:h,networkDetails:e,stats:o};if(s){let i=t.url;e&&"url"in e&&(i=e.url),g.response=k({url:i,data:void 0},s)}this.hls.trigger(a.ERROR,g)}handlePlaylistLoaded(t,e,i,s,o,l){const h=this.hls,{type:d,level:c,levelOrTrack:g,id:m,groupId:p,deliveryDirectives:v}=s,y=Jh(e,s),E=Zh(s);let T="number"==typeof s.level&&E===f.MAIN?c:void 0;g&&"iframes"in g&&g.iframes&&!t.iframesOnly&&(t.playlistParsingError=new Error("EXT-X-I-FRAME-STREAM-INF media playlist MUST contain an EXT-X-I-FRAMES-ONLY tag"),t.iframesOnly=!0);const S=t.playlistParsingError;if(S){if(this.hls.logger.warn(`${S} ${t.url}`),!h.config.ignorePlaylistParsingErrors)return void h.trigger(a.ERROR,{type:r.NETWORK_ERROR,details:n.LEVEL_PARSING_ERROR,fatal:!1,url:y,error:S,reason:S.message,response:e,context:s,level:T,parent:E,networkDetails:o,stats:i});t.playlistParsingError=null}if(!t.fragments.length){const l=t.playlistParsingError=new Error("No Segments found in Playlist");return void h.trigger(a.ERROR,{type:r.NETWORK_ERROR,details:n.LEVEL_EMPTY_ERROR,fatal:!1,url:y,error:l,reason:l.message,response:e,context:s,level:T,parent:E,networkDetails:o,stats:i})}switch(t.live&&l&&(l.getCacheAge&&(t.ageHeader=l.getCacheAge()||0),l.getCacheAge&&!isNaN(t.ageHeader)||(t.ageHeader=0)),d){case u.MANIFEST:case u.LEVEL:if(T)if(g){if(g!==h.levels[T]){const t=h.levels.indexOf(g);t>-1&&(T=t)}}else T=0;h.trigger(a.LEVEL_LOADED,{details:t,levelInfo:g||h.levels[0],level:T||0,id:m||0,stats:i,networkDetails:o,deliveryDirectives:v,withoutMultiVariant:d===u.MANIFEST,context:s});break;case u.AUDIO_TRACK:h.trigger(a.AUDIO_TRACK_LOADED,{details:t,track:g,id:m||0,groupId:p||"",stats:i,networkDetails:o,deliveryDirectives:v,context:s});break;case u.SUBTITLE_TRACK:h.trigger(a.SUBTITLE_TRACK_LOADED,{details:t,track:g,id:m||0,groupId:p||"",stats:i,networkDetails:o,deliveryDirectives:v,context:s})}}}class ed{static get version(){return Lr}static isMSESupported(){return Fl()}static isSupported(){return function(){if(!Fl())return!1;const t=Y();return"function"==typeof(null==t?void 0:t.isTypeSupported)&&(["avc1.42E01E,mp4a.40.2","av01.0.01M.08","vp09.00.50.08"].some(e=>t.isTypeSupported(ce(e,"video")))||["mp4a.40.2","fLaC"].some(e=>t.isTypeSupported(ce(e,"audio"))))}()}static getMediaSource(){return Y()}static get Events(){return a}static get MetadataSchema(){return Mr}static get ErrorTypes(){return r}static get ErrorDetails(){return n}static get DefaultConfig(){return ed.defaultConfig?ed.defaultConfig:Gh}static set DefaultConfig(t){ed.defaultConfig=t}constructor(t={}){this.config=void 0,this.userConfig=void 0,this.logger=void 0,this._url=null,this.streamController=void 0,this.coreComponents=void 0,this.networkControllers=void 0,this._emitter=new Ar,this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.abrController=void 0,this.bufferController=void 0,this.capLevelController=void 0,this.latencyController=void 0,this.levelController=void 0,this.audioStreamController=void 0,this.subtititleStreamController=void 0,this.audioTrackController=void 0,this.subtitleTrackController=void 0,this.interstitialsController=void 0,this.iframeController=void 0,this.gapController=void 0,this.emeController=void 0,this.cmcdController=void 0,this._media=null,this._sessionId=void 0,this.triggeringException=void 0,this.started=!1;const e=this.logger=function(t,e,i){const s=V();if("object"==typeof console&&!0===t||"object"==typeof t){const r=["debug","log","info","warn","error"];r.forEach(e=>{s[e]=j(e,t,i)});try{s.log(`Debug logs enabled for "${e}" in hls.js version 1.7.3`)}catch(t){return V()}r.forEach(e=>{H[e]=j(e,t)})}else I(H,s);return s}(t.debug||!1,"Hls instance",t.loggerId||t.assetPlayerId),i=this.config=Kh(ed.DefaultConfig,t,e);this.userConfig=t,i.progressive&&jh(i,e);const{streamController:s,abrController:r,bufferController:n,capLevelController:o,errorController:l,fpsController:h,id3TrackController:d,iframeController:c,gapController:u}=i,f=new l(this),g=this.abrController=new r(this),m=new Ti(this),p=i.interstitialsController,v=p?this.interstitialsController=new p(this,ed):null,y=n?this.bufferController=new n(this,m):null,E=o?this.capLevelController=new o(this):null,T=h?new h(this):null,S=i.cmcdController,b=S?this.cmcdController=new S(this):null,A=new td(this),L=i.contentSteeringController,R=L?new L(this):null,k=this.levelController=new Hh(this,R),_=d?new d(this):void 0,D=new Xh(this.config,this.logger),w=this.streamController=new s(this,m,D),P=this.gapController=u?new u(this,m):void 0;E&&E.setStreamController(w);const C=[A,k,w];v&&C.splice(1,0,v),R&&C.splice(1,0,R),this.networkControllers=C;const x=[g];y&&x.push(y),P&&x.push(P),E&&x.push(E),T&&(T.setStreamController(w),x.push(T)),_&&x.push(_),x.push(m),this.audioTrackController=this.createController(i.audioTrackController,C);const M=i.audioStreamController;M&&C.push(this.audioStreamController=new M(this,m,D)),this.subtitleTrackController=this.createController(i.subtitleTrackController,C);const O=i.subtitleStreamController;O&&C.push(this.subtititleStreamController=new O(this,m,D)),this.createController(i.timelineController,x),D.emeController=this.emeController=this.createController(i.emeController,x),b&&x.push(b),this.latencyController=this.createController(i.latencyController,x),this.coreComponents=x,this.iframeController=c?new c(this,ed):void 0,C.push(f);const F=f.onErrorOut;"function"==typeof F&&this.on(a.ERROR,F,f),this.on(a.MANIFEST_LOADED,A.onManifestLoaded,A)}createController(t,e){if(t){const i=new t(this);return e&&e.push(i),i}return null}on(t,e,i=this){this._emitter.on(t,e,i)}once(t,e,i=this){this._emitter.once(t,e,i)}removeAllListeners(t){this._emitter.removeAllListeners(t)}off(t,e,i=this,s){this._emitter.off(t,e,i,s)}listeners(t){return this._emitter.listeners(t)}emit(t,e,i){return this._emitter.emit(t,e,i)}trigger(t,e){if(this.config.debug)return this.emit(t,t,e);try{return this.emit(t,t,e)}catch(e){if(this.logger.error("An internal error happened while handling event "+t+'. Error message: "'+e.message+'". Here is a stacktrace:',e),!this.triggeringException){this.triggeringException=!0;const i=t===a.ERROR;this.trigger(a.ERROR,{type:r.OTHER_ERROR,details:n.INTERNAL_EXCEPTION,fatal:i,event:t,error:e}),this.triggeringException=!1}}return!1}listenerCount(t){return this._emitter.listenerCount(t)}destroy(){this.logger.log("destroy"),this.trigger(a.DESTROYING,void 0),this.detachMedia(),this.removeAllListeners(),this._autoLevelCapping=-1,this._url=null,this.networkControllers.forEach(t=>t.destroy()),this.networkControllers.length=0,this.coreComponents.forEach(t=>t.destroy()),this.coreComponents.length=0,this.iframeController=void 0;const t=this.config;t.xhrSetup=t.fetchSetup=void 0,this.userConfig=null}attachMedia(t){if(!t||"media"in t&&!t.media){const e=new Error(`attachMedia failed: invalid argument (${t})`);return void this.trigger(a.ERROR,{type:r.OTHER_ERROR,details:n.ATTACH_MEDIA_ERROR,fatal:!0,error:e})}this.logger.log("attachMedia"),this._media&&(this.logger.warn("media must be detached before attaching"),this.detachMedia());const e="media"in t,i=e?t.media:t,s=e?t:{media:i};this._media=i,this.trigger(a.MEDIA_ATTACHING,s)}detachMedia(){this.logger.log("detachMedia");const t={};this.trigger(a.MEDIA_DETACHING,t),this._media=null,this.trigger(a.MEDIA_DETACHED,t)}transferMedia(){var t;this._media=null;const e=(null==(t=this.bufferController)?void 0:t.transferMedia())||null,i={transferMedia:e};return this.trigger(a.MEDIA_DETACHING,i),this.trigger(a.MEDIA_DETACHED,i),e}loadSource(t){var e;this.stopLoad();const i=this.media,s=this._url,r=this._url=d.buildAbsoluteURL(self.location.href,t,{alwaysNormalize:!0});this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.logger.log(`loadSource:${r}`),i&&s&&(s!==r||null!=(e=this.bufferController)&&e.hasSourceTypes())&&(this.detachMedia(),this.attachMedia(i)),this.trigger(a.MANIFEST_LOADING,{url:t})}get url(){return this._url}get hasEnoughToStart(){return this.streamController.hasEnoughToStart}get startPosition(){return this.streamController.startPositionValue}startLoad(t=-1,e){this.logger.log(`startLoad(${t+(e?", <skip seek to start>":"")})`),this.started=!0,this.resumeBuffering();for(let i=0;i<this.networkControllers.length&&(this.networkControllers[i].startLoad(t,e),this.started&&this.networkControllers);i++);}stopLoad(){this.logger.log("stopLoad"),this.started=!1;for(let t=0;t<this.networkControllers.length&&(this.networkControllers[t].stopLoad(),!this.started&&this.networkControllers);t++);}get loadingEnabled(){return this.started&&this.streamController.state!==rr}get bufferingEnabled(){return this.streamController.bufferingEnabled}resumeBuffering(){this.bufferingEnabled||(this.logger.log("resume buffering"),this.networkControllers.forEach(t=>{t.resumeBuffering&&t.resumeBuffering()}))}pauseBuffering(){this.bufferingEnabled&&(this.logger.log("pause buffering"),this.networkControllers.forEach(t=>{t.pauseBuffering&&t.pauseBuffering()}))}get inFlightFragments(){const t={[f.MAIN]:this.streamController.inFlightFrag};return this.audioStreamController&&(t[f.AUDIO]=this.audioStreamController.inFlightFrag),this.subtititleStreamController&&(t[f.SUBTITLE]=this.subtititleStreamController.inFlightFrag),t}swapAudioCodec(){this.logger.log("swapAudioCodec"),this.streamController.swapAudioCodec()}recoverMediaError(){this.logger.log("recoverMediaError");const t=this._media,e=this.started,i=null==t?void 0:t.currentTime;this.detachMedia(),t&&(this.attachMedia(t),e&&(i?this.startLoad(i):this.config.autoStartLoad||this.startLoad()))}removeLevel(t){this.levelController.removeLevel(t)}get sessionId(){let t=this._sessionId;return t||(t=this._sessionId=tt()),t}get levels(){const t=this.levelController.levels;return t||[]}get latestLevelDetails(){return this.streamController.getLevelDetails()||null}get loadLevelObj(){return this.levelController.loadLevelObj}get currentLevel(){return this.streamController.currentLevel}set currentLevel(t){this.logger.log(`set currentLevel:${t}`),this.levelController.manualLevel=t,this.streamController.immediateLevelSwitch()}get nextLevel(){return this.streamController.nextLevel}set nextLevel(t){this.logger.log(`set nextLevel:${t}`),this.levelController.manualLevel=t,this.streamController.nextLevelSwitch()}get loadLevel(){return this.levelController.level}set loadLevel(t){this.logger.log(`set loadLevel:${t}`),this.levelController.manualLevel=t}get nextLoadLevel(){return this.levelController.nextLoadLevel}set nextLoadLevel(t){this.levelController.nextLoadLevel=t}get firstLevel(){return Math.max(this.levelController.firstLevel,this.minAutoLevel)}set firstLevel(t){this.logger.log(`set firstLevel:${t}`),this.levelController.firstLevel=t}get startLevel(){const t=this.levelController.startLevel;return-1===t&&this.abrController.forcedAutoLevel>-1?this.abrController.forcedAutoLevel:t}set startLevel(t){this.logger.log(`set startLevel:${t}`),-1!==t&&(t=Math.max(t,this.minAutoLevel)),this.levelController.startLevel=t}get capLevelToPlayerSize(){return this.config.capLevelToPlayerSize}set capLevelToPlayerSize(t){const e=this.capLevelController,i=!!t;e&&i!==this.config.capLevelToPlayerSize&&(i?e.startCapping():(e.stopCapping(),this.autoLevelCapping=-1,this.streamController.nextLevelSwitch()),this.config.capLevelToPlayerSize=i)}get autoLevelCapping(){return this._autoLevelCapping}get bandwidthEstimate(){const{bwEstimator:t}=this.abrController;return t?t.getEstimate():NaN}set bandwidthEstimate(t){this.abrController.resetEstimator(t)}get abrEwmaDefaultEstimate(){const{bwEstimator:t}=this.abrController;return t?t.defaultEstimate:NaN}get ttfbEstimate(){const{bwEstimator:t}=this.abrController;return t?t.getEstimateTTFB():NaN}set autoLevelCapping(t){this._autoLevelCapping!==t&&(this.logger.log(`set autoLevelCapping:${t}`),this._autoLevelCapping=t,this.levelController.checkMaxAutoUpdated())}get maxHdcpLevel(){return this._maxHdcpLevel}set maxHdcpLevel(t){(function(t){return we.indexOf(t)>-1})(t)&&this._maxHdcpLevel!==t&&(this._maxHdcpLevel=t,this.levelController.checkMaxAutoUpdated())}get autoLevelEnabled(){return-1===this.levelController.manualLevel}get manualLevel(){return this.levelController.manualLevel}get minAutoLevel(){const{levels:t,config:{minAutoBitrate:e}}=this;if(!t)return 0;const i=t.length;for(let s=0;s<i;s++)if(t[s].maxBitrate>=e)return s;return 0}get maxAutoLevel(){const{levels:t,autoLevelCapping:e,maxHdcpLevel:i}=this;let s;if(s=-1===e&&null!=t&&t.length?t.length-1:e,i)for(let e=s;e--;){const s=t[e].attrs["HDCP-LEVEL"];if(s&&s<=i)return e}return s}get firstAutoLevel(){return this.abrController.firstAutoLevel}get nextAutoLevel(){return this.abrController.nextAutoLevel}set nextAutoLevel(t){this.abrController.nextAutoLevel=t}get playingDate(){return this.streamController.currentProgramDateTime}get mainForwardBufferInfo(){return this.streamController.getMainFwdBufferInfo()}get audioForwardBufferInfo(){var t;return(null==(t=this.audioStreamController)?void 0:t.getFwdBufferInfo())||null}get maxBufferLength(){return this.streamController.maxBufferLength}setAudioOption(t){var e;return(null==(e=this.audioTrackController)?void 0:e.setAudioOption(t))||null}setSubtitleOption(t){var e;return(null==(e=this.subtitleTrackController)?void 0:e.setSubtitleOption(t))||null}get allAudioTracks(){const t=this.audioTrackController;return t?t.allAudioTracks:[]}get audioTracks(){const t=this.audioTrackController;return t?t.audioTracks:[]}get audioTrack(){const t=this.audioTrackController;return t?t.audioTrack:-1}set audioTrack(t){const e=this.audioTrackController;e&&(e.audioTrack=t)}get nextAudioTrack(){var t,e;return null!=(t=null==(e=this.audioStreamController)?void 0:e.nextAudioTrack)?t:-1}set nextAudioTrack(t){const{audioTrackController:e}=this;e&&(e.nextAudioTrack=t)}get allSubtitleTracks(){const t=this.subtitleTrackController;return t?t.allSubtitleTracks:[]}get subtitleTracks(){const t=this.subtitleTrackController;return t?t.subtitleTracks:[]}get subtitleTrack(){const t=this.subtitleTrackController;return t?t.subtitleTrack:-1}get media(){return this._media}set subtitleTrack(t){const e=this.subtitleTrackController;e&&(e.subtitleTrack=t)}get subtitleDisplay(){const t=this.subtitleTrackController;return!!t&&t.subtitleDisplay}set subtitleDisplay(t){const e=this.subtitleTrackController;e&&(e.subtitleDisplay=t)}get lowLatencyMode(){return this.config.lowLatencyMode}set lowLatencyMode(t){this.config.lowLatencyMode=t}get liveSyncPosition(){var t,e;return null!=(t=null==(e=this.latencyController)?void 0:e.liveSyncPosition)?t:null}get latency(){var t;return(null==(t=this.latencyController)?void 0:t.latency)||0}get maxLatency(){var t;return(null==(t=this.latencyController)?void 0:t.maxLatency)||0}get targetLatency(){var t;return(null==(t=this.latencyController)?void 0:t.targetLatency)||null}set targetLatency(t){this.latencyController&&(this.latencyController.targetLatency=t)}get drift(){var t;return(null==(t=this.latencyController)?void 0:t.drift)||null}get forceStartLoad(){return this.streamController.forceStartLoad}get pathways(){return this.levelController.pathways}get pathwayPriority(){return this.levelController.pathwayPriority}set pathwayPriority(t){this.levelController.pathwayPriority=t}get bufferedToEnd(){var t;return!(null==(t=this.bufferController)||!t.bufferedToEnd)}get interstitialsManager(){return this.interstitialsController?this.interstitialsController.interstitialsManager:null}get iframeVariants(){const t=this.levelController.iframeVariants;return t||[]}createIFramePlayer(t){return this._url&&this.iframeController?this.iframeController.createIFramePlayer(t):null}createImageIFramePlayer(t){return this._url&&this.iframeController?this.iframeController.createImageIFramePlayer(t):null}getMediaDecodingInfo(t,e=this.allAudioTracks){return Re(t,Ke(e),navigator.mediaCapabilities)}}function id(t){const{baseUrl:e,apiKey:i,clientId:s,fetch:r,apiVersion:n}=t,a=r??globalThis.fetch;if(!a)throw new Error("No fetch implementation found. Provide one in SDKConfig.fetch for Node or custom environments.");const o={"Content-Type":"application/json","x-api-key":i},l=t=>function(t,e,i,s){if(/^https?:\/\//i.test(s))return s;const r=function(t){let e=t.length;for(;e>0&&"/"===t[e-1];)e--;return t.slice(0,e)}(t),n=s.replace(/^\/+/,"");return`${r}/b2b/${e}/subscription/${encodeURIComponent(i)}${n.startsWith("/")?n:`/${n}`}`}(e,function(t){const e=t.toLowerCase();return"v1"===e||"v2"===e?e:"v1"}(n),s,t),h=async(t,e,i,s)=>{const r={method:t,headers:{...o,...i?.headers},...i};void 0!==s&&(r.body=JSON.stringify(s));return async function(t){if(!t.ok){const e=await t.text().catch(()=>"");throw new Error(`HTTP ${t.status}: ${e||t.statusText}`)}if(204!==t.status)return t.json()}(await a(l(e),r))};return{get:(t,e)=>h("GET",t,e),post:(t,e,i)=>h("POST",t,i,e),put:(t,e,i)=>h("PUT",t,i,e),patch:(t,e,i)=>h("PATCH",t,i,e),delete:(t,e)=>h("DELETE",t,e)}}ed.defaultConfig=void 0;const sd=t=>void 0!==t?.subdomain?`?subdomain=${encodeURIComponent(t.subdomain)}`:"";const rd="https://api.jaaq.app";class nd{constructor(t,e){"v2"===e?(this.videos=function(t){return{async getById(e){const i=`/videos/${encodeURIComponent(e)}`;return(await t.get(i)).video}}}(t),this.collections=function(t){return{list:async()=>(await t.get("/collections")).collections,async getById(e,i){const s=`/collections/${encodeURIComponent(e)}${sd(i)}`;return(await t.get(s)).collection},async getSummaryById(e,i){const s=`/collections/${encodeURIComponent(e)}/summary${sd(i)}`;return(await t.get(s)).collection}}}(t)):(this.videos=function(t){return{async getById(e){const i=`/videos/${encodeURIComponent(e)}`;return(await t.get(i)).video}}}(t),this.collections=function(t){return{list:async()=>(await t.get("/collections")).collections,async getById(e){const i=`/collections/${encodeURIComponent(e)}`;return(await t.get(i)).collection}}}(t))}static fromHttp(t,e){return new nd(t,e)}static init(t){return ad(t)}}function ad(t){const{baseUrl:e=rd,apiKey:i,clientId:s,fetch:r,apiVersion:n="v1"}=t,a=id({baseUrl:e,apiKey:i,clientId:s,fetch:r??globalThis.fetch,apiVersion:n});return nd.fromHttp(a,n)}function od(t,e,i){return Math.max(e,Math.min(i,t))}var ld=".jaaq-video-player {\n position: relative;\n width: 100%;\n max-width: none;\n margin: 0;\n background: #000;\n border-radius: 12px;\n overflow: hidden;\n box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);\n font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, sans-serif;\n aspect-ratio: 9 / 16;\n}\n\n.jaaq-video-player video {\n position: absolute;\n top: 0;\n left: 0;\n width: 100%;\n height: 100%;\n display: block;\n background: #000;\n object-fit: cover;\n}\n\n.jaaq-video-player.fullscreen {\n max-width: 100%;\n border-radius: 0;\n aspect-ratio: auto;\n}\n\n.jaaq-controls {\n position: absolute;\n bottom: 0;\n left: 0;\n right: 0;\n background: linear-gradient(to top, rgba(0, 0, 0, 0.8), transparent);\n padding: 40px 16px 16px;\n opacity: 1;\n z-index: 5;\n}\n\n.jaaq-progress-bar {\n width: 100%;\n flex: 1 1 0;\n min-width: 80px;\n height: 4px;\n background: rgba(255, 255, 255, 0.3);\n border-radius: 2px;\n cursor: pointer;\n position: relative;\n}\n\n.jaaq-progress-filled {\n height: 100%;\n background: #007bff;\n border-radius: 2px;\n width: 0%;\n transition: width 0.1s linear;\n}\n\n.jaaq-progress-bar:hover .jaaq-progress-filled {\n background: #0056b3;\n}\n\n.jaaq-controls-bottom {\n display: flex;\n align-items: center;\n justify-content: center;\n gap: 12px;\n color: white;\n}\n\n.jaaq-control-btn {\n background: transparent;\n border: none;\n color: white;\n cursor: pointer;\n padding: 8px;\n display: flex;\n align-items: center;\n justify-content: center;\n transition: transform 0.2s;\n font-size: 20px;\n line-height: 1;\n}\n\n.jaaq-control-btn:hover {\n transform: scale(1.1);\n}\n\n.jaaq-control-btn:disabled {\n opacity: 0.5;\n cursor: not-allowed;\n}\n\n.jaaq-loading {\n position: absolute;\n top: 50%;\n left: 50%;\n transform: translate(-50%, -50%);\n width: 50px;\n height: 50px;\n border: 4px solid rgba(255, 255, 255, 0.3);\n border-top-color: #007bff;\n border-radius: 50%;\n animation: jaaq-spin 1s linear infinite;\n}\n\n@keyframes jaaq-spin {\n to {\n transform: translate(-50%, -50%) rotate(360deg);\n }\n}\n\n.jaaq-error {\n position: absolute;\n top: 50%;\n left: 50%;\n transform: translate(-50%, -50%);\n background: rgba(220, 53, 69, 0.9);\n color: white;\n padding: 16px 24px;\n border-radius: 8px;\n max-width: 80%;\n text-align: center;\n font-size: 14px;\n}\n\n.jaaq-video-info {\n padding: 16px;\n background: #f8f9fa;\n border-radius: 0 0 12px 12px;\n margin-top: -12px;\n}\n\n.jaaq-video-info h3 {\n margin: 0 0 8px 0;\n color: #333;\n font-size: 18px;\n font-weight: 600;\n}\n\n.jaaq-video-info p {\n margin: 4px 0;\n color: #666;\n font-size: 14px;\n}\n\n.jaaq-video-info strong {\n color: #333;\n}\n\n.jaaq-logo {\n position: absolute;\n top: 20px;\n left: 22px;\n color: white;\n font-size: 16px;\n font-weight: 600;\n z-index: 10;\n font-family:\n 'Archivo',\n -apple-system,\n BlinkMacSystemFont,\n 'Segoe UI',\n Roboto,\n sans-serif;\n letter-spacing: 0.5px;\n pointer-events: none;\n}\n\n.jaaq-center-play-btn {\n position: absolute;\n top: 50%;\n left: 50%;\n transform: translate(-50%, -50%);\n width: 84px;\n height: 84px;\n background: transparent;\n border: none;\n cursor: pointer;\n z-index: 15;\n display: flex;\n align-items: center;\n justify-content: center;\n transition: transform 0.2s;\n padding: 0;\n}\n\n.jaaq-center-play-btn:hover {\n transform: translate(-50%, -50%) scale(1.1);\n}\n\n.jaaq-center-play-btn svg {\n width: 100%;\n height: 100%;\n filter: drop-shadow(0 4px 8px rgba(0, 0, 0, 0.3));\n}\n\n.jaaq-video-player.is-playing .jaaq-center-play-btn {\n display: none;\n}\n\n.jaaq-gradient-overlay {\n position: absolute;\n bottom: 0;\n left: 0;\n right: 0;\n background: linear-gradient(180deg, transparent 0%, #0f0f0f 100%);\n padding: 80px 22px 85px;\n pointer-events: none;\n z-index: 5;\n}\n\n.jaaq-caption-display {\n font-family:\n 'Archivo',\n -apple-system,\n BlinkMacSystemFont,\n 'Segoe UI',\n Roboto,\n sans-serif;\n font-weight: 400;\n font-size: 16px;\n line-height: 20px;\n color: white;\n background: rgba(0, 0, 0, 0.8);\n padding: 8px 16px;\n margin-bottom: 12px;\n border-radius: 4px;\n text-align: center;\n max-width: 90%;\n margin-left: auto;\n margin-right: auto;\n}\n\n.jaaq-video-title {\n font-family:\n 'Archivo',\n -apple-system,\n BlinkMacSystemFont,\n 'Segoe UI',\n Roboto,\n sans-serif;\n font-weight: 600;\n font-size: 18.695px;\n line-height: 21.5px;\n color: white;\n margin-bottom: 8px;\n letter-spacing: 0.37px;\n}\n\n.jaaq-video-author {\n font-family:\n 'Archivo',\n -apple-system,\n BlinkMacSystemFont,\n 'Segoe UI',\n Roboto,\n sans-serif;\n font-weight: 500;\n font-size: 14.021px;\n line-height: 16.825px;\n color: white;\n opacity: 0.7;\n margin-bottom: 8px;\n letter-spacing: -0.14px;\n}\n\n.jaaq-video-description {\n font-family:\n 'Archivo',\n -apple-system,\n BlinkMacSystemFont,\n 'Segoe UI',\n Roboto,\n sans-serif;\n font-weight: 400;\n font-size: 11px;\n line-height: 16px;\n color: #aaa8aa;\n letter-spacing: -0.11px;\n}\n\n.jaaq-description-text {\n color: #aaa8aa;\n}\n\n.jaaq-read-more {\n color: white;\n cursor: pointer;\n pointer-events: auto;\n}\n\n.jaaq-read-more:hover {\n text-decoration: underline;\n}\n\n.jaaq-progress-bar {\n background: rgba(255, 255, 255, 0.2);\n}\n\n.jaaq-progress-filled {\n background: white;\n}\n\n.jaaq-captions-btn {\n font-size: 14px;\n font-weight: 600;\n border: 1.5px solid white;\n border-radius: 3px;\n padding: 4px 6px;\n line-height: 1;\n}\n\n.jaaq-captions-btn.active {\n background: white;\n color: #000;\n}\n";class hd{constructor(t,e){if(this.client=null,this.hls=null,this.videoElement=null,this.listeners=new Map,this.captionCues=[],this.elements={},this.container="string"==typeof t?document.querySelector(t):t,!this.container)throw new Error("Container element not found");if(this.config=e,this.state={isPlaying:!1,currentTime:0,duration:0,volume:1,isMuted:!0===e.startMuted,isFullscreen:!1,isLoading:!0,error:null,videoData:null,captionsEnabled:!1},e.client)this.client=e.client;else{if(!e.apiKey||!e.clientId)throw new Error("Please provide either a client instance or apiKey and clientId");this.client=function(t){return ad(t)}({apiKey:e.apiKey,clientId:e.clientId,baseUrl:e.baseUrl})}this.init()}async init(){this.createDOM(),await this.loadVideo(),this.attachEventListeners(),!0===this.config.startMuted&&this.updateVolumeUI()}createDOM(){this.container.innerHTML="";const t=document.createElement("div");t.style.width=this.config.width||"100%",t.style.height=this.config.height||"auto";const e=document.createElement("div");e.className=`jaaq-video-player jaaq-vanilla-player ${this.config.className||""}`,this.elements.player=e;const i=document.createElement("video");this.videoElement=i,!0===this.config.startMuted&&(i.muted=!0,i.setAttribute("muted","")),e.appendChild(i);const s=document.createElement("div");s.className="jaaq-logo",s.innerHTML='\n <svg xmlns="http://www.w3.org/2000/svg" width="50" height="15" viewBox="0 0 50 15" fill="none">\n <path d="M48.0329 10.7826C48.7578 9.6622 49.1402 8.37108 49.1402 7.02322C49.1402 3.19784 46.0283 0.0859375 42.2029 0.0859375C38.3775 0.0859375 35.2656 3.19784 35.2656 7.02322C35.2656 10.8486 38.3753 13.9578 42.1985 13.9605C42.1991 13.9605 42.2002 13.9605 42.2007 13.9605H42.2029C43.8475 13.9605 45.4305 13.3687 46.6698 12.3285L49.9971 14.56V12.0999L48.0334 10.7826H48.0329ZM37.309 7.02322C37.309 4.32479 39.5045 2.12927 42.2035 2.12927C44.9024 2.12927 47.0974 4.32479 47.0974 7.02322C47.0974 7.96252 46.8345 8.862 46.3359 9.64475L43.9817 8.06561C43.4531 7.71378 42.8373 7.52778 42.2002 7.52778C40.4394 7.52778 39.0054 8.95036 38.9846 10.7062C37.9586 9.80839 37.3084 8.49053 37.3084 7.02322H37.309ZM42.2035 11.9172C42.2035 11.9172 42.2002 11.9172 42.1985 11.9172C41.5527 11.9161 41.0274 11.3903 41.0274 10.7439C41.0274 10.0975 41.5538 9.57056 42.2007 9.57056C42.4331 9.57056 42.6578 9.6382 42.8493 9.76584L44.8714 11.1224C44.0853 11.633 43.1586 11.9172 42.2029 11.9172H42.2035Z" fill="white"/>\n <path d="M31.0751 0.686201C30.9856 0.579834 30.8858 0.483286 30.7767 0.39983C30.4374 0.138004 30.0283 0 29.5946 0C29.161 0 28.7524 0.138549 28.4126 0.39983C28.2304 0.540561 28.0755 0.711838 27.9533 0.909844C27.8835 1.02276 27.8257 1.14003 27.7815 1.25785L23.1172 13.7317H25.4551L29.5946 2.66135L33.7342 13.7317H36.0721L31.4078 1.25785C31.3303 1.05003 31.218 0.858024 31.0745 0.686746L31.0751 0.686201Z" fill="white"/>\n <path d="M17.4969 0.686201C17.4075 0.579834 17.3076 0.483286 17.1986 0.39983C16.8593 0.138004 16.4502 0 16.0165 0C15.5829 0 15.1743 0.138549 14.8345 0.39983C14.6523 0.540561 14.4974 0.711838 14.3752 0.909844C14.3054 1.02276 14.2476 1.14003 14.2034 1.25785L9.53906 13.7317H11.8769L16.0165 2.66135L20.1561 13.7317H22.494L17.8302 1.25731C17.7527 1.04948 17.6404 0.857478 17.4969 0.686201Z" fill="white"/>\n <path d="M9.86046 0.511825V0.371094H7.82204V9.02333C7.82204 10.6248 6.51891 11.928 4.91741 11.928C3.47028 11.928 2.23261 10.849 2.03897 9.41771L2.01988 9.27807L1.88024 9.29716L0.13964 9.5328L0 9.5519L0.0190914 9.69154C0.348555 12.1292 2.45462 13.9669 4.91741 13.9669C7.64313 13.9669 9.86046 11.7496 9.86046 9.02388V0.511825Z" fill="white"/>\n </svg>\n ',this.elements.logo=s,e.appendChild(s);const r=document.createElement("button");r.className="jaaq-center-play-btn",r.innerHTML='\n <svg viewBox="0 0 84 84" fill="none">\n <circle cx="42" cy="42" r="42" fill="white" fill-opacity="0.9"/>\n <path d="M33 28L56 42L33 56V28Z" fill="#000"/>\n </svg>\n ',r.setAttribute("aria-label","Play video"),this.elements.centerPlayBtn=r,e.appendChild(r);const n=document.createElement("div");n.className="jaaq-gradient-overlay",this.elements.gradientOverlay=n;const a=document.createElement("div");a.className="jaaq-caption-display",a.style.display="none",this.elements.captionDisplay=a,n.appendChild(a);const o=document.createElement("div");o.className="jaaq-video-title",this.elements.videoTitle=o,n.appendChild(o);const l=document.createElement("div");l.className="jaaq-video-author",this.elements.videoAuthor=l,n.appendChild(l);const h=document.createElement("div");h.className="jaaq-video-description",this.elements.videoDescription=h,n.appendChild(h),e.appendChild(n);const d=document.createElement("div");d.className="jaaq-loading",this.elements.loading=d,e.appendChild(d);const c=document.createElement("div");c.className="jaaq-error",c.style.display="none",this.elements.error=c,e.appendChild(c);const u=document.createElement("div");u.className="jaaq-controls",this.elements.controls=u;const f=document.createElement("div");f.className="jaaq-controls-bottom";const g=document.createElement("button");g.className="jaaq-control-btn",g.textContent="▶",g.setAttribute("aria-label","Play"),this.elements.playPauseBtn=g,f.appendChild(g);const m=document.createElement("button");m.className="jaaq-control-btn",m.innerHTML='\n <svg xmlns="http://www.w3.org/2000/svg" width="22" height="20" viewBox="0 0 22 20" fill="none">\n <path d="M11.2168 19.9287L4.20801 13.7031H0V6.22559H4.20898L11.2168 0V19.9287ZM14.0215 0.150391C16.2405 0.150468 18.1409 1.39074 19.4385 3.17676C20.7365 4.9634 21.499 7.36811 21.499 9.96484C21.499 12.5613 20.7363 14.9654 19.4385 16.752C18.1409 18.538 16.2405 19.7792 14.0215 19.7793V17.1025C15.2032 17.1025 16.3824 16.4464 17.3135 15.165C18.2442 13.8839 18.8593 12.0493 18.8594 9.96484C18.8594 7.88034 18.2442 6.04581 17.3135 4.76465C16.3824 3.4832 15.2033 2.82723 14.0215 2.82715V0.150391ZM14.0215 5.75879C15.5701 5.75896 16.8252 7.64189 16.8252 9.96484C16.8251 12.2877 15.57 14.1707 14.0215 14.1709V5.75879Z" fill="white"/>\n </svg>\n ',m.setAttribute("aria-label","Mute"),this.elements.volumeBtn=m,f.appendChild(m);const p=document.createElement("div");p.className="jaaq-progress-bar",this.elements.progressBar=p;const v=document.createElement("div");v.className="jaaq-progress-filled",this.elements.progressFilled=v,p.appendChild(v),f.appendChild(p);const y=document.createElement("button");y.className="jaaq-control-btn jaaq-captions-btn",y.innerHTML="CC",y.setAttribute("aria-label","Captions"),this.elements.captionsBtn=y,f.appendChild(y);const E=document.createElement("button");E.className="jaaq-control-btn",E.textContent="⛶",E.setAttribute("aria-label","Fullscreen"),this.elements.fullscreenBtn=E,f.appendChild(E),u.appendChild(f),e.appendChild(u),t.appendChild(e),this.container.appendChild(t),this.updateControlsVisibility()}updateControlsVisibility(){const t=!1!==this.config.controls;this.elements.controls&&(this.elements.controls.style.display=t?"":"none")}async loadVideo(){if(this.client&&this.videoElement)try{this.setState({isLoading:!0,error:null});const t=await this.client.videos.getById(this.config.videoId);this.setState({videoData:t}),t.subtitle&&(this.captionCues=this.parseWebVTT(t.subtitle)),this.updateOverlayContent(t),this.emit("loaded",t);const e=t.videoUrl;if(e.includes(".m3u8"))if(ed.isSupported()){this.hls&&this.hls.destroy();const t=new ed({enableWorker:!0,lowLatencyMode:!0});!0===this.config.startMuted&&this.videoElement&&(this.videoElement.muted=!0,this.videoElement.setAttribute("muted","")),t.loadSource(e),t.attachMedia(this.videoElement),!0===this.config.startMuted&&this.videoElement&&(this.videoElement.muted=!0,this.videoElement.setAttribute("muted","")),t.on(ed.Events.MANIFEST_PARSED,()=>{this.setState({isLoading:!1}),this.elements.loading&&(this.elements.loading.style.display="none"),!0===this.config.startMuted&&this.videoElement&&(this.videoElement.muted=!0,this.videoElement.setAttribute("muted",""),this.setState({isMuted:!0}),this.updateVolumeUI()),this.config.autoplay&&(!0===this.config.startMuted&&this.videoElement&&(this.videoElement.muted=!0,this.videoElement.setAttribute("muted",""),this.setState({isMuted:!0}),this.updateVolumeUI()),this.play())}),t.on(ed.Events.ERROR,(t,e)=>{if(e.fatal){const t=`HLS Error: ${e.type} - ${e.details}`;this.showError(t),this.emit("error",new Error(t))}}),this.hls=t}else{if(!this.videoElement.canPlayType("application/vnd.apple.mpegurl"))throw new Error("HLS is not supported in this browser");this.videoElement.src=e,!0===this.config.startMuted&&(this.videoElement.muted=!0,this.videoElement.setAttribute("muted",""),this.setState({isMuted:!0}),this.updateVolumeUI()),this.setState({isLoading:!1}),this.elements.loading&&(this.elements.loading.style.display="none"),this.config.autoplay&&(!0===this.config.startMuted&&this.videoElement&&(this.videoElement.muted=!0,this.videoElement.setAttribute("muted",""),this.setState({isMuted:!0}),this.updateVolumeUI()),this.play())}else this.videoElement.src=e,!0===this.config.startMuted&&(this.videoElement.muted=!0,this.videoElement.setAttribute("muted",""),this.setState({isMuted:!0}),this.updateVolumeUI()),this.setState({isLoading:!1}),this.elements.loading&&(this.elements.loading.style.display="none"),this.config.autoplay&&(!0===this.config.startMuted&&this.videoElement&&(this.videoElement.muted=!0,this.videoElement.setAttribute("muted",""),this.setState({isMuted:!0}),this.updateVolumeUI()),this.play())}catch(t){const e=t instanceof Error?t.message:"Failed to load video";this.showError(e),this.setState({isLoading:!1}),this.emit("error",t instanceof Error?t:new Error(e))}}parseWebVTT(t){const e=[],i=t.split("\n");let s=0;for(;s<i.length;){const t=i[s].trim();if(t.includes("--\x3e")){const[r,n]=t.split("--\x3e").map(t=>t.trim()),a=t=>{const e=t.split(":");if(3===e.length){return 3600*parseFloat(e[0])+60*parseFloat(e[1])+parseFloat(e[2])}if(2===e.length){return 60*parseFloat(e[0])+parseFloat(e[1])}return 0},o=a(r),l=a(n);s++;const h=[];for(;s<i.length&&""!==i[s].trim();)h.push(i[s].trim()),s++;h.length>0&&e.push({start:o,end:l,text:h.join(" ")})}s++}return e}updateOverlayContent(t){const e=!1!==this.config.showLogo,i=!1!==this.config.showTitle,s=!1!==this.config.showAuthor,r=!1!==this.config.showDescription,n=!1!==this.config.showCaptions;if(this.elements.logo&&(this.elements.logo.style.display=e?"block":"none"),this.elements.videoTitle){const e=t.question||"",s=t.creator||"",r=s?`${e} - ${s}`:e;this.elements.videoTitle.textContent=r,this.elements.videoTitle.style.display=i&&e?"block":"none"}if(this.elements.videoAuthor){const e=t.author||t.creator||t.userName||"";this.elements.videoAuthor.textContent=e,this.elements.videoAuthor.style.display=s&&e?"block":"none"}if(this.elements.videoDescription){const e=t.creatorBiography||t.description||"";if(e){const t=150,i=e.length>t?e.substring(0,t)+"...":e;this.elements.videoDescription.innerHTML=`\n <span class="jaaq-description-text">${i}</span>\n ${e.length>t?'<span class="jaaq-read-more"> Read more</span>':""}\n `}this.elements.videoDescription.style.display=r&&e?"block":"none"}this.elements.captionsBtn&&(this.elements.captionsBtn.style.display=n?"flex":"none")}attachEventListeners(){this.videoElement&&(this.videoElement.addEventListener("play",()=>{this.setState({isPlaying:!0}),this.updatePlayPauseButton(),this.elements.centerPlayBtn&&(this.elements.centerPlayBtn.style.display="none"),this.emit("play",void 0)}),this.videoElement.addEventListener("pause",()=>{this.setState({isPlaying:!1}),this.updatePlayPauseButton(),this.elements.centerPlayBtn&&(this.elements.centerPlayBtn.style.display="flex"),this.emit("pause",void 0)}),this.videoElement.addEventListener("timeupdate",()=>{this.setState({currentTime:this.videoElement.currentTime}),this.updateProgress(),this.updateCaptions(),this.emit("timeupdate",this.videoElement.currentTime)}),this.videoElement.addEventListener("durationchange",()=>{this.setState({duration:this.videoElement.duration})}),this.videoElement.addEventListener("volumechange",()=>{this.setState({volume:this.videoElement.volume,isMuted:this.videoElement.muted}),this.updateVolumeUI(),this.emit("volumechange",this.videoElement.volume)}),this.videoElement.addEventListener("ended",()=>{this.emit("ended",void 0)}),this.elements.playPauseBtn?.addEventListener("click",()=>{this.togglePlayPause()}),this.elements.centerPlayBtn?.addEventListener("click",()=>{this.play(),this.elements.centerPlayBtn&&(this.elements.centerPlayBtn.style.display="none")}),this.elements.progressBar?.addEventListener("click",t=>{this.handleSeek(t)}),this.elements.volumeBtn?.addEventListener("click",()=>{this.toggleMute()}),this.elements.captionsBtn?.addEventListener("click",()=>{this.toggleCaptions()}),this.elements.fullscreenBtn?.addEventListener("click",()=>{this.toggleFullscreen()}),document.addEventListener("fullscreenchange",()=>{const t=!!document.fullscreenElement;this.setState({isFullscreen:t}),this.elements.player?.classList.toggle("fullscreen",t),this.emit("fullscreenchange",t)}),this.elements.player?.addEventListener("mousemove",()=>{this.elements.player?.classList.remove("is-paused")}),this.videoElement.addEventListener("pause",()=>{this.elements.player?.classList.add("is-paused")}),this.videoElement.addEventListener("play",()=>{this.elements.player?.classList.remove("is-paused")}))}setState(t){this.state={...this.state,...t}}updatePlayPauseButton(){this.elements.playPauseBtn&&(this.elements.playPauseBtn.textContent=this.state.isPlaying?"⏸":"▶",this.elements.playPauseBtn.setAttribute("aria-label",this.state.isPlaying?"Pause":"Play"))}updateProgress(){if(this.elements.progressFilled&&this.state.duration>0){const t=this.state.currentTime/this.state.duration*100;this.elements.progressFilled.style.width=`${t}%`}}updateVolumeUI(){if(this.elements.volumeBtn){const{isMuted:t,volume:e}=this.state;this.elements.volumeBtn.innerHTML=t||0===e?'\n <svg xmlns="http://www.w3.org/2000/svg" width="22" height="20" viewBox="0 0 22 20" fill="none">\n <path d="M11.2168 19.9287L4.20801 13.7031H0V6.22559H4.20898L11.2168 0V19.9287Z" fill="white"/>\n </svg>\n ':'\n <svg xmlns="http://www.w3.org/2000/svg" width="22" height="20" viewBox="0 0 22 20" fill="none">\n <path d="M11.2168 19.9287L4.20801 13.7031H0V6.22559H4.20898L11.2168 0V19.9287ZM14.0215 0.150391C16.2405 0.150468 18.1409 1.39074 19.4385 3.17676C20.7365 4.9634 21.499 7.36811 21.499 9.96484C21.499 12.5613 20.7363 14.9654 19.4385 16.752C18.1409 18.538 16.2405 19.7792 14.0215 19.7793V17.1025C15.2032 17.1025 16.3824 16.4464 17.3135 15.165C18.2442 13.8839 18.8593 12.0493 18.8594 9.96484C18.8594 7.88034 18.2442 6.04581 17.3135 4.76465C16.3824 3.4832 15.2033 2.82723 14.0215 2.82715V0.150391ZM14.0215 5.75879C15.5701 5.75896 16.8252 7.64189 16.8252 9.96484C16.8251 12.2877 15.57 14.1707 14.0215 14.1709V5.75879Z" fill="white"/>\n </svg>\n '}}updateCaptions(){if(!this.elements.captionDisplay||!this.state.captionsEnabled)return void(this.elements.captionDisplay&&(this.elements.captionDisplay.style.display="none"));const t=this.state.currentTime,e=this.captionCues.find(e=>t>=e.start&&t<=e.end);e?(this.elements.captionDisplay.textContent=e.text,this.elements.captionDisplay.style.display="block"):this.elements.captionDisplay.style.display="none"}handleSeek(t){if(!this.videoElement||!this.state.duration||!this.elements.progressBar)return;const e=this.elements.progressBar.getBoundingClientRect(),i=(t.clientX-e.left)/e.width;this.videoElement.currentTime=this.state.duration*od(i,0,1)}showError(t){this.setState({error:t,isLoading:!1}),this.elements.error&&(this.elements.error.textContent=t,this.elements.error.style.display="block"),this.elements.loading&&(this.elements.loading.style.display="none")}togglePlayPause(){this.state.isPlaying?this.pause():this.play()}toggleCaptions(){this.setState({captionsEnabled:!this.state.captionsEnabled}),this.updateCaptionsButton(),this.updateCaptions()}updateCaptionsButton(){this.elements.captionsBtn&&(this.state.captionsEnabled?this.elements.captionsBtn.classList.add("active"):this.elements.captionsBtn.classList.remove("active"))}toggleFullscreen(){var t;this.elements.player&&(t=this.elements.player,document.fullscreenElement?document.exitFullscreen():t.requestFullscreen())}play(){this.videoElement&&(!0!==this.config.startMuted||this.videoElement.muted||(this.videoElement.muted=!0,this.videoElement.setAttribute("muted",""),this.setState({isMuted:!0})),this.videoElement.play())}pause(){this.videoElement?.pause()}setVolume(t){this.videoElement&&(this.videoElement.volume=od(t,0,1),this.videoElement.muted=0===t)}toggleMute(){this.videoElement&&(this.videoElement.muted=!this.videoElement.muted)}seek(t){this.videoElement&&(this.videoElement.currentTime=od(t,0,this.state.duration))}setFeatures(t){this.config={...this.config,...t},void 0!==t.controls&&this.updateControlsVisibility(),void 0!==t.startMuted&&this.videoElement&&(this.videoElement.muted=!0===t.startMuted,!0===t.startMuted?this.videoElement.setAttribute("muted",""):this.videoElement.removeAttribute("muted"),this.setState({isMuted:!0===t.startMuted}),this.updateVolumeUI()),this.state.videoData?this.updateOverlayContent(this.state.videoData):(void 0!==t.showLogo&&this.elements.logo&&(this.elements.logo.style.display=t.showLogo?"block":"none"),void 0!==t.showCaptions&&this.elements.captionsBtn&&(this.elements.captionsBtn.style.display=t.showCaptions?"flex":"none"))}getState(){return{...this.state}}on(t,e){this.listeners.has(t)||this.listeners.set(t,new Set),this.listeners.get(t).add(e)}off(t,e){const i=this.listeners.get(t);i&&i.delete(e)}emit(t,e){const i=this.listeners.get(t);i&&i.forEach(t=>t(e))}destroy(){this.hls&&(this.hls.destroy(),this.hls=null),this.videoElement&&(this.videoElement.pause(),this.videoElement.src="",this.videoElement=null),this.listeners.clear(),this.container.innerHTML=""}}class dd extends HTMLElement{static get observedAttributes(){return["video-id","api-key","client-id","autoplay","base-url","width","height","controls","show-logo","show-title","show-author","show-description","show-captions","start-muted"]}constructor(){super(),this.player=null,this.container=null,this.clientInstance=null,this.connected=!1,this.attachShadow({mode:"open"})}connectedCallback(){this.connected=!0,this.render(),this.initPlayer()}disconnectedCallback(){this.connected=!1,this.destroyPlayer()}attributeChangedCallback(t,e,i){if(this.connected&&e!==i)if("video-id"===t&&this.player)this.destroyPlayer(),this.initPlayer();else if("width"===t||"height"===t)this.updateContainerStyles();else if(("controls"===t||"show-logo"===t||"show-title"===t||"show-author"===t||"show-description"===t||"show-captions"===t||"start-muted"===t)&&this.player){const e={};"controls"===t?e.controls=!this.hasAttribute("controls")||"false"!==this.getAttribute("controls"):"show-logo"===t?e.showLogo=!this.hasAttribute("show-logo")||"false"!==this.getAttribute("show-logo"):"show-title"===t?e.showTitle=!this.hasAttribute("show-title")||"false"!==this.getAttribute("show-title"):"show-author"===t?e.showAuthor=!this.hasAttribute("show-author")||"false"!==this.getAttribute("show-author"):"show-description"===t?e.showDescription=!this.hasAttribute("show-description")||"false"!==this.getAttribute("show-description"):"show-captions"===t?e.showCaptions=!this.hasAttribute("show-captions")||"false"!==this.getAttribute("show-captions"):"start-muted"===t&&(e.startMuted=this.hasAttribute("start-muted")&&"false"!==this.getAttribute("start-muted")),this.player.setFeatures(e)}}render(){if(!this.shadowRoot)return;const t=document.createElement("style");t.textContent=`\n ${ld}\n .jaaq-vanilla-player {\n user-select: none;\n}\n\n.jaaq-vanilla-player video {\n outline: none;\n}\n\n.jaaq-collection-player {\n width: 100%;\n max-width: 1400px;\n margin: 0 auto;\n font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, sans-serif;\n}\n\n.jaaq-collection-loading {\n display: flex;\n justify-content: center;\n align-items: center;\n min-height: 400px;\n}\n\n.jaaq-collection-spinner {\n width: 50px;\n height: 50px;\n border: 4px solid rgba(0, 123, 255, 0.3);\n border-top-color: #007bff;\n border-radius: 50%;\n animation: jaaq-collection-spin 1s linear infinite;\n}\n\n@keyframes jaaq-collection-spin {\n to {\n transform: rotate(360deg);\n }\n}\n\n.jaaq-collection-error {\n background: rgba(220, 53, 69, 0.9);\n color: white;\n padding: 16px 24px;\n border-radius: 8px;\n text-align: center;\n font-size: 14px;\n margin: 20px;\n}\n\n.jaaq-collection-carousel .splide__track {\n padding: 40px 0;\n}\n\n.jaaq-collection-carousel .splide__slide {\n opacity: 0.7;\n transition: all 0.3s ease;\n display: flex;\n align-items: center;\n justify-content: center;\n}\n\n.jaaq-collection-carousel .splide__slide.is-active {\n opacity: 1;\n}\n\n.jaaq-collection-carousel .splide__slide jaaq-video-player {\n width: 100%;\n max-width: 600px;\n transition: all 0.3s ease;\n}\n\n.jaaq-collection-carousel .splide__slide.is-active jaaq-video-player {\n max-width: 800px;\n}\n\n.jaaq-collection-carousel .splide__arrow {\n background: rgba(0, 0, 0, 0.5);\n border: none;\n width: 48px;\n height: 48px;\n border-radius: 50%;\n color: white;\n cursor: pointer;\n transition: all 0.2s;\n display: flex;\n align-items: center;\n justify-content: center;\n font-size: 20px;\n}\n\n.jaaq-collection-carousel .splide__arrow:hover {\n background: rgba(0, 0, 0, 0.8);\n transform: scale(1.1);\n}\n\n.jaaq-collection-carousel .splide__arrow:disabled {\n opacity: 0.3;\n cursor: not-allowed;\n}\n\n.jaaq-collection-carousel .splide__arrow svg {\n fill: white;\n width: 20px;\n height: 20px;\n}\n\n.jaaq-collection-carousel .splide__pagination {\n bottom: -30px;\n}\n\n.jaaq-collection-carousel .splide__pagination__page {\n background: #ccc;\n border: none;\n width: 10px;\n height: 10px;\n margin: 0 4px;\n border-radius: 50%;\n transition: all 0.2s;\n cursor: pointer;\n}\n\n.jaaq-collection-carousel .splide__pagination__page.is-active {\n background: #007bff;\n transform: scale(1.3);\n}\n\n@media (max-width: 1024px) {\n .jaaq-collection-carousel .splide__slide jaaq-video-player {\n max-width: 500px;\n }\n\n .jaaq-collection-carousel .splide__slide.is-active jaaq-video-player {\n max-width: 650px;\n }\n}\n\n@media (max-width: 768px) {\n .jaaq-collection-carousel .splide__track {\n padding: 20px 0;\n }\n\n .jaaq-collection-carousel .splide__slide jaaq-video-player {\n max-width: 400px;\n }\n\n .jaaq-collection-carousel .splide__slide.is-active jaaq-video-player {\n max-width: 500px;\n }\n\n .jaaq-collection-carousel .splide__arrow {\n width: 40px;\n height: 40px;\n }\n}\n\n@media (max-width: 480px) {\n .jaaq-collection-carousel .splide__slide jaaq-video-player {\n max-width: 100%;\n }\n\n .jaaq-collection-carousel .splide__slide.is-active jaaq-video-player {\n max-width: 100%;\n }\n}\n\n \n:host {\n display: block;\n width: 100%;\n}\n\n:host([hidden]) {\n display: none;\n}\n\n `,this.container=document.createElement("div"),this.container.className="jaaq-webcomponent-container",this.shadowRoot.appendChild(t),this.shadowRoot.appendChild(this.container),this.updateContainerStyles()}updateContainerStyles(){if(!this.container)return;const t=this.getAttribute("width")||"100%",e=this.getAttribute("height")||"auto";this.container.style.width=t,this.container.style.height=e}async initPlayer(){if(!this.container||this.player)return;const t=this.getAttribute("video-id");if(!t)return void this.emitError(new Error("video-id attribute is required"));const e=this.getAttribute("api-key"),i=this.getAttribute("client-id"),s=this.getAttribute("base-url")||void 0,r=this.getAttribute("api-version")||void 0,n=this.hasAttribute("autoplay")&&"false"!==this.getAttribute("autoplay"),a=!this.hasAttribute("controls")||"false"!==this.getAttribute("controls"),o=!this.hasAttribute("show-logo")||"false"!==this.getAttribute("show-logo"),l=!this.hasAttribute("show-title")||"false"!==this.getAttribute("show-title"),h=!this.hasAttribute("show-author")||"false"!==this.getAttribute("show-author"),d=!this.hasAttribute("show-description")||"false"!==this.getAttribute("show-description"),c=!this.hasAttribute("show-captions")||"false"!==this.getAttribute("show-captions"),u=this.hasAttribute("start-muted")&&"false"!==this.getAttribute("start-muted");if(this.clientInstance||e||i)try{this.player=new hd(this.container,{videoId:t??void 0,apiKey:e??void 0,clientId:i??void 0,client:this.clientInstance||void 0,baseUrl:s,apiVersion:r,autoplay:n,controls:a,showLogo:o,showTitle:l,showAuthor:h,showDescription:d,showCaptions:c,startMuted:u}),this.attachPlayerEvents()}catch(t){this.emitError(t instanceof Error?t:new Error("Failed to initialize player"))}else this.emitError(new Error("Either client property or api-key and client-id attributes are required"))}attachPlayerEvents(){this.player&&(this.player.on("loaded",t=>{this.dispatchEvent(new CustomEvent("jaaq:loaded",{detail:t,bubbles:!0,composed:!0}))}),this.player.on("play",()=>{this.dispatchEvent(new CustomEvent("jaaq:play",{bubbles:!0,composed:!0}))}),this.player.on("pause",()=>{this.dispatchEvent(new CustomEvent("jaaq:pause",{bubbles:!0,composed:!0}))}),this.player.on("timeupdate",t=>{this.dispatchEvent(new CustomEvent("jaaq:timeupdate",{detail:t,bubbles:!0,composed:!0}))}),this.player.on("volumechange",t=>{this.dispatchEvent(new CustomEvent("jaaq:volumechange",{detail:t,bubbles:!0,composed:!0}))}),this.player.on("ended",()=>{this.dispatchEvent(new CustomEvent("jaaq:ended",{bubbles:!0,composed:!0}))}),this.player.on("error",t=>{this.emitError(t)}),this.player.on("fullscreenchange",t=>{this.dispatchEvent(new CustomEvent("jaaq:fullscreenchange",{detail:t,bubbles:!0,composed:!0}))}))}emitError(t){this.dispatchEvent(new CustomEvent("jaaq:error",{detail:t,bubbles:!0,composed:!0}))}destroyPlayer(){this.player&&(this.player.destroy(),this.player=null)}get client(){return this.clientInstance}set client(t){this.clientInstance=t,this.connected&&(this.destroyPlayer(),this.initPlayer())}get videoId(){return this.getAttribute("video-id")}set videoId(t){t?this.setAttribute("video-id",t):this.removeAttribute("video-id")}play(){this.player?.play()}pause(){this.player?.pause()}setVolume(t){this.player?.setVolume(t)}toggleMute(){this.player?.toggleMute()}seek(t){this.player?.seek(t)}getState(){return this.player?.getState()||null}destroy(){this.destroyPlayer()}}function cd(t,e,i){return e&&function(t,e){for(var i=0;i<e.length;i++){var s=e[i];s.enumerable=s.enumerable||!1,s.configurable=!0,"value"in s&&(s.writable=!0),Object.defineProperty(t,s.key,s)}}(t.prototype,e),Object.defineProperty(t,"prototype",{writable:!1}),t}
1
+ !function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).JaaqWebComponents={})}(this,function(t){"use strict";const e=Number.isFinite||function(t){return"number"==typeof t&&isFinite(t)},i=Number.isSafeInteger||function(t){return"number"==typeof t&&Math.abs(t)<=s},s=Number.MAX_SAFE_INTEGER||9007199254740991;let r=function(t){return t.NETWORK_ERROR="networkError",t.MEDIA_ERROR="mediaError",t.KEY_SYSTEM_ERROR="keySystemError",t.MUX_ERROR="muxError",t.OTHER_ERROR="otherError",t}({}),n=function(t){return t.KEY_SYSTEM_NO_KEYS="keySystemNoKeys",t.KEY_SYSTEM_NO_ACCESS="keySystemNoAccess",t.KEY_SYSTEM_NO_SESSION="keySystemNoSession",t.KEY_SYSTEM_NO_CONFIGURED_LICENSE="keySystemNoConfiguredLicense",t.KEY_SYSTEM_LICENSE_REQUEST_FAILED="keySystemLicenseRequestFailed",t.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED="keySystemServerCertificateRequestFailed",t.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED="keySystemServerCertificateUpdateFailed",t.KEY_SYSTEM_SESSION_UPDATE_FAILED="keySystemSessionUpdateFailed",t.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED="keySystemStatusOutputRestricted",t.KEY_SYSTEM_STATUS_INTERNAL_ERROR="keySystemStatusInternalError",t.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR="keySystemDestroyMediaKeysError",t.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR="keySystemDestroyCloseSessionError",t.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR="keySystemDestroyRemoveSessionError",t.MANIFEST_LOAD_ERROR="manifestLoadError",t.MANIFEST_LOAD_TIMEOUT="manifestLoadTimeOut",t.MANIFEST_PARSING_ERROR="manifestParsingError",t.MANIFEST_INCOMPATIBLE_CODECS_ERROR="manifestIncompatibleCodecsError",t.LEVEL_EMPTY_ERROR="levelEmptyError",t.PLAYLIST_UNCHANGED_ERROR="playlistUnchangedError",t.LEVEL_LOAD_ERROR="levelLoadError",t.LEVEL_LOAD_TIMEOUT="levelLoadTimeOut",t.LEVEL_PARSING_ERROR="levelParsingError",t.LEVEL_SWITCH_ERROR="levelSwitchError",t.AUDIO_TRACK_LOAD_ERROR="audioTrackLoadError",t.AUDIO_TRACK_LOAD_TIMEOUT="audioTrackLoadTimeOut",t.SUBTITLE_LOAD_ERROR="subtitleTrackLoadError",t.SUBTITLE_TRACK_LOAD_TIMEOUT="subtitleTrackLoadTimeOut",t.FRAG_LOAD_ERROR="fragLoadError",t.FRAG_LOAD_TIMEOUT="fragLoadTimeOut",t.FRAG_DECRYPT_ERROR="fragDecryptError",t.FRAG_PARSING_ERROR="fragParsingError",t.FRAG_GAP="fragGap",t.REMUX_ALLOC_ERROR="remuxAllocError",t.KEY_LOAD_ERROR="keyLoadError",t.KEY_LOAD_TIMEOUT="keyLoadTimeOut",t.BUFFER_ADD_CODEC_ERROR="bufferAddCodecError",t.BUFFER_INCOMPATIBLE_CODECS_ERROR="bufferIncompatibleCodecsError",t.BUFFER_APPEND_ERROR="bufferAppendError",t.BUFFER_APPENDING_ERROR="bufferAppendingError",t.BUFFER_APPEND_NO_PROGRESS="bufferAppendNoProgress",t.BUFFER_STALLED_ERROR="bufferStalledError",t.BUFFER_FULL_ERROR="bufferFullError",t.BUFFER_SEEK_OVER_HOLE="bufferSeekOverHole",t.BUFFER_NUDGE_ON_STALL="bufferNudgeOnStall",t.ASSET_LIST_LOAD_ERROR="assetListLoadError",t.ASSET_LIST_LOAD_TIMEOUT="assetListLoadTimeout",t.ASSET_LIST_PARSING_ERROR="assetListParsingError",t.INTERSTITIAL_ASSET_ITEM_ERROR="interstitialAssetItemError",t.INTERNAL_EXCEPTION="internalException",t.INTERNAL_ABORTED="aborted",t.ATTACH_MEDIA_ERROR="attachMediaError",t.MEDIA_SOURCE_REQUIRES_RESET="mediaSourceRequiresReset",t.UNKNOWN="unknown",t}({}),a=function(t){return t.MEDIA_ATTACHING="hlsMediaAttaching",t.MEDIA_ATTACHED="hlsMediaAttached",t.MEDIA_DETACHING="hlsMediaDetaching",t.MEDIA_DETACHED="hlsMediaDetached",t.MEDIA_ENDED="hlsMediaEnded",t.STALL_RESOLVED="hlsStallResolved",t.BUFFER_RESET="hlsBufferReset",t.BUFFER_CODECS="hlsBufferCodecs",t.BUFFER_CREATED="hlsBufferCreated",t.BUFFER_APPENDING="hlsBufferAppending",t.BUFFER_APPENDED="hlsBufferAppended",t.BUFFER_EOS="hlsBufferEos",t.BUFFERED_TO_END="hlsBufferedToEnd",t.BUFFER_FLUSHING="hlsBufferFlushing",t.BUFFER_FLUSHED="hlsBufferFlushed",t.MANIFEST_LOADING="hlsManifestLoading",t.MANIFEST_LOADED="hlsManifestLoaded",t.MANIFEST_PARSED="hlsManifestParsed",t.LEVEL_SWITCHING="hlsLevelSwitching",t.LEVEL_SWITCHED="hlsLevelSwitched",t.LEVEL_LOADING="hlsLevelLoading",t.LEVEL_LOADED="hlsLevelLoaded",t.LEVEL_UPDATED="hlsLevelUpdated",t.LEVEL_PTS_UPDATED="hlsLevelPtsUpdated",t.LEVELS_UPDATED="hlsLevelsUpdated",t.AUDIO_TRACKS_UPDATED="hlsAudioTracksUpdated",t.AUDIO_TRACK_SWITCHING="hlsAudioTrackSwitching",t.AUDIO_TRACK_SWITCHED="hlsAudioTrackSwitched",t.AUDIO_TRACK_LOADING="hlsAudioTrackLoading",t.AUDIO_TRACK_LOADED="hlsAudioTrackLoaded",t.AUDIO_TRACK_UPDATED="hlsAudioTrackUpdated",t.SUBTITLE_TRACKS_UPDATED="hlsSubtitleTracksUpdated",t.SUBTITLE_TRACKS_CLEARED="hlsSubtitleTracksCleared",t.SUBTITLE_TRACK_SWITCH="hlsSubtitleTrackSwitch",t.SUBTITLE_TRACK_LOADING="hlsSubtitleTrackLoading",t.SUBTITLE_TRACK_LOADED="hlsSubtitleTrackLoaded",t.SUBTITLE_TRACK_UPDATED="hlsSubtitleTrackUpdated",t.SUBTITLE_FRAG_PROCESSED="hlsSubtitleFragProcessed",t.CUES_PARSED="hlsCuesParsed",t.NON_NATIVE_TEXT_TRACKS_FOUND="hlsNonNativeTextTracksFound",t.INIT_PTS_FOUND="hlsInitPtsFound",t.FRAG_LOADING="hlsFragLoading",t.FRAG_LOAD_EMERGENCY_ABORTED="hlsFragLoadEmergencyAborted",t.FRAG_LOADED="hlsFragLoaded",t.FRAG_DECRYPTED="hlsFragDecrypted",t.FRAG_PARSING_INIT_SEGMENT="hlsFragParsingInitSegment",t.FRAG_PARSING_USERDATA="hlsFragParsingUserdata",t.FRAG_PARSING_METADATA="hlsFragParsingMetadata",t.FRAG_PARSED="hlsFragParsed",t.FRAG_BUFFERED="hlsFragBuffered",t.FRAG_CHANGED="hlsFragChanged",t.FPS_DROP="hlsFpsDrop",t.FPS_DROP_LEVEL_CAPPING="hlsFpsDropLevelCapping",t.MAX_AUTO_LEVEL_UPDATED="hlsMaxAutoLevelUpdated",t.ERROR="hlsError",t.DESTROYING="hlsDestroying",t.KEY_LOADING="hlsKeyLoading",t.KEY_LOADED="hlsKeyLoaded",t.LIVE_BACK_BUFFER_REACHED="hlsLiveBackBufferReached",t.BACK_BUFFER_REACHED="hlsBackBufferReached",t.STEERING_MANIFEST_LOADED="hlsSteeringManifestLoaded",t.ASSET_LIST_LOADING="hlsAssetListLoading",t.ASSET_LIST_LOADED="hlsAssetListLoaded",t.INTERSTITIALS_UPDATED="hlsInterstitialsUpdated",t.INTERSTITIALS_BUFFERED_TO_BOUNDARY="hlsInterstitialsBufferedToBoundary",t.INTERSTITIAL_ASSET_PLAYER_CREATED="hlsInterstitialAssetPlayerCreated",t.INTERSTITIAL_STARTED="hlsInterstitialStarted",t.INTERSTITIAL_ASSET_STARTED="hlsInterstitialAssetStarted",t.INTERSTITIAL_ASSET_ENDED="hlsInterstitialAssetEnded",t.INTERSTITIAL_ASSET_ERROR="hlsInterstitialAssetError",t.INTERSTITIAL_ENDED="hlsInterstitialEnded",t.INTERSTITIALS_PRIMARY_RESUMED="hlsInterstitialsPrimaryResumed",t.PLAYOUT_LIMIT_REACHED="hlsPlayoutLimitReached",t.EVENT_CUE_ENTER="hlsEventCueEnter",t}({});function o(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var l,h={exports:{}};var d=(l||(l=1,function(t){var e,i,s,r,n;e=/^(?=((?:[a-zA-Z0-9+\-.]+:)?))\1(?=((?:\/\/[^\/?#]*)?))\2(?=((?:(?:[^?#\/]*\/)*[^;?#\/]*)?))\3((?:;[^?#]*)?)(\?[^#]*)?(#[^]*)?$/,i=/^(?=([^\/?#]*))\1([^]*)$/,s=/(?:\/|^)\.(?=\/)/g,r=/(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g,n={buildAbsoluteURL:function(t,e,s){if(s=s||{},t=t.trim(),!(e=e.trim())){if(!s.alwaysNormalize)return t;var r=n.parseURL(t);if(!r)throw new Error("Error trying to parse base URL.");return r.path=n.normalizePath(r.path),n.buildURLFromParts(r)}var a=n.parseURL(e);if(!a)throw new Error("Error trying to parse relative URL.");if(a.scheme)return s.alwaysNormalize?(a.path=n.normalizePath(a.path),n.buildURLFromParts(a)):e;var o=n.parseURL(t);if(!o)throw new Error("Error trying to parse base URL.");if(!o.netLoc&&o.path&&"/"!==o.path[0]){var l=i.exec(o.path);o.netLoc=l[1],o.path=l[2]}o.netLoc&&!o.path&&(o.path="/");var h={scheme:o.scheme,netLoc:a.netLoc,path:null,params:a.params,query:a.query,fragment:a.fragment};if(!a.netLoc&&(h.netLoc=o.netLoc,"/"!==a.path[0]))if(a.path){var d=o.path,c=d.substring(0,d.lastIndexOf("/")+1)+a.path;h.path=n.normalizePath(c)}else h.path=o.path,a.params||(h.params=o.params,a.query||(h.query=o.query));return null===h.path&&(h.path=s.alwaysNormalize?n.normalizePath(a.path):a.path),n.buildURLFromParts(h)},parseURL:function(t){var i=e.exec(t);return i?{scheme:i[1]||"",netLoc:i[2]||"",path:i[3]||"",params:i[4]||"",query:i[5]||"",fragment:i[6]||""}:null},normalizePath:function(t){for(t=t.split("").reverse().join("").replace(s,"");t.length!==(t=t.replace(r,"")).length;);return t.split("").reverse().join("")},buildURLFromParts:function(t){return t.scheme+t.netLoc+t.path+t.params+t.query+t.fragment}},t.exports=n}(h)),h.exports);class c{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}}}let u=function(t){return t.MANIFEST="manifest",t.LEVEL="level",t.AUDIO_TRACK="audioTrack",t.SUBTITLE_TRACK="subtitleTrack",t.MEDIA_FRAGMENT="media-fragment",t.KEY="key",t.STEERING_MANIFEST="steering-manifest",t.SERVER_CERTIFICATE="server-certificate",t.INTERSTITIAL_ASSET_LIST="interstitial-asset-list",t}({}),f=function(t){return t.MAIN="main",t.AUDIO="audio",t.SUBTITLE="subtitle",t}({});var g="audio",m="video",p="audiovideo";class v{constructor(t){this._byteRange=null,this._url=null,this._stats=null,this._streams=null,this.base=void 0,this.relurl=void 0,"string"==typeof t&&(t={url:t}),this.base=t,function(t,e){const i=A(t,e);i&&(i.enumerable=!0,Object.defineProperty(t,e,i))}(this,"stats")}setByteRange(t,e){const i=t.split("@",2);let s;s=1===i.length?(null==e?void 0:e.byteRangeEndOffset)||0:parseInt(i[1]),this._byteRange=[s,parseInt(i[0])+s]}get baseurl(){return this.base.url}get byteRange(){return null===this._byteRange?[]:this._byteRange}get byteRangeStartOffset(){return this.byteRange[0]}get byteRangeEndOffset(){return this.byteRange[1]}get elementaryStreams(){return null===this._streams&&(this._streams={[g]:null,[m]:null,[p]:null}),this._streams}set elementaryStreams(t){this._streams=t}get hasStats(){return null!==this._stats}get hasStreams(){return null!==this._streams}get stats(){return null===this._stats&&(this._stats=new c),this._stats}set stats(t){this._stats=t}get url(){return!this._url&&this.relurl&&(this._url=d.buildAbsoluteURL(this.baseurl,this.relurl,{alwaysNormalize:!0})),this._url||""}set url(t){this._url=t}clearElementaryStreamInfo(){const{elementaryStreams:t}=this;t[g]=null,t[m]=null,t[p]=null,this.url=null}}function y(t){return"initSegment"!==t.sn}function E(t,e){return t.sn===(null==e?void 0:e.sn)&&t.level===e.level}function T(t,e){return t.sn===(null==e?void 0:e.sn)&&t.level===e.level&&t.cc===e.cc}class S extends v{constructor(t,e){super(e),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=t}get byteLength(){if(this.hasStats){const t=this.stats.total;if(t)return t}if(this.byteRange.length){const t=this.byteRange[0],i=this.byteRange[1];if(e(t)&&e(i))return i-t}return null}get bitrate(){return this.byteLength?8*this.byteLength/this.duration:this._bitrate?this._bitrate:null}set bitrate(t){this._bitrate=t}get decryptdata(){var t;const{levelkeys:e}=this;if(!e||e.NONE)return null;if(e.identity)this._decryptdata||(this._decryptdata=e.identity.getDecryptData(this.sn));else if(null==(t=this._decryptdata)||!t.keyId){const t=Object.keys(e);if(1===t.length){const i=this._decryptdata=e[t[0]]||null;i&&(this._decryptdata=i.getDecryptData(this.sn,e))}}return this._decryptdata}get end(){return this.start+this.duration}get endProgramDateTime(){if(null===this.programDateTime)return null;const t=e(this.duration)?this.duration:0;return this.programDateTime+1e3*t}get encrypted(){var t;if(null!=(t=this._decryptdata)&&t.encrypted)return!0;if(this.levelkeys){var e;const t=Object.keys(this.levelkeys),i=t.length;if(i>1||1===i&&null!=(e=this.levelkeys[t[0]])&&e.encrypted)return!0}return!1}get programDateTime(){return null===this._programDateTime&&this.rawProgramDateTime&&(this.programDateTime=Date.parse(this.rawProgramDateTime)),this._programDateTime}set programDateTime(t){e(t)?this._programDateTime=t:this._programDateTime=this.rawProgramDateTime=null}get ref(){return y(this)?(this._ref||(this._ref={base:this.base,start:this.start,duration:this.duration,sn:this.sn,programDateTime:this.programDateTime}),this._ref):null}addStart(t){this.setStart(this.start+t)}setStart(t){this.start=t,this._ref&&(this._ref.start=t)}setDuration(t){this.duration=t,this._ref&&(this._ref.duration=t)}setKeyFormat(t){const e=this.levelkeys;if(e){var i;const s=e[t];!s||null!=(i=this._decryptdata)&&i.keyId||(this._decryptdata=s.getDecryptData(this.sn,e))}}abortRequests(){var t,e;null==(t=this.loader)||t.abort(),null==(e=this.keyLoader)||e.abort()}setElementaryStreamInfo(t,e,i,s,r,n=!1){const{elementaryStreams:a}=this,o=a[t];o?(o.startPTS=Math.min(o.startPTS,e),o.endPTS=Math.max(o.endPTS,i),o.startDTS=Math.min(o.startDTS,s),o.endDTS=Math.max(o.endDTS,r)):a[t]={startPTS:e,endPTS:i,startDTS:s,endDTS:r,partial:n}}}class b extends v{constructor(t,e,i,s,r){super(i),this.fragOffset=0,this.duration=0,this.independent=!1,this.relurl=void 0,this.fragment=void 0,this.index=void 0,this.gap=!1,this.duration=t.decimalFloatingPoint("DURATION"),this.gap=t.bool("GAP"),this.independent=t.bool("INDEPENDENT"),this.relurl=t.enumeratedString("URI"),this.fragment=e,this.index=s;const n=t.enumeratedString("BYTERANGE");n&&this.setByteRange(n,r),r&&(this.fragOffset=r.fragOffset+r.duration)}get start(){return this.fragment.start+this.fragOffset}get end(){return this.start+this.duration}get loaded(){const{elementaryStreams:t}=this;return!!(t.audio||t.video||t.audiovideo||this.fragment.type===f.SUBTITLE&&this.stats.loading.end>0)}}function A(t,e){const i=Object.getPrototypeOf(t);if(i){const t=Object.getOwnPropertyDescriptor(i,e);return t||A(i,e)}}function L(t,e,i){return(e=function(t){var e=function(t,e){if("object"!=typeof t||!t)return t;var i=t[Symbol.toPrimitive];if(void 0!==i){var s=i.call(t,e);if("object"!=typeof s)return s;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:e+""}(e))in t?Object.defineProperty(t,e,{value:i,enumerable:!0,configurable:!0,writable:!0}):t[e]=i,t}function I(){return I=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var i=arguments[e];for(var s in i)({}).hasOwnProperty.call(i,s)&&(t[s]=i[s])}return t},I.apply(null,arguments)}function R(t,e){var i=Object.keys(t);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(t);e&&(s=s.filter(function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable})),i.push.apply(i,s)}return i}function k(t){for(var e=1;e<arguments.length;e++){var i=null!=arguments[e]?arguments[e]:{};e%2?R(Object(i),!0).forEach(function(e){L(t,e,i[e])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(i)):R(Object(i)).forEach(function(e){Object.defineProperty(t,e,Object.getOwnPropertyDescriptor(i,e))})}return t}function _(t,e){if(null==t)return{};var i,s,r=function(t,e){if(null==t)return{};var i={};for(var s in t)if({}.hasOwnProperty.call(t,s)){if(-1!==e.indexOf(s))continue;i[s]=t[s]}return i}(t,e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(t);for(s=0;s<n.length;s++)i=n[s],-1===e.indexOf(i)&&{}.propertyIsEnumerable.call(t,i)&&(r[i]=t[i])}return r}function D(t){switch(t.details){case n.FRAG_LOAD_TIMEOUT:case n.KEY_LOAD_TIMEOUT:case n.LEVEL_LOAD_TIMEOUT:case n.MANIFEST_LOAD_TIMEOUT:case n.AUDIO_TRACK_LOAD_TIMEOUT:case n.SUBTITLE_TRACK_LOAD_TIMEOUT:case n.ASSET_LIST_LOAD_TIMEOUT:return!0}return!1}function w(t){return t.details.startsWith("key")}function P(t){return w(t)&&!!t.frag&&!t.frag.decryptdata}function C(t,e){const i=D(e);return t.default[(i?"timeout":"error")+"Retry"]}function x(t,e){const i="linear"===t.backoff?1:Math.pow(2,e);return Math.min(i*t.retryDelayMs,t.maxRetryDelayMs)}function M(t){return k(k({},t),{errorRetry:null,timeoutRetry:null})}function O(t,e,i,s){if(!t)return!1;const r=null==s?void 0:s.code,n=e<t.maxNumRetry&&(function(t){return F(t)||!!t&&(t<400||t>499)}(r)||!!i);return t.shouldRetry?t.shouldRetry(t,e,i,s,n):n}function F(t){return 0===t&&!1===navigator.onLine}function N(t,e){return e>0&&t.loadError>0&&0!==t.loadErrorTime&&self.performance.now()-t.loadErrorTime>e}class ${constructor(t,e=0,i=0){this.halfLife=void 0,this.alpha_=void 0,this.estimate_=void 0,this.totalWeight_=void 0,this.halfLife=t,this.alpha_=t?Math.exp(Math.log(.5)/t):0,this.estimate_=e,this.totalWeight_=i}sample(t,e){const i=Math.pow(this.alpha_,t);this.estimate_=e*(1-i)+i*this.estimate_,this.totalWeight_+=t}getTotalWeight(){return this.totalWeight_}getEstimate(){if(this.alpha_){const t=1-Math.pow(this.alpha_,this.totalWeight_);if(t)return this.estimate_/t}return this.estimate_}}class B{constructor(t,e,i,s=100){this.defaultEstimate_=void 0,this.minWeight_=void 0,this.minDelayMs_=void 0,this.slow_=void 0,this.fast_=void 0,this.defaultTTFB_=void 0,this.ttfb_=void 0,this.defaultEstimate_=i,this.minWeight_=.001,this.minDelayMs_=50,this.slow_=new $(t),this.fast_=new $(e),this.defaultTTFB_=s,this.ttfb_=new $(t)}update(t,e){const{slow_:i,fast_:s,ttfb_:r}=this;i.halfLife!==t&&(this.slow_=new $(t,i.getEstimate(),i.getTotalWeight())),s.halfLife!==e&&(this.fast_=new $(e,s.getEstimate(),s.getTotalWeight())),r.halfLife!==t&&(this.ttfb_=new $(t,r.getEstimate(),r.getTotalWeight()))}sample(t,e){if(e<=0)return;const i=Math.min(this.minDelayMs_,e/1e5),s=8*e,r=Math.max(t,i)/1e3,n=s/r;this.fast_.sample(r,n),this.slow_.sample(r,n)}sampleTTFB(t){const e=t/1e3,i=Math.sqrt(2)*Math.exp(-Math.pow(e,2)/2);this.ttfb_.sample(i,Math.max(t,5))}canEstimate(){return this.fast_.getTotalWeight()>=this.minWeight_}getEstimate(){return this.canEstimate()?Math.min(this.fast_.getEstimate(),this.slow_.getEstimate()):this.defaultEstimate_}getEstimateTTFB(){return this.ttfb_.getTotalWeight()>=this.minWeight_?this.ttfb_.getEstimate():this.defaultTTFB_}get defaultEstimate(){return this.defaultEstimate_}destroy(){}}class U{constructor(t,e){this.trace=void 0,this.debug=void 0,this.log=void 0,this.warn=void 0,this.info=void 0,this.error=void 0;const i=`[${t}]:`;this.trace=G,this.debug=e.debug.bind(null,i),this.log=e.log.bind(null,i),this.warn=e.warn.bind(null,i),this.info=e.info.bind(null,i),this.error=e.error.bind(null,i)}}const G=function(){},K={trace:G,debug:G,log:G,warn:G,info:G,error:G};function V(){return I({},K)}function j(t,e,i){return e[t]?e[t].bind(e):function(t,e){const i=self.console[t];return i?i.bind(self.console,`${e?"["+e+"] ":""}[${t}] >`):G}(t,i)}const H=V();const q=H;function Y(t=!0){if("undefined"==typeof self)return;return(t||!self.MediaSource)&&self.ManagedMediaSource||self.MediaSource||self.WebKitMediaSource}function W(t,e){const i=Object.keys(t),s=Object.keys(e),r=i.length,n=s.length;return!r||!n||r===n&&!i.some(t=>-1===s.indexOf(t))}function z(t){return t instanceof ArrayBuffer||"undefined"!=typeof SharedArrayBuffer&&t instanceof SharedArrayBuffer}const X="utf-16be",Q="utf-16le",Z="utf-8";function J(t,e){if(t<0)return-J(-t,e);const i=Math.pow(10,e);if(Math.abs(t*i%1-.5)<Number.EPSILON){const e=Math.floor(t*i);return(e%2==0?e:e+1)/i}return Math.round(t*i)/i}function tt(){try{return crypto.randomUUID()}catch(t){try{const t=URL.createObjectURL(new Blob),e=t.toString();return URL.revokeObjectURL(t),e.slice(e.lastIndexOf("/")+1)}catch(t){let e=(new Date).getTime();return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,t=>{const i=(e+16*Math.random())%16|0;return e=Math.floor(e/16),("x"==t?i:3&i|8).toString(16)})}}}function et(t,e){return e+10<=t.length&&73===t[e]&&68===t[e+1]&&51===t[e+2]&&t[e+3]<255&&t[e+4]<255&&t[e+6]<128&&t[e+7]<128&&t[e+8]<128&&t[e+9]<128}function it(t,e){let i=0;return i=(127&t[e])<<21,i|=(127&t[e+1])<<14,i|=(127&t[e+2])<<7,i|=127&t[e+3],i}function st(t,e){return et(t,e)&&it(t,e+6)+10<=t.length-e}function rt(t,e){return e+10<=t.length&&51===t[e]&&68===t[e+1]&&73===t[e+2]&&t[e+3]<255&&t[e+4]<255&&t[e+6]<128&&t[e+7]<128&&t[e+8]<128&&t[e+9]<128}function nt(t,e){const i=e;let s=0;for(;et(t,e);){s+=10;s+=it(t,e+6),rt(t,e+10)&&(s+=10),e+=s}if(s>0)return t.subarray(i,i+s)}function at(t,e=0,i=1/0){return function(t,e,i,s){const r=(n=t,z(n)?n:n.buffer);var n;let a=1;"BYTES_PER_ELEMENT"in s&&(a=s.BYTES_PER_ELEMENT);const o=(c=t,c&&z(c.buffer)&&void 0!==c.byteLength&&void 0!==c.byteOffset?t.byteOffset:0),l=(o+t.byteLength)/a,h=(o+e)/a,d=Math.floor(Math.max(0,Math.min(h,l)));var c;return new s(r,d,Math.floor(Math.min(d+Math.max(i,0),l))-d)}(t,e,i,Uint8Array)}function ot(t,e=!1){const i=e?t.indexOf(0):t.length,s=function(t,e={}){let i;i=z(t)?new DataView(t):new DataView(t.buffer,t.byteOffset,t.byteLength);let s=0,{encoding:r}=e;if(!r){const t=i.getUint8(0),e=i.getUint8(1);239==t&&187==e&&191==i.getUint8(2)?(r=Z,s=3):254==t&&255==e?(r=X,s=2):255==t&&254==e?(r=Q,s=2):r=Z}if("undefined"!=typeof TextDecoder)return new TextDecoder(r).decode(i);const{byteLength:n}=i,a=r!==X;let o,l="";for(;s<n;){switch(r){case Z:if(o=i.getUint8(s),o<128)s++;else if(o>=194&&o<=223)if(s+1<n){const t=i.getUint8(s+1);t>=128&&t<=191?(o=(31&o)<<6|63&t,s+=2):s++}else s++;else if(o>=224&&o<=239)if(s+2<=n-1){const t=i.getUint8(s+1),e=i.getUint8(s+2);t>=128&&t<=191&&e>=128&&e<=191?(o=(15&o)<<12|(63&t)<<6|63&e,s+=3):s++}else s++;else if(o>=240&&o<=244)if(s+3<=n-1){const t=i.getUint8(s+1),e=i.getUint8(s+2),r=i.getUint8(s+3);t>=128&&t<=191&&e>=128&&e<=191&&r>=128&&r<=191?(o=(7&o)<<18|(63&t)<<12|(63&e)<<6|63&r,s+=4):s++}else s++;else s++;break;case X:case"utf-16":case Q:o=i.getUint16(s,a),s+=2}l+=String.fromCodePoint(o)}return l}(new DataView(t.buffer,t.byteOffset,i),{encoding:Z});return e?s:s.replace(/\0/g,"")}function lt(t){const e={key:t.type,description:"",data:"",mimeType:null,pictureType:null};if(t.size<2)return;if(3!==t.data[0])return void console.log("Ignore frame with unrecognized character encoding");const i=t.data.subarray(1).indexOf(0);if(-1===i)return;const s=ot(at(t.data,1,i)),r=t.data[2+i],n=t.data.subarray(3+i).indexOf(0);if(-1===n)return;const a=ot(at(t.data,3+i,n));let o;var l;return"--\x3e"===s?o=ot(at(t.data,4+i+n)):o=z(l=t.data.subarray(4+i+n))?l:0==l.byteOffset&&l.byteLength==l.buffer.byteLength?l.buffer:new Uint8Array(l).buffer,e.mimeType=s,e.pictureType=r,e.description=a,e.data=o,e}function ht(t){return"PRIV"===t.type?function(t){if(t.size<2)return;const e=ot(t.data,!0),i=new Uint8Array(t.data.subarray(e.length+1));return{key:t.type,info:e,data:i.buffer}}(t):"W"===t.type[0]?function(t){if("WXXX"===t.type){if(t.size<2)return;let e=1;const i=ot(t.data.subarray(e),!0);e+=i.length+1;const s=ot(t.data.subarray(e));return{key:t.type,info:i,data:s}}const e=ot(t.data);return{key:t.type,info:"",data:e}}(t):"APIC"===t.type?lt(t):function(t){if(t.size<2)return;if("TXXX"===t.type){let e=1;const{data:i}=t,s=ot(i.subarray(e),!0);e+=s.length+1;const r=ot(i.subarray(e));return{key:t.type,info:s,data:r}}const e=ot(t.data.subarray(1));return{key:t.type,info:"",data:e}}(t)}function dt(t){const e=String.fromCharCode(t[0],t[1],t[2],t[3]),i=it(t,4);return{type:e,size:i,data:t.subarray(10,10+i)}}function ct(t){let e=0;const i=[];for(;et(t,e);){const s=it(t,e+6);t[e+5]>>6&1&&(e+=10),e+=10;const r=e+s;for(;e+10<r;){const s=dt(t.subarray(e)),r=ht(s);r&&i.push(r),e+=s.size+10}rt(t,e)&&(e+=10)}return i}function ut(t){return t&&"PRIV"===t.key&&"com.apple.streaming.transportStreamTimestamp"===t.info}function ft(t){if(8===t.data.byteLength){const e=new Uint8Array(t.data),i=1&e[3];let s=(e[4]<<23)+(e[5]<<15)+(e[6]<<7)+e[7];return s/=45,i&&(s+=47721858.84),Math.round(s)}}function gt(t){const e=ct(t);for(const t of e)if(ut(t))return ft(t)}function mt(t){let e="";for(let i=0;i<t.length;i++){let s=t[i].toString(16);s.length<2&&(s="0"+s),e+=s}return e}function pt(t){return Uint8Array.from(t.replace(/^0x/,"").replace(/([\da-fA-F]{2}) ?/g,"0x$1 ").replace(/ +$/,"").split(" ")).buffer}function vt(t){return Uint8Array.from(atob(t),t=>t.charCodeAt(0))}function yt(t){return String.fromCharCode.apply(null,t)}const Et=Math.pow(2,32)-1,Tt={avc1:1635148593,avcC:1635148611,hvc1:1752589105,hvcC:1752589123,btrt:1651798644,dinf:1684631142,dref:1685218662,esds:1702061171,free:1718773093,ftyp:1718909296,hdlr:1751411826,mdat:1835295092,mdhd:1835296868,mdia:1835297121,mfhd:1835427940,minf:1835626086,moof:1836019558,moov:1836019574,mp4a:1836069985,".mp3":778924083,dac3:1684103987,"ac-3":1633889587,mvex:1836475768,mvhd:1836476516,pasp:1885434736,sdtp:1935963248,stbl:1937007212,stco:1937007471,stsc:1937011555,stsd:1937011556,stsz:1937011578,stts:1937011827,tfdt:1952867444,tfhd:1952868452,traf:1953653094,trak:1953653099,trun:1953658222,trex:1953654136,tkhd:1953196132,vmhd:1986881636,smhd:1936549988},St={video:1,audio:2,id3:3,text:4};function bt(t,e){const i=t[e]<<8|t[e+1];return i<0?65536+i:i}function At(t,e){const i=t[e]<<24|t[e+1]<<16|t[e+2]<<8|t[e+3];return i<0?4294967296+i:i}function Lt(t,e){let i=At(t,e);return i*=Math.pow(2,32),i+=At(t,e+4),i}function It(t,e){let i="";for(let s=e;s<t.length;s++)if(i+=String.fromCharCode(t[s]),0===t[s])return i;return null}function Rt(t,e){return t[e]<<24|t[e+1]<<16|t[e+2]<<8|t[e+3]}function kt(t,e,i){t[e]=i>>24,t[e+1]=i>>16&255,t[e+2]=i>>8&255,t[e+3]=255&i}function _t(t,e,i){const s=e.byteOffset-t.byteOffset-8,r=8+i,n=e.byteLength+8-r;n<8||(kt(t,s,r),kt(t,s+r,n),kt(t,s+r+4,Tt.free))}function Dt(t,e){return[t.byteOffset-e-8,t.byteOffset-e+t.byteLength]}function wt(t,e){e.sort((t,e)=>t[0]-e[0]);const i=e.reduce((t,[e,i])=>t+i-e,0),s=new Uint8Array(t.byteLength-i);let r=0,n=0;for(let i=0;i<e.length;i++){const[a,o]=e[i];s.set(t.subarray(r,a),n),n+=a-r,r=o}s.set(t.subarray(r),n);return{result:s,dropped:i,droppedBefore:t=>e.reduce((e,[i,s])=>s<=t?e+s-i:e,0)}}function Pt(t,e){const i=[];return e.length?(Ct(t,e,0,0,t.byteLength,i),i):i}function Ct(t,e,i,s,r,n){const a=e[i];if(4!==(null==a?void 0:a.length))return;const o=a.charCodeAt(0),l=a.charCodeAt(1),h=a.charCodeAt(2),d=a.charCodeAt(3),c=e.length-1;for(let a=s;a<r;){const s=a+8<=r,u=a+4<=r?16777216*t[a]+(t[a+1]<<16|t[a+2]<<8|t[a+3]):At(t,a),f=u>1?a+u:r;if(s&&t[a+4]===o&&t[a+5]===l&&t[a+6]===h&&t[a+7]===d){const s=Math.min(f,r);i===c?n.push(t.subarray(a+8,s)):Ct(t,e,i+1,a+8,s,n)}a=f}}function xt(t){const e=[],i=t[0];let s=8;const r=At(t,s);s+=4;let n=0,a=0;0===i?(n=At(t,s),a=At(t,s+4),s+=8):(n=Lt(t,s),a=Lt(t,s+8),s+=16),s+=2;let o=t.length+a;const l=bt(t,s);s+=2;for(let i=0;i<l;i++){let i=s;const n=At(t,i);i+=4;const a=2147483647&n;if(1===(2147483648&n)>>>31)return q.warn("SIDX has hierarchical references (not supported)"),null;const l=At(t,i);i+=4,e.push({referenceSize:a,subsegmentDuration:l,info:{duration:l/r,start:o,end:o+a-1}}),o+=a,i+=4,s=i}return{earliestPresentationTime:n,timescale:r,version:i,referencesCount:l,references:e}}function Mt(t){const e=[],i=Pt(t,["moov","trak"]);for(let t=0;t<i.length;t++){const s=i[t],r=Pt(s,["tkhd"])[0];if(r){let t=r[0];const i=At(r,0===t?12:20),n=Pt(s,["mdia","mdhd"])[0];if(n){t=n[0];const r=At(n,0===t?12:20),a=Pt(s,["mdia","hdlr"])[0];if(a){const t=yt(a.subarray(8,12)),n={soun:g,vide:m}[t],o=Ot(Pt(s,["mdia","minf","stbl","stsd"])[0]);n?(e[i]={timescale:r,type:n,stsd:o},e[n]=k({timescale:r,id:i},o)):e[i]={timescale:r,type:t,stsd:o}}}}}return Pt(t,["moov","mvex","trex"]).forEach(t=>{const i=At(t,4),s=e[i];s&&(s.default={duration:At(t,12),sampleSize:At(t,16),flags:At(t,20)})}),e}function Ot(t){const e=t.subarray(8),i=e.subarray(86),s=yt(e.subarray(4,8));let r,n=s;const a="enca"===s||"encv"===s;if(a){const t=Pt(e,[s])[0];Pt(t.subarray("enca"===s?28:78),["sinf"]).forEach(t=>{const e=Pt(t,["schm"])[0];if(e){const i=yt(e.subarray(4,8));if("cbcs"===i||"cenc"===i){const e=Pt(t,["frma"])[0];e&&(n=yt(e))}}})}const o=n;switch(n){case"avc1":case"avc2":case"avc3":case"avc4":{const t=Pt(i,["avcC"])[0];t&&t.length>3&&(n+="."+$t(t[1])+$t(t[2])+$t(t[3]),r=Ft("avc1"===o?"dva1":"dvav",i));break}case"mp4a":{const t=Pt(e,[s])[0],i=Pt(t.subarray(28),["esds"])[0];if(i&&i.length>7){let t=4;if(3!==i[t++])break;t=Nt(i,t),t+=2;const e=i[t++];if(128&e&&(t+=2),64&e&&(t+=i[t++]),4!==i[t++])break;t=Nt(i,t);const s=i[t++];if(64!==s)break;if(n+="."+$t(s),t+=12,5!==i[t++])break;t=Nt(i,t);const r=i[t++];let a=(248&r)>>3;31===a&&(a+=1+((7&r)<<3)+((224&i[t])>>5)),n+="."+a}break}case"hvc1":case"hev1":{const t=Pt(i,["hvcC"])[0];if(t&&t.length>12){const e=t[1],i=["","A","B","C"][e>>6],s=31&e,r=At(t,2),a=(32&e)>>5?"H":"L",o=t[12],l=t.subarray(6,12);n+="."+i+s,n+="."+function(t){let e=0;for(let i=0;i<32;i++)e|=(t>>i&1)<<31-i;return e>>>0}(r).toString(16).toUpperCase(),n+="."+a+o;let h="";for(let t=l.length;t--;){const e=l[t];if(e||h){h="."+e.toString(16).toUpperCase()+h}}n+=h}r=Ft("hev1"==o?"dvhe":"dvh1",i);break}case"dvh1":case"dvhe":case"dvav":case"dva1":case"dav1":n=Ft(n,i)||n;break;case"vp09":{const t=Pt(i,["vpcC"])[0];if(t&&t.length>6){const e=t[4],i=t[5],s=t[6]>>4&15;n+="."+Bt(e)+"."+Bt(i)+"."+Bt(s)}break}case"av01":{const t=Pt(i,["av1C"])[0];if(t&&t.length>2){const e=t[1]>>>5,s=31&t[1],a=t[2]>>>7?"H":"M",o=(64&t[2])>>6,l=(32&t[2])>>5,h=2===e&&o?l?12:10:o?10:8,d=(16&t[2])>>4,c=(8&t[2])>>3,u=(4&t[2])>>2,f=3&t[2],g=1,m=1,p=1,v=0;n+="."+e+"."+Bt(s)+a+"."+Bt(h)+"."+d+"."+c+u+f+"."+Bt(g)+"."+Bt(m)+"."+Bt(p)+"."+v,r=Ft("dav1",i)}break}}return{codec:n,encrypted:a,supplemental:r}}function Ft(t,e){const i=Pt(e,["dvvC"]),s=i.length?i[0]:Pt(e,["dvcC"])[0];if(s){const e=s[2]>>1&127,i=s[2]<<5&32|s[3]>>3&31;return t+"."+Bt(e)+"."+Bt(i)}}function Nt(t,e){const i=e+5;for(;128&t[e++]&&e<i;);return e}function $t(t){return("0"+t.toString(16).toUpperCase()).slice(-2)}function Bt(t){return(t<10?"0":"")+t}function Ut(t,e){Pt(t,["moov","trak"]).forEach(t=>{const i=Pt(t,["mdia","minf","stbl","stsd"])[0];if(!i)return;const s=i.subarray(8);let r=Pt(s,["enca"]);const n=r.length>0;n||(r=Pt(s,["encv"])),r.forEach(t=>{Pt(n?t.subarray(28):t.subarray(78),["sinf"]).forEach(t=>{const i=Gt(t);i&&e(i,n)})})})}function Gt(t){const e=Pt(t,["schm"])[0];if(e){const i=yt(e.subarray(4,8));if("cbcs"===i||"cenc"===i){const e=Pt(t,["schi","tenc"])[0];if(e)return e}}}let Kt;function Vt(t){if("undefined"==typeof TextDecoder)return ot(t);return(Kt||(Kt=new TextDecoder("utf-8"))).decode(t).replace(/\0/g,"")}function jt(t,i,s,r,n){const a={};let o=!1;const l=function(t){const e=t.byteLength,i=[];for(let s=0;s<e;){const r=s+8<=e,n=s+4<=e?16777216*t[s]+(t[s+1]<<16|t[s+2]<<8|t[s+3]):At(t,s),a=n>1?s+n:e;if(r&&109===t[s+4]&&111===t[s+5]&&111===t[s+6]&&102===t[s+7]){const r=Math.min(a,e);for(let e=s+8;e<r;){const n=e+8<=r,a=e+4<=r?16777216*t[e]+(t[e+1]<<16|t[e+2]<<8|t[e+3]):At(t,e),o=a>1?e+a:r;if(n&&116===t[e+4]&&114===t[e+5]&&97===t[e+6]&&102===t[e+7]){const n=Math.min(o,r);let a,l;const h=[];for(let i=e+8;i<n;){const e=i+8<=n,s=i+4<=n?16777216*t[i]+(t[i+1]<<16|t[i+2]<<8|t[i+3]):At(t,i),r=s>1?i+s:n;if(e&&116===t[i+4]){const e=Math.min(r,n);102===t[i+5]&&104===t[i+6]&&100===t[i+7]?l||(l=t.subarray(i+8,e)):102===t[i+5]&&100===t[i+6]&&116===t[i+7]?a||(a=t.subarray(i+8,e)):114===t[i+5]&&117===t[i+6]&&110===t[i+7]&&h.push(t.subarray(i+8,e))}i=r}i.push({moofOffset:t.byteOffset+s,tfdt:a,tfhd:l,truns:h})}e=o}}s=a}return i}(t),h=t.byteLength;for(let u=0;u<l.length;u++){const{moofOffset:f,tfdt:g,tfhd:p,truns:v}=l[u],y=At(p,4),E=i[y];if(!E)continue;const T=a[y]||(a[y]={start:NaN,duration:0,sampleCount:0,trun:[],timescale:E.timescale,type:E.type});let S;if(g){const t=g[0];S=At(g,4),1===t&&(S===Et?s.warn("[mp4-demuxer]: Ignoring assumed invalid signed 64-bit track fragment decode time"):(S*=Et+1,S+=At(g,8))),e(S)&&(!e(T.start)||S<T.start)&&(T.start=S),n&&e(S)&&(n.timeOffset=S/n.timescale)}const b=(null==n?void 0:n.trackId)===y&&E.type===m,A=E.default,L=16777215&At(p,0);let I,R=(null==A?void 0:A.duration)||0,k=(null==A?void 0:A.sampleSize)||0,_=8;1&L&&(_+=8),2&L&&(_+=4),8&L&&(R=At(p,_),I=p.byteOffset-t.byteOffset+_,_+=4),16&L&&(k=At(p,_));let D=0;const w=!!(1&L),P=!w&&!!(131072&L);w?(D=At(p,8),D*=Math.pow(2,32),D+=At(p,12)):P&&(D=f);let C=S||0,x=0,M=R;for(let i=0;i<v.length;i++){const s=v[i],a=At(s,4),o=T.sampleCount;T.sampleCount+=a;const l=1&s[3];let u=0;const f=4&s[3],g=1&s[2],m=2&s[2],p=4&s[2],y=8&s[2];let E=8;if(l&&(u=Rt(s,E),E+=4),f){1&s[E+1]||void 0!==T.keyFrameIndex||(T.keyFrameIndex=o),E+=4}let S,A,L,_=D+u;if(!r&&0===s[1]&&6===s[2]&&1===s[3]){var d,c;const i=C,r=_,o=E;let l=-1,u=0,f=0,g=null!=(d=null==n?void 0:n.timeOffset)?d:0;const m=R/(null!=(c=null==n?void 0:n.timescale)?c:1),p=!0===(null==n?void 0:n.isHEVCFlavor),v=p?2:1;for(let e=0;e<a;e++){const i=0===s[E]?s[E+1]<<16|s[E+2]<<8|s[E+3]:At(s,E),r=-1===l&&void 0===T.keyFrameIndex&&!(1&s[E+5]);E+=8;const a=_+i;if(b){if(i>0){let e=_;do{const i=0===t[e]?t[e+1]<<16|t[e+2]<<8|t[e+3]:At(t,e);e+=4;const s=t[e],r=p?s>>1&63:31&s;(p?39===r||40===r:6===r)&&Wt(t.subarray(e,e+i),v,g,n.samples),e+=i}while(e<a)}g+=m}_=a,r&&(l=e,u=_)}if(_<=h)f=a;else{let t=r,e=o;for(let i=0;i<a;i++){if(t+=0===s[e]?s[e+1]<<16|s[e+2]<<8|s[e+3]:At(s,e),t>h)break;f=i+1,e+=8}}if(b&&(n.timeOffset=g),-1!==l&&u<=h&&void 0===T.keyFrameIndex&&(T.keyFrameIndex=l,T.keyFrameStart=i+l*R),f){(!e(T.ptsMin)||i<T.ptsMin)&&(T.ptsMin=i);const t=i+f*R;(!e(T.ptsMax)||t>T.ptsMax)&&(T.ptsMax=t)}const y=R*a;C=i+y,x+=y;continue}r&&(S=[],A={sampleOffset:_,samples:S,defaultSampleDurationOffset:I},_<=h&&T.trun.push(A));for(let i=0;i<a;i++){let a,o,l;g?(r&&(a=s.byteOffset-t.byteOffset+E),M=At(s,E),E+=4):M=R,m?(L=At(s,E),E+=4):L=k,p&&(l=1&s[E+1]?1:0,r&&(o={isNonSync:l,dependsOn:1==(3&s[E])?1:2}),E+=4);let d=0;if(y){d=0===s[0]?At(s,E):Rt(s,E),E+=4}if(b){let e=_,i=0;for(;i<L;){const s=At(t,e);e+=4,Yt(n.isHEVCFlavor,t[e])&&Wt(t.subarray(e,e+s),n.isHEVCFlavor?2:1,n.timeOffset+d/n.timescale,n.samples),e+=s,i+=s+4}n.timeOffset+=M/n.timescale}if(_+=L,_<=h){A&&void 0!==a&&(A.lastSampleDurationOffset=a),0===l&&void 0===T.keyFrameIndex&&(T.keyFrameIndex=i,T.keyFrameStart=C);const t=C+d;(!e(T.ptsMin)||t<T.ptsMin)&&(T.ptsMin=t),(!e(T.ptsMax)||t+M>T.ptsMax)&&(T.ptsMax=t+M),S&&(S[i]={cts:d,duration:M,flags:o,size:L})}C+=M,x+=M}!x&&R&&(x+=R*a)}T.duration+=x,T.duration&&(o=!0)}if(!o){let i=1/0,s=0;const r=Pt(t,["sidx"]);for(let t=0;t<r.length;t++){const e=xt(r[t]);if(null!=e&&e.references){i=Math.min(i,e.earliestPresentationTime/e.timescale);const t=e.references.reduce((t,e)=>t+e.info.duration||0,0);s=Math.max(s,t+e.earliestPresentationTime/e.timescale)}}s&&e(s)&&Object.keys(a).forEach(t=>{a[t].duration||(a[t].duration=s*a[t].timescale-a[t].start)})}return a}function Ht(t,e){const i=new Uint8Array(t.length+e.length);return i.set(t),i.set(e,t.length),i}function qt(t){if(!t)return!1;const e=t.substring(0,4);return"hvc1"===e||"hev1"===e||"dvh1"===e||"dvhe"===e}function Yt(t,e){if(t){const t=e>>1&63;return 39===t||40===t}return 6===(31&e)}function Wt(t,e,i,s){const r=zt(t);let n=0;n+=e;let a=0,o=0,l=0;for(;n<r.length;){a=0;do{if(n>=r.length)break;l=r[n++],a+=l}while(255===l);o=0;do{if(n>=r.length)break;l=r[n++],o+=l}while(255===l);const t=r.length-n;let e=n;if(o<t)n+=o;else if(o>t){q.error(`Malformed SEI payload. ${o} is too small, only ${t} bytes left to parse.`);break}if(4===a){if(181===r[e++]){const t=bt(r,e);if(e+=2,49===t){const t=At(r,e);if(e+=4,1195456820===t){const t=r[e++];if(3===t){const n=r[e++],o=64&n,l=o?2+3*(31&n):0,h=new Uint8Array(l);if(o){h[0]=n;for(let t=1;t<l;t++)h[t]=r[e++]}s.push({type:t,payloadType:a,pts:i,bytes:h})}}}}}else if(5===a&&o>16){const t=[];for(let i=0;i<16;i++){const s=r[e++].toString(16);t.push(1==s.length?"0"+s:s),3!==i&&5!==i&&7!==i&&9!==i||t.push("-")}const n=o-16,l=new Uint8Array(n);for(let t=0;t<n;t++)l[t]=r[e++];s.push({payloadType:a,pts:i,uuid:t.join(""),userData:Vt(l),userDataBytes:l})}}}function zt(t){const e=t.byteLength;let i,s=t.indexOf(3,3);for(;-1!==s;)0===t[s-1]&&0===t[s-2]&&(i||(i=[])).push(s),s=t.indexOf(3,s+1);if(!i)return t;const r=e-i.length,n=new Uint8Array(r);let a=0,o=0;for(let e=0;e<r;o++,e++)o===i[a]&&(o++,a++),n[e]=t[o];return n}function Xt(t,e,i){if(16!==t.byteLength)throw new RangeError("Invalid system id");let s,r,n;s=0,r=new Uint8Array,n=new Uint8Array;const a=new Uint8Array(4);return i.byteLength>0&&new DataView(a.buffer).setUint32(0,i.byteLength,!1),function(t,...e){const i=e.length;let s=8,r=i;for(;r--;)s+=e[r].byteLength;const n=new Uint8Array(s);for(n[0]=s>>24&255,n[1]=s>>16&255,n[2]=s>>8&255,n[3]=255&s,n.set(t,4),r=0,s=8;r<i;r++)n.set(e[r],s),s+=e[r].byteLength;return n}([112,115,115,104],new Uint8Array([0,0,0,0]),t,n,r,a,i)}function Qt(t){const e=[];if(t instanceof ArrayBuffer){const i=t.byteLength;let s=0;for(;s+32<i;){const i=Zt(new DataView(t,s));e.push(i),s+=i.size}}return e}function Zt(t){const e=t.getUint32(0),i=t.byteOffset,s=t.byteLength;if(s<e)return{offset:i,size:s};if(1886614376!==t.getUint32(4))return{offset:i,size:e};const r=t.getUint32(8)>>>24;if(0!==r&&1!==r)return{offset:i,size:e};const n=t.buffer,a=mt(new Uint8Array(n,i+12,16));let o=null,l=null,h=0;if(0===r)h=28;else{const r=t.getUint32(28);if(!r||s<32+16*r)return{offset:i,size:e};o=[];for(let t=0;t<r;t++)o.push(new Uint8Array(n,i+32+16*t,16));h=32+16*r}if(!h)return{offset:i,size:e};const d=t.getUint32(h);return e-32<d?{offset:i,size:e}:(l=new Uint8Array(n,i+h+4,d),0===r&&(o=function(t){const e=[];for(let i=0;i<t.length;){const s=t[i++],r=7&s;if(0===r){for(;128&t[i++];);continue}if(2!==r){i+=1===r?8:4;continue}let n=0;for(let e=0,s=128;128&s;e+=7)n|=(127&(s=t[i++]))<<e;if(s>>3==2)if(32===n){const s=new Uint8Array(16);for(let e=0;e<16;e++)s[e]=parseInt(String.fromCharCode(t[i+2*e],t[i+2*e+1]),16);e.push(s)}else 16===n&&e.push(t.subarray(i,i+16));i+=n}return e}(l)),{version:r,systemId:a,kids:o,data:l,offset:i,size:e})}const Jt=re("userAgent"),te=re("vendor");let ee,ie,se;function re(t){try{return navigator[t]||""}catch(t){}return""}function ne(){if(void 0===ee){const t=Jt.match(/Chrome\/(\d+)/i);ee=t?parseInt(t[1]):0}return ee}function ae(){return/\(Windows.+Firefox\//i.test(Jt)}const oe={audio:{a3ds:1,"ac-3":.95,"ac-4":1,alac:.9,alaw:1,dra1:1,"dts+":1,"dts-":1,dtsc:1,dtse:1,dtsh:1,"ec-3":.9,enca:1,fLaC:.9,flac:.9,FLAC:.9,g719:1,g726:1,m4ae:1,mha1:1,mha2:1,mhm1:1,mhm2:1,mlpa:1,mp4a:1,"raw ":1,Opus:1,opus:1,samr:1,sawb:1,sawp:1,sevc:1,sqcp:1,ssmv:1,twos:1,ulaw:1},video:{avc1:1,avc2:1,avc3:1,avc4:1,avcp:1,av01:.8,dav1:.8,drac:1,dva1:1,dvav:1,dvh1:.7,dvhe:.7,encv:1,hev1:.75,hvc1:.75,mjp2:1,mp4v:1,mvc1:1,mvc2:1,mvc3:1,mvc4:1,resv:1,rv60:1,s263:1,svc1:1,svc2:1,"vc-1":1,vp08:1,vp09:.9},text:{stpp:1,wvtt:1},image:{mjpg:1}};function le(t,e){const i=oe[e];return!!i&&!!i[t.slice(0,4)]}function he(t,e,i=!0){return!t.split(",").some(t=>!de(t,e,i))}function de(t,e,i=!0){var s;const r=Y(i);return null!=(s=null==r?void 0:r.isTypeSupported(ce(t,e)))&&s}function ce(t,e){return`${e}/mp4;codecs=${t}`}function ue(t){if(t){const e=t.substring(0,4);return oe.video[e]}return 2}function fe(t){const e=ae();return t.split(",").reduce((t,i)=>{const s=e&&qt(i)?9:oe.video[i];return s?(2*s+t)/(t?3:2):(oe.audio[i]+t)/(t?2:1)},0)}const ge={};const me=/flac|opus|mp4a\.40\.34/i;function pe(t,e=!0){return t.replace(me,t=>function(t,e=!0){if(ge[t])return ge[t];const i={flac:["flac","fLaC","FLAC"],opus:["opus","Opus"],"mp4a.40.34":["mp3"]}[t];for(let r=0;r<i.length;r++){var s;if(de(i[r],"audio",e))return ge[t]=i[r],i[r];if("mp3"===i[r]&&null!=(s=Y(e))&&s.isTypeSupported("audio/mpeg"))return""}return t}(t.toLowerCase(),e))}function ve(t,e){if(t&&(t.length>4||-1!==["ac-3","ec-3","alac","fLaC","Opus"].indexOf(t))&&(ye(t,"audio")||ye(t,"video")))return t;if(e){const i=e.split(",");if(i.length>1){if(t)for(let e=i.length;e--;)if(i[e].substring(0,4)===t.substring(0,4))return i[e];return i[0]}}return e||t}function ye(t,e){return le(t,e)&&de(t,e)}function Ee(t){if(t.startsWith("av01.")){const e=t.split("."),i=["0","111","01","01","01","0"];for(let t=e.length;t>4&&t<10;t++)e[t]=i[t-4];return e.join(".")}return t}function Te(t){const e=Y(t)||{isTypeSupported:()=>!1};return{mpeg:e.isTypeSupported("audio/mpeg"),mp3:e.isTypeSupported('audio/mp4; codecs="mp3"'),ac3:e.isTypeSupported('audio/mp4; codecs="ac-3"')}}function Se(t){return t.replace(/^.+codecs=["']?([^"']+).*$/,"$1")}const be={supported:!1,smooth:!1,powerEfficient:!1},Ae={supported:!0,configurations:[],decodingInfoResults:[{supported:!0,powerEfficient:!0,smooth:!0}]};function Le(t,e){return{supported:!1,configurations:e,decodingInfoResults:[be],error:t}}function Ie(t,i,s,r,n,a){const o=t.videoCodec,l=t.audioCodec?t.audioGroups:null,h=null==a?void 0:a.audioCodec,d=null==a?void 0:a.channels,c=d?parseInt(d):h?1/0:2;let u=null;if(null!=l&&l.length)try{u=1===l.length&&l[0]?i.groups[l[0]].channels:l.reduce((t,e)=>{if(e){const s=i.groups[e];if(!s)throw new Error(`Audio track group ${e} not found`);Object.keys(s.channels).forEach(e=>{t[e]=(t[e]||0)+s.channels[e]})}return t},{2:0})}catch(t){return!0}return void 0!==o&&(o.split(",").some(t=>qt(t))||t.width>1920&&t.height>1088||t.height>1920&&t.width>1088||t.frameRate>Math.max(r,30)||"SDR"!==t.videoRange&&t.videoRange!==s||t.bitrate>Math.max(n,8e6))||!!u&&e(c)&&Object.keys(u).some(t=>parseInt(t)>c)}function Re(t,e,i,s={}){const r=t.videoCodec;if(!r&&!t.audioCodec||!i)return Promise.resolve(Ae);const n=[],a=function(t){var e;const i=null==(e=t.videoCodec)?void 0:e.split(","),s=_e(t),r=t.width||640,n=t.height||480,a=t.frameRate||30,o=t.videoRange.toLowerCase();return i?i.map(t=>{const e={contentType:ce(Ee(t),"video"),width:r,height:n,bitrate:s,framerate:a};return"sdr"!==o&&(e.transferFunction=o),e}):[]}(t),o=a.length,l=function(t,e,i){var s;const r=null==(s=t.audioCodec)?void 0:s.split(","),n=_e(t);if(r&&t.audioGroups)return t.audioGroups.reduce((t,s)=>{var a;const o=s?null==(a=e.groups[s])?void 0:a.tracks:null;return o?o.reduce((t,e)=>{if(e.groupId===s){const s=parseFloat(e.channels||"");r.forEach(e=>{const r={contentType:ce(e,"audio"),bitrate:i?ke(e,n):n};s&&(r.channels=""+s),t.push(r)})}return t},t):t},[]);return[]}(t,e,o>0),h=l.length;for(let t=o||1*h||1;t--;){const e={type:"media-source"};if(o&&(e.video=a[t%o]),h){e.audio=l[t%h];const i=e.audio.bitrate;e.video&&i&&(e.video.bitrate-=i)}n.push(e)}if(r){const t=navigator.userAgent;if(r.split(",").some(t=>qt(t))&&ae())return Promise.resolve(Le(new Error(`Overriding Windows Firefox HEVC MediaCapabilities result based on user-agent string: (${t})`),n))}return Promise.all(n.map(t=>{const e=function(t){let e="";const{audio:i,video:s}=t;if(s){e+=`${Se(s.contentType)}_r${s.height}x${s.width}f${Math.ceil(s.framerate)}${s.transferFunction||"sd"}_${Math.ceil(s.bitrate/1e5)}`}if(i){e+=`${s?"_":""}${Se(i.contentType)}_c${i.channels}`}return e}(t);return s[e]||(s[e]=i.decodingInfo(t))})).then(t=>({supported:!t.some(t=>!t.supported),configurations:n,decodingInfoResults:t})).catch(t=>({supported:!1,configurations:n,decodingInfoResults:[],error:t}))}function ke(t,e){if(e<=1)return 1;let i=128e3;return"ec-3"===t?i=768e3:"ac-3"===t&&(i=64e4),Math.min(e/2,i)}function _e(t){return 1e3*Math.ceil(Math.max(.9*t.bitrate,t.averageBitrate)/1e3)||1}function De(t,e,i){const s=encodeURIComponent(e),r=`${s}=${encodeURIComponent(i)}`;let n=!1;const a=[];t.search.substring(1).split("&").forEach(t=>{t===s||t.startsWith(s+"=")?n||(a.push(r),n=!0):t&&a.push(t)}),n||a.push(r),t.search=a.join("&")}const we=["NONE","TYPE-0","TYPE-1",null];const Pe=["SDR","PQ","HLG"];var Ce="",xe="YES",Me="v2";function Oe(t){const{canSkipUntil:e,canSkipDateRanges:i,age:s}=t;return e&&s<e/2?i?Me:xe:Ce}class Fe{constructor(t,e,i){this.msn=void 0,this.part=void 0,this.skip=void 0,this.msn=t,this.part=e,this.skip=i}addDirectives(t){const e=new self.URL(t);return void 0!==this.msn&&De(e,"_HLS_msn",this.msn.toString()),void 0!==this.part&&De(e,"_HLS_part",this.part.toString()),this.skip&&De(e,"_HLS_skip",this.skip),e.href}}class Ne{constructor(t){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.imageCodec=void 0,this.iframes=void 0,this.details=void 0,this.fragmentError=0,this.loadError=0,this.loadErrorTime=0,this.loaded=void 0,this.realBitrate=0,this.supportedPromise=void 0,this.supportedResult=void 0,this._avgBitrate=0,this._audioGroups=void 0,this._subtitleGroups=void 0,this._urlId=0,this.url=[t.url],this._attrs=[t.attrs],this.bitrate=t.bitrate,t.details&&(this.details=t.details),this.id=t.id||0,this.name=t.name,this.width=t.width||0,this.height=t.height||0,this.frameRate=t.attrs.optionalFloat("FRAME-RATE",0),this._avgBitrate=t.attrs.decimalInteger("AVERAGE-BANDWIDTH"),this.audioCodec=t.audioCodec,this.videoCodec=t.videoCodec,"imageCodec"in t&&(this.imageCodec=t.imageCodec),this.codecSet=[t.videoCodec,t.audioCodec].filter(t=>!!t).map(t=>t.substring(0,4)).join(","),"supplemental"in t){var e;this.supplemental=t.supplemental;const i=null==(e=t.supplemental)?void 0:e.videoCodec;i&&i!==t.videoCodec&&(this.codecSet+=`,${i.substring(0,4)}`)}"iframes"in t&&t.iframes?this.iframes=!0:(this.addGroupId("audio",t.attrs.AUDIO),this.addGroupId("text",t.attrs.SUBTITLES))}get maxBitrate(){return Math.max(this.realBitrate,this.bitrate)}get averageBitrate(){return this._avgBitrate||this.realBitrate||this.bitrate}get attrs(){return this._attrs[0]}get codecs(){return this.attrs.CODECS||""}get pathwayId(){return this.attrs["PATHWAY-ID"]||"."}get videoRange(){return this.attrs["VIDEO-RANGE"]||"SDR"}get score(){return this.attrs.optionalFloat("SCORE",0)}get uri(){return this.url[0]||""}hasAudioGroup(t){return $e(this._audioGroups,t)}hasSubtitleGroup(t){return $e(this._subtitleGroups,t)}get audioGroups(){return this._audioGroups}get subtitleGroups(){return this._subtitleGroups}addGroupId(t,e){if(e)if("audio"===t){let t=this._audioGroups;t||(t=this._audioGroups=[]),-1===t.indexOf(e)&&t.push(e)}else if("text"===t){let t=this._subtitleGroups;t||(t=this._subtitleGroups=[]),-1===t.indexOf(e)&&t.push(e)}}get urlId(){return 0}set urlId(t){}get audioGroupIds(){return this.audioGroups?[this.audioGroupId]:void 0}get textGroupIds(){return this.subtitleGroups?[this.textGroupId]:void 0}get audioGroupId(){var t;return null==(t=this.audioGroups)?void 0:t[0]}get textGroupId(){var t;return null==(t=this.subtitleGroups)?void 0:t[0]}addFallback(){}}function $e(t,e){return!(!e||!t)&&-1!==t.indexOf(e)}function Be(t,e){let i=!1,s=[];if(t&&(i="SDR"!==t,s=[t]),e){s=e.allowedVideoRanges||Pe.slice(0);const t="SDR"!==s.join("")&&!e.videoCodec;i=void 0!==e.preferHDR?e.preferHDR:t&&function(){if("function"==typeof matchMedia){const t=matchMedia("(dynamic-range: high)"),e=matchMedia("bad query");if(t.media!==e.media)return!0===t.matches}return!1}(),i||(s=["SDR"])}return{preferHDR:i,allowedVideoRanges:s}}const Ue=(t,e)=>JSON.stringify(t,(t=>{const e=new WeakSet;return(i,s)=>{if(t&&(s=t(i,s)),"object"==typeof s&&null!==s){if(e.has(s))return;e.add(s)}return s}})(e));function Ge(t,e){q.log(`[abr] start candidates with "${t}" ignored because ${e}`)}function Ke(t){return t.reduce((t,e)=>{let i=t.groups[e.groupId];i||(i=t.groups[e.groupId]={tracks:[],channels:{2:0},hasDefault:!1,hasAutoSelect:!1}),i.tracks.push(e);const s=e.channels||"2";return i.channels[s]=(i.channels[s]||0)+1,i.hasDefault=i.hasDefault||e.default,i.hasAutoSelect=i.hasAutoSelect||e.autoselect,i.hasDefault&&(t.hasDefaultAudio=!0),i.hasAutoSelect&&(t.hasAutoSelectAudio=!0),t},{hasDefaultAudio:!1,hasAutoSelectAudio:!1,groups:{}})}function Ve(t){if(!t)return t;const{lang:e,assocLang:i,characteristics:s,channels:r,audioCodec:n}=t;return{lang:e,assocLang:i,characteristics:s,channels:r,audioCodec:n}}function je(t,e,i){if("attrs"in t){const i=e.indexOf(t);if(-1!==i)return i}for(let s=0;s<e.length;s++){if(He(t,e[s],i))return s}return-1}function He(t,e,i){const{groupId:s,name:r,lang:n,assocLang:a,default:o}=t,l=t.forced;return(void 0===s||e.groupId===s)&&(void 0===r||e.name===r)&&(void 0===n||function(t,e="--"){if(t.length===e.length)return t===e;return t.startsWith(e)||e.startsWith(t)}(n,e.lang))&&(void 0===a||e.assocLang===a)&&(void 0===o||e.default===o)&&(void 0===l||e.forced===l)&&(!("characteristics"in t)||function(t,e=""){const i=t.split(","),s=e.split(",");return i.length===s.length&&!i.some(t=>-1===s.indexOf(t))}(t.characteristics||"",e.characteristics))&&(void 0===i||i(t,e))}function qe(t,e){const{audioCodec:i,channels:s}=t;return!(void 0!==i&&(e.audioCodec||"").substring(0,4)!==i.substring(0,4)||void 0!==s&&s!==(e.channels||"2"))}function Ye(t,e,i){for(let s=e;s>-1;s--)if(i(t[s]))return s;for(let s=e+1;s<t.length;s++)if(i(t[s]))return s;return-1}function We(t,e){var i;return!!t&&t!==(null==(i=e.loadLevelObj)?void 0:i.uri)}function ze(t,e){return!e||-1!==e.indexOf(t)}function Xe(t,e){if(e||t){const i=I({},e);return t&&(t.videoCodec&&(i.videoCodec=t.videoCodec),t.videoRange&&(i.allowedVideoRanges=[t.videoRange])),i}}class Qe{constructor(t){this.tracks=void 0,this.queues={video:[],audio:[],audiovideo:[]},this.tracks=t}destroy(){this.tracks=this.queues=null}append(t,e,i){if(null===this.queues||null===this.tracks)return;const s=this.queues[e];s.push(t),1!==s.length||i||this.executeNext(e)}appendBlocker(t){return new Promise(e=>{const i={label:"async-blocker",execute:e,onStart:()=>{},onComplete:()=>{},onError:()=>{}};this.append(i,t)})}prependBlocker(t){return new Promise(e=>{if(this.queues){const i={label:"async-blocker-prepend",execute:e,onStart:()=>{},onComplete:()=>{},onError:()=>{}};this.queues[t].unshift(i)}})}removeBlockers(){null!==this.queues&&[this.queues.video,this.queues.audio,this.queues.audiovideo].forEach(t=>{var e;const i=null==(e=t[0])?void 0:e.label;"async-blocker"===i||"async-blocker-prepend"===i?(t[0].execute(),t.splice(0,1)):"block-audio"===i&&t.splice(0,1)})}insertNext(t,e){null!==this.queues&&this.queues[e].splice(1,0,...t)}unblockAudio(){var t;null!==this.queues&&"block-audio"===(null==(t=this.current("audio"))?void 0:t.label)&&this.shiftAndExecuteNext("audio")}audioBlocking(){return null!==this.queues&&this.queues.audio.some(t=>"block-audio"===t.label)}executeNext(t){if(null===this.queues||null===this.tracks)return;const e=this.queues[t];if(e.length){const s=e[0];try{s.execute()}catch(e){var i;if(s.onError(e),null===this.queues||null===this.tracks)return;const r=null==(i=this.tracks[t])?void 0:i.buffer;null!=r&&r.updating||this.shiftAndExecuteNext(t)}}}shiftAndExecuteNext(t){null!==this.queues&&(this.queues[t].shift(),this.executeNext(t))}current(t){var e;return(null==(e=this.queues)?void 0:e[t][0])||null}toString(){const{queues:t,tracks:e}=this;return null===t||null===e?"<destroyed>":`\n${this.list("video")}\n${this.list("audio")}\n${this.list("audiovideo")}}`}list(t){var e,i;return null!=(e=this.queues)&&e[t]||null!=(i=this.tracks)&&i[t]?`${t}: (${this.listSbInfo(t)}) ${this.listOps(t)}`:""}listSbInfo(t){var e;const i=null==(e=this.tracks)?void 0:e[t],s=null==i?void 0:i.buffer;return s?`SourceBuffer${s.updating?" updating":""}${i.ended?" ended":""}${i.ending?" ending":""}`:"none"}listOps(t){var e;return(null==(e=this.queues)?void 0:e[t].map(t=>t.label).join(", "))||""}}const Ze=function(t,e){let i=0,s=t.length-1,r=null,n=null;for(;i<=s;){r=(i+s)/2|0,n=t[r];const a=e(n);if(a>0)i=r+1;else{if(!(a<0))return n;s=r-1}}return null};function Je(t,e,i=0,s=0,r=.005){let n=null;if(t){n=e[1+t.sn-e[0].sn]||null;const s=t.endDTS-i;s>0&&s<15e-7&&(i+=15e-7),n&&t.level!==n.level&&n.end<=t.end&&(n=e[2+t.sn-e[0].sn]||null)}else 0===i&&0===e[0].start&&(n=e[0]);if(n&&((!t||t.level===n.level)&&0===ti(i,s,n)||function(t,e,i){if(0===(null==e?void 0:e.start)&&e.level<t.level&&(e.endPTS||0)>0){const s=e.tagList.reduce((t,e)=>("INF"===e[0]&&(t+=parseFloat(e[1])),t),i);return t.start<=s}return!1}(n,t,Math.min(r,s))))return n;const a=Ze(e,ti.bind(null,i,s));return!a||a===t&&n?n:a}function ti(t=0,e=0,i){if(i.start<=t&&i.start+i.duration>t)return 0;const s=Math.min(e,i.duration+(i.deltaPTS?i.deltaPTS:0));return i.start+i.duration-s<=t?1:i.start-s>t&&i.start?-1:0}function ei(t,e,i){const s=1e3*Math.min(e,i.duration+(i.deltaPTS?i.deltaPTS:0));return(i.endProgramDateTime||0)-s>t}function ii(t,e,i){if(t&&t.startCC<=e&&t.endCC>=e){let s=t.fragments;const{fragmentHint:r}=t;let n;return r&&(s=s.concat(r)),Ze(s,t=>t.cc<e?1:t.cc>e?-1:(n=t,t.end<=i?1:t.start>i?-1:0)),n||null}return null}function si(t,e){return e===t.endSN&&t.fragmentHint?t.fragmentHint:t.fragments[1+e-t.startSN]||null}var ri=0,ni=2,ai=3,oi=5,li=0,hi=1,di=2,ci=4,ui=8,fi=16;function gi(t){const e=t.details;return e===n.BUFFER_ADD_CODEC_ERROR||e===n.MEDIA_SOURCE_REQUIRES_RESET||e===n.BUFFER_APPEND_ERROR&&!mi(t)}function mi(t){return t.details===n.BUFFER_APPEND_ERROR&&("QuotaExceededError"===t.error.name||"InvalidStateError"===t.error.name)}function pi(t){const e={action:ri,flags:li};return t&&(e.resolved=!0),e}class vi{constructor(t){this.PTSKnown=!1,this.alignedSliding=!1,this.averagetargetduration=void 0,this.endCC=0,this.endSN=0,this.fragments=void 0,this.fragmentHint=void 0,this.partList=null,this.dateRanges=void 0,this.dateRangeTagCount=0,this.live=!0,this.iframesOnly=!1,this.requestScheduled=-1,this.ageHeader=0,this.advancedDateTime=void 0,this.updated=!0,this.advanced=!0,this.misses=0,this.startCC=0,this.startSN=0,this.startTimeOffset=null,this.targetduration=0,this.totalduration=0,this.type=null,this.url=void 0,this.m3u8="",this.version=null,this.canBlockReload=!1,this.canSkipUntil=0,this.canSkipDateRanges=!1,this.skippedSegments=0,this.recentlyRemovedDateranges=void 0,this.partHoldBack=0,this.holdBack=0,this.partTarget=0,this.preloadHint=void 0,this.renditionReports=void 0,this.tuneInGoal=0,this.deltaUpdateFailed=void 0,this.driftStartTime=0,this.driftEndTime=0,this.driftStart=0,this.driftEnd=0,this.encryptedFragments=void 0,this.playlistParsingError=null,this.variableList=null,this.hasVariableRefs=!1,this.appliedTimelineOffset=void 0,this.fragments=[],this.encryptedFragments=[],this.dateRanges={},this.url=t}reloaded(t){if(!t)return this.advanced=!0,void(this.updated=!0);const e=this.lastPartSn-t.lastPartSn,i=this.lastPartIndex-t.lastPartIndex;this.updated=this.endSN!==t.endSN||!!i||!!e||!this.live,this.advanced=this.endSN>t.endSN||e>0||0===e&&i>0,this.updated||this.advanced?this.misses=0:this.misses=t.misses+1}hasKey(t){return this.encryptedFragments.some(e=>{let i=e.decryptdata;return i||(e.setKeyFormat(t.keyFormat),i=e.decryptdata),!!i&&t.matches(i)})}get hasProgramDateTime(){return!!this.fragments.length&&e(this.fragments[this.fragments.length-1].programDateTime)}get levelTargetDuration(){return this.averagetargetduration||this.targetduration||10}get drift(){const t=this.driftEndTime-this.driftStartTime;if(t>0){return 1e3*(this.driftEnd-this.driftStart)/t}return 1}get edge(){return this.partEnd||this.fragmentEnd}get partEnd(){var t;return null!=(t=this.partList)&&t.length?this.partList[this.partList.length-1].end:this.fragmentEnd}get fragmentEnd(){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 t;return null!=(t=this.partList)&&t.length?this.partList[this.partList.length-1].index:-1}get maxPartIndex(){const t=this.partList;if(t){const e=this.lastPartIndex;if(-1!==e){for(let i=t.length;i--;)if(t[i].index>e)return t[i].index;return e}}return 0}get lastPartSn(){var t;return null!=(t=this.partList)&&t.length?this.partList[this.partList.length-1].fragment.sn:this.endSN}get expired(){if(this.live&&void 0!==this.advancedDateTime&&this.misses<3){const t=this.partEnd-this.fragmentStart;return this.age>Math.max(t,this.totalduration)+this.levelTargetDuration}return!1}get partsExpired(){return!!(this.live&&this.partTarget&&void 0!==this.advancedDateTime&&this.misses<3)&&this.age>1.5*(this.partHoldBack||3*this.partTarget)}}const yi={length:0,start:()=>0,end:()=>0};class Ei{static isBuffered(t,e){if(t){const i=Ei.getBuffered(t);for(let t=i.length;t--;)if(e>=i.start(t)&&e<=i.end(t))return!0}return!1}static bufferedRanges(t){if(t){const e=Ei.getBuffered(t);return Ei.timeRangesToArray(e)}return[]}static timeRangesToArray(t){const e=[];for(let i=0;i<t.length;i++)e.push({start:t.start(i),end:t.end(i)});return e}static bufferInfo(t,e,i){if(t){const s=Ei.bufferedRanges(t);if(s.length)return Ei.bufferedInfo(s,e,i)}return{len:0,start:e,end:e,bufferedIndex:-1}}static bufferedInfo(t,e,i){e=Math.max(0,e),t.length>1&&t.sort((t,e)=>t.start-e.start||e.end-t.end);let s=-1,r=[];if(i)for(let n=0;n<t.length;n++){e>=t[n].start&&e<=t[n].end&&(s=n);const a=r.length;if(a){const e=r[a-1].end;t[n].start-e<i?t[n].end>e&&(r[a-1].end=t[n].end):r.push(t[n])}else r.push(t[n])}else r=t;let n,a=0,o=e,l=e;for(let t=0;t<r.length;t++){const h=r[t].start,d=r[t].end;if(-1===s&&e>=h&&e<=d&&(s=t),e+i>=h&&e<d)o=h,l=d,a=l-e;else if(e+i<h){n=h;break}}return{len:a,start:o||0,end:l||0,nextStart:n,buffered:t,bufferedIndex:s}}static getBuffered(t){try{return t.buffered||yi}catch(t){return q.log("failed to get media.buffered",t),yi}}}function Ti(t,e,i){Si(t,e,i),t.addEventListener(e,i)}function Si(t,e,i){t.removeEventListener(e,i)}function bi(t){let e="";const i=t.length;for(let s=0;s<i;s++)e+=`[${t.start(s).toFixed(3)}-${t.end(s).toFixed(3)}]`;return e}const Ai=/(avc[1234]|hvc1|hev1|dvh[1e]|vp09|av01)(?:\.[^.,]+)+/,Li="HlsJsTrackRemovedError",Ii="HlsJsSourceBufferError";class Ri extends Error{constructor(t){super(t),this.name=Li}}function ki(t){const e=t.querySelectorAll("source");[].slice.call(e).forEach(e=>{t.removeChild(e)})}function _i(t){return"audio"===t?1:0}function Di(t,e){return`${t?"":" - triggering recovery"}${e?" with HTMLMediaElement Error: "+e.message:""}`}function wi(t){return`${t.type}_${t.sn}_${t.level}`}function Pi(t,e){const{start:i,end:s}=e;let r=0;for(let e=0;e<t.length;e++){const n=t[e];if(n.start>=s)break;const a=Math.max(i,n.start),o=Math.min(s,n.end);o>a&&(r+=o-a)}return r}function Ci(t,e){return e.duration-t<=.05}var xi="NOT_LOADED",Mi="APPENDING",Oi="PARTIAL",Fi="OK";class Ni{constructor(t){this.activePartLists=Object.create(null),this.endListFragments=Object.create(null),this.fragments=Object.create(null),this.timeRanges=Object.create(null),this.bufferPadding=.2,this.hls=void 0,this.hasGaps=!1,this.hls=t,this._registerListeners()}_registerListeners(){const{hls:t}=this;t&&(t.on(a.MANIFEST_LOADING,this.onManifestLoading,this),t.on(a.BUFFER_APPENDED,this.onBufferAppended,this),t.on(a.FRAG_BUFFERED,this.onFragBuffered,this),t.on(a.FRAG_LOADED,this.onFragLoaded,this))}_unregisterListeners(){const{hls:t}=this;t&&(t.off(a.MANIFEST_LOADING,this.onManifestLoading,this),t.off(a.BUFFER_APPENDED,this.onBufferAppended,this),t.off(a.FRAG_BUFFERED,this.onFragBuffered,this),t.off(a.FRAG_LOADED,this.onFragLoaded,this))}destroy(){this._unregisterListeners(),this.hls=this.fragments=this.activePartLists=this.endListFragments=this.timeRanges=null}getAppendedFrag(t,e){const i=this.activePartLists[e];if(i)for(let e=i.length;e--;){const s=i[e];if(!s)break;if(s.start<=t&&t<=s.end&&s.loaded)return s}return this.getBufferedFrag(t,e)}getBufferedFrag(t,e){return this.getFragAtPos(t,e,!0)}getFragAtPos(t,e,i){const{fragments:s}=this,r=Object.keys(s);for(let n=r.length;n--;){const a=s[r[n]];if((null==a?void 0:a.body.type)===e&&(!i||a.buffered)){const e=a.body;if(e.start<=t&&t<=e.end)return e}}return null}detectEvictedFragments(t,e,i,s,r,n){this.timeRanges&&(this.timeRanges[t]=e);const o=(null==r?void 0:r.fragment.sn)||-1;Object.keys(this.fragments).forEach(r=>{const l=this.fragments[r];if(!l||!this.hls)return;const h=l.body;if(o>=h.sn)return;if(!l.buffered&&(!l.loaded||n))return void(h.type===i&&this.removeFragment(h));const d=l.range[t];if(d)if(0!==d.time.length){if(d.time.some(t=>{const i=!this.isTimeBuffered(t.startPTS,t.endPTS,e);return i&&this.removeFragment(h),i}),s&&s!==h&&ne()){const t=s.endPTS,e=h.startPTS;if(t&&e&&l.range.video){const i=e-t;i<0&&i>-.1&&(this.removeFragment(h),this.hls.trigger(a.BUFFER_FLUSHING,{startOffset:t+.004,endOffset:1/0,type:"video"}))}}}else this.removeFragment(h)})}detectPartialFragments(t){const e=this.timeRanges,{frag:i,part:s,id:r}=t;if(!e||!y(i))return;const n=Bi(i),a=this.fragments[n];if(!a||a.buffered&&i.gap)return;const o=!i.relurl;Object.keys(e).forEach(t=>{const n=i.elementaryStreams[t];if(!n)return;const l=e[t],h=o||!0===n.partial;a.range[t]=this.getBufferedTimes(i,s,h,l),this.detectEvictedFragments(t,l,r,i,s)}),a.loaded=null;const l=Object.keys(a.range);if(l.length){if(this.bufferedEnd(a,i),$i(a)||this.removeParts(i.sn-1,i.type),!s){const t=Math.min(.004,i.duration);l.some(e=>{var s;const r=null==(s=a.range[e])?void 0:s.time,n=0===r.length||1===r.length&&r[0].endPTS-r[0].startPTS<t;return n&&this.addAsGap(i),n})}}else this.removeFragment(i)}addAsGap(t){t.gap=!0,this.removeFragment(t),this.fragBuffered(t,!0)}bufferedEnd(t,e){t.buffered=!0;(t.body.endList=e.endList||t.body.endList)&&!e.gap&&(this.endListFragments[t.body.type]=t)}removeParts(t,e){const i=this.activePartLists[e];i&&(this.activePartLists[e]=Ui(i,e=>e.fragment.sn>=t))}fragBuffered(t,e){const i=Bi(t);let s=this.fragments[i];return!s&&e&&(s=this.fragments[i]={body:t,appendedPTS:null,loaded:null,buffered:!1,range:Object.create(null)},t.gap&&(this.hasGaps=!0)),s&&(s.loaded=null,this.bufferedEnd(s,t)),s}getBufferedTimes(t,e,i,s){const r={time:[],partial:i},n=t.start,a=t.end,o=t.minEndPTS||a,l=t.maxStartPTS||n;for(let t=0;t<s.length;t++){const e=s.start(t)-this.bufferPadding,i=s.end(t)+this.bufferPadding;if(l>=e&&o<=i){r.time.push({startPTS:Math.max(n,s.start(t)),endPTS:Math.min(a,s.end(t))});break}if(n<i&&a>e){const e=Math.max(n,s.start(t)),i=Math.min(a,s.end(t));i>e&&(r.partial=!0,r.time.push({startPTS:e,endPTS:i}))}else if(a<=e)break}return r}getPartialFragment(t){let e,i,s,r=null,n=0;const{bufferPadding:a,fragments:o}=this;return Object.keys(o).forEach(l=>{const h=o[l];h&&$i(h)&&(i=h.body.start-a,s=h.body.end+a,t>=i&&t<=s&&(e=Math.min(t-i,s-t),n<=e&&(r=h.body,n=e)))}),r}isEndListAppended(t){const e=this.endListFragments[t];return void 0!==e&&(e.buffered||$i(e))}getState(t){const e=Bi(t),i=this.fragments[e];return i?i.buffered?$i(i)?Oi:Fi:Mi:xi}isTimeBuffered(t,e,i){let s,r;for(let n=0;n<i.length;n++){if(s=i.start(n)-this.bufferPadding,r=i.end(n)+this.bufferPadding,t>=s&&e<=r)return!0;if(e<=s)return!1}return!1}onManifestLoading(){this.removeAllFragments()}onFragLoaded(t,e){if(!y(e.frag)||e.frag.bitrateTest)return;const i=e.frag,s=e.part?null:e,r=Bi(i);this.fragments[r]={body:i,appendedPTS:null,loaded:s,buffered:!1,range:Object.create(null)}}onBufferAppended(t,e){const{frag:i,part:s,timeRanges:r}=e;if(!y(i))return;const n=i.type;if(s){let t=this.activePartLists[n];t||(this.activePartLists[n]=t=[]),t.push(s)}this.timeRanges=r}onFragBuffered(t,e){this.detectPartialFragments(e)}hasFragment(t){const e=Bi(t);return!!this.fragments[e]}hasFragments(t){const{fragments:e}=this,i=Object.keys(e);if(!t)return i.length>0;for(let s=i.length;s--;){const r=e[i[s]];if((null==r?void 0:r.body.type)===t)return!0}return!1}hasParts(t){var e;return!(null==(e=this.activePartLists[t])||!e.length)}getBackBufferEvictionEnd(t,e,i){const{fragments:s}=this;let r=0,n=0;const a=Object.keys(s);for(let o=0;o<a.length;o++){const l=s[a[o]];if(!l||!l.buffered||l.body.type!==e)continue;const h=l.body;if(h.gap)return 0;const d=h.hasStats&&h.stats.loaded||h.byteLength||h.bitrate&&8*h.bitrate*h.duration;if(h.end<=t&&d&&(r+=d,n=Math.max(n,h.end),r>=i))return n}return n>0?n:0}removeFragmentsInRange(t,e,i,s,r){s&&!this.hasGaps||Object.keys(this.fragments).forEach(n=>{const a=this.fragments[n];if(!a)return;const o=a.body;o.type!==i||s&&!o.gap||o.start<e&&o.end>t&&(a.buffered||r)&&this.removeFragment(o)})}removeFragment(t){const e=Bi(t);t.clearElementaryStreamInfo();const i=this.activePartLists[t.type];if(i){const e=t.sn;this.activePartLists[t.type]=Ui(i,t=>t.fragment.sn!==e)}delete this.fragments[e],t.endList&&delete this.endListFragments[t.type]}gapFragments(){return this.hasGaps?Object.keys(this.fragments).map(t=>{var e;return null==(e=this.fragments[t])?void 0:e.body}).filter(t=>!(null==t||!t.gap)):[]}removeAllFragments(){var t;this.fragments=Object.create(null),this.endListFragments=Object.create(null),this.activePartLists=Object.create(null),this.hasGaps=!1;const e=null==(t=this.hls)||null==(t=t.latestLevelDetails)?void 0:t.partList;e&&e.forEach(t=>t.clearElementaryStreamInfo())}}function $i(t){var e,i,s,r;return t.buffered&&!!(t.body.gap||null!=(e=t.range.video)&&e.partial||null!=(i=t.range.audio)&&i.partial||null!=(s=t.range.audiovideo)&&s.partial||null!=(r=t.range.subs)&&r.partial)}function Bi(t){return`${t.type}_${t.level}_${t.sn}`}function Ui(t,e){return t.filter(t=>{const i=e(t);return i||t.clearElementaryStreamInfo(),i})}var Gi=0,Ki=1;class Vi{constructor(t,e,i){this.subtle=void 0,this.aesIV=void 0,this.aesMode=void 0,this.subtle=t,this.aesIV=e,this.aesMode=i}decrypt(t,e){switch(this.aesMode){case Gi:return this.subtle.decrypt({name:"AES-CBC",iv:this.aesIV},e,t);case Ki:return this.subtle.decrypt({name:"AES-CTR",counter:this.aesIV,length:64},e,t);default:throw new Error(`[AESCrypto] invalid aes mode ${this.aesMode}`)}}}class ji{constructor(){this.rcon=[0,1,2,4,8,16,32,64,128,27,54],this.subMix=[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)],this.invSubMix=[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)],this.sBox=new Uint32Array(256),this.invSBox=new Uint32Array(256),this.key=new Uint32Array(0),this.ksRows=0,this.keySize=0,this.keySchedule=void 0,this.invKeySchedule=void 0,this.initTable()}uint8ArrayToUint32Array_(t){const e=new DataView(t),i=new Uint32Array(4);for(let t=0;t<4;t++)i[t]=e.getUint32(4*t);return i}initTable(){const t=this.sBox,e=this.invSBox,i=this.subMix,s=i[0],r=i[1],n=i[2],a=i[3],o=this.invSubMix,l=o[0],h=o[1],d=o[2],c=o[3],u=new Uint32Array(256);let f=0,g=0,m=0;for(m=0;m<256;m++)u[m]=m<128?m<<1:m<<1^283;for(m=0;m<256;m++){let i=g^g<<1^g<<2^g<<3^g<<4;i=i>>>8^255&i^99,t[f]=i,e[i]=f;const o=u[f],m=u[o],p=u[m];let v=257*u[i]^16843008*i;s[f]=v<<24|v>>>8,r[f]=v<<16|v>>>16,n[f]=v<<8|v>>>24,a[f]=v,v=16843009*p^65537*m^257*o^16843008*f,l[i]=v<<24|v>>>8,h[i]=v<<16|v>>>16,d[i]=v<<8|v>>>24,c[i]=v,f?(f=o^u[u[u[p^o]]],g^=u[u[g]]):f=g=1}}expandKey(t){const e=this.uint8ArrayToUint32Array_(t);let i=!0,s=0;for(;s<e.length&&i;)i=e[s]===this.key[s],s++;if(i)return;this.key=e;const r=this.keySize=e.length;if(4!==r&&6!==r&&8!==r)throw new Error("Invalid aes key size="+r);const n=this.ksRows=4*(r+6+1);let a,o;const l=this.keySchedule=new Uint32Array(n),h=this.invKeySchedule=new Uint32Array(n),d=this.sBox,c=this.rcon,u=this.invSubMix,f=u[0],g=u[1],m=u[2],p=u[3];let v,y;for(a=0;a<n;a++)a<r?v=l[a]=e[a]:(y=v,a%r===0?(y=y<<8|y>>>24,y=d[y>>>24]<<24|d[y>>>16&255]<<16|d[y>>>8&255]<<8|d[255&y],y^=c[a/r|0]<<24):r>6&&a%r===4&&(y=d[y>>>24]<<24|d[y>>>16&255]<<16|d[y>>>8&255]<<8|d[255&y]),l[a]=v=(l[a-r]^y)>>>0);for(o=0;o<n;o++)a=n-o,y=3&o?l[a]:l[a-4],h[o]=o<4||a<=4?y:f[d[y>>>24]]^g[d[y>>>16&255]]^m[d[y>>>8&255]]^p[d[255&y]],h[o]=h[o]>>>0}networkToHostOrderSwap(t){return t<<24|(65280&t)<<8|(16711680&t)>>8|t>>>24}decrypt(t,e,i){const s=this.keySize+6,r=this.invKeySchedule,n=this.invSBox,a=this.invSubMix,o=a[0],l=a[1],h=a[2],d=a[3],c=this.uint8ArrayToUint32Array_(i);let u=c[0],f=c[1],g=c[2],m=c[3];const p=new Int32Array(t),v=new Int32Array(p.length);let y,E,T,S,b,A,L,I,R,k,_,D,w,P;const C=this.networkToHostOrderSwap;for(;e<p.length;){for(R=C(p[e]),k=C(p[e+1]),_=C(p[e+2]),D=C(p[e+3]),b=R^r[0],A=D^r[1],L=_^r[2],I=k^r[3],w=4,P=1;P<s;P++)y=o[b>>>24]^l[A>>16&255]^h[L>>8&255]^d[255&I]^r[w],E=o[A>>>24]^l[L>>16&255]^h[I>>8&255]^d[255&b]^r[w+1],T=o[L>>>24]^l[I>>16&255]^h[b>>8&255]^d[255&A]^r[w+2],S=o[I>>>24]^l[b>>16&255]^h[A>>8&255]^d[255&L]^r[w+3],b=y,A=E,L=T,I=S,w+=4;y=n[b>>>24]<<24^n[A>>16&255]<<16^n[L>>8&255]<<8^n[255&I]^r[w],E=n[A>>>24]<<24^n[L>>16&255]<<16^n[I>>8&255]<<8^n[255&b]^r[w+1],T=n[L>>>24]<<24^n[I>>16&255]<<16^n[b>>8&255]<<8^n[255&A]^r[w+2],S=n[I>>>24]<<24^n[b>>16&255]<<16^n[A>>8&255]<<8^n[255&L]^r[w+3],v[e]=C(y^u),v[e+1]=C(S^f),v[e+2]=C(T^g),v[e+3]=C(E^m),u=R,f=k,g=_,m=D,e+=4}return v.buffer}}class Hi{constructor(t,e,i){this.subtle=void 0,this.key=void 0,this.aesMode=void 0,this.subtle=t,this.key=e,this.aesMode=i}expandKey(){const t=function(t){switch(t){case Gi:return"AES-CBC";case Ki:return"AES-CTR";default:throw new Error(`[FastAESKey] invalid aes mode ${t}`)}}(this.aesMode);return this.subtle.importKey("raw",this.key,{name:t},!1,["encrypt","decrypt"])}}class qi{constructor(t,e){if(this.logEnabled=!0,this.decryptRange=void 0,this.subtle=null,this.softwareDecrypter=null,this.key=null,this.fastAesKey=null,this.remainderData=null,this.currentIV=null,this.currentResult=null,this.useSoftware=void 0,this.enableSoftwareAES=void 0,this.enableSoftwareAES=t.enableSoftwareAES,!0!==e)try{const t=self.crypto;t&&(this.subtle=t.subtle||t.webkitSubtle)}catch(t){}this.useSoftware=!this.subtle}destroy(){this.subtle=null,this.softwareDecrypter=null,this.key=null,this.fastAesKey=null,this.remainderData=null,this.currentIV=null,this.currentResult=null}isSync(){return this.useSoftware}flush(){const{currentResult:t,remainderData:e}=this;if(!t||e)return this.reset(),null;const i=new Uint8Array(t);this.reset();const s=this.decryptRange;return s?0===s.start&&s.end>=i.length?i:i.slice(s.start,s.end):function(t){const e=t.byteLength,i=e&&new DataView(t.buffer).getUint8(e-1);return i?t.slice(0,e-i):t}(i)}reset(){this.currentResult=null,this.currentIV=null,this.remainderData=null,this.softwareDecrypter&&(this.softwareDecrypter=null)}decrypt(t,e,i,s,r){return this.decryptRange=r,this.useSoftware||r?new Promise((r,n)=>{const a=ArrayBuffer.isView(t)?t:new Uint8Array(t);this.softwareDecrypt(a,e,i,s);const o=this.flush();o?r(o.buffer):n(new Error("[softwareDecrypt] Failed to decrypt data"))}):this.webCryptoDecrypt(new Uint8Array(t),e,i,s)}softwareDecrypt(t,e,i,s){const{currentIV:r,currentResult:n,remainderData:a}=this;if(s!==Gi||16!==e.byteLength)return q.warn("SoftwareDecrypt: can only handle AES-128-CBC"),null;this.logOnce("JS AES decrypt"),a&&(t=Ht(a,t),this.remainderData=null);const o=this.getValidChunk(t);if(!o.length)return null;r&&(i=r);let l=this.softwareDecrypter;l||(l=this.softwareDecrypter=new ji),l.expandKey(e);const h=n;return this.currentResult=l.decrypt(o.buffer,0,i),this.currentIV=o.slice(-16).buffer,h||null}webCryptoDecrypt(t,e,i,s){if(this.key!==e||!this.fastAesKey){if(!this.subtle)return Promise.resolve(this.onWebCryptoError(t,e,i,s));this.key=e,this.fastAesKey=new Hi(this.subtle,e,s)}return this.fastAesKey.expandKey().then(e=>{if(!this.subtle)return Promise.reject(new Error("web crypto not initialized"));this.logOnce("WebCrypto AES decrypt");return new Vi(this.subtle,new Uint8Array(i),s).decrypt(t.buffer,e)}).catch(r=>(q.warn(`[decrypter]: WebCrypto Error, disable WebCrypto API, ${r.name}: ${r.message}`),this.onWebCryptoError(t,e,i,s)))}onWebCryptoError(t,e,i,s){const r=this.enableSoftwareAES;if(r){this.useSoftware=!0,this.logEnabled=!0,this.softwareDecrypt(t,e,i,s);const r=this.flush();if(r)return r.buffer}throw new Error("WebCrypto"+(r?" and softwareDecrypt":"")+": failed to decrypt data")}getValidChunk(t){let e=t;const i=t.length-t.length%16;return i!==t.length&&(e=t.slice(0,i),this.remainderData=t.slice(i)),e}logOnce(t){this.logEnabled&&(q.log(`[decrypter]: ${t}`),this.logEnabled=!1)}}const Yi=Math.pow(2,17);class Wi{constructor(t){this.config=void 0,this.loader=null,this.partLoadTimeout=-1,this.config=t}destroy(){this.loader&&(this.loader.destroy(),this.loader=null)}abort(){this.loader&&this.loader.abort()}load(t,e,i,s){const a=t.url;if(!a)return Promise.reject(new Zi({type:r.NETWORK_ERROR,details:n.FRAG_LOAD_ERROR,fatal:!1,frag:t,error:new Error("Fragment does not have a "+(a?"part list":"url")),networkDetails:null}));this.abort();const o=this.config,l=o.fLoader,h=o.loader;return new Promise((d,c)=>{if(this.loader&&this.loader.destroy(),t.gap){if(t.tagList.some(t=>"GAP"===t[0]))return void c(Qi(t));t.gap=!1}const u=this.loader=l?new l(o):new h(o),f=zi(t,null,e);t.loader=u;const g=M(o.fragLoadPolicy.default),m={loadPolicy:g,timeout:g.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:"initSegment"===t.sn?1/0:Yi};u.stats.retry=t.stats.retry,t.stats=u.stats;const p={onSuccess:(e,i,s,r)=>{this.resetLoader(t,u);let n=e.data;s.resetIV&&t.decryptdata&&(t.decryptdata.iv=new Uint8Array(n.slice(0,16)),n=n.slice(16)),d({frag:t,part:null,payload:n,networkDetails:r})},onError:(e,i,s,o)=>{this.resetLoader(t,u),c(new Zi({type:r.NETWORK_ERROR,details:n.FRAG_LOAD_ERROR,fatal:!1,frag:t,response:k({url:a,data:void 0},e),error:new Error(`HTTP Error ${e.code} ${e.text}`),networkDetails:s,stats:o}))},onAbort:(e,i,s)=>{this.resetLoader(t,u),c(new Zi({type:r.NETWORK_ERROR,details:n.INTERNAL_ABORTED,fatal:!1,frag:t,error:new Error("Aborted"),networkDetails:s,stats:e}))},onTimeout:(e,i,s)=>{this.resetLoader(t,u),c(new Zi({type:r.NETWORK_ERROR,details:n.FRAG_LOAD_TIMEOUT,fatal:!1,frag:t,error:new Error(`Timeout after ${m.timeout}ms`),networkDetails:s,stats:e}))}};if(i){const e=this.gateProgress(i,s);p.onProgress=(i,s,r,n)=>e({frag:t,part:null,payload:r,networkDetails:n})}u.load(f,m,p)})}gateProgress(t,e){let i=t;if(e){const s=[];let r=!1;e.then(()=>{r=!0,s.forEach(e=>t(e)),s.length=0}).catch(()=>{}),i=e=>{r?t(e):s.push(e)}}return i}loadPart(t,e,i){this.abort();const s=this.config,a=s.fLoader,o=s.loader;return new Promise((l,h)=>{if(this.loader&&this.loader.destroy(),t.gap||e.gap)return void h(Qi(t,e));const d=this.loader=a?new a(s):new o(s),c=zi(t,e);t.loader=d;const u=M(s.fragLoadPolicy.default),f={loadPolicy:u,timeout:u.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:Yi};e.stats=d.stats,d.load(c,f,{onSuccess:(s,r,n,a)=>{this.resetLoader(t,d),this.updateStatsFromPart(t,e);const o={frag:t,part:e,payload:s.data,networkDetails:a};i(o),l(o)},onError:(i,s,a,o)=>{this.resetLoader(t,d),h(new Zi({type:r.NETWORK_ERROR,details:n.FRAG_LOAD_ERROR,fatal:!1,frag:t,part:e,response:k({url:c.url,data:void 0},i),error:new Error(`HTTP Error ${i.code} ${i.text}`),networkDetails:a,stats:o}))},onAbort:(i,s,a)=>{t.stats.aborted=e.stats.aborted,this.resetLoader(t,d),h(new Zi({type:r.NETWORK_ERROR,details:n.INTERNAL_ABORTED,fatal:!1,frag:t,part:e,error:new Error("Aborted"),networkDetails:a,stats:i}))},onTimeout:(i,s,a)=>{this.resetLoader(t,d),h(new Zi({type:r.NETWORK_ERROR,details:n.FRAG_LOAD_TIMEOUT,fatal:!1,frag:t,part:e,error:new Error(`Timeout after ${f.timeout}ms`),networkDetails:a,stats:i}))}})})}updateStatsFromPart(t,e){const i=t.stats,s=e.stats,r=s.total;if(i.loaded+=s.loaded,r){const s=Math.round(t.duration/e.duration),n=Math.min(Math.round(i.loaded/r),s),a=(s-n)*Math.round(i.loaded/n);i.total=i.loaded+a}else i.total=Math.max(i.loaded,i.total);const n=i.loading,a=s.loading;n.start?n.first+=a.first-a.start:(n.start=a.start,n.first=a.first),n.end=a.end}resetLoader(t,e){t.loader=null,t.url=null,this.loader===e&&(self.clearTimeout(this.partLoadTimeout),this.loader=null),e.destroy()}}function zi(t,e=null,i){const s=e||t,r={type:u.MEDIA_FRAGMENT,frag:t,part:e,responseType:"arraybuffer",url:s.url,headers:{},rangeStart:0,rangeEnd:0},n=Xi(t,e,i);return n.resetIV&&(r.resetIV=!0),n.byteRange&&(r.rangeStart=n.byteRange.start,r.rangeEnd=n.byteRange.end),r}function Xi(t,i=null,s){const r={},n=i||t,a=n.byteRangeStartOffset,o=n.byteRangeEndOffset;var l,h;if(e(a)&&e(o))if("initSegment"!==t.sn&&!s||"AES-128"!==(h=null==(l=t.decryptdata)?void 0:l.method)&&"AES-256"!==h)r.byteRange={start:a,end:o};else{let t=16*Math.floor(a/16);const e=16*Math.ceil(o/16);r.decryptRange={start:a-t,end:o-t},t>=16&&(r.resetIV=!0,t-=16),r.byteRange={start:t,end:e}}return r}function Qi(t,e){const i=new Error(`GAP ${t.gap?"tag":"attribute"} found`),s={type:r.MEDIA_ERROR,details:n.FRAG_GAP,fatal:!1,frag:t,error:i,networkDetails:null};return e&&(s.part=e),(e||t).stats.aborted=!0,new Zi(s)}class Zi extends Error{constructor(t){super(t.error.message),this.data=void 0,this.data=t}}class Ji extends U{constructor(t,e){super(t,e),this._boundTick=void 0,this._tickTimer=null,this._tickInterval=null,this._tickCallCount=0,this._boundTick=this.tick.bind(this)}destroy(){this.onHandlerDestroying(),this.onHandlerDestroyed()}onHandlerDestroying(){this.clearNextTick(),this.clearInterval()}onHandlerDestroyed(){}hasInterval(){return!!this._tickInterval}hasNextTick(){return!!this._tickTimer}setInterval(t){return!this._tickInterval&&(this._tickCallCount=0,this._tickInterval=self.setInterval(this._boundTick,t),!0)}clearInterval(){return!!this._tickInterval&&(self.clearInterval(this._tickInterval),this._tickInterval=null,!0)}clearNextTick(){return!!this._tickTimer&&(self.clearTimeout(this._tickTimer),this._tickTimer=null,!0)}tick(){this._tickCallCount++,1===this._tickCallCount?(this.doTick(),this._tickCallCount>1&&this.tickImmediate(),this._tickCallCount=0):(this.log(`possible exception thrown in task-loop (${this.constructor.name}.doTick)`),this._tickCallCount=0)}tickImmediate(){this.clearNextTick(),this._tickTimer=self.setTimeout(this._boundTick,0)}doTick(){}}class ts{constructor(t,e,i,s=0,r=-1,n=!1,a,o,l){this.level=void 0,this.sn=void 0,this.part=void 0,this.id=void 0,this.size=void 0,this.partial=void 0,this.iframe=void 0,this.duration=void 0,this.decryptRange=void 0,this.transmuxing={start:0,executeStart:0,executeEnd:0,end:0},this.buffering={audio:{start:0,executeStart:0,executeEnd:0,end:0},video:{start:0,executeStart:0,executeEnd:0,end:0},audiovideo:{start:0,executeStart:0,executeEnd:0,end:0}},this.level=t,this.sn=e,this.id=i,this.size=s,this.part=r,this.partial=n,this.duration=a||0,this.decryptRange=l,this.iframe=o||!1}}const es=/\{\$([a-zA-Z0-9-_]+)\}/g;function is(t){return es.lastIndex=0,es.test(t)}function ss(t,e){if(null!==t.variableList||t.hasVariableRefs){const i=t.variableList;return e.replace(es,e=>{const s=e.substring(2,e.length-1),r=null==i?void 0:i[s];return void 0===r?(t.playlistParsingError||(t.playlistParsingError=new Error(`Missing preceding EXT-X-DEFINE tag for Variable Reference: "${s}"`)),e):r})}return e}function rs(t,e,i){let s,r,n=t.variableList;if(n||(t.variableList=n={}),"QUERYPARAM"in e){s=e.QUERYPARAM;try{const t=new self.URL(i).searchParams;if(!t.has(s))throw new Error(`"${s}" does not match any query parameter in URI: "${i}"`);r=t.get(s)}catch(e){t.playlistParsingError||(t.playlistParsingError=new Error(`EXT-X-DEFINE QUERYPARAM: ${e.message}`))}}else s=e.NAME,r=e.VALUE;s in n?t.playlistParsingError||(t.playlistParsingError=new Error(`EXT-X-DEFINE duplicate Variable Name declarations: "${s}"`)):n[s]=r||""}function ns(t,e,i){const s=e.IMPORT;if(i&&s in i){let e=t.variableList;e||(t.variableList=e={}),e[s]=i[s]}else t.playlistParsingError||(t.playlistParsingError=new Error(`EXT-X-DEFINE IMPORT attribute not found in Multivariant Playlist: "${s}"`))}const as=/^(\d+)x(\d+)$/,os=/(.+?)=(".*?"|.*?)(?:,|$)/g;class ls{constructor(t,e){"string"==typeof t&&(t=ls.parseAttrList(t,e)),I(this,t)}get clientAttrs(){return Object.keys(this).filter(t=>"X-"===t.substring(0,2))}decimalInteger(t){const e=parseInt(this[t],10);return e>Number.MAX_SAFE_INTEGER?1/0:e}hexadecimalInteger(t){if(this[t]){let e=(this[t]||"0x").slice(2);e=(1&e.length?"0":"")+e;const i=new Uint8Array(e.length/2);for(let t=0;t<e.length/2;t++)i[t]=parseInt(e.slice(2*t,2*t+2),16);return i}return null}hexadecimalIntegerAsNumber(t){const e=parseInt(this[t],16);return e>Number.MAX_SAFE_INTEGER?1/0:e}decimalFloatingPoint(t){return parseFloat(this[t])}optionalFloat(t,e){const i=this[t];return i?parseFloat(i):e}enumeratedString(t){return this[t]}enumeratedStringList(t,e){const i=this[t];return(i?i.split(/[ ,]+/):[]).reduce((t,e)=>(t[e.toLowerCase()]=!0,t),e)}bool(t){return"YES"===this[t]}decimalResolution(t){const e=as.exec(this[t]);if(null!==e)return{width:parseInt(e[1],10),height:parseInt(e[2],10)}}static parseAttrList(t,e){let i;const s={};for(os.lastIndex=0;null!==(i=os.exec(t));){const r=i[1].trim();let n=i[2];const a=0===n.indexOf('"')&&n.lastIndexOf('"')===n.length-1;let o=!1;if(a)n=n.slice(1,-1);else switch(r){case"IV":case"SCTE35-CMD":case"SCTE35-IN":case"SCTE35-OUT":o=!0}if(e&&(a||o))n=ss(e,n);else if(!o&&!a)switch(r){case"CLOSED-CAPTIONS":if("NONE"===n)break;case"ALLOWED-CPC":case"CLASS":case"ASSOC-LANGUAGE":case"AUDIO":case"BYTERANGE":case"CHANNELS":case"CHARACTERISTICS":case"CODECS":case"DATA-ID":case"END-DATE":case"GROUP-ID":case"ID":case"IMPORT":case"INSTREAM-ID":case"KEYFORMAT":case"KEYFORMATVERSIONS":case"LANGUAGE":case"NAME":case"PATHWAY-ID":case"QUERYPARAM":case"RECENTLY-REMOVED-DATERANGES":case"SERVER-URI":case"STABLE-RENDITION-ID":case"STABLE-VARIANT-ID":case"START-DATE":case"SUBTITLES":case"SUPPLEMENTAL-CODECS":case"URI":case"VALUE":case"VIDEO":case"X-ASSET-LIST":case"X-ASSET-URI":q.warn(`${t}: attribute ${r} is missing quotes`)}s[r]=n}return s}}function hs(t){return"ID"!==t&&"CLASS"!==t&&"CUE"!==t&&"START-DATE"!==t&&"DURATION"!==t&&"END-DATE"!==t&&"END-ON-NEXT"!==t}function ds(t){return"SCTE35-OUT"===t||"SCTE35-IN"===t||"SCTE35-CMD"===t}class cs{constructor(t,i,s=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=(null==i?void 0:i.tagAnchor)||null,this.tagOrder=null!=(r=null==i?void 0:i.tagOrder)?r:s,i){const e=i.attr;for(const i in e)if(Object.prototype.hasOwnProperty.call(t,i)&&t[i]!==e[i]){q.warn(`DATERANGE tag attribute: "${i}" does not match for tags with ID: "${t.ID}"`),this._badValueForSameId=i;break}t=I(new ls({}),e,t)}if(this.attr=t,i?(this._startDate=i._startDate,this._cue=i._cue,this._endDate=i._endDate,this._dateAtEnd=i._dateAtEnd):this._startDate=new Date(t["START-DATE"]),"END-DATE"in t){const s=(null==i?void 0:i.endDate)||new Date(t["END-DATE"]);e(s.getTime())&&(this._endDate=s)}}get id(){return this.attr.ID}get class(){return this.attr.CLASS}get cue(){const t=this._cue;return void 0===t?this._cue=this.attr.enumeratedStringList(this.attr.CUE?"CUE":"X-CUE",{pre:!1,post:!1,once:!1}):t}get startTime(){const{tagAnchor:t}=this;return null===t||null===t.programDateTime?(q.warn(`Expected tagAnchor Fragment with PDT set for DateRange "${this.id}": ${t}`),NaN):t.start+(this.startDate.getTime()-t.programDateTime)/1e3}get startDate(){return this._startDate}get endDate(){const t=this._endDate||this._dateAtEnd;if(t)return t;const e=this.duration;return null!==e?this._dateAtEnd=new Date(this._startDate.getTime()+1e3*e):null}get duration(){if("DURATION"in this.attr){const t=this.attr.decimalFloatingPoint("DURATION");if(e(t))return t}else if(this._endDate)return(this._endDate.getTime()-this._startDate.getTime())/1e3;return null}get plannedDuration(){return"PLANNED-DURATION"in this.attr?this.attr.decimalFloatingPoint("PLANNED-DURATION"):null}get endOnNext(){return this.attr.bool("END-ON-NEXT")}get isInterstitial(){return"com.apple.hls.interstitial"===this.class}get isValid(){return!!this.id&&!this._badValueForSameId&&e(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)}get invalidReason(){return this.id?this._badValueForSameId?`Date range ${this._badValueForSameId} mismatch`:e(this.startDate.getTime())?!this.isInterstitial||"X-ASSET-URI"in this.attr||"X-ASSET-LIST"in this.attr?this.isValid?null:"Unknown (check DURATION(|END|NEXT), CLASS, and CUE)":"Interstitial Date range missing X-ASSET-(LIST|URI)":"Date range invalid start date":"Missing ID"}}function us(t,e){return t.length===e.length&&!t.some((t,i)=>t!==e[i])}function fs(t,e){return!t&&!e||!(!t||!e)&&us(t,e)}function gs(t){return"AES-128"===t||"AES-256"===t||"AES-256-CTR"===t}function ms(t){switch(t){case"AES-128":case"AES-256":return Gi;case"AES-256-CTR":return Ki;default:throw new Error(`invalid full segment method ${t}`)}}function ps(t){return Uint8Array.from(unescape(encodeURIComponent(t)),t=>t.charCodeAt(0))}function vs(t){const e=function(t,e,i){const s=t[e];t[e]=t[i],t[i]=s};e(t,0,3),e(t,1,2),e(t,4,5),e(t,6,7)}function ys(t){const e=t.split(":");let i=null;if("data"===e[0]&&2===e.length){const t=e[1].split(";"),s=t[t.length-1].split(",");if(2===s.length){const e="base64"===s[0],r=s[1];e?(t.splice(-1,1),i=vt(r)):i=function(t){const e=ps(t).subarray(0,16),i=new Uint8Array(16);return i.set(e,16-e.length),i}(r)}}return i}const Es="undefined"!=typeof self?self:void 0;var Ts={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.fps",PLAYREADY:"com.microsoft.playready",WIDEVINE:"com.widevine.alpha"},Ss="org.w3.clearkey",bs="com.apple.streamingkeydelivery",As="com.microsoft.playready",Ls="urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed";function Is(t){switch(t){case bs:return Ts.FAIRPLAY;case As:return Ts.PLAYREADY;case Ls:return Ts.WIDEVINE;case Ss:return Ts.CLEARKEY}}var Rs="edef8ba979d64acea3c827dcd51d21ed";function ks(t){switch(t){case Ts.FAIRPLAY:return bs;case Ts.PLAYREADY:return As;case Ts.WIDEVINE:return Ls;case Ts.CLEARKEY:return Ss}}function _s(t){const{drmSystems:e,widevineLicenseUrl:i}=t,s=e?[Ts.FAIRPLAY,Ts.WIDEVINE,Ts.PLAYREADY,Ts.CLEARKEY].filter(t=>!!e[t]):[];return!s[Ts.WIDEVINE]&&i&&s.push(Ts.WIDEVINE),s}const Ds=null!=Es&&null!=(ws=Es.navigator)&&ws.requestMediaKeySystemAccess?self.navigator.requestMediaKeySystemAccess.bind(self.navigator):null;var ws;function Ps(t){const e=yt(new Uint16Array(t.buffer,t.byteOffset,t.byteLength/2)),i=e.substring(e.indexOf("<"),e.length),s=(new DOMParser).parseFromString(i,"text/xml").getElementsByTagName("KID")[0];if(s){const t=s.childNodes[0]?s.childNodes[0].nodeValue:s.getAttribute("VALUE");if(t){const e=vt(t).subarray(0,16);return vs(e),e}}return null}let Cs={};class xs{static clearKeyUriToKeyIdMap(){Cs={}}static setKeyIdForUri(t,e){Cs[t]=e}static addKeyIdForUri(t){const e=Object.keys(Cs).length%Number.MAX_SAFE_INTEGER,i=new Uint8Array(16);return new DataView(i.buffer,12,4).setUint32(0,e),Cs[t]=i,i}constructor(t,e,i,s=[1],r=null,n){this.uri=void 0,this.method=void 0,this.keyFormat=void 0,this.keyFormatVersions=void 0,this.encrypted=void 0,this.isCommonEncryption=void 0,this.iv=null,this.key=null,this.keyId=null,this.pssh=null,this.scheme=void 0,this.method=t,this.uri=e,this.keyFormat=i,this.keyFormatVersions=s,this.iv=r,this.encrypted=!!t&&"NONE"!==t,this.isCommonEncryption=this.encrypted&&!gs(t),null!=n&&n.startsWith("0x")&&(this.keyId=new Uint8Array(pt(n)))}matches(t){return t.uri===this.uri&&t.method===this.method&&t.encrypted===this.encrypted&&t.keyFormat===this.keyFormat&&us(t.keyFormatVersions,this.keyFormatVersions)&&fs(t.iv,this.iv)&&fs(t.keyId,this.keyId)}isSupported(){if(this.method){if(gs(this.method)||"NONE"===this.method)return!0;if("identity"===this.keyFormat)return"SAMPLE-AES"===this.method;switch(this.keyFormat){case bs:case Ls:case As:case Ss:return-1!==["SAMPLE-AES","SAMPLE-AES-CENC","SAMPLE-AES-CTR"].indexOf(this.method)}}return!1}getDecryptData(t,e){var i;if(!this.encrypted||!this.uri)return null;if(gs(this.method)){let e=this.iv;e||("number"!=typeof t&&(q.warn(`missing IV for initialization segment with method="${this.method}" - compliance issue`),t=0),e=function(t){const e=new Uint8Array(16);for(let i=12;i<16;i++)e[i]=t>>8*(15-i)&255;return e}(t));return new xs(this.method,this.uri,"identity",this.keyFormatVersions,e)}if(this.keyId){const t=Cs[this.uri];if(t&&!us(this.keyId,t)&&xs.setKeyIdForUri(this.uri,this.keyId),this.pssh)return this}const s=ys(this.uri);if(s)switch(this.keyFormat){case Ls:if(this.pssh=s,!this.keyId){const t=Qt(s.buffer).filter(t=>t.systemId===Rs);if(t.length){var r;const e=t[0];this.keyId=null!=(r=e.kids)&&r.length?e.kids[0]:null}}this.keyId||(this.keyId=Ms(e));break;case As:{const t=new Uint8Array([154,4,240,121,152,64,66,134,171,146,230,91,224,136,95,149]);this.pssh=Xt(t,0,s),this.keyId=Ps(s);break}default:{let t=s.subarray(0,16);if(16!==t.length){const e=new Uint8Array(16);e.set(t,16-t.length),t=e}this.keyId=t;break}}if(16!==(null==(i=this.keyId)?void 0:i.byteLength)){let t;t=function(t){const e=null==t?void 0:t[Ls];if(e)return e.keyId;return null}(e),t||(t=Ms(e),t||(t=Cs[this.uri])),t&&(this.keyId=t,xs.setKeyIdForUri(this.uri,t))}return this}}function Ms(t){const e=null==t?void 0:t[As];if(e){const t=ys(e.uri);if(t)return Ps(t)}return null}const Os=/#EXT-X-STREAM-INF:([^\r\n]*)(?:[\r\n](?:#[^\r\n]*)?)*([^\r\n]+)|#EXT-X-(I-FRAME-STREAM-INF|SESSION-DATA|SESSION-KEY|DEFINE|CONTENT-STEERING|START):([^\r\n]*)(?:[\r\n]+|$)/g,Fs=/#EXT-X-MEDIA:(.*)/g,Ns=/^#EXT(?:INF|-X-TARGETDURATION):/m,$s=new RegExp([/#EXTINF:\s*(\d+(?:\.\d*)?|\.\d+)?(?:,(.*)\s+)?/.source,/(?!#) *(\S[^\r\n]*)/.source,/#.*/.source].join("|"),"g"),Bs=new RegExp([/#EXT-X-(PROGRAM-DATE-TIME|BYTERANGE|DATERANGE|DEFINE|KEY|MAP|PART|PART-INF|PLAYLIST-TYPE|PRELOAD-HINT|RENDITION-REPORT|SERVER-CONTROL|SKIP|START):(.+)/.source,/#EXT-X-(BITRATE|DISCONTINUITY-SEQUENCE|MEDIA-SEQUENCE|TARGETDURATION|VERSION): *(\d+)/.source,/#EXT-X-(DISCONTINUITY|ENDLIST|GAP|INDEPENDENT-SEGMENTS|I-FRAMES-ONLY)/.source,/(#)([^:]*):(.*)/.source,/(#)(.*)(?:.*)\r?\n?/.source].join("|"));class Us{static findGroup(t,e){for(let i=0;i<t.length;i++){const s=t[i];if(s.id===e)return s}}static resolve(t,e){return d.buildAbsoluteURL(e,t,{alwaysNormalize:!0})}static isMediaPlaylist(t){return Ns.test(t)}static parseMasterPlaylist(t,e){const i={contentSteering:null,levels:[],iframeVariants:[],playlistParsingError:null,sessionData:null,sessionKeys:null,startTimeOffset:null,variableList:null,hasVariableRefs:is(t)},s=[];if(Os.lastIndex=0,!t.startsWith("#EXTM3U"))return i.playlistParsingError=new Error("no EXTM3U delimiter"),i;let r;for(;null!=(r=Os.exec(t));)if(r[1]){const t=Gs(new ls(r[1],i),r[2],e,i,s);t&&i.levels.push(t)}else if(r[3]){const t=r[3],n=r[4];switch(t){case"I-FRAME-STREAM-INF":{const t=new ls(n,i),r=Gs(t,t.URI,e,i,s,!0);r&&i.iframeVariants.push(r)}break;case"SESSION-DATA":{const t=new ls(n,i),e=t["DATA-ID"];e&&(null===i.sessionData&&(i.sessionData={}),i.sessionData[e]=t);break}case"SESSION-KEY":{const t=js(n,e,i);t.encrypted&&t.isSupported()?(null===i.sessionKeys&&(i.sessionKeys=[]),i.sessionKeys.push(t)):q.warn(`[Keys] Ignoring invalid EXT-X-SESSION-KEY tag: "${n}"`);break}case"DEFINE":rs(i,new ls(n,i),e);break;case"CONTENT-STEERING":{const t=new ls(n,i);i.contentSteering={uri:Us.resolve(t["SERVER-URI"],e),pathwayId:t["PATHWAY-ID"]||"."};break}case"START":i.startTimeOffset=Hs(n)}}const n=s.length>0&&s.length<i.levels.length;return i.levels=n?s:i.levels,0===i.levels.length&&(i.playlistParsingError=new Error("no levels found in manifest")),i}static parseMasterPlaylistMedia(t,e,i){let s;const r={},n=i.levels,a={AUDIO:n.map(t=>({id:t.attrs.AUDIO,audioCodec:t.audioCodec})),SUBTITLES:n.map(t=>({id:t.attrs.SUBTITLES,textCodec:t.textCodec})),"CLOSED-CAPTIONS":[]};let o=0;for(Fs.lastIndex=0;null!==(s=Fs.exec(t));){const t=new ls(s[1],i),n=t.TYPE;if(n){const i=a[n],s=r[n]||[];r[n]=s;const l=t.LANGUAGE,h=t["ASSOC-LANGUAGE"],d=t.CHANNELS,c=t.CHARACTERISTICS,u=t["INSTREAM-ID"],f={attrs:t,bitrate:0,id:o++,groupId:t["GROUP-ID"]||"",name:t.NAME||l||"",type:n,default:t.bool("DEFAULT"),autoselect:t.bool("AUTOSELECT"),forced:t.bool("FORCED"),lang:l,url:t.URI?Us.resolve(t.URI,e):""};if(h&&(f.assocLang=h),d&&(f.channels=d),c&&(f.characteristics=c),u&&(f.instreamId=u),null!=i&&i.length){const t=Us.findGroup(i,f.groupId)||i[0];Ys(f,t,"audioCodec"),Ys(f,t,"textCodec")}s.push(f)}}return r}static parseLevelPlaylist(t,i,s,r,n,a){var o;const l={url:i},h=new vi(i),d=h.fragments,c=[];let u,f,g,m,p=null,v=0,y=0,E=0,T=0,A=0,L=null,R=new S(r,l),k=-1,_=!1,D=null;if($s.lastIndex=0,h.m3u8=t,h.hasVariableRefs=is(t),"#EXTM3U"!==(null==(o=$s.exec(t))?void 0:o[0]))return h.playlistParsingError=new Error("Missing format identifier #EXTM3U"),h;for(;null!==(u=$s.exec(t));){_&&(_=!1,R=new S(r,l),R.playlistOffset=E,R.setStart(E),R.sn=v,R.cc=T,A&&(R.bitrate=A),R.level=s,p&&(R.initSegment=p,p.rawProgramDateTime&&(R.rawProgramDateTime=p.rawProgramDateTime,p.rawProgramDateTime=null),D&&(R.setByteRange(D),D=null)));const t=u[1];if(t){R.duration=parseFloat(t);const e=(" "+u[2]).slice(1);R.title=e||null,R.tagList.push(e?["INF",t,e]:["INF",t])}else if(u[3]){if(e(R.duration)){var w;R.playlistOffset=E,R.setStart(E),g&&Xs(R,g,h),R.sn=v,R.level=s,R.cc=T;const t=(" "+u[3]).slice(1);R.relurl=ss(h,t),Ws(R,L,c),L=R,E+=R.duration,v++,y=0;const e=R.byteRange;if(2===e.length&&(R.bitrate=8*(e[1]-e[0])/R.duration|0),h.iframesOnly&&e[0]&&(null==(w=p)?void 0:w.cc)!==T){const t=new S(r,l);t.relurl=R.relurl,t.setByteRange(`${Math.min(e[0],1316)}@0`),t.level=s,t.sn="initSegment",g&&(t.levelkeys=g,g.identity&&(t._decryptdata=g.identity.getDecryptData(0))),p=t,R.initSegment=p}d.push(R),_=!0}}else{if(u=u[0].match(Bs),!u){q.warn("No matches on slow regex match for level playlist!");continue}for(f=1;f<u.length&&void 0===u[f];f++);const t=(" "+u[f]).slice(1),n=(" "+u[f+1]).slice(1),o=u[f+2]?(" "+u[f+2]).slice(1):null;switch(t){case"BYTERANGE":L?R.setByteRange(n,L):R.setByteRange(n);break;case"PROGRAM-DATE-TIME":R.rawProgramDateTime=n,R.tagList.push(["PROGRAM-DATE-TIME",n]),-1===k&&(k=d.length);break;case"PLAYLIST-TYPE":h.type&&Qs(h,t,u),h.type=n.toUpperCase();break;case"MEDIA-SEQUENCE":0!==h.startSN?Qs(h,t,u):null!==L&&Zs(h,t,u),h.startSN=parseInt(n),v=h.startSN+h.skippedSegments;break;case"SKIP":{h.skippedSegments&&Qs(h,t,u);const i=new ls(n,h),s=i.decimalInteger("SKIPPED-SEGMENTS");if(e(s)){h.skippedSegments+=s;for(let t=s;t--;)d.push(null);v+=s}const r=i.enumeratedString("RECENTLY-REMOVED-DATERANGES");r&&(h.recentlyRemovedDateranges=(h.recentlyRemovedDateranges||[]).concat(r.split("\t")));break}case"TARGETDURATION":0!==h.targetduration&&Qs(h,t,u),h.targetduration=Math.max(parseInt(n),1);break;case"VERSION":null!==h.version&&Qs(h,t,u),h.version=parseInt(n);break;case"INDEPENDENT-SEGMENTS":break;case"I-FRAMES-ONLY":h.iframesOnly=!0;break;case"ENDLIST":h.live||Qs(h,t,u),h.live=!1;break;case"#":(n||o)&&R.tagList.push(o?[n,o]:[n]);break;case"DISCONTINUITY":T++,R.tagList.push(["DIS"]);break;case"GAP":R.gap=!0,R.tagList.push([t]);break;case"BITRATE":R.tagList.push([t,n]),A=1e3*parseInt(n),e(A)?R.bitrate=A:A=0;break;case"DATERANGE":{const t=new ls(n,h),e=new cs(t,h.dateRanges[t.ID],h.dateRangeTagCount);h.dateRangeTagCount++,e.isValid||h.skippedSegments?h.dateRanges[e.id]=e:q.log(`Ignoring invalid DATERANGE tag: ${e.invalidReason}: ${n}`),R.tagList.push(["EXT-X-DATERANGE",n]);break}case"DEFINE":{const t=new ls(n,h);"IMPORT"in t?ns(h,t,a):rs(h,t,i)}break;case"DISCONTINUITY-SEQUENCE":0!==h.startCC&&Qs(h,t,u),h.startCC=T=parseInt(n),d.forEach(t=>t&&(t.cc=T));break;case"KEY":{const t=js(n,i,h);if(t.isSupported()){if("NONE"===t.method){g=void 0;break}g||(g={});const e=g[t.keyFormat];null!=e&&e.matches(t)||(e&&(g=I({},g)),g[t.keyFormat]=t)}else q.warn(`[Keys] Ignoring unsupported EXT-X-KEY tag: "${n}"`);break}case"START":h.startTimeOffset=Hs(n);break;case"MAP":{const t=new ls(n,h);if(R.duration){const e=new S(r,l);zs(e,t,s,g),p=e,R.initSegment=p,p.rawProgramDateTime&&!R.rawProgramDateTime&&(R.rawProgramDateTime=p.rawProgramDateTime)}else{const e=R.byteRangeEndOffset;if(e){const t=R.byteRangeStartOffset;D=`${e-t}@${t}`}else D=null;zs(R,t,s,g),p=R,_=!0}p.cc=T;break}case"SERVER-CONTROL":m&&Qs(h,t,u),m=new ls(n),h.canBlockReload=m.bool("CAN-BLOCK-RELOAD"),h.canSkipUntil=m.optionalFloat("CAN-SKIP-UNTIL",0),h.canSkipDateRanges=h.canSkipUntil>0&&m.bool("CAN-SKIP-DATERANGES"),h.partHoldBack=m.optionalFloat("PART-HOLD-BACK",0),h.holdBack=m.optionalFloat("HOLD-BACK",0);break;case"PART-INF":{h.partTarget&&Qs(h,t,u);const e=new ls(n);h.partTarget=e.decimalFloatingPoint("PART-TARGET");break}case"PART":{let t=h.partList;t||(t=h.partList=[]);const e=y>0?t[t.length-1]:void 0,i=y++,s=new ls(n,h),r=new b(s,R,l,i,e);t.push(r),R.duration+=r.duration;break}case"PRELOAD-HINT":{const t=new ls(n,h);h.preloadHint=t;break}case"RENDITION-REPORT":{const t=new ls(n,h);h.renditionReports=h.renditionReports||[],h.renditionReports.push(t);break}default:q.warn(`line parsed but not handled: ${u}`)}}}L&&!L.relurl?(d.pop(),E-=L.duration,h.partList&&(h.fragmentHint=L)):h.partList&&(Ws(R,L,c),R.cc=T,h.fragmentHint=R,g&&Xs(R,g,h)),h.targetduration||(h.playlistParsingError=new Error("Missing Target Duration"));const P=d.length,C=d[0],x=d[P-1];if(E+=h.skippedSegments*h.targetduration,E>0&&P&&x){h.averagetargetduration=E/P;const t=x.sn;h.endSN="initSegment"!==t?t:0,h.live||(x.endList=!0),k>0&&(!function(t,e,i){if(i||(i=t[e]),!i)return;for(let s=e;s--;){const e=t[s];if(!e)return;e.programDateTime=i.programDateTime-1e3*e.duration,i=e}}(d,k,k>P-1?R:null),C&&c.unshift(C))}return h.fragmentHint&&(E+=h.fragmentHint.duration),h.totalduration=E,c.length&&h.dateRangeTagCount&&C&&Ks(c,h),h.endCC=T,h}}function Gs(t,e,i,s,r,n){var a;if(void 0===e)return null;const o=ss(s,e),l={attrs:t,bitrate:t.decimalInteger("BANDWIDTH")||t.decimalInteger("AVERAGE-BANDWIDTH"),name:t.NAME,url:Us.resolve(o,i)},h=t.decimalResolution("RESOLUTION");h&&(l.width=h.width,l.height=h.height),qs(t.CODECS,l);const d=t["SUPPLEMENTAL-CODECS"];return d&&(l.supplemental={},qs(d,l.supplemental)),null!=(a=l.unknownCodecs)&&a.length||r.push(l),n&&(l.iframes=!0),l}function Ks(t,e){let i=t.length;if(!i){if(!e.hasProgramDateTime)return;{const s=e.fragments[e.fragments.length-1];t.push(s),i++}}const s=t[i-1],r=e.live?1/0:e.totalduration,n=Object.keys(e.dateRanges);for(let o=n.length;o--;){const l=e.dateRanges[n[o]],h=l.startDate.getTime();l.tagAnchor=s.ref;for(let s=i;s--;){var a;if((null==(a=t[s])?void 0:a.sn)<e.startSN)break;const i=Vs(e,h,t,s,r);if(i){l.tagAnchor=i.ref;break}}}}function Vs(t,e,i,s,r){const n=i[s];if(n){const o=n.programDateTime;if(e>=o||0===s){var a;if(e<=o+1e3*(((null==(a=i[s+1])?void 0:a.start)||r)-n.start)){const r=n.sn-t.startSN,a=t.fragments;if(r>=0&&r<a.length){if(a.length>i.length){const n=i[s+1]||a[a.length-1];for(let i=Math.min(n.sn-t.startSN,a.length-1);i>r;i--){const t=a[i].programDateTime;if(e>=t&&e<t+1e3*a[i].duration)return a[i]}}return a[r]}}}}return null}function js(t,e,i){var s,r;const n=new ls(t,i),a=null!=(s=n.METHOD)?s:"",o=n.URI,l=n.hexadecimalInteger("IV"),h=n.KEYFORMATVERSIONS,d=null!=(r=n.KEYFORMAT)?r:"identity";o&&n.IV&&!l&&q.error(`Invalid IV: ${n.IV}`);const c=o?Us.resolve(o,e):"",u=(h||"1").split("/").map(Number).filter(Number.isFinite);return new xs(a,c,d,u,l,n.KEYID)}function Hs(t){const i=new ls(t).decimalFloatingPoint("TIME-OFFSET");return e(i)?i:null}function qs(t,e){let i=(t||"").split(/[ ,]+/).filter(t=>t);["video","audio","text","image"].forEach(t=>{const s=i.filter(e=>le(e,t));s.length&&(e[`${t}Codec`]=s.map(t=>t.split("/")[0]).join(","),i=i.filter(t=>-1===s.indexOf(t)))}),e.unknownCodecs=i}function Ys(t,e,i){const s=e[i];s&&(t[i]=s)}function Ws(t,e,i){t.rawProgramDateTime?i.push(t):null!=e&&e.programDateTime&&(t.programDateTime=e.endProgramDateTime)}function zs(t,e,i,s){t.relurl=e.URI,e.BYTERANGE&&t.setByteRange(e.BYTERANGE),t.level=i,t.sn="initSegment",s&&(t.levelkeys=s),t.initSegment=null}function Xs(t,e,i){t.levelkeys=e;const{encryptedFragments:s}=i;s.length&&s[s.length-1].levelkeys===e||!Object.keys(e).some(t=>e[t].isCommonEncryption)||s.push(t)}function Qs(t,e,i){t.playlistParsingError=new Error(`#EXT-X-${e} must not appear more than once (${i[0]})`)}function Zs(t,e,i){t.playlistParsingError=new Error(`#EXT-X-${e} must appear before the first Media Segment (${i[0]})`)}function Js(t,i){const s=i.startPTS;if(e(s)){let e,r=0;i.sn>t.sn?(r=s-t.start,e=t):(r=t.start-s,e=i),e.duration!==r&&e.setDuration(r)}else if(i.sn>t.sn){t.cc===i.cc&&t.minEndPTS?i.setStart(t.start+(t.minEndPTS-t.start)):i.setStart(t.start+t.duration)}else i.setStart(Math.max(t.start-i.duration,0))}function tr(t,i,s,r,n,a,o,l){r-s<=0&&(l.warn("Fragment should have a positive duration",i),r=s+i.duration,a=n+i.duration);let h=s,d=r;const c=i.startPTS,u=i.endPTS;if(e(c)){const o=Math.abs(c-s);t&&o>t.totalduration?l.warn(`media timestamps and playlist times differ by ${o}s for level ${i.level} ${t.url}`):e(i.deltaPTS)?i.deltaPTS=Math.max(o,i.deltaPTS):i.deltaPTS=o,h=Math.max(s,c),s=Math.min(s,c),n=void 0!==i.startDTS?Math.min(n,i.startDTS):n,d=Math.min(r,u),r=Math.max(r,u),a=void 0!==i.endDTS?Math.max(a,i.endDTS):a}const f=s-i.start;return 0!==i.start&&i.setStart(s),i.setDuration(r-i.start),i.startPTS=s,i.maxStartPTS=h,i.startDTS=n,i.endPTS=r,i.minEndPTS=d,i.endDTS=a,er(t,i,f)}function er(t,e,i){var s;const r=e.sn;if(!t||r<t.startSN||r>((null==(s=t.fragmentHint)?void 0:s.sn)||t.endSN))return 0;let n;const a=r-t.startSN,o=t.fragments;for(o[a]=e,n=a;n>0;n--)Js(o[n],o[n-1]);for(n=a;n<o.length-1;n++)Js(o[n],o[n+1]);return t.fragmentHint&&Js(o[o.length-1],t.fragmentHint),t.PTSKnown=t.alignedSliding=!0,i}function ir(t,i,s){if(t===i)return;let r=null;const n=t.fragments;for(let t=n.length-1;t>=0;t--){const e=n[t].initSegment;if(e){r=e;break}}let a;t.fragmentHint&&delete t.fragmentHint.endPTS,function(t,e,i){var s;const r=e.skippedSegments,n=Math.max(t.startSN,e.startSN)-e.startSN,a=(t.fragmentHint?1:0)+(r?e.endSN:Math.min(t.endSN,e.endSN))-e.startSN,o=e.startSN-t.startSN,l=e.fragmentHint?e.fragments.concat(e.fragmentHint):e.fragments,h=null!=(s=t.fragmentHint)&&s.duration?t.fragments.concat(t.fragmentHint):t.fragments;for(let s=n;s<=a;s++){const n=h[o+s];let a=l[s];if(r&&!a&&n&&(a=e.fragments[s]=n),n&&a){i(n,a,s,l);const r=n.relurl,o=a.relurl;if(r&&dr(r,o))return void(e.playlistParsingError=sr(`media sequence mismatch ${a.sn}:`,t,e,n,a));if(n.cc!==a.cc)return void(e.playlistParsingError=sr(`discontinuity sequence mismatch (${n.cc}!=${a.cc})`,t,e,n,a))}}}(t,i,(t,s,n,o)=>{if(s.cc!==t.cc&&(t.cc>s.cc||i.skippedSegments)){const e=t.cc-s.cc;for(let t=n;t<o.length;t++)o[t].cc+=e;i.endCC=o[o.length-1].cc}e(t.startPTS)&&e(t.endPTS)&&(s.setStart(s.startPTS=t.startPTS),s.startDTS=t.startDTS,s.maxStartPTS=t.maxStartPTS,s.endPTS=t.endPTS,s.endDTS=t.endDTS,s.minEndPTS=t.minEndPTS,s.setDuration(t.endPTS-t.startPTS),s.duration&&(a=s),i.PTSKnown=i.alignedSliding=!0),t.hasStreams&&(s.elementaryStreams=t.elementaryStreams),s.loader=t.loader,s.gap=t.gap||s.gap,t.hasStats&&(s.stats=t.stats),t.initSegment&&(s.initSegment=t.initSegment,r=t.initSegment)});const o=i.fragments,l=i.fragmentHint?o.concat(i.fragmentHint):o;if(r&&l.forEach(t=>{var e;!t||t.initSegment&&t.initSegment.relurl!==(null==(e=r)?void 0:e.relurl)||(t.initSegment=r)}),i.skippedSegments){if(i.deltaUpdateFailed=o.some(t=>!t),i.deltaUpdateFailed){s.warn("[level-helper] Previous playlist missing segments skipped in delta playlist");for(let t=i.skippedSegments;t--;)o.shift();i.startSN=o[0].sn}else{i.canSkipDateRanges&&(i.dateRanges=function(t,e,i){const{dateRanges:s,recentlyRemovedDateranges:r}=e,n=I({},t);r&&r.forEach(t=>{delete n[t]});const a=Object.keys(n).length;if(!a)return s;return Object.keys(s).forEach(t=>{const e=n[t],r=new cs(s[t].attr,e);r.isValid?(n[t]=r,e||(r.tagOrder+=a)):i.warn(`Ignoring invalid Playlist Delta Update DATERANGE tag: "${Ue(s[t].attr)}"`)}),n}(t.dateRanges,i,s));const e=t.fragments.filter(t=>t.rawProgramDateTime);if(t.hasProgramDateTime&&!i.hasProgramDateTime)for(let t=1;t<l.length;t++)null===l[t].programDateTime&&Ws(l[t],l[t-1],e);Ks(e,i)}i.endCC=o[o.length-1].cc}else if(i.startSN>t.endSN&&o[0].cc<t.endCC){const e=t.endCC-o[0].cc;l.forEach(t=>{t.cc+=e}),i.endCC+=e}if(!i.startCC){var h;const e=ar(t,i.startSN-1);i.startCC=null!=(h=null==e?void 0:e.cc)?h:o[0].cc}if(function(t,e,i){if(t&&e){let s=0;for(let r=0,n=t.length;r<n;r++){const n=t[r],a=e[r+s];n&&a&&n.index===a.index&&n.fragment.sn===a.fragment.sn?i(n,a):s--}}}(t.partList,i.partList,(t,e)=>{e.elementaryStreams=t.elementaryStreams,e.stats=t.stats,e.gap=t.gap||e.gap}),a){i.iframesOnly&&(a.type,f.MAIN);tr(i,a,a.startPTS,a.endPTS,a.startDTS,a.endDTS,0,s)}else rr(t,i);o.length&&(i.totalduration=i.edge-o[0].start),i.driftStartTime=t.driftStartTime,i.driftStart=t.driftStart;const d=i.advancedDateTime;if(i.advanced&&d){const t=i.edge;i.driftStart||(i.driftStartTime=d,i.driftStart=t),i.driftEndTime=d,i.driftEnd=t}else i.driftEndTime=t.driftEndTime,i.driftEnd=t.driftEnd,i.advancedDateTime=t.advancedDateTime;-1===i.requestScheduled&&(i.requestScheduled=t.requestScheduled)}function sr(t,e,i,s,r){return new Error(`${t} ${r.url}\nPlaylist starting @${e.startSN}\n${e.m3u8}\n\nPlaylist starting @${i.startSN}\n${i.m3u8}`)}function rr(t,e,i=!0,s){const r=e.startSN+e.skippedSegments-t.startSN,n=t.fragments,a=r>=0;let o=0;if(a&&r<n.length)o=n[r].start,null==s||s.log(`Aligning playlists based on SN ${e.startSN} (diff: ${o})`);else if(a&&e.startSN===t.endSN+1)o=t.fragmentEnd,null==s||s.log(`Aligning playlists based on first/last SN ${e.startSN} (diff: ${o})`);else if(a&&i)o=t.fragmentStart+r*e.levelTargetDuration;else{if(e.skippedSegments||0!==e.fragmentStart)return o;o=t.fragmentStart,null==s||s.log(`Aligning playlists based on first SN ${e.startSN} (diff: ${o})`)}return function(t,e){if(e){const i=t.fragments;for(let s=t.skippedSegments;s<i.length;s++)i[s].addStart(e);t.fragmentHint&&t.fragmentHint.addStart(e)}}(e,o),o}function nr(t,e=1/0){let i=1e3*t.targetduration;if(t.updated){const s=t.fragments,r=4;if(s.length&&i*r>e){const t=1e3*s[s.length-1].duration;t>0&&t<i&&(i=t)}}else i/=2;return Math.round(i)}function ar(t,e,i){var s;if(!t)return null;let r=t.fragments[e-t.startSN];return r||(r=t.fragmentHint,(null==(s=r)?void 0:s.sn)===e?r:i&&e<t.startSN&&i.sn===e?i:null)}function or(t,e,i){return t?lr(t.partList,e,i):null}function lr(t,e,i){if(t)for(let s=t.length;s--;){const r=t[s];if(r.index===i&&r.fragment.sn===e)return r}return null}function hr(t){t.forEach((t,e)=>{var i;null==(i=t.details)||i.fragments.forEach(t=>{t.level=e,t.initSegment&&(t.initSegment.level=e)})})}function dr(t,e){return!(t===e||!e)&&cr(t)!==cr(e)}function cr(t){return t.replace(/\?[^?]*$/,"")}function ur(t,e){for(let s=0,r=t.length;s<r;s++){var i;if((null==(i=t[s])?void 0:i.cc)===e)return t[s]}return null}function fr(t,e){const i=t.start+e;t.setStart(i)}function gr(t,e){const i=e.fragments;for(let e=0,s=i.length;e<s;e++)fr(i[e],t);e.fragmentHint&&fr(e.fragmentHint,t),e.alignedSliding=!0}function mr(t,e,i){t&&(!function(t,e,i){if(!function(t,e){return!!(t&&e.startCC<t.endCC&&e.endCC>t.startCC)}(e,t))return;const s=Math.min(e.endCC,t.endCC),r=ur(e.fragments,s),n=ur(t.fragments,s);if(!r||!n)return;const a=r.start-n.start;i.log(`Aligning playlists using dicontinuity sequence ${s} (diff: ${a})`),gr(a,t)}(e,t,i),e.alignedSliding||function(t,e,i){if(!t.hasProgramDateTime||!e.hasProgramDateTime)return;const s=t.fragments,r=e.fragments;if(!s.length||!r.length)return;let n,a;const o=Math.min(e.endCC,t.endCC);e.startCC<o&&t.startCC<o&&(n=ur(r,o),a=ur(s,o));n&&a||(n=r[Math.floor(r.length/2)]||r.filter(t=>!!t)[0],a=ur(s,n.cc)||s[Math.floor(s.length/2)]);const l=n.programDateTime,h=a.programDateTime;if(!l||!h)return;const d=(h-l)/1e3;if(Math.abs(d)>Math.max(60,t.totalduration))return void i.log(`Cannot align playlists using PDT without overlap (${Math.abs(d)} > ${t.totalduration})`);const c=d-(a.start-n.start);i.log(`Aligning playlists using PDT (diff: ${c})`),gr(c,t)}(e,t,i),e.alignedSliding||e.skippedSegments||rr(t,e,!1,i))}const pr="STOPPED",vr="IDLE",yr="KEY_LOADING",Er="FRAG_LOADING",Tr="FRAG_LOADING_WAITING_RETRY",Sr="WAITING_TRACK",br="PARSING",Ar="PARSED",Lr="ENDED",Ir="ERROR",Rr="WAITING_INIT_PTS",kr="WAITING_LEVEL";class _r extends Ji{constructor(t,e,i,s,r){super(s,t.logger),this.hls=void 0,this.fragPrevious=null,this.fragCurrent=null,this.fragPlaying=null,this.fragmentTracker=void 0,this.transmuxer=null,this._state=pr,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=-1,this.startTimeOffset=null,this.retryDate=0,this.levels=null,this.fragmentLoader=void 0,this.initFragmentLoader=void 0,this.keyLoader=void 0,this.levelLastLoaded=null,this.startFragRequested=!1,this.decrypter=void 0,this.initPTS=[],this.buffering=!0,this.loadingParts=!1,this.loopSn=void 0,this.onMediaSeeking=()=>{const{config:t,fragCurrent:e,media:i,mediaBuffer:s,state:r}=this,n=i?i.currentTime:0,a=Ei.bufferInfo(s||i,n,t.maxBufferHole),o=a.len;if(this.log(`Media seeking to ${n}, state: ${r}, ${o?"in":"out of"} buffer`),this.state===Lr)this.resetLoadingState();else if(e){const i=t.maxFragLookUpTolerance,s=e.start-i,r=e.start+e.duration+i;if(!o||r<a.start||s>a.end){const t=n<s,i=n>r;(t||i)&&(!e.loader||!i&&this.isFragmentNearlyDownloaded(e)?this.fragPrevious=null:(this.log(`Cancelling fragment load for seek (sn: ${e.sn}) - ${t?"backward":"forward"} seek`),e.abortRequests(),this.resetLoadingState()))}}if(i){var l;null!=(l=this.hls)&&l.hasEnoughToStart&&!o&&n!==this.startPosition&&this.fragmentTracker.removeFragmentsInRange(n,1/0,this.playlistType,!0);if(n>this.lastCurrentTime&&(this.lastCurrentTime=n),!this.loadingParts){const t=Math.max(a.end,n),e=this.shouldLoadParts(this.getLevelDetails(),t);e&&(this.log(`LL-Part loading ON after seeking to ${n} with buffer @${t}`),this.loadingParts=e)}}const h=!Ei.isBuffered(i,n);this.hls.hasEnoughToStart&&!h||(this.log(`Setting ${h?"startPosition":"nextLoadPosition"} to ${n} for seek without enough to start`),this.nextLoadPosition=n,h?this.startPosition=n:this.lastCurrentTime=n),o<1&&this.state===vr&&this.tickImmediate()},this.onMediaEnded=()=>{this.log("setting startPosition to 0 because media ended"),this.startPosition=this.nextLoadPosition=this.lastCurrentTime=0},this.playlistType=r,this.hls=t,this.fragmentLoader=new Wi(t.config),this.initFragmentLoader=new Wi(t.config),this.keyLoader=i,this.fragmentTracker=e,this.config=t.config,this.decrypter=new qi(t.config)}registerListeners(){const{hls:t}=this;t.on(a.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(a.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(a.MANIFEST_LOADING,this.onManifestLoading,this),t.on(a.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(a.ERROR,this.onError,this)}unregisterListeners(){const{hls:t}=this;t.off(a.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(a.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(a.MANIFEST_LOADING,this.onManifestLoading,this),t.off(a.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(a.ERROR,this.onError,this)}doTick(){}onTickEnd(){const{media:t}=this;null!=t&&t.readyState&&!1===t.seeking&&(this.lastCurrentTime=t.currentTime)}startLoad(t){}stopLoad(){if(this.state===pr)return;this.fragmentLoader.abort(),this.initFragmentLoader.abort(),this.keyLoader.abort(this.playlistType);const t=this.fragCurrent;null!=t&&t.loader&&(t.abortRequests(),this.fragmentTracker.removeFragment(t)),this.resetTransmuxer(),this.fragCurrent=null,this.fragPrevious=null,this.clearInterval(),this.clearNextTick(),this.state=pr}get startPositionValue(){const{nextLoadPosition:t,startPosition:e}=this;if(-1===e&&t){const e=this.getLevelDetails();if(null!=e&&e.live){return(this.hls.liveSyncPosition||e.fragmentStart)+this.timelineOffset}return t}return e}get bufferingEnabled(){return this.buffering}get backtrackFragment(){}set backtrackFragment(t){}get couldBacktrack(){return!1}set couldBacktrack(t){}pauseBuffering(){this.buffering=!1}resumeBuffering(){this.buffering=!0}get inFlightFrag(){return{frag:this.fragCurrent,state:this.state}}_streamEnded(t,e){if(e.live||!this.media)return!1;const i=t.end||0,s=this.config.timelineOffset||0;if(i<=s)return!1;const r=t.buffered;this.config.maxBufferHole&&r&&r.length>1&&(t=Ei.bufferedInfo(r,t.start,0));const n=t.nextStart;if(n&&n>s&&n<e.edge)return!1;if(this.media.currentTime<t.start)return!1;const a=e.partList;if(null!=a&&a.length){const t=a[a.length-1];return Ei.isBuffered(this.media,t.start+t.duration/2)}const o=e.fragments[e.fragments.length-1];return this.fragmentTracker.isEndListAppended(o.type)}getLevelDetails(){if(this.levels&&null!==this.levelLastLoaded)return this.levelLastLoaded.details}get timelineOffset(){const t=this.config.timelineOffset;var e;return t?(null==(e=this.getLevelDetails())?void 0:e.appliedTimelineOffset)||t:0}onMediaAttached(t,e){const i=this.media=this.mediaBuffer=e.media;Ti(i,"seeking",this.onMediaSeeking),Ti(i,"ended",this.onMediaEnded);const s=this.config;this.levels&&s.autoStartLoad&&this.state===pr&&this.startLoad(s.startPosition)}onMediaDetaching(t,e){this.fragPlaying=null;const i=!!e.transferMedia,s=this.media;if(null===s)return;if(s.ended&&(this.log("MSE detaching and video ended, reset startPosition"),this.startPosition=this.lastCurrentTime=0),Si(s,"seeking",this.onMediaSeeking),Si(s,"ended",this.onMediaEnded),this.media=this.mediaBuffer=null,this.loopSn=void 0,i)return this.resetLoadingState(),void this.resetTransmuxer();this.loadingParts=!1;const{fragmentTracker:r}=this,n=r.gapFragments();r.removeAllFragments(),n.forEach(t=>r.addAsGap(t)),this.stopLoad()}onManifestLoading(){this.initPTS=[],this.fragPlaying=this.levels=this.levelLastLoaded=this.fragCurrent=null,this.lastCurrentTime=this.nextLoadPosition=0,this.startPosition=-1,this.startFragRequested=!1}onError(t,e){}onManifestLoaded(t,e){this.startTimeOffset=e.startTimeOffset}onHandlerDestroying(){this.stopLoad(),this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null),super.onHandlerDestroying(),this.hls=this.onMediaSeeking=this.onMediaEnded=null}onHandlerDestroyed(){this.state=pr,this.fragmentLoader&&this.fragmentLoader.destroy(),this.initFragmentLoader&&this.initFragmentLoader.destroy(),this.keyLoader&&this.keyLoader.destroy(),this.decrypter&&this.decrypter.destroy(),this.hls=this.decrypter=this.keyLoader=null,this.fragmentLoader=this.initFragmentLoader=this.fragmentTracker=null,super.onHandlerDestroyed()}loadFragment(t,e,i){this.startFragRequested=!0,this._loadFragForPlayback(t,e,i)}_loadFragForPlayback(t,e,i){this._doFragLoad(t,e,i,t=>{const e=t.frag;if(this.fragContextChanged(e))return this.warn(`${e.type} sn: ${e.sn}${t.part?" part: "+t.part.index:""} of ${this.fragInfo(e,!1,t.part)} was dropped during download.`),void this.fragmentTracker.removeFragment(e);const i=++e.stats.chunkCount;this.log(`load progress ${e.type} sn: ${e.sn}${t.part?" part: "+t.part.index:""} of ${this.fragInfo(e,!1,t.part)} chunk: ${i}`),this._handleFragmentLoadProgress(t)}).then(t=>{if(!t)return;const e=this.state,i=t.frag;this.fragContextChanged(i)?(e===Er||!this.fragCurrent&&e===br)&&(this.fragmentTracker.removeFragment(i),this.state=vr):("payload"in t&&(this.log(`Loaded ${i.type} sn: ${i.sn} of ${this.playlistLabel()} ${i.level} (bytes ${i.stats.loaded})`),this.hls.trigger(a.FRAG_LOADED,t)),this._handleFragmentLoadComplete(t))}).catch(e=>{this.state!==pr&&this.state!==Ir&&(this.log(`Frag error ${t.type} sn:${t.sn} cc:${t.cc}: ${(null==e?void 0:e.message)||e}`),this.resetFragmentLoading(t))})}clearTrackerIfNeeded(t){var e;const{fragmentTracker:i}=this;if(i.getState(t)===Mi){const e=t.type,s=this.getFwdBufferInfo(this.mediaBuffer,e),r=Math.max(t.duration,s?s.len:this.config.maxBufferLength),n=this.backtrackFragment;(1===(n?t.sn-n.sn:0)||this.reduceMaxBufferLength(r,t.duration))&&i.removeFragment(t)}else 0===(null==(e=this.mediaBuffer)?void 0:e.buffered.length)?i.removeAllFragments():i.hasParts(t.type)&&(i.detectPartialFragments({frag:t,part:null,stats:t.stats,id:t.type}),i.getState(t)===Oi&&i.removeFragment(t))}checkLiveUpdate(t){if(t.updated&&!t.live){const e=this.fragmentTracker,i=t.fragments[t.fragments.length-1];if(i.endList&&!e.isEndListAppended(this.playlistType)){const t=e.getPartialFragment(i.end);t&&(e.removeFragment(t),e.fragBuffered(i,!0))}e.detectPartialFragments({frag:i,part:null,stats:i.stats,id:i.type})}t.fragments[0]||(t.deltaUpdateFailed=!0)}waitForLive(t){const e=t.details;return(null==e?void 0:e.live)&&"EVENT"!==e.type&&void 0!==e.advancedDateTime&&(e.expired||this.loadingParts&&e.partsExpired||e.misses<3&&e.partEnd<=this.getLoadPosition())}flushMainBuffer(t,e,i=null){if(!(t-e))return;const s={startOffset:t,endOffset:e,type:i};this.hls.trigger(a.BUFFER_FLUSHING,s)}_loadInitSegment(t){const{hls:e}=this;return this.initFragmentLoader.abort(),e.trigger(a.FRAG_LOADING,{frag:t,targetBufferTime:0}),this.initFragmentLoader.load(t).then(t=>{var e;const i=t.frag;if(!this.levels||!T(i,null==(e=this.fragCurrent)?void 0:e.initSegment))throw new Zi({type:r.NETWORK_ERROR,details:n.INTERNAL_ABORTED,error:new Error("init load aborted"),fatal:!1,frag:i,networkDetails:null});return t}).then(t=>{const{frag:i,payload:s}=t,o=i.decryptdata;if(s&&s.byteLength>0&&null!=o&&o.key&&o.iv&&gs(o.method)){const l=self.performance.now(),{decryptRange:h}=Xi(i,null,this.iframesOnly);return this.decrypter.decrypt(new Uint8Array(s),o.key.buffer,o.iv.buffer,ms(o.method),h).catch(t=>{throw e.trigger(a.ERROR,{type:r.MEDIA_ERROR,details:n.FRAG_DECRYPT_ERROR,fatal:!1,error:t,reason:t.message,frag:i}),this.fragmentLoader.abort(),t}).then(s=>{const r=self.performance.now();return e.trigger(a.FRAG_DECRYPTED,{frag:i,part:null,payload:s,stats:{tstart:l,tdecrypt:r}}),t.payload=s,this.completeInitSegmentLoad(t)})}return this.completeInitSegmentLoad(t)})}completeInitSegmentLoad(t){const e=t.frag.stats;t.frag.data=new Uint8Array(t.payload),e.parsing.start=e.buffering.start=self.performance.now(),e.parsing.end=e.buffering.end=self.performance.now()}loadInitSegmentIfNeeded(t){const{initSegment:e}=t;if(!this.bitrateTest&&y(t)&&e&&!e.data){var i;return(!e.encrypted||null!=(i=e.decryptdata)&&i.key?this._loadInitSegment(e):this.keyLoader.load(e).then(()=>this._loadInitSegment(e))).catch(e=>{if(this.state===pr||this.state===Ir)throw e;throw"data"in e&&(this.fragmentLoader.abort(),this.handleFragLoadError(e,t)),this.resetFragmentLoading(t),e})}}unhandledEncryptionError(t,e){var i,s;const o=t.tracks;if(o&&!e.encrypted&&(null!=(i=o.audio)&&i.encrypted||null!=(s=o.video)&&s.encrypted)&&(!this.config.emeEnabled||!this.keyLoader.emeController)){const t=this.media,i=new Error(`Encrypted track with no key in ${this.fragInfo(e)} (media ${t?"attached mediaKeys: "+t.mediaKeys:"detached"})`);return this.warn(i.message),!t||t.mediaKeys?!1:(this.hls.trigger(a.ERROR,{type:r.KEY_SYSTEM_ERROR,details:n.KEY_SYSTEM_NO_KEYS,fatal:!1,error:i,frag:e}),this.resetTransmuxer(),!0)}return!1}fragContextChanged(t){const{fragCurrent:e}=this;return!t||!T(t,e)}fragBufferedComplete(t,e){const i=this.mediaBuffer?this.mediaBuffer:this.media;if(this.log(`Buffered ${t.type} sn: ${t.sn}${e?" part: "+e.index:""} of ${this.fragInfo(t,!1,e)} > buffer:${i?bi(Ei.getBuffered(i)):"(detached)"})`),y(t)){var s;if(t.type!==f.SUBTITLE){const e=t.elementaryStreams;if(!Object.keys(e).some(t=>!!e[t]))return void(this.state=vr)}const i=null==(s=this.levels)?void 0:s[t.level];null!=i&&i.fragmentError&&(e||this.fragmentTracker.getState(t)!==Oi)&&(this.log(`Resetting level fragment error count of ${i.fragmentError} on frag buffered`),i.fragmentError=0,t.stats.retry=0)}this.state=vr}_handleFragmentLoadComplete(t){const{transmuxer:e}=this;if(!e)return;const i=t.frag,{part:s,partsLoaded:r}=t,n=!r||0===r.length||r.some(t=>!t),{decryptRange:a}=Xi(i,s),o=new ts(i.level,i.sn,i.stats.chunkCount+1,0,s?s.index:-1,!n,i.duration,this.iframesOnly,a);this.log(`load complete ${i.type} sn: ${i.sn}${s?" part: "+s.index:""} of ${this.fragInfo(i,!1,s)}`),e.flush(o)}_handleFragmentLoadProgress(t){}loadKeyFor(t,e,i){var s;let r=null;return!t.encrypted||null!=(s=t.decryptdata)&&s.key?t.encrypted||(r=this.keyLoader.loadClear(t,e.encryptedFragments,this.startFragRequested),r&&this.log(`[eme] blocking frag sn: ${t.sn} load until media-keys acquired`)):(this.log(`Loading key for ${t.sn} of [${e.startSN}-${e.endSN}], ${this.playlistLabel()} ${t.level}`),this.state=yr,r=this.keyLoader.load(t,i).then(t=>{if(!this.fragContextChanged(t.frag))return this.hls.trigger(a.KEY_LOADED,t),this.state===yr&&(this.state=vr),t}),this.hls.trigger(a.KEY_LOADING,{frag:t})),r}_doFragLoad(t,i,s=null,r){this.fragCurrent=t;const n=i.details;if(!this.levels||!n)throw new Error(`frag load aborted, missing level${n?"":" detail"}s`);const o=this.fragPrevious;if(!E(t,o)){const e=this.shouldLoadParts(i.details,t.end);e!==this.loadingParts&&(this.log(`LL-Part loading ${e?"ON":"OFF"} loading sn ${null==o?void 0:o.sn}->${t.sn}`),this.loadingParts=e)}if(s=Math.max(t.start,s||0),this.loadingParts){const e=n.partList;if(e&&r){s>n.fragmentEnd&&n.fragmentHint&&(t=n.fragmentHint);const l=this.getNextPart(e,t,s);if(l>-1){const h=e[l];if(!E(t=this.fragCurrent=h.fragment,o)&&!this.shouldLoadParts(i.details,t.end))return this.log(`LL-Part loading OFF @${this.playhead} next part: ${this.fragInfo(t,!1,h)}`),this.loadingParts=!1,Promise.resolve(null);if(!this.filterReplacedPrimary(h,i.details))return Promise.resolve(null);const d=this.loadKeyFor(t,n);if(this.fragContextChanged(t))return Promise.resolve(null);let c;this.log(`Loading ${t.type} sn: ${t.sn} part: ${h.index} (${l}/${e.length-1}) of ${this.fragInfo(t,!1,h)} cc: ${t.cc} [${n.startSN}-${n.endSN}], target: ${s}${h.byteRange.length?` range:${h.byteRange.join("-")}`:""}`),this.nextLoadPosition=h.start+h.duration,this.state=Er;const u=this.loadInitSegmentIfNeeded(t);if(d||u){const e=!!d;c=Promise.all([d,u]).then(([s])=>!e||s&&!this.fragContextChanged(s.frag)?this.doFragPartsLoad(t,h,i,r):null).catch(e=>this.handleFragLoadError(e,t))}else c=this.doFragPartsLoad(t,h,i,r).catch(e=>this.handleFragLoadError(e,t));return this.hls.trigger(a.FRAG_LOADING,{frag:t,part:h,targetBufferTime:s}),null===this.fragCurrent?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING parts")):c}if(!t.url||this.loadedEndOfParts(e,s))return Promise.resolve(null)}}var l;if(this.loadingParts)this.log(`LL-Part loading OFF after next part miss @${s} Check buffer at sn: ${t.sn} loaded parts: ${null==(l=n.partList)?void 0:l.filter(t=>t.loaded).map(t=>`[${t.start}-${t.end}]`)}`),this.loadingParts=!1;else if(!t.url)return Promise.resolve(null);if(!this.filterReplacedPrimary(t,i.details))return Promise.resolve(null);const h=this.loadInitSegmentIfNeeded(t),d=this.loadKeyFor(t,n,h);var c;if(this.fragContextChanged(t))return this.log(`Context changed in KEY_LOADING sn: ${t.sn} ${t.relurl} > ${null==(c=this.fragCurrent)?void 0:c.relurl}`),null==h||h.catch(()=>null),null==d||d.catch(()=>null),Promise.resolve(null);this.log(`Loading ${t.type} sn: ${t.sn} of ${this.fragInfo(t,!1)} cc: ${t.cc} ${"["+n.startSN+"-"+n.endSN+"]"}, target: ${s}${t.byteRange.length?` range:${t.byteRange.join("-")}`:""}`),e(t.sn)&&!this.bitrateTest&&(this.nextLoadPosition=t.start+t.duration),this.state=Er;const u=this.config.progressive&&t.type!==f.SUBTITLE;let g;return g=u&&d?d.then(e=>!e||this.fragContextChanged(e.frag)?null:this.fragmentLoader.load(t,this.iframesOnly,r,h)).catch(e=>this.handleFragLoadError(e,t)):Promise.all([this.fragmentLoader.load(t,this.iframesOnly,u?r:void 0,u?h:void 0),d,h]).then(([t])=>(!u&&r&&r(t),t)).catch(e=>this.handleFragLoadError(e,t)),this.hls.trigger(a.FRAG_LOADING,{frag:t,targetBufferTime:s}),null===this.fragCurrent?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING")):Promise.all([g,h]).then(([t])=>t)}doFragPartsLoad(t,e,i,s){return new Promise((r,n)=>{var o;const l=[],h=null==(o=i.details)?void 0:o.partList,d=e=>{this.fragmentLoader.loadPart(t,e,s).then(s=>{l[e.index]=s;const n=s.part;this.hls.trigger(a.FRAG_LOADED,s);const o=or(i.details,t.sn,e.index+1)||lr(h,t.sn,e.index+1);if(!o)return r({frag:t,part:n,partsLoaded:l});d(o)}).catch(n)};d(e)})}handleFragLoadError(t,e){if("data"in t){const i=t.data;i.details===n.INTERNAL_ABORTED?this.handleFragLoadAborted(e,i.part):i.type!==r.KEY_SYSTEM_ERROR||i.fatal||(e.abortRequests(),this.resetStartWhenNotLoaded(),this.resetFragmentLoading(e)),i.frag!==e?(i.frag&&this.warn(`${i.details} error cascading from ${this.fragInfo(i.frag,!1,i.part)} to ${this.fragInfo(e,!1)}`),this.hls.trigger(a.ERROR,k(k({},i),{},{frag:e}))):this.hls.trigger(a.ERROR,i)}else this.hls.trigger(a.ERROR,{type:r.OTHER_ERROR,details:n.INTERNAL_EXCEPTION,err:t,error:t,fatal:!0});return null}_handleTransmuxerFlush(t){const e=this.getCurrentContext(t);if(!e||this.state!==br)return void(this.fragCurrent||this.state===pr||this.state===Ir||(this.state=vr));const{frag:i,part:s,level:r}=e,n=self.performance.now();i.stats.parsing.end=n,s&&(s.stats.parsing.end=n);const a=this.getLevelDetails(),o=a&&i.sn>a.endSN||this.shouldLoadParts(a,i.end);o!==this.loadingParts&&(this.log(`LL-Part loading ${o?"ON":"OFF"} after parsing segment ending @${i.end}`),this.loadingParts=o),this.updateLevelTiming(i,s,r,t)}shouldLoadParts(t,e){if(this.config.lowLatencyMode){if(!t)return this.loadingParts;if(t.partList&&!this.iframesOnly){var i;const s=t.partList[0];if(e>=s.end+((null==(i=t.fragmentHint)?void 0:i.duration)||0)){if(this.playhead>s.start-s.fragment.duration)return!0}}}return!1}getCurrentContext(t){const{levels:e,fragCurrent:i}=this,{level:s,sn:r,part:n}=t;if(null==e||!e[s])return this.warn(`Levels object was unset while buffering fragment ${r} of ${this.playlistLabel()} ${s}. The current chunk will not be buffered.`),null;const a=e[s],o=a.details,l=n>-1?or(o,r,n):null,h=l?l.fragment:ar(o,r,i);return h?(i&&i!==h&&(h.stats=i.stats),{frag:h,part:l,level:a}):null}bufferFragmentData(t,e,i,s,r){if(this.state!==br)return;y(e)&&!this.fragContextChanged(e)&&(this.fragPrevious=e);const{data1:n,data2:o}=t;let l=n;if(o&&(l=Ht(n,o)),!l.length)return;const h=this.initPTS[e.cc],d=h?-h.baseTime/h.timescale:void 0,c={type:t.type,frag:e,part:i,chunkMeta:s,offset:d,parent:e.type,data:l};if(this.hls.trigger(a.BUFFER_APPENDING,c),t.dropped&&t.independent&&!i){if(r)return;this.flushBufferGap(e)}}flushBufferGap(t){const e=this.media;if(!e)return;if(!Ei.isBuffered(e,e.currentTime))return void this.flushMainBuffer(0,t.start);const i=e.currentTime,s=Ei.bufferInfo(e,i,0),r=t.duration,n=Math.min(2*this.config.maxFragLookUpTolerance,.25*r),a=Math.max(Math.min(t.start-n,s.end-n),i+n);t.start-a>n&&this.flushMainBuffer(a,t.start)}getFwdBufferInfo(t,e){var i;const s=this.playhead,r=this.lastCurrentTime>s||null!=(i=this.media)&&i.paused?0:this.config.maxBufferHole;return this.getFwdBufferInfoAtPos(t,s,e,r)}getFwdBufferInfoAtPos(t,e,i,s){const r=Ei.bufferInfo(t,e,s);if(0===r.len&&void 0!==r.nextStart){const n=this.fragmentTracker.getBufferedFrag(e,i);if(n&&(r.nextStart<=n.end||n.gap)){const i=Math.max(Math.min(r.nextStart,n.end)-e,s);return Ei.bufferInfo(t,e,i)}}return r}getMaxBufferLength(t){const{config:e}=this;let i;return i=t?Math.max(8*e.maxBufferSize/t,e.maxBufferLength):e.maxBufferLength,Math.min(i,e.maxMaxBufferLength)}exceedsMaxBuffer(t,e,i){const s=t.nextStart;if(s&&i.start>s){const s=t.buffered;if(s){let r=t.len;const n=t.bufferedIndex;for(let t=s.length-1;t>n;t--)s[t].start<i.start&&(r+=s[t].end-s[t].start);return r>=e}}return!1}reduceMaxBufferLength(t,e){const i=this.config,s=Math.max(Math.min(t-e,i.maxBufferLength),e/2),r=Math.max(t-3*e,i.maxMaxBufferLength/2,s);return r>=s&&(i.maxMaxBufferLength=r,this.warn(`Reduce max buffer length to ${r}s`),!0)}getAppendedFrag(t){const e=this.fragmentTracker?this.fragmentTracker.getAppendedFrag(t,this.playlistType):null;return e&&"fragment"in e?e.fragment:e}getNextFragment(t,e){const i=e.fragments,s=i.length;if(!s)return null;const{config:r}=this,n=e.fragmentStart,a=r.lowLatencyMode&&!!e.partList;let o=null;if(e.live){const i=r.initialLiveManifestSize;if(s<i)return this.warn(`Not enough fragments to start playback (have: ${s}, need: ${i})`),null;if(this.startFragRequested||!a||this.loadingParts||(this.log("LL-Part loading ON for initial live fragment"),this.loadingParts=!0),!e.PTSKnown&&!this.startFragRequested&&-1===this.startPosition||t<n){var l;o=this.getInitialLiveFragment(e);const i=this.config.startPosition,s=this.hls.startPosition,r=this.hls.liveSyncPosition,a=(null==(l=o)?void 0:l.start)||0;let h,d;if(-1!==s&&s>=n?(h=s,d=s===i?"config":"next load start"):r?(h=r,d="live edge"):(h=t,d="buffer pos"),h<a&&(h=a,d="live frag start"),h<n&&(h=n,d="playlist start"),this.startPosition!=h||this.nextLoadPosition!=h){const l=e.live&&!this.filterReplacedPrimary(o,e)?-1:h;this.log(`Setting startPosition to ${l} next load ${h} ${-1===s?"":`(from ${i}) `}based on ${d}. live edge: ${r} live frag start: ${a} playlist start: ${n} buffer pos: ${t}`),this.startPosition=l,this.nextLoadPosition=h}}}else t<=n&&(o=i[0]);if(!o){const i=this.loadingParts?e.partEnd:e.fragmentEnd;o=this.getFragmentAtPosition(t,i,e)}let h=this.filterReplacedPrimary(o,e);return!h&&o&&(h=si(e,o.sn),h&&(this.nextLoadPosition=h.start)),h}isLoopLoading(t,e){if(this.nextLoadPosition<=e)return!1;const i=this.fragmentTracker.getState(t);if(i===Fi)return!0;if(i===Oi){if(t.gap)return!0;if(t.stats.retry>1)return!0}return!1}getNextFragmentLoopLoading(t,e,i,s,r){let n=null;if(t.gap&&(n=this.getNextFragment(this.nextLoadPosition,e),n&&!n.gap&&i.nextStart)){const t=this.getFwdBufferInfoAtPos(this.mediaBuffer?this.mediaBuffer:this.media,i.nextStart,s,0);if(null!==t&&i.len+t.len>=r){const t=n.sn;return this.loopSn!==t&&(this.log(`buffer full after gaps in "${s}" playlist starting at sn: ${t}`),this.loopSn=t),null}}return this.loopSn=void 0,n}get primaryPrefetch(){if(wr(this.config)){var t;if(null==(t=this.hls.interstitialsManager)||null==(t=t.playingItem)?void 0:t.event)return!0}return!1}filterReplacedPrimary(t,e){if(!t)return t;if(wr(this.config)&&("type"in t?t:t.fragment).type!==f.SUBTITLE){const i=this.hls.interstitialsManager,s=null==i?void 0:i.bufferingItem;if(s){const i=s.event;if(i){if(!i.appendInPlace&&(Math.abs(t.start-s.start)>1||0===s.start))return null}else{if(t.end<=s.start&&!1===(null==e?void 0:e.live))return null;if(t.start>=s.end&&s.nextEvent&&(s.nextEvent.appendInPlace&&!s.nextEvent.hasPlayed||t.start-s.end>1))return null}}if(Dr(t,null==i?void 0:i.playerQueue,this.playhead))return null}return t}getNextPart(t,e,i){let s=-1,r=!1,n=!0;for(let a=0,o=t.length;a<o;a++){const o=t[a];if(n=n&&!o.independent,s>-1&&i<o.start)break;const l=o.loaded||o.gap;l?s=-1:(r||(o.independent||n)&&o.fragment===e)&&(s=a),r=l&&!o.gap}const a=t[s];return a&&a.fragment!==e&&this.log(`Need buffer at ${i} but next unloaded part starts at ${a.start} (sn: ${e.sn} -> ${a.fragment.sn})`),s}loadedEndOfParts(t,e){let i;for(let s=t.length;s--;){if(i=t[s],!i.loaded)return!1;if(e>i.start)return!0}return!1}getInitialLiveFragment(t){const i=t.fragments,s=this.fragPrevious;let r=null;if(s){if(t.hasProgramDateTime&&(r=function(t,i,s){if(null===i||!Array.isArray(t)||!t.length||!e(i))return null;if(i<(t[0].programDateTime||0))return null;if(i>=(t[t.length-1].endProgramDateTime||0))return null;for(let e=0;e<t.length;++e){const r=t[e];if(ei(i,s,r))return r}return null}(i,s.endProgramDateTime,this.config.maxFragLookUpTolerance),r&&this.log(`Live playlist, switching playlist, load frag with same PDT: ${s.programDateTime}`)),!r){const e=s.sn+1;if(e>=t.startSN&&e<=t.endSN){const n=i[e-t.startSN];s.cc===n.cc&&(r=n,this.log(`Live playlist, switching playlist, load frag with next SN: ${r.sn}`))}r||(r=ii(t,s.cc,s.end),r&&this.log(`Live playlist, switching playlist, load frag with same CC: ${r.sn}`))}}else{const e=this.hls.liveSyncPosition;null!==e&&(r=this.getFragmentAtPosition(e,this.bitrateTest?t.fragmentEnd:t.edge,t))}return r}getFragmentAtPosition(t,e,i){const{config:s}=this;let{fragPrevious:r}=this,{fragments:n,endSN:a}=i;const{fragmentHint:o}=i,{maxFragLookUpTolerance:l}=s,h=i.partList,d=!!(this.loadingParts&&null!=h&&h.length&&o);let c;if(d&&!this.bitrateTest&&h[h.length-1].fragment.sn===o.sn&&(n=n.concat(o),a=o.sn),r&&this.fragmentTracker.getState(r)===xi&&(r=null),t<e){var u;c=Je(r,n,t,t<this.lastCurrentTime||t>e-l||null!=(u=this.media)&&u.paused||this.loadingParts||!this.startFragRequested?0:l)}else c=n[n.length-1];if(c){const t=c.sn,e=t-i.startSN,s=this.fragmentTracker.getState(c);if((s===Fi||s===Oi&&c.gap)&&(r=c),E(c,r)&&(!d||h[0].fragment.sn>t||!i.live||!h.some(e=>e.fragment.sn===t&&!e.loaded&&!e.gap))){const t=n[e+1];c=c.sn<a&&this.fragmentTracker.getState(t)!==Fi?t:null}}return c}alignPlaylists(t,i,s){const r=t.fragments.length;if(!r)return this.warn("No fragments in live playlist"),0;const n=t.fragmentStart,a=!i,o=t.alignedSliding&&e(n);if(a||!o&&!n){mr(s,t,this);const e=t.fragmentStart;return this.log(`Live playlist sliding: ${e} start-sn: ${i?i.startSN:"na"}->${t.startSN} fragments: ${r}`),e}return n}waitForCdnTuneIn(t){return t.live&&t.canBlockReload&&t.partTarget&&t.tuneInGoal>Math.max(t.partHoldBack,3*t.partTarget)}setStartPosition(t,i){let s=this.startPosition;s<i&&(s=-1);const r=this.timelineOffset;if(-1===s){const n=null!==this.startTimeOffset,a=n?this.startTimeOffset:t.startTimeOffset;if(null!==a&&e(a))s=i+a,a<0&&(s+=t.edge),s=Math.min(Math.max(i,s),i+t.totalduration),this.log(`Setting startPosition to ${s} for start time offset ${a} found in ${n?"multivariant":"media"} playlist`),this.startPosition=s;else if(t.live){const t=this.hls.liveSyncPosition;s=t||i,this.log(`Setting startPosition to -1 to start at ${t?"live edge":"playlist start"} ${s}`),this.startPosition=-1}else this.log("setting startPosition to 0 by default"),this.startPosition=s=0;this.lastCurrentTime=s+r}this.nextLoadPosition=s+r}getLoadPosition(){var t;const{media:e}=this;let i=0;return null!=(t=this.hls)&&t.hasEnoughToStart&&e&&!this.iframesOnly?i=e.currentTime:this.nextLoadPosition>=0&&(i=this.nextLoadPosition),i}get playhead(){var t;if(null!=(t=this.hls)&&t.hasEnoughToStart){var i;const t=null==(i=this.media)?void 0:i.currentTime;return e(t)?t:this.lastCurrentTime}return this.getLoadPosition()}get iframesOnly(){var t;if(this.playlistType!==f.MAIN)return!1;const e=this.getLevelDetails();return e?e.iframesOnly:null==(t=this.levelLastLoaded)?void 0:t.iframes}handleFragLoadAborted(t,e){this.transmuxer&&t.type===this.playlistType&&y(t)&&t.stats.aborted&&(this.log(`Fragment ${t.sn}${e?" part "+e.index:""} of ${this.playlistLabel()} ${t.level} was aborted`),this.resetFragmentLoading(t))}resetFragmentLoading(t){this.state!==pr&&(this.fragCurrent&&(this.fragContextChanged(t)||this.state===Tr)||(this.state=vr))}onFragmentOrKeyLoadError(t,e){if(e.chunkMeta&&!e.frag){const t=this.getCurrentContext(e.chunkMeta);t&&(e.frag=t.frag)}const{frag:i,part:s}=e;if(!i||!this.levels||i.type!==t)return;var r;if(this.fragContextChanged(i))return void this.warn(`Frag load error must match current frag to retry ${i.relurl} > ${null==(r=this.fragCurrent)?void 0:r.relurl}`);const a=e.details===n.FRAG_GAP;a&&this.fragmentTracker.addAsGap(i);const o=e.errorAction;if(!o)return void(this.state=Ir);const{action:l,flags:h,retryCount:d=0,retryConfig:c}=o,u=!!c,f=u&&l===oi,g=u&&!o.resolved&&h&hi,m=this.hls.latestLevelDetails,p=null==m?void 0:m.live;if(!f&&g&&y(i)&&p&&i.sn<m.endSN&&!P(e))this.resetFragmentErrors(t),s?s.gap=!0:this.treatAsGap(i),o.resolved=!0;else if((f||g)&&d<c.maxNumRetry){var v;const s=F(null==(v=e.response)?void 0:v.code),r=x(c,d);if(this.resetStartWhenNotLoaded(),this.retryDate=self.performance.now()+r,this.state=Tr,o.resolved=!0,s)return this.log("Waiting for connection (offline)"),this.retryDate=1/0,void(e.reason="offline");this.warn(`Fragment ${i.sn} of ${t} ${i.level} errored with ${e.details}, retrying loading ${d+1}/${c.maxNumRetry} in ${r}ms`)}else if(c){if(this.resetFragmentErrors(t),!(d<c.maxNumRetry))return void this.warn(`${e.details} reached or exceeded max retry (${d})`);a||l===ai||(o.resolved=!0)}else this.state=l===ni?kr:Ir;this.tickImmediate()}onSourceBufferError(t,e){var i,s;const{frag:r,part:n,sourceBufferName:a}=e,o=r&&(null==(i=this.levels)||null==(i=i[r.level])?void 0:i.details);if(e.error.name!==Ii||(null==r?void 0:r.type)!==t||!y(r)||null==o||!o.live)return;const l=n?0===n.index?n:null:r,h=l&&a?null==(s=l.elementaryStreams[a])?void 0:s.startPTS:void 0;if(this.markSourceBufferErrorGap(ar(o,r.sn)||r),void 0===h)return;const d=ar(o,r.sn-1);d&&this.fragmentTracker.getState(d)!==xi&&!Ei.isBuffered(this.mediaBuffer||this.media,h-this.config.maxBufferHole)&&this.markSourceBufferErrorGap(d)}markSourceBufferErrorGap(t){this.warn(`Marking fragment ${t.sn} of ${this.playlistLabel()} ${t.level} as a gap after a SourceBuffer error`),this.fragmentTracker.addAsGap(t)}checkRetryDate(){const t=self.performance.now(),e=this.retryDate,i=e===1/0;(!e||t>=e||i&&!F(0))&&(i&&this.log("Connection restored (online)"),this.resetStartWhenNotLoaded(),this.state=vr)}reduceLengthAndFlushBuffer(t){if(this.state===br||this.state===Ar){const e=t.frag,i=t.parent,s=this.getFwdBufferInfo(this.mediaBuffer,i),r=s&&s.len>.5;r&&this.reduceMaxBufferLength(s.len,(null==e?void 0:e.duration)||10);const n=!r;return n?this.warn(`Buffer full error while media.currentTime (${this.playhead}) is not buffered, flush ${i} buffer`):s.nextStart&&e&&s.nextStart>e.start&&this.flushMainBuffer(s.nextStart,Number.POSITIVE_INFINITY,i===f.AUDIO?i:void 0),e&&(this.fragmentTracker.removeFragment(e),this.nextLoadPosition=e.start),this.resetLoadingState(),n}return!1}resetFragmentErrors(t){t===f.AUDIO&&(this.fragCurrent=null),this.hls.hasEnoughToStart||(this.startFragRequested=!1),this.state!==pr&&(this.state=vr)}afterBufferFlushed(t,e){if(!t)return;const i=Ei.getBuffered(t);this.fragmentTracker.detectEvictedFragments(e,i,this.playlistType),this.state===Lr&&this.resetLoadingState()}resetLoadingState(){this.log("Reset loading state"),this.fragCurrent=null,this.fragPrevious=null,this.state!==pr&&(this.state=vr)}resetStartWhenNotLoaded(){if(!this.hls.hasEnoughToStart){this.startFragRequested=!1;const t=this.getLevelDetails();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(t){this.log(`Loading context changed while buffering sn ${t.sn} of ${this.playlistLabel()} ${-1===t.level?"<removed>":t.level}. This chunk will not be buffered.`),this.removeUnbufferedFrags(),this.resetStartWhenNotLoaded(),this.resetLoadingState()}removeUnbufferedFrags(t=0){this.fragmentTracker.removeFragmentsInRange(t,1/0,this.playlistType,!1,!0)}updateLevelTiming(t,e,i,s){const o=i.details;if(!o)return void this.warn("level.details undefined");this.log(`update level timing ${t.type} sn: ${t.sn}${e?" part: "+e.index:""} of ${this.fragInfo(t,!1,e)}`);if(!Object.keys(t.elementaryStreams).reduce((r,n)=>{const l=t.elementaryStreams[n];if(l){const h=l.endPTS-l.startPTS;if(h<=0)return this.warn(`Could not parse fragment ${t.sn} ${n} duration reliably (${h})`),r||!1;let d=0;return s.partial?e&&0===s.part&&(d=e.start-l.startPTS,t.startPTS=t.maxStartPTS=l.startPTS,t.startDTS=l.startDTS,0!==t.start&&t.setStart(l.startPTS),er(o,t,d)):d=tr(o,t,l.startPTS,l.endPTS,l.startDTS,l.endDTS,this.iframesOnly,this),this.hls.trigger(a.LEVEL_PTS_UPDATED,{details:o,level:i,drift:d,type:n,frag:t,part:e,start:l.startPTS,end:l.endPTS}),!0}return r},!1)){var l,h,d,c;const s=null===(null==(l=this.transmuxer)?void 0:l.error),o=null!=(null==(h=this.transmuxer)?void 0:h.error),u=(null!=(d=null==(c=this.levels)?void 0:c.length)?d:0)>1;if((0===i.fragmentError||s&&(i.fragmentError<2||t.endList)||o&&u)&&this.treatAsGap(t,i),s){const s=new Error(`Found no media in ${this.playlistLabel()} ${t.level} ${e?`part: ${e.index} of `:""}sn: ${t.sn} at playlist time: ${t.start}. Resetting transmuxer to fallback to playlist timing`);if(this.warn(s.message),this.hls.trigger(a.ERROR,{type:r.MEDIA_ERROR,details:n.FRAG_PARSING_ERROR,fatal:!1,error:s,frag:t,reason:`Found no media in msn ${t.sn} of ${this.playlistLabel()} "${i.url}"`}),!this.hls)return;this.resetTransmuxer()}}this.state=Ar,this.log(`Parsed ${t.type} sn: ${t.sn}${e?" part: "+e.index:""} of ${this.fragInfo(t,!1,e)}`),this.hls.trigger(a.FRAG_PARSED,{frag:t,part:e,chunkMeta:s})}playlistLabel(){return`${this.playlistType} playlist`}fragInfo(t,e=!0,i){var s,r;return`${t.type} playlist ${t.level} (${i?"part":"frag"}:[${null!=(s=e&&!i?t.startPTS:(i||t).start)?s:NaN}-${null!=(r=e&&!i?t.endPTS:(i||t).end)?r:NaN}]${i&&"main"===t.type?"INDEPENDENT="+(i.independent?"YES":"NO"):""})`}treatAsGap(t,e){e&&e.fragmentError++,this.fragmentTracker.addAsGap(t)}resetTransmuxer(){var t;null==(t=this.transmuxer)||t.reset()}isFragmentNearlyDownloaded(t){var e;const i=null==(e=t.loader)?void 0:e.stats;if(!i)return!1;if(i.total<=0)return!1;const s=i.loading.first>0,r=8*(i.total-i.loaded)/(this.hls.bandwidthEstimate||this.hls.config.abrEwmaDefaultEstimate);return s&&r<=.15}recoverWorkerError(t){"demuxerWorker"===t.event&&(this.fragmentTracker.removeAllFragments(),this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null),this.resetStartWhenNotLoaded(),this.resetLoadingState())}set state(t){const e=this._state;e!==t&&(this._state=t,this.log(`${e}->${t}`))}get state(){return this._state}calculateOptimalSwitchPoint(t,e){let i=0;const{hls:s,media:r,config:n,levels:a,playlistType:o}=this,l=this.getLevelDetails();if(r&&!r.paused&&a){var h;const e=o===f.AUDIO?ke(t.audioCodec,128e3):t.maxBitrate,r=1+s.ttfbEstimate/1e3,a=s.bandwidthEstimate*n.abrBandWidthUpFactor;i=r+e*(l&&(this.loadingParts?l.partTarget:l.averagetargetduration)||(null==(h=this.fragCurrent)?void 0:h.duration)||6)/a,t.details||(i+=r)}const d=this.playhead;return{fetchdelay:i,okToFlushForwardBuffer:!(null!=l&&l.live)||e.end-d>1.5*i}}scheduleTrackSwitch(t,e,i){const{media:s,playlistType:r}=this;if(!s||!t)return;const n=i?this.getBufferedFrag(this.playhead+e):null;if(n){const t=this.followingBufferedFrag(n);if(t){var a;this.abortCurrentFrag();const e=t.maxStartPTS?t.maxStartPTS:t.start,i=t.duration,s=Math.max(n.end,e+Math.min(Math.max(i-this.config.maxFragLookUpTolerance,i*(this.couldBacktrack?.5:.125)),i*(this.couldBacktrack?.75:.25)));if(((null==(a=this.getLevelDetails())?void 0:a.fragmentStart)||0)>s)return;const o=r===f.MAIN?null:"audio";this.flushMainBuffer(s,Number.POSITIVE_INFINITY,o),this.cleanupBackBuffer()}}}cleanupBackBuffer(){const{media:t,playlistType:e}=this;if(!t)return;const i=this.getAppendedFrag(this.playhead);if(i&&i.start>1){const t=e===f.AUDIO;this.flushMainBuffer(0,i.start-(t?0:1),t?"audio":null)}}getBufferedFrag(t){return this.fragmentTracker.getBufferedFrag(t,this.playlistType)}followingBufferedFrag(t){return t?this.getBufferedFrag(t.end+.5):null}abortCurrentFrag(){var t;const e=this.fragCurrent;switch(this.fragCurrent=null,e&&(e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.state){case yr:case Er:case Tr:case br:case Ar:this.state=vr}this.nextLoadPosition=null!=(t=this.hls)&&t.hasEnoughToStart?this.playhead:this.lastCurrentTime}checkFragPlaying(){const t=this.media;let e=null;if(t&&t.readyState>1&&!1===t.seeking){const i=t.currentTime;if(Ei.isBuffered(t,i)?e=this.getAppendedFrag(i):Ei.isBuffered(t,i+.1)&&(e=this.getAppendedFrag(i+.1)),e&&(this.backtrackFragment=void 0,!E(e,this.fragPlaying)))return this.fragPlaying=e,!0}return!1}getBufferOutput(){return null}nextLevelSwitch(){const{levels:t,media:e,hls:i,config:s,playlistType:r}=this;if(null!=e&&e.readyState&&t&&i&&s){const e=this.getBufferOutput(),s=this.getFwdBufferInfo(e,r);if(!s)return;const n=t[r===f.AUDIO?i.nextAudioTrack:i.nextLoadLevel],{fetchdelay:a,okToFlushForwardBuffer:o}=this.calculateOptimalSwitchPoint(n,s);this.scheduleTrackSwitch(s,a,o)}this.tickImmediate()}}function Dr(t,e,i){if(e)for(let s=e.length;s--;){const r=e[s].interstitial,n=r.startTime,a=Math.min(n+r.duration,r.resumeTime);if(r.appendInPlace){if(t.start>=n&&t.end<=a)return!0;if(i>t.start&&t.end>n&&t.start<a)return!0}}return!1}function wr(t){return!!t.interstitialsController&&!1!==t.enableInterstitialPlayback}class Pr{constructor(){this.chunks=[],this.dataLength=0}push(t){this.chunks.push(t),this.dataLength+=t.length}flush(){const{chunks:t,dataLength:e}=this;let i;return t.length?(i=1===t.length?t[0]:function(t,e){const i=new Uint8Array(e);let s=0;for(let e=0;e<t.length;e++){const r=t[e];i.set(r,s),s+=r.length}return i}(t,e),this.reset(),i):new Uint8Array(0)}reset(){this.chunks.length=0,this.dataLength=0}}var Cr,xr={exports:{}};var Mr=(Cr||(Cr=1,function(t){var e=Object.prototype.hasOwnProperty,i="~";function s(){}function r(t,e,i){this.fn=t,this.context=e,this.once=i||!1}function n(t,e,s,n,a){if("function"!=typeof s)throw new TypeError("The listener must be a function");var o=new r(s,n||t,a),l=i?i+e:e;return t._events[l]?t._events[l].fn?t._events[l]=[t._events[l],o]:t._events[l].push(o):(t._events[l]=o,t._eventsCount++),t}function a(t,e){0===--t._eventsCount?t._events=new s:delete t._events[e]}function o(){this._events=new s,this._eventsCount=0}Object.create&&(s.prototype=Object.create(null),(new s).__proto__||(i=!1)),o.prototype.eventNames=function(){var t,s,r=[];if(0===this._eventsCount)return r;for(s in t=this._events)e.call(t,s)&&r.push(i?s.slice(1):s);return Object.getOwnPropertySymbols?r.concat(Object.getOwnPropertySymbols(t)):r},o.prototype.listeners=function(t){var e=i?i+t:t,s=this._events[e];if(!s)return[];if(s.fn)return[s.fn];for(var r=0,n=s.length,a=new Array(n);r<n;r++)a[r]=s[r].fn;return a},o.prototype.listenerCount=function(t){var e=i?i+t:t,s=this._events[e];return s?s.fn?1:s.length:0},o.prototype.emit=function(t,e,s,r,n,a){var o=i?i+t:t;if(!this._events[o])return!1;var l,h,d=this._events[o],c=arguments.length;if(d.fn){switch(d.once&&this.removeListener(t,d.fn,void 0,!0),c){case 1:return d.fn.call(d.context),!0;case 2:return d.fn.call(d.context,e),!0;case 3:return d.fn.call(d.context,e,s),!0;case 4:return d.fn.call(d.context,e,s,r),!0;case 5:return d.fn.call(d.context,e,s,r,n),!0;case 6:return d.fn.call(d.context,e,s,r,n,a),!0}for(h=1,l=new Array(c-1);h<c;h++)l[h-1]=arguments[h];d.fn.apply(d.context,l)}else{var u,f=d.length;for(h=0;h<f;h++)switch(d[h].once&&this.removeListener(t,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,e);break;case 3:d[h].fn.call(d[h].context,e,s);break;case 4:d[h].fn.call(d[h].context,e,s,r);break;default:if(!l)for(u=1,l=new Array(c-1);u<c;u++)l[u-1]=arguments[u];d[h].fn.apply(d[h].context,l)}}return!0},o.prototype.on=function(t,e,i){return n(this,t,e,i,!1)},o.prototype.once=function(t,e,i){return n(this,t,e,i,!0)},o.prototype.removeListener=function(t,e,s,r){var n=i?i+t:t;if(!this._events[n])return this;if(!e)return a(this,n),this;var o=this._events[n];if(o.fn)o.fn!==e||r&&!o.once||s&&o.context!==s||a(this,n);else{for(var l=0,h=[],d=o.length;l<d;l++)(o[l].fn!==e||r&&!o[l].once||s&&o[l].context!==s)&&h.push(o[l]);h.length?this._events[n]=1===h.length?h[0]:h:a(this,n)}return this},o.prototype.removeAllListeners=function(t){var e;return t?(e=i?i+t:t,this._events[e]&&a(this,e)):(this._events=new s,this._eventsCount=0),this},o.prototype.off=o.prototype.removeListener,o.prototype.addListener=o.prototype.on,o.prefixed=i,o.EventEmitter=o,t.exports=o}(xr)),xr.exports),Or=o(Mr);const Fr="1.7.4",Nr={};function $r(t,e){return 255===t[e]&&240==(246&t[e+1])}function Br(t,e){return 1&t[e+1]?7:9}function Ur(t,e){return(3&t[e+3])<<11|t[e+4]<<3|(224&t[e+5])>>>5}function Gr(t,e){return e+1<t.length&&$r(t,e)}function Kr(t,e){if(Gr(t,e)){const i=Br(t,e);if(e+i>=t.length)return!1;const s=Ur(t,e);if(s<=i)return!1;const r=e+s;return r===t.length||Gr(t,r)}return!1}function Vr(t,e,i,s,o){if(!t.samplerate){const l=function(t,e,i,s){const o=e[i+2],l=o>>2&15;if(l>12){const e=new Error(`invalid ADTS sampling index:${l}`);return void t.emit(a.ERROR,a.ERROR,{type:r.MEDIA_ERROR,details:n.FRAG_PARSING_ERROR,fatal:!0,error:e,reason:e.message})}const h=1+(o>>6&3),d=e[i+3]>>6&3|(1&o)<<2,c=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350][l];let u,f=l;5!==h&&29!==h||(f-=3);const g=(14&f)>>1,m=(1&f)<<7|d<<3;let p=0;if(1===h&&l>=6){p=5;const t=l-3;u=[p<<3|g,m|(14&t)>>1,(1&t)<<7|8,0]}else u=[h<<3|g,m];const v="mp4a.40."+(p||h);return q.log(`manifest codec:${s}, parsed codec:${v}, channels:${d}, rate:${c} (ADTS object type:${h} sampling index:${l} esds config:[${u.join(",")}])`),{config:u,samplerate:c,channelCount:d,codec:v,parsedCodec:v,manifestCodec:s}}(e,i,s,o);if(!l)return;I(t,l)}}function jr(t){return 9216e4/t}function Hr(t,e,i,s,r){const n=s+r*jr(t.samplerate),a=function(t,e){const i=Br(t,e);if(e+i<=t.length){const s=Ur(t,e)-i;if(s>0)return{headerLength:i,frameLength:s}}}(e,i);let o;if(a){const{frameLength:s,headerLength:r}=a,l=r+s,h=Math.max(0,i+l-e.length);h?(o=new Uint8Array(l-r),o.set(e.subarray(i+r,e.length),0)):o=e.subarray(i+r,i+l);const d={unit:o,pts:n};return h||t.samples.push(d),{sample:d,length:l,missing:h}}const l=e.length-i;o=new Uint8Array(l),o.set(e.subarray(i,e.length),0);return{sample:{unit:o,pts:n},length:l,missing:-1}}let qr=function(t){return t.audioId3="org.id3",t.dateRange="com.apple.quicktime.HLS",t.emsg="https://aomedia.org/emsg/ID3",t.misbklv="urn:misb:KLV:bin:1910.1",t}({});function Yr(t="",e=9e4){return{type:t,id:-1,pid:-1,inputTimeScale:e,sequenceNumber:-1,samples:[],dropped:0}}class Wr{constructor(){this._audioTrack=void 0,this._id3Track=void 0,this.frameIndex=0,this.cachedData=null,this.basePTS=null,this.initPTS=null,this.lastPTS=null}resetInitSegment(t,e,i,s){this._id3Track={type:"id3",id:3,pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0}}resetTimeStamp(t){this.initPTS=t,this.resetContiguity()}resetContiguity(){this.basePTS=null,this.lastPTS=null,this.frameIndex=0}canParse(t,e){return!1}appendFrame(t,e,i){}demux(t,i){this.cachedData&&(t=Ht(this.cachedData,t),this.cachedData=null);let s,r=nt(t,0),n=r?r.length:0;const a=this._audioTrack,o=this._id3Track,l=r?gt(r):void 0,h=t.length;for((null===this.basePTS||0===this.frameIndex&&e(l))&&(this.basePTS=zr(l,i,this.initPTS),this.lastPTS=this.basePTS),null===this.lastPTS&&(this.lastPTS=this.basePTS),r&&r.length>0&&o.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:r,type:qr.audioId3,duration:Number.POSITIVE_INFINITY});n<h;){if(this.canParse(t,n)){const e=this.appendFrame(a,t,n);e?(this.frameIndex++,this.lastPTS=e.sample.pts,n+=e.length,s=n):n=h}else st(t,n)?(r=nt(t,n),o.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:r,type:qr.audioId3,duration:Number.POSITIVE_INFINITY}),n+=r.length,s=n):n++;if(n===h&&s!==h){const e=t.slice(s);this.cachedData?this.cachedData=Ht(this.cachedData,e):this.cachedData=e}}return{audioTrack:a,videoTrack:Yr(),id3Track:o,textTrack:Yr()}}demuxSampleAes(t,e,i){return Promise.reject(new Error(`[${this}] This demuxer does not support Sample-AES decryption`))}flush(t){const e=this.cachedData;return e&&(this.cachedData=null,this.demux(e,0)),{audioTrack:this._audioTrack,videoTrack:Yr(),id3Track:this._id3Track,textTrack:Yr()}}destroy(){this.cachedData=null,this._audioTrack=this._id3Track=void 0}}const zr=(t,i,s)=>{if(e(t))return 90*t;return 9e4*i+(s?9e4*s.baseTime/s.timescale:0)},Xr=[32,64,96,128,160,192,224,256,288,320,352,384,416,448,32,48,56,64,80,96,112,128,160,192,224,256,320,384,32,40,48,56,64,80,96,112,128,160,192,224,256,320,32,48,56,64,80,96,112,128,144,160,176,192,224,256,8,16,24,32,40,48,56,64,80,96,112,128,144,160],Qr=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],Zr=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],Jr=[0,1,1,4];function tn(t,e,i,s,r){if(i+24>e.length)return;const n=en(e,i);if(n&&i+n.frameLength<=e.length){const a=s+r*(9e4*n.samplesPerFrame/n.sampleRate),o={unit:e.subarray(i,i+n.frameLength),pts:a,dts:a};return t.config=[],t.channelCount=n.channelCount,t.samplerate=n.sampleRate,t.samples.push(o),{sample:o,length:n.frameLength,missing:0}}}function en(t,e){const i=t[e+1]>>3&3,s=t[e+1]>>1&3,r=t[e+2]>>4&15,n=t[e+2]>>2&3;if(1!==i&&0!==r&&15!==r&&3!==n){const a=t[e+2]>>1&1,o=t[e+3]>>6,l=1e3*Xr[14*(3===i?3-s:3===s?3:4)+r-1],h=Qr[3*(3===i?0:2===i?1:2)+n],d=3===o?1:2,c=Zr[i][s],u=Jr[s],f=8*c*u,g=Math.floor(c*l/h+a)*u,m=ne();return!!m&&m<=87&&2===s&&l>=224e3&&0===o&&(t[e+3]=128|t[e+3]),{sampleRate:h,channelCount:d,frameLength:g,samplesPerFrame:f}}}function sn(t,e){return!(255!==t[e]||224&~t[e+1]||!(6&t[e+1]))}function rn(t,e){return e+1<t.length&&sn(t,e)}function nn(t,e){if(e+1<t.length&&sn(t,e)){const i=4,s=en(t,e);let r=i;null!=s&&s.frameLength&&(r=s.frameLength);const n=e+r;return n===t.length||rn(t,n)}return!1}class an{constructor(t,e,i){this.keyData=void 0,this.decrypter=void 0,this.keyData=i,this.decrypter=new qi(e,!0)}decryptBuffer(t){return this.decrypter.decrypt(t,this.keyData.key.buffer,this.keyData.iv.buffer,Gi,{start:0,end:t.byteLength})}decryptAacSample(t,e,i){const s=t[e].unit;if(s.length<=16)return;const r=s.subarray(16,s.length-s.length%16),n=r.buffer.slice(r.byteOffset,r.byteOffset+r.length);this.decryptBuffer(n).then(r=>{const n=new Uint8Array(r);s.set(n,16),this.decrypter.isSync()||this.decryptAacSamples(t,e+1,i)}).catch(i)}decryptAacSamples(t,e,i){for(;;e++){if(e>=t.length)return void i();if(!(t[e].unit.length<32)&&(this.decryptAacSample(t,e,i),!this.decrypter.isSync()))return}}getAvcEncryptedData(t){const e=16*Math.floor((t.length-48)/160)+16,i=new Int8Array(e);let s=0;for(let e=32;e<t.length-16;e+=160,s+=16)i.set(t.subarray(e,e+16),s);return i}getAvcDecryptedUnit(t,e){const i=new Uint8Array(e);let s=0;for(let e=32;e<t.length-16;e+=160,s+=16)t.set(i.subarray(s,s+16),e);return t}decryptAvcSample(t,e,i,s,r){const n=zt(r.data),a=this.getAvcEncryptedData(n);this.decryptBuffer(a.buffer).then(a=>{r.data=this.getAvcDecryptedUnit(n,a),this.decrypter.isSync()||this.decryptAvcSamples(t,e,i+1,s)}).catch(s)}decryptAvcSamples(t,e,i,s){if(t instanceof Uint8Array)throw new Error("Cannot decrypt samples of type Uint8Array");for(;;e++,i=0){if(e>=t.length)return void s();const r=t[e].units;for(;!(i>=r.length);i++){const n=r[i];if(!(n.data.length<=48||1!==n.type&&5!==n.type||(this.decryptAvcSample(t,e,i,s,n),this.decrypter.isSync())))return}}}}const on=(t,e)=>{let i=0,s=5;e+=s;const r=new Uint32Array(1),n=new Uint32Array(1),a=new Uint8Array(1);for(;s>0;){a[0]=t[e];const o=Math.min(s,8),l=8-o;n[0]=4278190080>>>24+l<<l,r[0]=(a[0]&n[0])>>l,i=i?i<<o|r[0]:r[0],e+=1,s-=o}return i};class ln extends Wr{constructor(t){super(),this.observer=void 0,this.observer=t}resetInitSegment(t,e,i,s){super.resetInitSegment(t,e,i,s),this._audioTrack={container:"audio/ac-3",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"ac3",samples:[],manifestCodec:e,duration:s,inputTimeScale:9e4,dropped:0}}canParse(t,e){return e+64<t.length}appendFrame(t,e,i){const s=hn(t,e,i,this.basePTS,this.frameIndex);if(-1!==s){return{sample:t.samples[t.samples.length-1],length:s,missing:0}}}static probe(t){if(!t)return!1;const e=nt(t,0);if(!e)return!1;const i=e.length;if(11===t[i]&&119===t[i+1]&&void 0!==gt(e)){if(on(t,i)<16)return!0;throw new Error("Containerless ec-3 is not supported")}return!1}}function hn(t,e,i,s,r){if(i+8>e.length)return-1;if(11!==e[i]||119!==e[i+1])return-1;const n=e[i+4]>>6;if(n>=3)return-1;const a=[48e3,44100,32e3][n],o=63&e[i+4],l=2*[64,69,96,64,70,96,80,87,120,80,88,120,96,104,144,96,105,144,112,121,168,112,122,168,128,139,192,128,140,192,160,174,240,160,175,240,192,208,288,192,209,288,224,243,336,224,244,336,256,278,384,256,279,384,320,348,480,320,349,480,384,417,576,384,418,576,448,487,672,448,488,672,512,557,768,512,558,768,640,696,960,640,697,960,768,835,1152,768,836,1152,896,975,1344,896,976,1344,1024,1114,1536,1024,1115,1536,1152,1253,1728,1152,1254,1728,1280,1393,1920,1280,1394,1920][3*o+n];if(i+l>e.length)return-1;const h=e[i+6]>>5;let d=0;2===h?d+=2:(1&h&&1!==h&&(d+=2),4&h&&(d+=2));const c=(e[i+6]<<8|e[i+7])>>12-d&1,u=[2,1,2,3,3,4,4,5][h]+c,f=e[i+5]>>3,g=7&e[i+5],m=new Uint8Array([n<<6|f<<1|g>>2,(3&g)<<6|h<<3|c<<2|o>>4,o<<4&224]),p=s+r*(1536/a*9e4),v=e.subarray(i,i+l);return t.config=m,t.channelCount=u,t.samplerate=a,t.samples.push({unit:v,pts:p}),l}const dn=/\/emsg[-/]ID3/i;function cn(t,i){return e(t.presentationTime)?t.presentationTime/t.timeScale:i+t.presentationTimeDelta/t.timeScale}class un{constructor(){this.VideoSample=null}createVideoSample(t,e,i){return{key:t,frame:!1,pts:e,dts:i,units:[],length:0}}getLastNalUnit(t){var e;let i,s=this.VideoSample;if(s&&0!==s.units.length||(s=t[t.length-1]),null!=(e=s)&&e.units){const t=s.units;i=t[t.length-1]}return i}pushAccessUnit(t,e){if(t.units.length&&t.frame){if(void 0===t.pts){const i=e.samples,s=i.length;if(!s)return void e.dropped++;{const e=i[s-1];t.pts=e.pts,t.dts=e.dts}}e.samples.push(t)}}parseNALu(t,e,i){const s=e.byteLength;if(0===s)return[];const r=t.naluState||0,n=-1===r?0:r,a=[];let o=0,l=0,h=-1,d=0;for(-1===r&&(h=0,d=this.getNALuType(e,0),l=1);l<s;){const i=e.indexOf(1,l);if(-1===i)break;l=i+1;let r=i;for(;r>0&&0===e[r-1];)r--;const c=i-r+(0===r?n:0);if(c<2)continue;const u=Math.min(c,3),f=Math.min(i-r,u),g=u-f;if(r=i-f,h>=0)a.push({data:e.subarray(h,r),type:d});else{const i=this.getLastNalUnit(t.samples);i&&(r>0?i.data=Ht(i.data,e.subarray(0,r)):g>0&&(i.data=i.data.subarray(0,i.data.byteLength-g)),i.state=0)}if(!(l<s)){o=-1,h=-1;break}h=l,d=this.getNALuType(e,l)}if(-1!==o){let t=s;for(;t>0&&0===e[t-1];)t--;o=s-t+(0===t?n:0)}if(h>=0)a.push({data:e.subarray(h),type:d,state:o});else if(0===a.length&&-1!==o){const i=this.getLastNalUnit(t.samples);i&&(i.data=Ht(i.data,e),i.state=o)}return t.naluState=o,a}}class fn{constructor(t){this.data=void 0,this.bytesAvailable=void 0,this.word=void 0,this.bitsAvailable=void 0,this.data=t,this.bytesAvailable=t.byteLength,this.word=0,this.bitsAvailable=0}loadWord(){const t=this.data,e=this.bytesAvailable,i=t.byteLength-e,s=new Uint8Array(4),r=Math.min(4,e);if(0===r)throw new Error("no bytes available");s.set(t.subarray(i,i+r)),this.word=new DataView(s.buffer).getUint32(0),this.bitsAvailable=8*r,this.bytesAvailable-=r}skipBits(t){let e;t=Math.min(t,8*this.bytesAvailable+this.bitsAvailable),this.bitsAvailable>t?(this.word<<=t,this.bitsAvailable-=t):(e=(t-=this.bitsAvailable)>>3,t-=e<<3,this.bytesAvailable-=e,this.loadWord(),this.word<<=t,this.bitsAvailable-=t)}readBits(t){let e=Math.min(this.bitsAvailable,t);const i=this.word>>>32-e;if(t>32&&q.error("Cannot read more than 32 bits at a time"),this.bitsAvailable-=e,this.bitsAvailable>0)this.word<<=e;else{if(!(this.bytesAvailable>0))throw new Error("no bits available");this.loadWord()}return e=t-e,e>0&&this.bitsAvailable?i<<e|this.readBits(e):i}skipLZ(){let t;for(t=0;t<this.bitsAvailable;++t)if(this.word&2147483648>>>t)return this.word<<=t,this.bitsAvailable-=t,t;return this.loadWord(),t+this.skipLZ()}skipUEG(){this.skipBits(1+this.skipLZ())}skipEG(){this.skipBits(1+this.skipLZ())}readUEG(){const t=this.skipLZ();return this.readBits(t+1)-1}readEG(){const t=this.readUEG();return 1&t?1+t>>>1:-1*(t>>>1)}readBoolean(){return 1===this.readBits(1)}readUByte(){return this.readBits(8)}}class gn extends un{parsePES(t,e,i,s,r){const n=r.iframe,a=this.parseNALu(t,i.data,s);let o,l=this.VideoSample,h=!1;i.data=null,l&&a.length&&!t.audFound&&(this.pushAccessUnit(l,t),l=this.VideoSample=this.createVideoSample(!1,i.pts,i.dts)),a.forEach(s=>{var r,a;switch(s.type){case 1:{if(n)break;let e=!1;o=!0;const r=s.data;if(h&&r.length>4){const t=this.readSliceType(r);2!==t&&4!==t&&7!==t&&9!==t||(e=!0)}var d;if(e)null!=(d=l)&&d.frame&&!l.key&&(this.pushAccessUnit(l,t),l=this.VideoSample=null);l||(l=this.VideoSample=this.createVideoSample(!0,i.pts,i.dts)),l.frame=!0,l.key=e;break}case 5:o=!0,null!=(r=l)&&r.frame&&!l.key&&(this.pushAccessUnit(l,t),l=this.VideoSample=null),l||(l=this.VideoSample=this.createVideoSample(!0,i.pts,i.dts)),l.key=!0,l.frame=!0;break;case 6:if(n)break;o=!0,Wt(s.data,1,i.pts,e.samples);break;case 7:{var c,u;o=!0,h=!0;const e=s.data,i=this.readSPS(e);if(!t.sps||t.width!==i.width||t.height!==i.height||(null==(c=t.pixelRatio)?void 0:c[0])!==i.pixelRatio[0]||(null==(u=t.pixelRatio)?void 0:u[1])!==i.pixelRatio[1]){t.width=i.width,t.height=i.height,t.pixelRatio=i.pixelRatio,t.sps=[e];const s=e.subarray(1,4);let r="avc1.";for(let t=0;t<3;t++){let e=s[t].toString(16);e.length<2&&(e="0"+e),r+=e}t.codec=r}break}case 8:o=!0,t.pps=[s.data];break;case 9:o=!0,t.audFound=!0,null!=(a=l)&&a.frame&&(this.pushAccessUnit(l,t),l=null),l||(l=this.VideoSample=this.createVideoSample(!1,i.pts,i.dts));break;case 12:o=!0;break;default:o=!1}if(l&&o){l.units.push(s)}}),s&&l&&(this.pushAccessUnit(l,t),this.VideoSample=null)}getNALuType(t,e){return 31&t[e]}readSliceType(t){const e=new fn(t);return e.readUByte(),e.readUEG(),e.readUEG()}skipScalingList(t,e){let i,s=8,r=8;for(let n=0;n<t;n++)0!==r&&(i=e.readEG(),r=(s+i+256)%256),s=0===r?s:r}readSPS(t){const e=new fn(t);let i,s,r,n=0,a=0,o=0,l=0;const h=e.readUByte.bind(e),d=e.readBits.bind(e),c=e.readUEG.bind(e),u=e.readBoolean.bind(e),f=e.skipBits.bind(e),g=e.skipEG.bind(e),m=e.skipUEG.bind(e),p=this.skipScalingList.bind(this);h();const v=h();if(d(5),f(3),h(),m(),100===v||110===v||122===v||244===v||44===v||83===v||86===v||118===v||128===v){const t=c();if(3===t&&f(1),m(),m(),f(1),u())for(s=3!==t?8:12,r=0;r<s;r++)u()&&p(r<6?16:64,e)}m();const y=c();if(0===y)c();else if(1===y)for(f(1),g(),g(),i=c(),r=0;r<i;r++)g();m(),f(1);const E=c(),T=c(),S=d(1);0===S&&f(1),f(1),u()&&(n=c(),a=c(),o=c(),l=c());let b=[1,1];if(u()&&u()){switch(h()){case 1:b=[1,1];break;case 2:b=[12,11];break;case 3:b=[10,11];break;case 4:b=[16,11];break;case 5:b=[40,33];break;case 6:b=[24,11];break;case 7:b=[20,11];break;case 8:b=[32,11];break;case 9:b=[80,33];break;case 10:b=[18,11];break;case 11:b=[15,11];break;case 12:b=[64,33];break;case 13:b=[160,99];break;case 14:b=[4,3];break;case 15:b=[3,2];break;case 16:b=[2,1];break;case 255:b=[h()<<8|h(),h()<<8|h()]}}return{width:Math.ceil(16*(E+1)-2*n-2*a),height:(2-S)*(T+1)*16-(S?2:4)*(o+l),pixelRatio:b}}}class mn extends un{constructor(...t){super(...t),this.initVPS=null}parsePES(t,e,i,s){const r=this.parseNALu(t,i.data,s);let n,a=this.VideoSample,o=!1;i.data=null;const l=t=>(a=this.VideoSample=this.createVideoSample(t,i.pts,i.dts),a);r.forEach((s,r)=>{var h,d;if(this.startsNewAccessUnit(a,t,s,r)){this.pushAccessUnit(a,t);const e=s.type>=16&&s.type<=23;a=l(e),o=!1}switch(s.type){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:case 8:case 9:a||(a=l(!1)),a.frame=!0,n=!0;break;case 16:case 17:case 18:case 21:case 22:case 23:var c;if(n=!0,o)null!=(c=a)&&c.frame&&!a.key&&(this.pushAccessUnit(a,t),a=this.VideoSample=null);a||(a=l(!0)),a.key=!0,a.frame=!0;break;case 19:case 20:n=!0,null!=(h=a)&&h.frame&&!a.key&&(this.pushAccessUnit(a,t),a=this.VideoSample=null),a||(a=l(!0)),a.key=!0,a.frame=!0;break;case 39:n=!0,Wt(s.data,2,i.pts,e.samples);break;case 32:n=!0,t.vps||("object"!=typeof t.params&&(t.params={}),t.params=I(t.params,this.readVPS(s.data)),this.initVPS=s.data),t.vps=[s.data];break;case 33:if(n=!0,o=!0,void 0===t.vps||t.vps[0]===this.initVPS||void 0===t.sps||this.matchSPS(t.sps[0],s.data)||(this.initVPS=t.vps[0],t.sps=t.pps=void 0),!t.sps){const e=this.readSPS(s.data);t.width=e.width,t.height=e.height,t.pixelRatio=e.pixelRatio,t.codec=e.codecString,t.sps=[],"object"!=typeof t.params&&(t.params={});for(const i in e.params)t.params[i]=e.params[i]}this.pushParameterSet(t.sps,s.data,t.vps),a||(a=l(!1));break;case 34:if(n=!0,"object"==typeof t.params){if(!t.pps){t.pps=[];const e=this.readPPS(s.data);for(const i in e)t.params[i]=e[i]}this.pushParameterSet(t.pps,s.data,t.vps)}break;case 35:n=!0,t.audFound=!0,null!=(d=a)&&d.frame&&(this.pushAccessUnit(a,t),a=null),a||(a=l(!1));break;default:n=!1}if(a&&n){a.units.push(s)}}),s&&a&&(this.pushAccessUnit(a,t),this.VideoSample=null)}pushParameterSet(t,e,i){(i&&i[0]===this.initVPS||!i&&!t.length)&&t.push(e)}startsNewAccessUnit(t,e,i,s){if(!t)return!1;if(!e.audFound&&0===s)return!0;if(!t.frame)return!1;const{type:r,data:n}=i;return!!(r>=32&&r<=35||39===r||r>=41&&r<=44||r>=48&&r<=55)||r<=31&&n.length>2&&!!(128&n[2])}getNALuType(t,e){return(126&t[e])>>>1}ebsp2rbsp(t){const e=new Uint8Array(t.byteLength);let i=0;for(let s=0;s<t.byteLength;s++)s>=2&&3===t[s]&&0===t[s-1]&&0===t[s-2]||(e[i]=t[s],i++);return new Uint8Array(e.buffer,0,i)}pushAccessUnit(t,e){super.pushAccessUnit(t,e),this.initVPS&&(this.initVPS=null)}readVPS(t){const e=new fn(t);e.readUByte(),e.readUByte(),e.readBits(4),e.skipBits(2),e.readBits(6);return{numTemporalLayers:e.readBits(3)+1,temporalIdNested:e.readBoolean()}}readSPS(t){const e=new fn(this.ebsp2rbsp(t));e.readUByte(),e.readUByte(),e.readBits(4);const i=e.readBits(3);e.readBoolean();const s=e.readBits(2),r=e.readBoolean(),n=e.readBits(5),a=e.readUByte(),o=e.readUByte(),l=e.readUByte(),h=e.readUByte(),d=e.readUByte(),c=e.readUByte(),u=e.readUByte(),f=e.readUByte(),g=e.readUByte(),m=e.readUByte(),p=e.readUByte(),v=[],y=[];for(let t=0;t<i;t++)v.push(e.readBoolean()),y.push(e.readBoolean());if(i>0)for(let t=i;t<8;t++)e.readBits(2);for(let t=0;t<i;t++)v[t]&&(e.readUByte(),e.readUByte(),e.readUByte(),e.readUByte(),e.readUByte(),e.readUByte(),e.readUByte(),e.readUByte(),e.readUByte(),e.readUByte(),e.readUByte()),y[t]&&e.readUByte();e.readUEG();const E=e.readUEG();3==E&&e.skipBits(1);const T=e.readUEG(),S=e.readUEG(),b=e.readBoolean();let A=0,L=0,I=0,R=0;b&&(A+=e.readUEG(),L+=e.readUEG(),I+=e.readUEG(),R+=e.readUEG());const k=e.readUEG(),_=e.readUEG(),D=e.readUEG();for(let t=e.readBoolean()?0:i;t<=i;t++)e.skipUEG(),e.skipUEG(),e.skipUEG();e.skipUEG(),e.skipUEG(),e.skipUEG(),e.skipUEG(),e.skipUEG(),e.skipUEG();if(e.readBoolean()){if(e.readBoolean())for(let t=0;t<4;t++)for(let i=0;i<(3===t?2:6);i++){if(e.readBoolean()){const i=Math.min(64,1<<4+(t<<1));t>1&&e.readEG();for(let t=0;t<i;t++)e.readEG()}else e.readUEG()}}e.readBoolean(),e.readBoolean();e.readBoolean()&&(e.readUByte(),e.skipUEG(),e.skipUEG(),e.readBoolean());const w=e.readUEG();let P=0;for(let t=0;t<w;t++){let i=!1;if(0!==t&&(i=e.readBoolean()),i){t===w&&e.readUEG(),e.readBoolean(),e.readUEG();let i=0;for(let t=0;t<=P;t++){const t=e.readBoolean();let s=!1;t||(s=e.readBoolean()),(t||s)&&i++}P=i}else{const t=e.readUEG(),i=e.readUEG();P=t+i;for(let i=0;i<t;i++)e.readUEG(),e.readBoolean();for(let t=0;t<i;t++)e.readUEG(),e.readBoolean()}}if(e.readBoolean()){const t=e.readUEG();for(let i=0;i<t;i++){for(let t=0;t<D+4;t++)e.readBits(1);e.readBits(1)}}let C=0,x=1,M=1,O=!0,F=1,N=0;e.readBoolean(),e.readBoolean();let $=!1;if(e.readBoolean()){if(e.readBoolean()){const t=e.readUByte();t>0&&t<16?(x=[1,12,10,16,40,24,20,32,80,18,15,64,160,4,3,2][t-1],M=[1,11,11,11,33,11,11,11,33,11,11,33,99,3,2,1][t-1]):255===t&&(x=e.readBits(16),M=e.readBits(16))}e.readBoolean()&&e.readBoolean();if(e.readBoolean()){e.readBits(3),e.readBoolean();e.readBoolean()&&(e.readUByte(),e.readUByte(),e.readUByte())}e.readBoolean()&&(e.readUEG(),e.readUEG()),e.readBoolean(),e.readBoolean(),e.readBoolean(),$=e.readBoolean(),$&&(e.skipUEG(),e.skipUEG(),e.skipUEG(),e.skipUEG());if(e.readBoolean()){F=e.readBits(32),N=e.readBits(32);e.readBoolean()&&e.readUEG();if(e.readBoolean()){const t=e.readBoolean(),s=e.readBoolean();let r=!1;(t||s)&&(r=e.readBoolean(),r&&(e.readUByte(),e.readBits(5),e.readBoolean(),e.readBits(5)),e.readBits(4),e.readBits(4),r&&e.readBits(4),e.readBits(5),e.readBits(5),e.readBits(5));for(let n=0;n<=i;n++){O=e.readBoolean();let i=!1;O||e.readBoolean()?e.readEG():i=e.readBoolean();const n=i?1:e.readUEG()+1;if(t)for(let t=0;t<n;t++)e.readUEG(),e.readUEG(),r&&(e.readUEG(),e.readUEG()),e.skipBits(1);if(s)for(let t=0;t<n;t++)e.readUEG(),e.readUEG(),r&&(e.readUEG(),e.readUEG()),e.skipBits(1)}}}e.readBoolean()&&(e.readBoolean(),e.readBoolean(),e.readBoolean(),C=e.readUEG())}let B=T,U=S;if(b){let t=1,e=1;1===E?t=e=2:2==E&&(t=2),B=T-t*L-t*A,U=S-e*R-e*I}const G=s?["A","B","C"][s]:"",K=a<<24|o<<16|l<<8|h;let V=0;for(let t=0;t<32;t++)V=(V|(K>>t&1)<<31-t)>>>0;let j=V.toString(16);1===n&&"2"===j&&(j="6");return{codecString:`hvc1.${G}${n}.${j}.${r?"H":"L"}${p}.B0`,params:{general_tier_flag:r,general_profile_idc:n,general_profile_space:s,general_profile_compatibility_flags:[a,o,l,h],general_constraint_indicator_flags:[d,c,u,f,g,m],general_level_idc:p,bit_depth:k+8,bit_depth_luma_minus8:k,bit_depth_chroma_minus8:_,min_spatial_segmentation_idc:C,chroma_format_idc:E,frame_rate:{fixed:O,fps:N/F}},width:B,height:U,pixelRatio:[x,M]}}readPPS(t){const e=new fn(this.ebsp2rbsp(t));e.readUByte(),e.readUByte(),e.skipUEG(),e.skipUEG(),e.skipBits(2),e.skipBits(3),e.skipBits(2),e.skipUEG(),e.skipUEG(),e.skipEG(),e.skipBits(2);e.readBoolean()&&e.skipUEG(),e.skipEG(),e.skipEG(),e.skipBits(4);const i=e.readBoolean(),s=e.readBoolean();let r=1;return s&&i?r=0:s?r=3:i&&(r=2),{parallelismType:r}}matchSPS(t,e){return yt(t).substring(3)===yt(e).substring(3)}}const pn=188;class vn{constructor(t,e,i,s){this.logger=void 0,this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.sampleAes=null,this.pmtParsed=!1,this.audioCodec=void 0,this.videoCodec=void 0,this._pmtId=-1,this._videoTrack=void 0,this._audioTrack=void 0,this._id3Track=void 0,this._txtTrack=void 0,this._klvPid=-1,this.aacOverFlow=null,this.remainderData=null,this.videoParser=void 0,this.videoIntegrityChecker=null,this.observer=t,this.config=e,this.typeSupported=i,this.logger=s,this.videoParser=null}static probe(t,e){const i=vn.syncOffset(t);return i>0&&e.warn(`MPEG2-TS detected but first sync word found @ offset ${i}`),-1!==i}static syncOffset(t){const e=t.length;let i=Math.min(940,e-pn)+1,s=0;for(;s<i;){let r=!1,n=-1,a=0;for(let o=s;o<e;o+=pn){if(71!==t[o]||e-o!==pn&&71!==t[o+pn]){if(a)return-1;break}if(a++,-1===n&&(n=o,0!==n&&(i=Math.min(n+18612,t.length-pn)+1)),r||(r=0===yn(t,o)),r&&a>1&&(0===n&&a>2||o+pn>i))return n}s++}return-1}static createTrack(t,e){return{container:"video"===t||"audio"===t?"video/mp2t":void 0,type:t,id:St[t],pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0,duration:"audio"===t?e:void 0}}resetInitSegment(t,e,i,s,r,n){this.pmtParsed=!1,this._pmtId=-1,this._videoTrack=vn.createTrack("video"),this._videoTrack.duration=s,this.videoIntegrityChecker="skip"===this.config.handleMpegTsVideoIntegrityErrors?new Ln(this.logger):null,this._audioTrack=vn.createTrack("audio",s),this._id3Track=vn.createTrack("id3"),this._txtTrack=vn.createTrack("text"),this._audioTrack.segmentCodec="aac",this.videoParser=null,this.aacOverFlow=null,this.remainderData=null,this.audioCodec=e,this.videoCodec=i,t&&this.demux(t,0,n,"SAMPLE-AES"===(null==r?void 0:r.method))}resetTimeStamp(){}resetContiguity(){const{_audioTrack:t,_videoTrack:e,_id3Track:i}=this;t&&(t.pesData=null),e&&(e.pesData=null),i&&(i.pesData=null),this.videoParser=null,this.aacOverFlow=null,this.remainderData=null}demux(t,e,i,s=!1,r=!1){let n;s||(this.sampleAes=null);const a=this._videoTrack,o=this.videoIntegrityChecker,l=this._audioTrack,h=this._id3Track,d=this._txtTrack,c=i.iframe;let u=a.pid,f=a.pesData,g=l.pid,m=h.pid,p=this._klvPid,v=l.pesData,y=h.pesData,E=null,T=null,S=this.pmtParsed,b=this._pmtId,A=t.length;if(this.remainderData&&(A=(t=Ht(this.remainderData,t)).length,this.remainderData=null),A<pn&&!r)return this.remainderData=t,{audioTrack:l,videoTrack:a,id3Track:h,textTrack:d};const L=Math.max(0,vn.syncOffset(t));A-=(A-L)%pn,A<t.byteLength&&!r&&(this.remainderData=new Uint8Array(t.buffer,A,t.buffer.byteLength-A));let I=0;for(let e=L;e<A;e+=pn)if(71===t[e]){const r=!!(64&t[e+1]),A=yn(t,e);let I;if((48&t[e+3])>>4>1){if(I=e+5+t[e+4],I===e+pn)continue}else I=e+4;switch(A){case u:r&&(!f||null!=o&&o.isCorrupted||!(n=An(f,this.logger))||(this.readyVideoParser(a.segmentCodec),null!==this.videoParser&&this.videoParser.parsePES(a,d,n,!1,i)),f={data:[],size:0},null==o||o.reset(u)),null==o||o.handlePacket(t.subarray(e)),f&&(f.data.push(t.subarray(I,e+pn)),f.size+=e+pn-I);break;case g:if(c)break;if(r){if(v&&(n=An(v,this.logger)))switch(l.segmentCodec){case"aac":this.parseAACPES(l,n,i);break;case"mp3":this.parseMPEGPES(l,n);break;case"ac3":this.parseAC3PES(l,n)}v={data:[],size:0}}v&&(v.data.push(t.subarray(I,e+pn)),v.size+=e+pn-I);break;case m:if(c)break;r&&(y&&(n=An(y,this.logger))&&this.parseID3PES(h,n),y={data:[],size:0}),y&&(y.data.push(t.subarray(I,e+pn)),y.size+=e+pn-I);break;case p:if(c)break;r&&(E&&(n=An(E,this.logger))&&this.parseKlvPES(h,n),E={data:[],size:0}),E&&(E.data.push(t.subarray(I,e+pn)),E.size+=e+pn-I);break;case 0:r&&(I+=t[I]+1),b=this._pmtId=En(t,I);break;case b:{r&&(I+=t[I]+1);const n=Tn(t,I,this.typeSupported,s,this.observer,this.logger,this.config,i);u=n.videoPid,u>0&&(a.pid=u,a.segmentCodec=n.segmentVideoCodec),g=n.audioPid,g>0&&(l.pid=g,l.segmentCodec=n.segmentAudioCodec),m=n.id3Pid,m>0&&(h.pid=m),p=n.klvPid,p>0&&(this._klvPid=p),null===T||S||(this.logger.warn(`MPEG-TS PMT found at ${e} after unknown PID '${T}'. Backtracking to sync byte @${L} to parse all TS packets.`),T=null,e=L-188),S=this.pmtParsed=!0;break}case 17:case 8191:break;default:T=A}}else I++;I>0&&Sn(this.observer,new Error(`Found ${I} TS packet/s that do not start with 0x47`),i,void 0,this.logger),a.pesData=f,l.pesData=v,h.pesData=y;const R={audioTrack:l,videoTrack:a,id3Track:h,textTrack:d};return r&&this.extractRemainingSamples(R,i),R}flush(t,e){const{remainderData:i}=this;let s;return this.remainderData=null,s=i?this.demux(i,0,e,!1,!0):{videoTrack:this._videoTrack,audioTrack:this._audioTrack,id3Track:this._id3Track,textTrack:this._txtTrack},this.extractRemainingSamples(s,e),this.sampleAes?this.decrypt(s,this.sampleAes):s}extractRemainingSamples(t,e){const{audioTrack:i,videoTrack:s,id3Track:r,textTrack:n}=t,a=s.pesData,o=i.pesData,l=r.pesData,h=this.videoIntegrityChecker;let d;if(!a||null!=h&&h.isCorrupted||!(d=An(a,this.logger))?s.pesData=a:(this.readyVideoParser(s.segmentCodec),null!==this.videoParser&&(this.videoParser.parsePES(s,n,d,!0,e),s.pesData=null)),o&&(d=An(o,this.logger))){switch(i.segmentCodec){case"aac":this.parseAACPES(i,d,e);break;case"mp3":this.parseMPEGPES(i,d);break;case"ac3":this.parseAC3PES(i,d)}i.pesData=null}else null!=o&&o.size&&this.logger.log("last AAC PES packet truncated,might overlap between fragments"),i.pesData=o;l&&(d=An(l,this.logger))?(this.parseID3PES(r,d),r.pesData=null):r.pesData=l}demuxSampleAes(t,e,i,s){const r=this.demux(t,i,s,!0,!this.config.progressive),n=this.sampleAes=new an(this.observer,this.config,e);return this.decrypt(r,n)}readyVideoParser(t){null===this.videoParser&&("avc"===t?this.videoParser=new gn:"hevc"===t&&(this.videoParser=new mn))}decrypt(t,e){return new Promise(i=>{const{audioTrack:s,videoTrack:r}=t;s.samples&&"aac"===s.segmentCodec?e.decryptAacSamples(s.samples,0,()=>{r.samples?e.decryptAvcSamples(r.samples,0,0,()=>{i(t)}):i(t)}):r.samples&&e.decryptAvcSamples(r.samples,0,0,()=>{i(t)})})}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,this.videoIntegrityChecker=null}parseAACPES(t,e,i){let s=0;const r=this.aacOverFlow;let n,a,o,l=e.data;if(r){this.aacOverFlow=null;const e=r.missing,i=r.sample.unit.byteLength;if(-1===e)l=Ht(r.sample.unit,l);else{const n=i-e;r.sample.unit.set(l.subarray(0,e),n),t.samples.push(r.sample),s=r.missing}}for(n=s,a=l.length;n<a-1&&!Gr(l,n);n++);if(n!==s){let t;const e=n<a-1;if(t=e?`AAC PES did not start with ADTS header,offset:${n}`:"No ADTS header found in AAC PES",Sn(this.observer,new Error(t),i,e,this.logger),!e)return}if(Vr(t,this.observer,l,n,this.audioCodec),void 0!==e.pts)o=e.pts;else{if(!r)return void this.logger.warn("[tsdemuxer]: AAC PES unknown PTS");{const e=jr(t.samplerate);o=r.sample.pts+e}}let h,d=0;for(;n<a;){if(h=Hr(t,l,n,o,d),n+=h.length,h.missing){this.aacOverFlow=h;break}for(d++;n<a-1&&!Gr(l,n);n++);}}parseMPEGPES(t,e){const i=e.data,s=i.length;let r=0,n=0;const a=e.pts;if(void 0!==a)for(;n<s;)if(rn(i,n)){const e=tn(t,i,n,a,r);if(!e)break;n+=e.length,r++}else n++;else this.logger.warn("[tsdemuxer]: MPEG PES unknown PTS")}parseAC3PES(t,e){{const i=e.data,s=e.pts;if(void 0===s)return void this.logger.warn("[tsdemuxer]: AC3 PES unknown PTS");const r=i.length;let n,a=0,o=0;for(;o<r&&(n=hn(t,i,o,s,a++))>0;)o+=n}}parseID3PES(t,e){if(void 0===e.pts)return void this.logger.warn("[tsdemuxer]: ID3 PES unknown PTS");const i=I({},e,{type:this._videoTrack?qr.emsg:qr.audioId3,duration:Number.POSITIVE_INFINITY});t.samples.push(i)}parseKlvPES(t,e){var i;const s=null!=(i=e.pts)?i:e.dts;if(void 0===s)return void this.logger.warn("[tsdemuxer]: KLV PES unknown PTS and DTS");const r=e.data;if(r.length<16)return void this.logger.warn("[tsdemuxer]: KLV PES payload too short");let n=0;for(;n<r.length;){var a;if(n+16>r.length)break;const i=n;if(n+=16,n>=r.length)break;const o=r[n];n+=1;let l=0;if(128&o){const t=127&o;if(0===t||t>4||n+t>r.length){this.logger.warn("[tsdemuxer]: Invalid KLV length encoding");break}for(let e=0;e<t;e++)l=l<<8|r[n+e];n+=t}else l=o;if(n+l>r.length){this.logger.warn("[tsdemuxer]: KLV value extends beyond PES payload");break}const h=n+l,d=r.subarray(i,h),c={data:d,len:d.byteLength,pts:s,dts:null!=(a=e.dts)?a:s,type:qr.misbklv,duration:Number.POSITIVE_INFINITY};t.samples.push(c),n=h}}}function yn(t,e){return((31&t[e+1])<<8)+t[e+2]}function En(t,e){return(31&t[e+10])<<8|t[e+11]}function Tn(t,e,i,s,r,n,a,o){const l={audioPid:-1,videoPid:-1,id3Pid:-1,klvPid:-1,segmentVideoCodec:"avc",segmentAudioCodec:"aac"},h=e+3+((15&t[e+1])<<8|t[e+2])-4;for(e+=12+((15&t[e+10])<<8|t[e+11]);e<h;){const h=yn(t,e),d=(15&t[e+3])<<8|t[e+4];switch(t[e]){case 207:if(!s){bn("ADTS AAC",n);break}case 15:-1===l.audioPid&&(l.audioPid=h);break;case 21:-1===l.id3Pid&&(l.id3Pid=h);break;case 219:if(!s){bn("H.264",n);break}case 27:-1===l.videoPid&&(l.videoPid=h);break;case 3:case 4:i.mpeg||i.mp3?-1===l.audioPid&&(l.audioPid=h,l.segmentAudioCodec="mp3"):n.log("MPEG audio found, not supported in this browser");break;case 193:if(!s){bn("AC-3",n);break}case 129:i.ac3?-1===l.audioPid&&(l.audioPid=h,l.segmentAudioCodec="ac3"):n.log("AC-3 audio found, not supported in this browser");break;case 6:if(d>0){let s=e+5,r=d;for(;r>2;){switch(t[s]){case 106:-1===l.audioPid&&(!0!==i.ac3?n.log("AC-3 audio found, not supported in this browser for now"):(l.audioPid=h,l.segmentAudioCodec="ac3"));break;case 5:-1===l.klvPid&&a.enableEmsgKLVMetadata&&(l.klvPid=h,n.log(`KLV metadata PID found: ${h}`))}const e=t[s+1]+2;s+=e,r-=e}}break;case 194:case 135:return Sn(r,new Error("Unsupported EC-3 in M2TS found"),o,void 0,n),l;case 36:-1===l.videoPid&&(l.videoPid=h,l.segmentVideoCodec="hevc",n.log("HEVC in M2TS found"))}e+=d+5}return l}function Sn(t,e,i,s,o){o.warn(`parsing error: ${e.message}`),t.emit(a.ERROR,a.ERROR,{type:r.MEDIA_ERROR,details:n.FRAG_PARSING_ERROR,fatal:!1,levelRetry:s,chunkMeta:i,error:e,reason:e.message})}function bn(t,e){e.log(`${t} with AES-128-CBC encryption found in unencrypted stream`)}function An(t,e){let i,s,r,n,a,o=0;const l=t.data;if(!t||0===t.size)return null;for(;l[0].length<19&&l.length>1;)l[0]=Ht(l[0],l[1]),l.splice(1,1);i=l[0];if(1===(i[0]<<16)+(i[1]<<8)+i[2]){if(s=(i[4]<<8)+i[5],s&&s>t.size-6)return null;const h=i[7];192&h&&(n=536870912*(14&i[9])+4194304*(255&i[10])+16384*(254&i[11])+128*(255&i[12])+(254&i[13])/2,64&h?(a=536870912*(14&i[14])+4194304*(255&i[15])+16384*(254&i[16])+128*(255&i[17])+(254&i[18])/2,n-a>54e5&&(e.warn(`${Math.round((n-a)/9e4)}s delta between PTS and DTS, align them`),n=a)):a=n),r=i[8];let d=r+9;if(t.size<=d)return null;t.size-=d;const c=new Uint8Array(t.size);for(let t=0,e=l.length;t<e;t++){i=l[t];let e=i.byteLength;if(d){if(d>e){d-=e;continue}i=i.subarray(d),e-=d,d=0}c.set(i,o),o+=e}return s&&(s-=r+3),{data:c,pts:n,dts:a,len:s}}return null}class Ln{constructor(t){this.logger=void 0,this.pid=0,this.lastContinuityCounter=-1,this.integrityState="ok",this.logger=t}get isCorrupted(){return"ok"!==this.integrityState}reset(t){this.pid=t,this.lastContinuityCounter=-1,this.integrityState="ok"}handlePacket(t){if(t.byteLength<4)return;const e=yn(t,0);if(e!==this.pid)return void this.logger.debug(`Packet PID mismatch, expected ${this.pid} got ${e}`);const i=(48&t[3])>>4;if(0===i)return;const s=15&t[3],r=this.lastContinuityCounter;this.lastContinuityCounter=s;const n=!!(1&i);if(!!(2&i)&&0!=t[4]&&!!(128&t[5]))return;if(r<0)return;const a=n?r+1&15:r;return s!==a?(this.logger.warn(`MPEG-TS Continuity Counter check failed for PID='${e}', CC=${s}, Expected-CC=${a} Last-CC=${r}`),void(this.integrityState="cc-failed")):128&t[1]?(this.logger.warn(`MPEG-TS Packet had TEI flag set for PID='${e}'`),void(this.integrityState="tei-bit")):void 0}}class In{static getSilentFrame(t,e){if("mp4a.40.2"===t){if(1===e)return new Uint8Array([0,200,0,128,35,128]);if(2===e)return new Uint8Array([33,0,73,144,2,25,0,35,128]);if(3===e)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,142]);if(4===e)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,128,44,128,8,2,56]);if(5===e)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,56]);if(6===e)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,0,178,0,32,8,224])}else{if(1===e)return new Uint8Array([1,64,34,128,163,78,230,128,186,8,0,0,0,28,6,241,193,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);if(2===e)return new Uint8Array([1,64,34,128,163,94,230,128,186,8,0,0,0,0,149,0,6,241,161,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);if(3===e)return new Uint8Array([1,64,34,128,163,94,230,128,186,8,0,0,0,0,149,0,6,241,161,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94])}}}var Rn;const kn={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])},_n=new Uint8Array([0,0,0,0,0,0,0,0]),Dn=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),wn=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0]),Pn=new Uint8Array([0,0,0,0,0,0,0,0]),Cn=new Uint8Array([0,0,0,0,0,0,0,1]),xn=new Uint8Array([105,115,111,109]),Mn=new Uint8Array([97,118,99,49]),On=new Uint8Array([0,0,0,1]);class Fn{static box(t,...e){let i=8,s=e.length;const r=s;for(;s--;)i+=e[s].byteLength;const n=new Uint8Array(i);for(kt(n,0,i),kt(n,4,t),s=0,i=8;s<r;s++)n.set(e[s],i),i+=e[s].byteLength;return n}static hdlr(t){return Fn.box(Tt.hdlr,kn[t])}static mdat(t){return Fn.box(Tt.mdat,t)}static mdhd(t,e){e*=t;const i=Math.floor(e/(Et+1)),s=Math.floor(e%(Et+1));return Fn.box(Tt.mdhd,new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,t>>24&255,t>>16&255,t>>8&255,255&t,i>>24,i>>16&255,i>>8&255,255&i,s>>24,s>>16&255,s>>8&255,255&s,85,196,0,0]))}static mdia(t){return Fn.box(Tt.mdia,Fn.mdhd(t.timescale||0,t.duration||0),Fn.hdlr(t.type),Fn.minf(t))}static mfhd(t){return Fn.box(Tt.mfhd,new Uint8Array([0,0,0,0,t>>24,t>>16&255,t>>8&255,255&t]))}static minf(t){return"audio"===t.type?Fn.box(Tt.minf,Fn.box(Tt.smhd,Pn),Fn.DINF,Fn.stbl(t)):Fn.box(Tt.minf,Fn.box(Tt.vmhd,wn),Fn.DINF,Fn.stbl(t))}static moof(t,e,i){return Fn.box(Tt.moof,Fn.mfhd(t),Fn.traf(i,e))}static moov(t){let e=t.length;const i=[];for(;e--;)i[e]=Fn.trak(t[e]);return Fn.box.apply(null,[Tt.moov,Fn.mvhd(t[0].timescale||0,t[0].duration||0)].concat(i).concat(Fn.mvex(t)))}static mvex(t){let e=t.length;const i=[];for(;e--;)i[e]=Fn.trex(t[e]);return Fn.box.apply(null,[Tt.mvex,...i])}static mvhd(t,e){e*=t;const i=Math.floor(e/(Et+1)),s=Math.floor(e%(Et+1)),r=new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,t>>24&255,t>>16&255,t>>8&255,255&t,i>>24,i>>16&255,i>>8&255,255&i,s>>24,s>>16&255,s>>8&255,255&s,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,255,255,255,255]);return Fn.box(Tt.mvhd,r)}static sdtp(t){const e=t.samples||[],i=new Uint8Array(4+e.length);let s,r;for(s=0;s<e.length;s++)r=e[s].flags,i[s+4]=r.dependsOn<<4|r.isDependedOn<<2|r.hasRedundancy;return Fn.box(Tt.sdtp,i)}static stbl(t){return Fn.box(Tt.stbl,Fn.stsd(t),Fn.box(Tt.stts,_n),Fn.box(Tt.stsc,_n),Fn.box(Tt.stsz,Dn),Fn.box(Tt.stco,_n))}static avc1(t){let e,i,s,r=[],n=[];for(e=0;e<t.sps.length;e++)i=t.sps[e],s=i.byteLength,r.push(s>>>8&255),r.push(255&s),r=r.concat(Array.prototype.slice.call(i));for(e=0;e<t.pps.length;e++)i=t.pps[e],s=i.byteLength,n.push(s>>>8&255),n.push(255&s),n=n.concat(Array.prototype.slice.call(i));const a=Fn.box(Tt.avcC,new Uint8Array([1,r[3],r[4],r[5],255,224|t.sps.length].concat(r).concat([t.pps.length]).concat(n))),o=t.width,l=t.height,h=t.pixelRatio[0],d=t.pixelRatio[1];return Fn.box(Tt.avc1,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,o>>8&255,255&o,l>>8&255,255&l,0,72,0,0,0,72,0,0,0,0,0,0,0,1,18,100,97,105,108,121,109,111,116,105,111,110,47,104,108,115,46,106,115,0,0,0,0,0,0,0,0,0,0,0,0,0,0,24,17,17]),a,Fn.box(Tt.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),Fn.box(Tt.pasp,new Uint8Array([h>>24,h>>16&255,h>>8&255,255&h,d>>24,d>>16&255,d>>8&255,255&d])))}static esds(t){const e=t.config,i=e.length;return new Uint8Array([0,0,0,0,3,23+i,0,1,0,4,15+i,64,21,0,0,0,0,0,0,0,0,0,0,0,5,i,...e,6,1,2])}static audioStsd(t){const e=t.samplerate||0;return new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,t.channelCount||0,0,16,0,0,0,0,e>>8&255,255&e,0,0])}static mp4a(t){return Fn.box(Tt.mp4a,Fn.audioStsd(t),Fn.box(Tt.esds,Fn.esds(t)))}static mp3(t){return Fn.box(Tt[".mp3"],Fn.audioStsd(t))}static ac3(t){return Fn.box(Tt["ac-3"],Fn.audioStsd(t),Fn.box(Tt.dac3,t.config))}static stsd(t){const{segmentCodec:e}=t;if("audio"===t.type){if("aac"===e)return Fn.box(Tt.stsd,Cn,Fn.mp4a(t));if("ac3"===e&&t.config)return Fn.box(Tt.stsd,Cn,Fn.ac3(t));if("mp3"===e&&"mp3"===t.codec)return Fn.box(Tt.stsd,Cn,Fn.mp3(t))}else{if(!t.pps||!t.sps)throw new Error("video track missing pps or sps");if("avc"===e)return Fn.box(Tt.stsd,Cn,Fn.avc1(t));if("hevc"===e&&t.vps)return Fn.box(Tt.stsd,Cn,Fn.hvc1(t))}throw new Error(`unsupported ${t.type} segment codec (${e}/${t.codec})`)}static tkhd(t){const e=t.id,i=(t.duration||0)*(t.timescale||0),s=t.width||0,r=t.height||0,n=Math.floor(i/(Et+1)),a=Math.floor(i%(Et+1));return Fn.box(Tt.tkhd,new Uint8Array([1,0,0,7,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,e>>24&255,e>>16&255,e>>8&255,255&e,0,0,0,0,n>>24,n>>16&255,n>>8&255,255&n,a>>24,a>>16&255,a>>8&255,255&a,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,s>>8&255,255&s,0,0,r>>8&255,255&r,0,0]))}static traf(t,e){const i=Fn.sdtp(t),s=t.id,r=Math.floor(e/(Et+1)),n=Math.floor(e%(Et+1));return Fn.box(Tt.traf,Fn.box(Tt.tfhd,new Uint8Array([0,0,0,0,s>>24,s>>16&255,s>>8&255,255&s])),Fn.box(Tt.tfdt,new Uint8Array([1,0,0,0,r>>24,r>>16&255,r>>8&255,255&r,n>>24,n>>16&255,n>>8&255,255&n])),Fn.trun(t,i.length+16+20+8+16+8+8),i)}static trak(t){return t.duration=t.duration||4294967295,Fn.box(Tt.trak,Fn.tkhd(t),Fn.mdia(t))}static trex(t){const e=t.id;return Fn.box(Tt.trex,new Uint8Array([0,0,0,0,e>>24,e>>16&255,e>>8&255,255&e,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,1]))}static trun(t,e){const i=t.samples||[],s=i.length,r=12+16*s,n=new Uint8Array(r);let a,o,l,h,d,c;for(e+=8+r,n.set(["video"===t.type?1:0,0,15,1,s>>>24&255,s>>>16&255,s>>>8&255,255&s,e>>>24&255,e>>>16&255,e>>>8&255,255&e],0),a=0;a<s;a++)o=i[a],l=o.duration,h=o.size,d=o.flags,c=o.cts,n.set([l>>>24&255,l>>>16&255,l>>>8&255,255&l,h>>>24&255,h>>>16&255,h>>>8&255,255&h,d.isLeading<<2|d.dependsOn,d.isDependedOn<<6|d.hasRedundancy<<4|d.paddingValue<<1|d.isNonSync,61440&d.degradPrio,15&d.degradPrio,c>>>24&255,c>>>16&255,c>>>8&255,255&c],12+16*a);return Fn.box(Tt.trun,n)}static initSegment(t){const e=Fn.moov(t);return Ht(Fn.FTYP,e)}static hvc1(t){const e=t.params,i=[t.vps,t.sps,t.pps],s=new Uint8Array([1,e.general_profile_space<<6|(e.general_tier_flag?32:0)|e.general_profile_idc,e.general_profile_compatibility_flags[0],e.general_profile_compatibility_flags[1],e.general_profile_compatibility_flags[2],e.general_profile_compatibility_flags[3],e.general_constraint_indicator_flags[0],e.general_constraint_indicator_flags[1],e.general_constraint_indicator_flags[2],e.general_constraint_indicator_flags[3],e.general_constraint_indicator_flags[4],e.general_constraint_indicator_flags[5],e.general_level_idc,240|e.min_spatial_segmentation_idc>>8,255&e.min_spatial_segmentation_idc,252|e.parallelismType,252|e.chroma_format_idc,248|e.bit_depth_luma_minus8,248|e.bit_depth_chroma_minus8,0,parseInt(e.frame_rate.fps),3|e.temporal_id_nested<<2|e.num_temporal_layers<<3|(e.frame_rate.fixed?64:0),i.length]);let r=s.length;for(let t=0;t<i.length;t+=1){r+=3;for(let e=0;e<i[t].length;e+=1)r+=2+i[t][e].length}const n=new Uint8Array(r);n.set(s,0),r=s.length;const a=i.length-1;for(let t=0;t<i.length;t+=1){n.set(new Uint8Array([32+t|(t===a?128:0),0,i[t].length]),r),r+=3;for(let e=0;e<i[t].length;e+=1)n.set(new Uint8Array([i[t][e].length>>8,255&i[t][e].length]),r),r+=2,n.set(i[t][e],r),r+=i[t][e].length}const o=Fn.box(Tt.hvcC,n),l=t.width,h=t.height,d=t.pixelRatio[0],c=t.pixelRatio[1];return Fn.box(Tt.hvc1,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,l>>8&255,255&l,h>>8&255,255&h,0,72,0,0,0,72,0,0,0,0,0,0,0,1,18,100,97,105,108,121,109,111,116,105,111,110,47,104,108,115,46,106,115,0,0,0,0,0,0,0,0,0,0,0,0,0,0,24,17,17]),o,Fn.box(Tt.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),Fn.box(Tt.pasp,new Uint8Array([d>>24,d>>16&255,d>>8&255,255&d,c>>24,c>>16&255,c>>8&255,255&c])))}}Rn=Fn,Fn.FTYP=Rn.box(Tt.ftyp,xn,On,xn,Mn),Fn.DINF=Rn.box(Tt.dinf,Rn.box(Tt.dref,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,12,117,114,108,32,0,0,0,1])));function Nn(t,e,i=1,s=!1){const r=t*e*i;return s?Math.round(r):r}function $n(t,e=!1){return Nn(t,1e3,1/9e4,e)}function Bn(t){const{baseTime:e,timescale:i,trackId:s}=t;return`${e/i} (${e}/${i}) trackId: ${s}`}const Un=8589934592;function Gn(t,e,i,s){return{duration:e,size:i,cts:s,flags:{isLeading:0,isDependedOn:0,hasRedundancy:0,degradPrio:0,dependsOn:t?2:1,isNonSync:t?0:1,paddingValue:0}}}class Kn extends U{constructor(t,e,i,s){super("mp4-remuxer",s),this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.ISGenerated=!1,this._initPTS=null,this._initDTS=null,this.nextVideoTs=null,this.nextAudioTs=null,this.videoSampleDuration=null,this.isAudioContiguous=!1,this.isVideoContiguous=!1,this.videoTrackConfig=void 0,this.observer=t,this.config=e,this.typeSupported=i,this.ISGenerated=!1}destroy(){this.config=this.videoTrackConfig=this._initPTS=this._initDTS=null}resetTimeStamp(t){const e=this._initPTS;e&&t&&t.trackId===e.trackId&&t.baseTime===e.baseTime&&t.timescale===e.timescale||this.log(`Reset initPTS: ${e?Bn(e):e} > ${t?Bn(t):t}`),this._initPTS=this._initDTS=t}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(t){let e=!1;const i=t[0].pts,s=t.reduce((t,s)=>{let r=s.pts,n=r-t;return n<-4294967296&&(e=!0,r=Vn(r,i),n=r-t),n>0?t:r},i);return e&&this.debug("PTS rollover detected"),s}remux(t,e,i,s,r,n,a,o,l){let h,d,c,u,g,m,p=r,v=r;const y=!l.iframe&&t.pid>-1,E=e.pid>-1,T=e.samples.length,S=t.samples.length>0,b=a&&T>0||T>1;if((!y||S)&&(!E||b)||this.ISGenerated||a){if(this.ISGenerated){var A,L,I,R;const t=this.videoTrackConfig;(t&&(e.width!==t.width||e.height!==t.height||(null==(A=e.pixelRatio)?void 0:A[0])!==(null==(L=t.pixelRatio)?void 0:L[0])||(null==(I=e.pixelRatio)?void 0:I[1])!==(null==(R=t.pixelRatio)?void 0:R[1]))||!t&&b||null===this.nextAudioTs&&S)&&this.resetInitSegment()}this.ISGenerated||(c=this.generateIS(t,e,r,n));const i=this.isVideoContiguous;let s,a=-1;if(b&&(a=function(t){for(let e=0;e<t.length;e++)if(t[e].key)return e;return-1}(e.samples),!i&&this.config.forceKeyFrameOnDiscontinuity))if(m=!0,a>0){this.warn(`Dropped ${a} out of ${T} video samples due to a missing keyframe`);const t=this.getVideoStartPts(e.samples);e.samples=e.samples.slice(a),e.dropped+=a,v+=(e.samples[0].pts-t)/e.inputTimeScale,s=v}else-1===a&&(this.warn(`No keyframe found out of ${T} video samples`),m=!1);if(this.ISGenerated){if(S&&b&&r){const i=this.getVideoStartPts(e.samples),s=(Vn(t.samples[0].pts,i)-i)/e.inputTimeScale;p+=Math.max(0,s),v+=Math.max(0,-s)}if(S){if(t.samplerate||(this.warn("regenerate InitSegment as audio detected"),c=this.generateIS(t,e,r,n)),d=this.remuxAudio(t,p,this.isAudioContiguous,n,E||b||o===f.AUDIO?v:void 0,l),b){const s=d?d.endPTS-d.startPTS:0;e.inputTimeScale||(this.warn("regenerate InitSegment as video detected"),c=this.generateIS(t,e,r,n)),h=this.remuxVideo(e,v,i,s,l)}}else b&&(h=this.remuxVideo(e,v,i,0,l));h&&(h.firstKeyFrame=a,h.independent=-1!==a,h.firstKeyFramePTS=s)}}return this.ISGenerated&&this._initPTS&&this._initDTS&&(i.samples.length&&(g=jn(i,r,this._initPTS,this._initDTS)),s.samples.length&&(u=Hn(s,r,this._initPTS))),{audio:d,video:h,initSegment:c,independent:m,text:u,id3:g}}computeInitPts(t,e,i,s){const r=Math.round(i*e);let n=Vn(t,r);if(n<r)for(this.log(`Adjusting PTS for rollover in timeline near ${(r-n)/e} ${s}`);n<r;)n+=Un;return n-r}generateIS(t,i,s,r){const n=t.samples,a=i.samples,o=this.typeSupported,l={},h=this._initPTS,d=!h||r;let c,u,f,g="audio/mp4",m=-1;if(d&&(c=u=1/0),t.config&&n.length){switch(t.timescale=t.samplerate,t.segmentCodec){case"mp3":o.mpeg?(g="audio/mpeg",t.codec=""):o.mp3&&(t.codec="mp3");break;case"ac3":t.codec="ac-3"}if(l.audio={id:"audio",container:g,codec:t.codec,initSegment:"mp3"===t.segmentCodec&&o.mpeg?new Uint8Array(0):Fn.initSegment([t]),metadata:{channelCount:t.channelCount}},d){m=t.id,f=t.inputTimeScale;const e=this.computeInitPts(n[0].pts,f,s,"audio");(!h||f!==h.timescale||0===s&&e<h.baseTime)&&(c=u=e)}}if(i.sps&&i.pps&&a.length){if(i.timescale=i.inputTimeScale,l.video={id:"main",container:"video/mp4",codec:i.codec,initSegment:Fn.initSegment([i]),metadata:{width:i.width,height:i.height}},d){m=i.id,f=i.inputTimeScale;const t=this.getVideoStartPts(a),r=Vn(a[0].dts,t),n=this.computeInitPts(r,f,s,"video"),o=this.computeInitPts(t,f,s,"video");if(!h||f!==h.timescale||e(c)||0===s&&o<h.baseTime){u=Math.min(u,n);const t=!h&&this.isVideoContiguous?o:n;c=Math.min(c,t)}}this.videoTrackConfig={width:i.width,height:i.height,pixelRatio:i.pixelRatio}}if(Object.keys(l).length)return this.ISGenerated=!0,d&&e(c)?(h&&this.warn(`Timestamps at playlist time: ${r?"":"~"}${s} ${c/f} != initPTS: ${h.baseTime/h.timescale} (${h.baseTime}/${h.timescale}) trackId: ${h.trackId}`),this.log(`Found initPTS at playlist time: ${s} offset: ${c/f} (${c}/${f}) trackId: ${m}`),this._initPTS={baseTime:c,timescale:f,trackId:m},this._initDTS={baseTime:u,timescale:f,trackId:m}):c=f=void 0,{tracks:l,initPTS:c,timescale:f,trackId:m}}remuxVideo(t,e,i,s,o){const l=t.inputTimeScale,h=t.samples,d=[],c=h.length,u=this._initPTS,f=u.baseTime*l/u.timescale;let g,m,p=this.nextVideoTs,v=8,y=this.videoSampleDuration,E=Number.POSITIVE_INFINITY,T=Number.NEGATIVE_INFINITY,S=!1;if(!i||null===p){const t=f+e*l,s=h[0].pts-Vn(h[0].dts,h[0].pts);ne()&&null!==p&&Math.abs(t-s-(p+f))<15e3?i=!0:p=t-s-f}const b=p+f;for(let t=0;t<c;t++){const e=h[t];e.pts=Vn(e.pts,b),e.dts=Vn(e.dts,b),e.dts<h[t>0?t-1:t].dts&&(S=!0)}S&&h.sort(function(t,e){const i=t.dts-e.dts,s=t.pts-e.pts;return i||s}),g=h[0].dts,m=h[h.length-1].dts;const A=m-g,L=A?Math.round(A/(c-1)):y||t.inputTimeScale/30;if(i){const i=g-b,s=i>L,r=i<-1;if((s||r)&&(s?this.warn(`${(t.segmentCodec||"").toUpperCase()}: ${$n(i,!0)} ms (${i}dts) hole between fragments detected at ${e.toFixed(3)}`):this.warn(`${(t.segmentCodec||"").toUpperCase()}: ${$n(-i,!0)} ms (${i}dts) overlapping between fragments detected at ${e.toFixed(3)}`),!r||b>=h[0].pts||ne())){g=b;const t=h[0].pts-i;if(s)h[0].dts=g,h[0].pts=t;else{let e=!0;for(let s=0;s<h.length&&!(h[s].dts>t&&e);s++){const t=h[s].pts;if(h[s].dts-=i,h[s].pts-=i,s<h.length-1){const i=h[s+1].pts;e=i<=h[s].pts==i<=t}}}this.log(`Video: Initial PTS/DTS adjusted: ${$n(t,!0)}/${$n(g,!0)}, delta: ${$n(i,!0)} ms`)}}g=Math.max(0,g);let R=0,k=0,_=g;for(let t=0;t<c;t++){const e=h[t],i=e.units,s=i.length;let r=0;for(let t=0;t<s;t++)r+=i[t].data.length;k+=r,R+=s,e.length=r,e.dts<_?(e.dts=_,_+=L/4|0||1):_=e.dts,E=Math.min(e.pts,E),T=Math.max(e.pts,T)}m=h[c-1].dts;const D=k+4*R+8;let w;try{w=new Uint8Array(D)}catch(t){return void this.observer.emit(a.ERROR,a.ERROR,{type:r.MUX_ERROR,details:n.REMUX_ALLOC_ERROR,fatal:!1,chunkMeta:o,error:t,bytes:D,reason:`fail allocating video mdat ${D}`})}kt(w,0,D),kt(w,4,Tt.mdat);let P=!1,C=Number.POSITIVE_INFINITY,x=Number.POSITIVE_INFINITY,M=Number.NEGATIVE_INFINITY,O=Number.NEGATIVE_INFINITY;for(let t=0;t<c;t++){const e=h[t],r=e.units;let n,a=0;for(let t=0,e=r.length;t<e;t++){const e=r[t],i=e.data,s=e.data.byteLength;kt(w,v,s),v+=4,w.set(i,v),v+=s,a+=4+s}if(t<c-1)y=h[t+1].dts-e.dts,n=h[t+1].pts-e.pts;else{const i=this.config,r=t>0?e.dts-h[t-1].dts:L;if(n=t>0?e.pts-h[t-1].pts:L,i.stretchShortVideoTrack&&null!==this.nextAudioTs){const t=Math.floor(i.maxBufferHole*l),n=(s?E+s*l:this.nextAudioTs+f)-e.pts;n>t?(y=n-r,y<0?y=r:P=!0,this.log(`It is approximately ${n/90} ms to the next segment; using duration ${y/90} ms for the last video frame.`)):y=r}else y=r}let u=Math.round(e.pts-e.dts);if(C=Math.min(C,y),M=Math.max(M,y),x=Math.min(x,n),O=Math.max(O,n),!i&&0===t&&u>y){const t=Math.round(u/L)*L;t-u===1&&(this.log(`pad first CTS ${u} -> ${t} of sn: ${o.sn}`),u=t)}d.push(Gn(e.key,y,a,u))}if(d.length){const t=ne();if(t){if(t<70){const t=d[0].flags;t.dependsOn=2,t.isNonSync=0}}else if(function(){if(void 0===se){const t=Jt.match(/Safari\/(\d+)/i);se=t?parseInt(t[1]):0}return se}()&&O-x<M-C&&L/M<.025&&0===d[0].cts){this.warn("Found irregular gaps in sample duration. Using PTS instead of DTS to determine MP4 sample duration.");let t=g;for(let e=0,i=d.length;e<i;e++){const s=t+d[e].duration,r=t+d[e].cts;if(e<i-1){const t=s+d[e+1].cts;d[e].duration=t-r}else d[e].duration=e?d[e-1].duration:L;d[e].cts=0,t=s}}}y=P||!y?L:y;const F=m+y;this.nextVideoTs=p=F-f,this.videoSampleDuration=y,this.isVideoContiguous=!0,o.iframe&&(1===d.length?(d[0].duration=y=o.duration*l,this.nextVideoTs=p=g+y-f):this.warn(`Not adjusting IFrame duration (sample count ${d.length})`));const N={data1:Fn.moof(o.sn,g,I(t,{samples:d})),data2:w,startPTS:(E-f)/l,endPTS:(T+y-f)/l,startDTS:(g-f)/l,endDTS:p/l,type:"video",hasAudio:!1,hasVideo:!0,nb:d.length,dropped:t.dropped};return t.samples=[],t.dropped=0,N}getSamplesPerFrame(t){switch(t.segmentCodec){case"mp3":return 1152;case"ac3":return 1536;default:return 1024}}remuxAudio(t,e,i,s,o,l){const h=t.inputTimeScale,d=h/(t.samplerate?t.samplerate:h),c=this.getSamplesPerFrame(t),u=c*d,f=this._initPTS,g="mp3"===t.segmentCodec&&this.typeSupported.mpeg,m=[],p=void 0!==o;let v=t.samples,y=g?0:8,E=this.nextAudioTs||-1;const T=f.baseTime*h/f.timescale,S=T+e*h;if(this.isAudioContiguous=i=i||v.length&&E>0&&(s&&Math.abs(S-(E+T))<9e3||Math.abs(Vn(v[0].pts,S)-(E+T))<20*u),v.forEach(function(t){t.pts=Vn(t.pts,S)}),!i||E<0){const t=v.length;if(v=v.filter(t=>t.pts>=0),t!==v.length&&this.warn(`Removed ${v.length-t} of ${t} samples (initPTS ${T} / ${h})`),!v.length)return;E=0===o?0:s&&!p?Math.max(0,S-T):v[0].pts-T}if("aac"===t.segmentCodec){const e=this.config.maxAudioFramesDrift;for(let i=0,s=E+T;i<v.length;i++){const r=v[i],n=r.pts,a=n-s,o=Math.abs(1e3*a/h);if(a<=-e*u&&p)0===i&&(this.warn(`Audio frame @ ${(n/h).toFixed(3)}s overlaps marker by ${Math.round(1e3*a/h)} ms.`),this.nextAudioTs=E=n-T,s=n);else if(a>=e*u&&o<1e4&&p){let e=Math.round(a/u);for(s=n-e*u;s<T&&e&&u;)e--,s+=u;0===i&&(this.nextAudioTs=E=s-T),this.warn(`Injecting ${e} audio frames @ ${((s-T)/h).toFixed(3)}s due to ${Math.round(1e3*a/h)} ms gap.`);for(let n=0;n<e;n++){let e=In.getSilentFrame(t.parsedCodec||t.manifestCodec||t.codec,t.channelCount);e||(this.log("Unable to get silent frame for given audio codec; duplicating last frame instead."),e=r.unit.subarray()),v.splice(i,0,{unit:e,pts:s}),s+=u,i++}}r.pts=s,s+=u}}let b,A=null,L=null,R=0,k=v.length;for(;k--;)R+=v[k].unit.byteLength;for(let e=0,s=v.length;e<s;e++){const s=v[e],o=s.unit;let h=s.pts;if(null!==L){m[e-1].duration=Math.round((h-L)/d)}else{if(i&&"aac"===t.segmentCodec&&(h=E+T),A=h,!(R>0))return;R+=y;try{b=new Uint8Array(R)}catch(t){return void this.observer.emit(a.ERROR,a.ERROR,{type:r.MUX_ERROR,details:n.REMUX_ALLOC_ERROR,fatal:!1,chunkMeta:l,error:t,bytes:R,reason:`fail allocating audio mdat ${R}`})}g||(kt(b,0,R),kt(b,4,Tt.mdat))}b&&b.set(o,y);const u=o.byteLength;y+=u,m.push(Gn(!0,c,u,0)),L=h}const _=m.length;if(!_)return;const D=m[m.length-1];E=L-T,this.nextAudioTs=E+d*D.duration;const w=g?new Uint8Array(0):Fn.moof(t.sequenceNumber++,A/d,I({},t,{samples:m}));t.samples=[];const P=(A-T)/h,C=this.nextAudioTs/h,x={data1:w,data2:b,startPTS:P,endPTS:C,startDTS:P,endDTS:C,type:"audio",hasAudio:!0,hasVideo:!1,nb:_};return this.isAudioContiguous=!0,x}}function Vn(t,e){let i;if(null===e)return t;for(i=e<t?-8589934592:Un;Math.abs(t-e)>4294967296;)t+=i;return t}function jn(t,e,i,s){const r=t.samples.length;if(!r)return;const n=t.inputTimeScale;for(let a=0;a<r;a++){const r=t.samples[a];r.pts=Vn(r.pts-i.baseTime*n/i.timescale,e*n)/n,r.dts=Vn(r.dts-s.baseTime*n/s.timescale,e*n)/n}const a=t.samples;return t.samples=[],{samples:a}}function Hn(t,e,i){const s=t.samples.length;if(!s)return;const r=t.inputTimeScale;for(let n=0;n<s;n++){const s=t.samples[n];s.pts=Vn(s.pts-i.baseTime*r/i.timescale,e*r)/r}t.samples.sort((t,e)=>t.pts-e.pts);const n=t.samples;return t.samples=[],{samples:n}}function qn(t,e,i=!1){return void 0!==(null==t?void 0:t.start)?(t.start+(i?t.duration:0))/t.timescale:e}function Yn(t,e,i){const s=t.codec;if(s&&s.length>4)return s;if(e===g){if("ec-3"===s||"ac-3"===s||"alac"===s)return s;if("fLaC"===s||"Opus"===s){return pe(s,!1)}return i.warn(`Unhandled audio codec "${s}" in mp4 MAP`),s||"mp4a"}return"mjpg"===s?s:(i.warn(`Unhandled video codec "${s}" in mp4 MAP`),s||"avc1")}let Wn;try{Wn=self.performance.now.bind(self.performance)}catch(t){Wn=Date.now}const zn=[{demux:class{constructor(t,e,i,s=q){this.remainderData=null,this.timeOffset=0,this.config=void 0,this.videoTrack=void 0,this.audioTrack=void 0,this.id3Track=void 0,this.txtTrack=void 0,this.initData=void 0,this.logger=void 0,this.config=e,this.logger=s}resetTimeStamp(){}resetInitSegment(t,e,i,s){const r=this.videoTrack=Yr("video",1),n=this.audioTrack=Yr("audio",1),a=this.txtTrack=Yr("text",1);if(this.id3Track=Yr("id3",1),this.initData=void 0,this.timeOffset=0,null==t||!t.byteLength)return;const o=this.initData=Mt(t);if(o.video){const{id:t,timescale:e,codec:i,supplemental:s}=o.video;r.id=t,r.timescale=a.timescale=e,r.codec=i,r.supplemental=s}if(o.audio){const{id:t,timescale:e,codec:i}=o.audio;n.id=t,n.timescale=e,n.codec=i}a.id=St.text,r.sampleDuration=0,r.duration=n.duration=s}resetContiguity(){this.remainderData=null}static probe(t){return function(t,e){const i=t.byteLength;for(let s=0;s<i;){const r=At(t,s);if(r>8&&At(t,s+4)===Tt[e])return!0;s=r>1?s+r:i}return!1}(t,"moof")}demux(t,e,i){this.timeOffset=e;let s=t;const r=this.videoTrack,n=this.txtTrack;if(this.config.progressive){this.remainderData&&(s=Ht(this.remainderData,t));const e=function(t){const e={valid:null,remainder:null},i=Pt(t,["moof"]);if(i.length<2)return e.remainder=t,e;const s=i[i.length-1];return e.valid=t.slice(0,s.byteOffset-8),e.remainder=t.slice(s.byteOffset-8),e}(s);this.remainderData=e.remainder,r.samples=e.valid||new Uint8Array}else r.samples=s;const a=this.extractID3Track(r,e),o=this.parseFragment(r,n,e,i);return{videoTrack:r,audioTrack:this.audioTrack,id3Track:a,textTrack:this.txtTrack,initData:this.initData,sampleData:o}}flush(t,e){const i=this.timeOffset,s=this.videoTrack,r=this.txtTrack;s.samples=this.remainderData||new Uint8Array,this.remainderData=null;const n=this.extractID3Track(s,this.timeOffset),a=this.parseFragment(s,r,i,e);return{videoTrack:s,audioTrack:Yr(),id3Track:n,textTrack:Yr(),initData:this.initData,sampleData:a}}parseFragment(t,e,i,s){const r=this.initData;if(r&&s){const{samples:n,sampleData:a}=function(t,e,i,s,r=!1){const n=[];return{samples:n,sampleData:{includeSampleDetails:r,tracks:jt(e.samples,i,s,r,{isHEVCFlavor:qt(e.codec),samples:n,timeOffset:t,timescale:e.timescale,trackId:e.id})}}}(i,t,r,this.logger,s.iframe);return e.samples=n,a}e.samples=function(t,e){const i=[],s=e.samples,r=e.timescale,n=e.id;let a=!1;return Pt(s,["moof"]).map(o=>{const l=o.byteOffset-8;Pt(o,["traf"]).map(o=>{const h=Pt(o,["tfdt"]).map(t=>{const e=t[0];let i=At(t,4);return 1===e&&(i*=Math.pow(2,32),i+=At(t,8)),i/r})[0];return void 0!==h&&(t=h),Pt(o,["tfhd"]).map(h=>{const d=At(h,4),c=16777215&At(h,0),u=!!(1&c);let f=0;const g=!!(2&c),p=!!(8&c);let v=0;const y=!!(16&c);let E=0;const T=!!(32&c),S=!u&&!!(131072&c);let b=8;d===n&&(u?(f=At(h,b),b+=4,f*=Math.pow(2,32),f+=At(h,b),b+=4):S&&(f=l),g&&(b+=4),p&&(v=At(h,b),b+=4),y&&(E=At(h,b),b+=4),T&&(b+=4),"video"===e.type&&(a=qt(e.codec)),Pt(o,["trun"]).map(n=>{const o=n[0],l=16777215&At(n,0),h=!!(1&l);let d=0;const c=!!(4&l),u=!!(256&l);let g=0;const p=!!(512&l);let y=0;const T=!!(1024&l),S=!!(2048&l);let b=0;const A=At(n,4);let L=8;h&&(d=At(n,L),L+=4),c&&(L+=4);let I=f+d;for(let l=0;l<A;l++){if(u?(g=At(n,L),L+=4):g=v,p?(y=At(n,L),L+=4):y=E,T&&(L+=4),S&&(b=0===o?At(n,L):Rt(n,L),L+=4),e.type===m){let e=0;for(;e<y;){const n=At(s,I);I+=4,Yt(a,s[I])&&Wt(s.subarray(I,I+n),a?2:1,t+b/r,i),I+=n,e+=n+4}}t+=g/r}}))})})}),i}(i,t)}extractID3Track(t,e){const s=this.id3Track;if(t.samples.length){const r=Pt(t.samples,["emsg"]);r&&r.forEach(t=>{const r=function(t){const e=t[0];let s,r="",n="",a=0,o=0,l=0,h=0,d=4;if(0===e){const e=It(t,d),i=null!==e?It(t,d+e.length):null;null!==e&&null!==i?(r=e,n=i,d+=e.length+i.length,a=At(t,d),d+=4,o=At(t,d),d+=4,l=At(t,d),d+=4,h=At(t,d),d+=4):(q.warn(`Unterminated ${null===e?"scheme_id_uri":"value"} in parsing emsg box: version 0 box ends inside a string, dropping all of its fields`),d=t.length)}else if(1===e){a=At(t,d),d+=4;const e=At(t,d);d+=4;const o=At(t,d);d+=4,s=2**32*e+o,i(s)||(s=Number.MAX_SAFE_INTEGER,q.warn("Presentation time exceeds safe integer limit and wrapped to max safe integer in parsing emsg box")),l=At(t,d),d+=4,h=At(t,d),d+=4;const c=It(t,d),u=null!==c?It(t,d+c.length):null;null!==c&&(r=c,d+=c.length),null!==u?(n=u,d+=u.length):(q.warn(`Unterminated ${null===c?"scheme_id_uri":"value"} in parsing emsg box: version 1 box ends inside a string, dropping its ${null===c?"strings and payload":"value and payload"}`),d=t.length)}return{schemeIdUri:r,value:n,timeScale:a,presentationTime:s,presentationTimeDelta:o,eventDuration:l,id:h,payload:t.subarray(d,t.byteLength)}}(t);if(dn.test(r.schemeIdUri)){const t=cn(r,e);let i=4294967295===r.eventDuration?Number.POSITIVE_INFINITY:r.eventDuration/r.timeScale;i<=.001&&(i=Number.POSITIVE_INFINITY);const n=r.payload;s.samples.push({data:n,len:n.byteLength,dts:t,pts:t,type:qr.emsg,duration:i})}else if(this.config.enableEmsgKLVMetadata){const t=this.config.emsgKLVSchemaUri||qr.misbklv;if(r.schemeIdUri.startsWith(t)){const t=cn(r,e);s.samples.push({data:r.payload,len:r.payload.byteLength,dts:t,pts:t,type:qr.misbklv,duration:Number.POSITIVE_INFINITY})}}})}return s}demuxSampleAes(t,e,i){return Promise.reject(new Error("The MP4 demuxer does not support SAMPLE-AES decryption"))}destroy(){this.config=null,this.remainderData=null,this.videoTrack=this.audioTrack=this.id3Track=this.txtTrack=void 0,this.initData=void 0}},remux:class extends U{constructor(t,e,i,s){super("passthrough-remuxer",s),this.observer=void 0,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,this.videoOnlyRemux=!1,this.decryptdata=null,this.pendingInitSegment=void 0,this.observer=t}destroy(){this.observer&&this.observer.removeAllListeners(),this.observer=null}resetTimeStamp(t){this.lastEndTime=null;const e=this.initPTS;e&&t&&e.baseTime===t.baseTime&&e.timescale===t.timescale||(this.initPTS=t)}resetNextTimestamp(){this.isVideoContiguous=!1,this.lastEndTime=null}resetInitSegment(t,e,i,s){this.audioCodec=e,this.videoCodec=i,this.decryptdata=s,this.pendingInitSegment=t,this.videoOnlyRemux=!1,this.initTracks=void 0,this.initData=void 0,this.emitInitSegment=!0}generateInitSegment(t,e,i){this.videoOnlyRemux=!1;let{audioCodec:s,videoCodec:r}=this;if(null==t||!t.byteLength)return this.initTracks=void 0,void(this.initData=void 0);const{audio:n,video:a}=this.initData=i||Mt(t);if(e)!function(t,e){if(!t||!e)return;const i=e.keyId;16===(null==i?void 0:i.byteLength)&&e.isCommonEncryption&&Ut(t,(t,e)=>{const s=t.subarray(8,24);s.some(t=>0!==t)||(q.log(`[eme] Patching keyId in 'enc${e?"a":"v"}>sinf>>tenc' box: ${mt(s)} -> ${mt(i)}`),t.set(i,8))})}(t,e);else{const t=n||a;null!=t&&t.encrypted&&this.warn(`Init segment with encrypted track with has no key ("${t.codec}")!`)}n&&(s=Yn(n,g,this)),a&&(r=Yn(a,m,this));const o={};n&&a?o.audiovideo={container:"video/mp4",codec:s+","+r,supplemental:a.supplemental,encrypted:a.encrypted,initSegment:t,id:"main"}:n?o.audio={container:"audio/mp4",codec:s,encrypted:n.encrypted,initSegment:t,id:"audio"}:a?o.video={container:"video/mp4",codec:r,supplemental:a.supplemental,encrypted:a.encrypted,initSegment:t,id:"main"}:this.warn("initSegment does not contain moov or trak boxes."),this.initTracks=o}remux(t,i,s,r,n,a,o,l,h,d,c){var u,f;let{initPTS:g,lastEndTime:m}=this;const p={audio:void 0,video:void 0,text:void 0,id3:s,initSegment:void 0};e(m)||(m=this.lastEndTime=n||0);const v=i.samples;if(!v.length)return p;const y=this.pendingInitSegment;y&&(this.pendingInitSegment=void 0,this.generateInitSegment(y,this.decryptdata,d));const E={initPTS:void 0,timescale:void 0,trackId:void 0};let T=this.initData;if(null!=(u=T)&&u.length||(this.generateInitSegment(v),T=this.initData),null==(f=T)||!f.length)return this.warn("Failed to generate initSegment."),p;if(h.iframe&&T.audio&&T.video){var S;const t=null==(S=this.initTracks)||null==(S=S.audiovideo)?void 0:S.initSegment,e=t?function(t){const e=Pt(t,["moov"]);if(1!==e.length||Pt(t,["moof"]).length)return null;const i=t.byteOffset,s=[],r=[];let n=!1;const a=Pt(e[0],["trak"]);for(let t=0;t<a.length;t++){const e=a[t],o=Pt(e,["mdia","hdlr"])[0];if("vide"===(o?yt(o.subarray(8,12)):"")){n=!0;continue}const l=Pt(e,["tkhd"])[0];if(!l)return null;const h=l[0];r.push(At(l,0===h?12:20)),s.push(Dt(e,i))}if(!n||!s.length)return null;const o=Pt(e[0],["mvex"])[0];let l=0;if(o){const t=Pt(o,["trex"]);for(let e=0;e<t.length;e++){const n=t[e];-1!==r.indexOf(At(n,4))&&(s.push(Dt(n,i)),l+=n.byteLength+8)}}const{result:h,dropped:d,droppedBefore:c}=wt(t,s);if(kt(h,e[0].byteOffset-i-8,e[0].byteLength+8-d),o&&l){const t=o.byteOffset-i-8;kt(h,t-c(t),o.byteLength+8-l)}return h}(t):null;var b;if(e)this.log("Converted muxed init segment to video-only for I-Frame playback"),this.generateInitSegment(e,this.decryptdata),null!=(b=this.initData)&&b.length&&(T=this.initData,this.emitInitSegment=!0,this.videoOnlyRemux=!0)}this.emitInitSegment&&(E.tracks=this.initTracks,p.initSegment=E,this.emitInitSegment=!1);const A=h.iframe,L=!c||A&&!c.includeSampleDetails?function(t,e,i,s,r=!0){return jt(t,e,s,r)}(v,T,0,this,A):c.tracks,I=T.audio?L[T.audio.id]:null,R=T.video?L[T.video.id]:null,k=!!T.audio,_=!!T.video;let D="";k&&(D+="audio"),_&&(D+="video");const w=qn(R,1/0),P=qn(I,1/0),C=qn(R,0,!0),x=qn(I,0,!0);let M=n,O=0;R&&I&&T.audio&&(P>C||w>x)&&this.warn(`audio and video track sample timestamps do not overlap. v: ${w}-${C} a: ${P}-${x}}`,R,I);const F=!!I&&(!R||!g&&P<w||!!g&&g.trackId===T.audio.id),N=F?I:R;if(!N)return this.log(`No media samples found in ${l} ${h.level} ${-1===h.part?"":`part: ${h.part} of`} sn: ${h.sn} at playlist time: ${n}`),p;let $,B=v;if(R&&R.sampleCount>=1&&T.video&&h.iframe){const{trun:t,start:e}=R,i=1===t.length,s=t.length?i?t[0].samples:t[0].samples.concat(...t.slice(1).map(t=>t.samples)):[];if(s.length){const r=t[0];let n=r;for(let e=t.length;e--;)if(t[e].samples.length){n=t[e];break}const a=n.lastSampleDurationOffset,{defaultSampleDurationOffset:o}=r,l=Math.abs(h.duration-(C-w))>.05,d=s.length<R.sampleCount;if(l||d||this.videoOnlyRemux||!i){const t=d?n.sampleOffset+n.samples.reduce((t,e)=>t+e.size,0):void 0,i=l?h.duration:C-w,r=function(t,e,i,s){if(void 0!==i){const s=t[t.length-1];let r=e;for(let e=0;e<t.length-1;e++)r-=t[e].duration;return r<=0&&(r=s.duration),s.duration=r,{durationOffset:i,value:r}}if(void 0===s)return;const r=Math.round(e/t.length);for(let e=0;e<t.length;e++)t[e].duration=r;return{durationOffset:s,value:r}}(s,i*T.video.timescale,a,o),c=function(t,e,i,s,r){if(i<1)return null;const n=Pt(t,["moof"]);if(1!==n.length)return null;const a=n[0],o=t.byteOffset,l=[],h=[],d=Pt(a,["traf"]);let c=!0;for(let t=0;t<d.length;t++){const i=d[t],s=Pt(i,["tfhd"])[0];if(!s)return null;At(s,4)===e?(l.push(i),131072&At(s,0)||(c=!1)):h.push(Dt(i,o))}if(!l.length)return null;if(h.length&&!c)return null;if(void 0!==s){let e=i;for(let i=0;i<l.length;i++){const s=l[i];let r=0;const n=Pt(s,["trun"]);for(let i=0;i<n.length;i++){const s=n[i],a=Math.min(e,At(s,4));if(a){kt(t,s.byteOffset-o+4,a);const e=16777215&At(s,0);_t(t,s,8+(1&e?4:0)+(4&e?4:0)+a*((256&e?4:0)+(512&e?4:0)+(1024&e?4:0)+(2048&e?4:0)))}else kt(t,s.byteOffset-o-4,Tt.free);e-=a,r+=a}const a=Pt(s,["senc"])[0];a&&kt(t,a.byteOffset-o+4,r);const h=Pt(s,["saiz"])[0];if(h){let e=4;1&(h[1]<<16|h[2]<<8|h[3])&&(e+=8);const i=h[e];e+=1,kt(t,h.byteOffset-o+e,r),_t(t,h,e+4+(0===i?r:0))}}const r=Pt(t,["mdat"]);if(1===r.length){const e=r[0].byteOffset-o-8;kt(t,e,s-e)}}let u=t,f=0,g=()=>0;if(h.length){({result:u,dropped:f,droppedBefore:g}=wt(t,h)),kt(u,a.byteOffset-o-8,a.byteLength+8-f);for(let t=0;t<l.length;t++){const e=l[t],i=g(e.byteOffset-o),s=Pt(e,["trun"]);for(let t=0;t<s.length;t++){const e=s[t];1&At(e,0)&&kt(u,e.byteOffset-o-i+8,At(e,8)-f)}if(i){const t=Pt(e,["saio"]);for(let e=0;e<t.length;e++){const s=t[e],r=0===s[0]?4:8;let n=1&At(s,0)?12:4,a=At(s,n);for(n+=4;a--;n+=r){const t=n+r-4;kt(u,s.byteOffset-o-i+t,At(s,t)-i)}}}}}if(r){const{durationOffset:t,value:e}=r;kt(u,t-g(t),e)}return void 0!==s?u.subarray(0,s-f):u}(v,T.video.id,s.length,t,r);c?(B=c,$=function(t,e){let i=t,s=t;for(let t=0;t<e.length;t++){const{cts:r,duration:n}=e[t];s=Math.max(s,i+(r||0)+n),i+=n}return s}(e,s)):this.warn(`IFrame remux skipped (sn ${h.sn}); using native sample duration`),O=c&&r?i:C-w}else O=C-w}else this.warn(`Could not remux IFrame track fragment (no samples in range, trun count ${t.length})`),O=C-w}else O=F?x-P:C-w;if(this.videoOnlyRemux&&B===v)return this.warn(`Dropping muxed I-Frame fragment that could not be remuxed to video-only (sn: ${h.sn})`),p;const U=N.timescale,G=N.start-n*U,K=F?T.audio.id:T.video.id;M=N.start/U;if(!(!!g&&h.id>1)&&(a||!g)&&(function(t,e,i,s){if(null===t)return!0;const r=Math.max(s,1),n=e-t.baseTime/t.timescale;return Math.abs(n-i)>=r}(g,M,n,O)||U!==g.timescale)){let t=!1;const e=F?"audio":"video";if(g){const i=0!==n?M/n:1+M/1;t=M>=0&&Math.abs(1-i)<.001,this.log(`${e} timestamps in track ${K} at playlist time: ${a?"":"~"}${n} maps to ${M} with initPTS: ${g.baseTime/g.timescale} (${G/U-g.baseTime/g.timescale}s diff) (${D}) drift estimate: ${i} ${t?"(ignoring drift)":"remapping timestamps (initPTS)"}`)}t||(this.log(`Found initPTS in ${e} track ${K} at playlist time: ${n} offset: ${M-n} (${G}/${U})`),g=null,E.initPTS=G,E.timescale=U,E.trackId=K)}g?(E.initPTS=g.baseTime,E.timescale=g.timescale,E.trackId=g.trackId):(E.timescale&&void 0!==E.trackId&&void 0!==E.initPTS||(this.warn("Could not set initPTS"),E.initPTS=M,E.timescale=1,E.trackId=-1),this.initPTS=g={baseTime:E.initPTS,timescale:E.timescale,trackId:E.trackId});const V=M-g.baseTime/g.timescale,j=V+O,H=_&&void 0!==(null==N?void 0:N.ptsMin)?N.ptsMin/N.timescale-g.baseTime/g.timescale:V,q=void 0!==$&&R?$/R.timescale-g.baseTime/g.timescale:_&&null!=N&&N.ptsMax?N.ptsMax/N.timescale-g.baseTime/g.timescale:j;O>0?this.lastEndTime=j:(this.warn("Duration parsed from mp4 should be greater than zero"),this.resetNextTimestamp());const Y={data1:B,data2:void 0,startPTS:H,startDTS:V,endPTS:q,endDTS:j,type:D,hasAudio:k,hasVideo:_,nb:1,dropped:0,encrypted:!!T.audio&&T.audio.encrypted||!!T.video&&T.video.encrypted};p.audio=k&&!_?Y:void 0,p.video=_?Y:void 0;const W=this.isVideoContiguous,z=null==R?void 0:R.sampleCount;if(z){const t=R.keyFrameIndex,e=-1!==t;Y.nb=z,Y.dropped=0===t||W?0:e?t:z,Y.independent=e,Y.firstKeyFrame=t,e&&R.keyFrameStart&&(Y.firstKeyFramePTS=(R.keyFrameStart-g.baseTime)/g.timescale),W||(p.independent=e),this.isVideoContiguous||(this.isVideoContiguous=e),Y.dropped&&this.warn(`fmp4 does not start with IDR: firstIDR ${t}/${z} dropped: ${Y.dropped} start: ${Y.firstKeyFramePTS||"NA"}`)}return p.initSegment=E,p.id3=jn(s,n,g,g),r.samples.length&&(p.text=Hn(r,n,g)),p}}},{demux:vn,remux:Kn},{demux:class extends Wr{constructor(t,e){super(),this.observer=void 0,this.config=void 0,this.sampleAes=null,this.observer=t,this.config=e}resetInitSegment(t,e,i,s){super.resetInitSegment(t,e,i,s),this._audioTrack={container:"audio/adts",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"aac",samples:[],manifestCodec:e,duration:s,inputTimeScale:9e4,dropped:0}}static probe(t,e){if(!t)return!1;const i=nt(t,0);let s=(null==i?void 0:i.length)||0;if(nn(t,s))return!1;for(let i=t.length;s<i;s++)if(Kr(t,s))return e.log("ADTS sync word found !"),!0;return!1}canParse(t,e){return function(t,e){return function(t,e){return e+5<t.length}(t,e)&&$r(t,e)&&Ur(t,e)<=t.length-e}(t,e)}appendFrame(t,e,i){Vr(t,this.observer,e,i,t.manifestCodec);const s=Hr(t,e,i,this.basePTS,this.frameIndex);if(0===(null==s?void 0:s.missing))return s}demuxSampleAes(t,e,i){const s=this.demux(t,i),r=this.sampleAes=new an(this.observer,this.config,e);return new Promise(t=>{r.decryptAacSamples(s.audioTrack.samples,0,()=>{t(s)})})}},remux:Kn},{demux:class extends Wr{resetInitSegment(t,e,i,s){super.resetInitSegment(t,e,i,s),this._audioTrack={container:"audio/mpeg",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"mp3",samples:[],manifestCodec:e,duration:s,inputTimeScale:9e4,dropped:0}}static probe(t){if(!t)return!1;const e=nt(t,0);let i=(null==e?void 0:e.length)||0;if(e&&11===t[i]&&119===t[i+1]&&void 0!==gt(e)&&on(t,i)<=16)return!1;for(let e=t.length;i<e;i++)if(nn(t,i))return q.log("MPEG Audio sync word found !"),!0;return!1}canParse(t,e){return function(t,e){return sn(t,e)&&4<=t.length-e}(t,e)}appendFrame(t,e,i){if(null!==this.basePTS)return tn(t,e,i,this.basePTS,this.frameIndex)}},remux:Kn}];zn.splice(2,0,{demux:ln,remux:Kn});class Xn{constructor(t,e,i,s,r,n){this.asyncResult=!1,this.logger=void 0,this.observer=void 0,this.typeSupported=void 0,this.config=void 0,this.id=void 0,this.demuxer=void 0,this.remuxer=void 0,this.decrypter=void 0,this.probe=void 0,this.decryptionPromise=null,this.transmuxConfig=void 0,this.currentTransmuxState=void 0,this.observer=t,this.typeSupported=e,this.config=i,this.id=r,this.logger=n}configure(t){this.transmuxConfig=t,this.decrypter&&this.decrypter.reset()}push(t,e,i,s){if(!this.observer)return Qn(i);const o=i.transmuxing;o.executeStart=Wn();const l=new Uint8Array(t),{currentTransmuxState:h,transmuxConfig:d}=this;s&&(this.currentTransmuxState=s);const{contiguous:c,discontinuity:u,trackSwitch:f,accurateTimeOffset:g,timeOffset:m,initSegmentChange:p}=s||h,{audioCodec:v,videoCodec:y,defaultInitPts:E,duration:T,initSegmentData:S}=d,b=function(t,e){let i=null;t.byteLength>0&&null!=(null==e?void 0:e.key)&&null!==e.iv&&null!=e.method&&(i=e);return i}(l,e);if(b&&gs(b.method)){const t=this.getDecrypter(),e=ms(b.method);return this.asyncResult=!0,this.decryptionPromise=t.decrypt(l,b.key.buffer,b.iv.buffer,e,i.decryptRange).then(t=>{const e=this.push(t,null,i);return this.decryptionPromise=null,e}),this.decryptionPromise}const A=this.needsProbing(u,f);if(A){const t=i.iframe&&S&&vn.probe(S,this.logger)?S:l,e=this.configureTransmuxer(t);if(e)return this.logger.warn(`[transmuxer] ${e.message}`),this.observer.emit(a.ERROR,a.ERROR,{type:r.MEDIA_ERROR,details:n.FRAG_PARSING_ERROR,fatal:!1,error:e,reason:e.message}),o.executeEnd=Wn(),Qn(i)}(u||f||p||A)&&this.resetInitSegment(S,v,y,T,e,i),(u||p||A)&&this.resetInitialTimestamp(E),c||this.resetContiguity();const L=this.transmux(l,b,m,g,i);this.asyncResult=Zn(L);const I=this.currentTransmuxState;return I.contiguous=!0,I.discontinuity=!1,I.trackSwitch=!1,o.executeEnd=Wn(),L}flush(t){const e=t.transmuxing;e.executeStart=Wn();const{decrypter:i,currentTransmuxState:s,decryptionPromise:r}=this;if(r)return this.asyncResult=!0,r.then(()=>this.flush(t));const n=[],{timeOffset:a}=s;if(i){const e=i.flush();e&&n.push(this.push(e.buffer,null,t))}const{demuxer:o,remuxer:l}=this;if(!o||!l){e.executeEnd=Wn();const i=[Qn(t)];return this.asyncResult?Promise.resolve(i):i}const h=o.flush(a,t);return Zn(h)?(this.asyncResult=!0,h.then(e=>(this.flushRemux(n,e,t),n))):(this.flushRemux(n,h,t),this.asyncResult?Promise.resolve(n):n)}flushRemux(t,e,i){if(!this.remuxer)return;const{audioTrack:s,videoTrack:r,id3Track:n,textTrack:a}=e,{accurateTimeOffset:o,timeOffset:l}=this.currentTransmuxState;this.logger.log(`[transmuxer.ts]: Flushed ${this.id} sn: ${i.sn}${i.part>-1?" part: "+i.part:""} of ${this.id} playlist ${i.level}`);const h=this.remuxer.remux(s,r,n,a,l,o,!0,this.id,i,e.initData,e.sampleData);t.push({remuxResult:h,chunkMeta:i}),i.transmuxing.executeEnd=Wn()}resetInitialTimestamp(t){const{demuxer:e,remuxer:i}=this;e&&i&&(e.resetTimeStamp(t),i.resetTimeStamp(t))}resetContiguity(){const{demuxer:t,remuxer:e}=this;t&&e&&(t.resetContiguity(),e.resetNextTimestamp())}resetInitSegment(t,e,i,s,r,n){const{demuxer:a,remuxer:o}=this;a&&o&&(a.resetInitSegment(t,e,i,s,r,n),o.resetInitSegment(t,e,i,r))}destroy(){this.demuxer&&(this.demuxer.destroy(),this.demuxer=void 0),this.remuxer&&(this.remuxer.destroy(),this.remuxer=void 0),this.observer&&this.observer.removeAllListeners(),this.decryptionPromise=null,this.decrypter=this.observer=void 0,this.logger=this.config=this.probe=void 0}transmux(t,e,i,s,r){let n;return n="SAMPLE-AES"===(null==e?void 0:e.method)?this.transmuxSampleAes(t,e,i,s,r):this.transmuxUnencrypted(t,i,s,r),n}transmuxUnencrypted(t,e,i,s){const{demuxer:r,remuxer:n}=this;if(!r||!n)return Qn(s);const a=r.demux(t,e,s,!1,!this.config.progressive),{audioTrack:o,videoTrack:l,id3Track:h,textTrack:d}=a;return{remuxResult:n.remux(o,l,h,d,e,i,!1,this.id,s,a.initData,a.sampleData),chunkMeta:s}}transmuxSampleAes(t,e,i,s,r){return this.demuxer?this.demuxer.demuxSampleAes(t,e,i,r).then(t=>({remuxResult:this.remuxer.remux(t.audioTrack,t.videoTrack,t.id3Track,t.textTrack,i,s,!1,this.id,r,t.initData,t.sampleData),chunkMeta:r})):Promise.reject(new Error("no demuxer"))}configureTransmuxer(t){const{config:e,observer:i,typeSupported:s}=this;if(!i)return;let r;try{for(let e=0,i=zn.length;e<i;e++){var n;if(null!=(n=zn[e].demux)&&n.probe(t,this.logger)){r=zn[e];break}}}catch(t){return t}if(!r)return new Error("Failed to find demuxer by probing fragment data");const a=this.demuxer,o=this.remuxer,l=r.demux,h=r.remux;a&&a instanceof l||(this.logger.log(`Using ${l.name}`),this.demuxer=new l(i,e,s,this.logger),this.probe=l.probe),o&&o instanceof h||(this.logger.log(`Using ${h.name}`),this.remuxer=new h(i,e,s,this.logger))}needsProbing(t,e){return!this.demuxer||!this.remuxer||t||e}getDecrypter(){let t=this.decrypter;return t||(t=this.decrypter=new qi(this.config)),t}}const Qn=t=>({remuxResult:{},chunkMeta:t});function Zn(t){return"then"in t&&t.then instanceof Function}class Jn{constructor(t,e,i,s,r){this.audioCodec=void 0,this.videoCodec=void 0,this.initSegmentData=void 0,this.duration=void 0,this.defaultInitPts=void 0,this.audioCodec=t,this.videoCodec=e,this.initSegmentData=i,this.duration=s,this.defaultInitPts=r||null}}class ta{constructor(t,e,i,s,r,n){this.discontinuity=void 0,this.contiguous=void 0,this.accurateTimeOffset=void 0,this.trackSwitch=void 0,this.timeOffset=void 0,this.initSegmentChange=void 0,this.discontinuity=t,this.contiguous=e,this.accurateTimeOffset=i,this.trackSwitch=s,this.timeOffset=r,this.initSegmentChange=n}}let ea=0;class ia{constructor(t,e,i,s){this.error=null,this.hls=void 0,this.id=void 0,this.instanceNo=ea++,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=t=>{const e=t.data,i=this.hls;if(i&&null!=e&&e.event&&e.instanceNo===this.instanceNo)switch(e.event){case"init":{var s;const t=null==(s=this.workerContext)?void 0:s.objectURL;t&&self.URL.revokeObjectURL(t);break}case"transmuxComplete":this.handleTransmuxComplete(e.data);break;case"flush":this.onFlush(e.data);break;case"workerLog":i.logger[e.data.logType]&&i.logger[e.data.logType](e.data.message);break;default:e.data=e.data||{},e.data.frag=this.frag,e.data.part=this.part,e.data.id=this.id,i.trigger(e.event,e.data)}},this.onWorkerError=t=>{if(!this.hls)return;const e=new Error(`${t.message} (${t.filename}:${t.lineno})`);this.hls.config.enableWorker=!1,this.hls.logger.warn(`Error in "${this.id}" Web Worker, fallback to inline`),this.hls.trigger(a.ERROR,{type:r.OTHER_ERROR,details:n.INTERNAL_EXCEPTION,fatal:!1,event:"demuxerWorker",error:e})};const o=t.config;this.hls=t,this.id=e,this.useWorker=!!o.enableWorker,this.onTransmuxComplete=i,this.onFlush=s;const l=(t,e)=>{(e=e||{}).frag=this.frag||void 0,t===a.ERROR&&(e.parent=this.id,e.part=this.part,this.error=e.error),this.hls.trigger(t,e)};this.observer=new Or,this.observer.on(a.FRAG_DECRYPTED,l),this.observer.on(a.ERROR,l);const h=Te(o.preferManagedMediaSource);if(this.useWorker&&"undefined"!=typeof Worker){const i=this.hls.logger;if(o.workerPath||"function"==typeof __HLS_WORKER_BUNDLE__){try{o.workerPath?(i.log(`loading Web Worker ${o.workerPath} for "${e}"`),this.workerContext=function(t){const e=Nr[t];if(e)return e.clientCount++,e;const i=new self.URL(t,self.location.href).href,s={worker:new self.Worker(i),scriptURL:i,clientCount:1};return Nr[t]=s,s}(o.workerPath)):(i.log(`injecting Web Worker for "${e}"`),this.workerContext=function(){const t=Nr[Fr];if(t)return t.clientCount++,t;const e=new self.Blob([`var exports={};var module={exports:exports};function define(f){f()};define.amd=true;(${__HLS_WORKER_BUNDLE__.toString()})(true);`],{type:"text/javascript"}),i=self.URL.createObjectURL(e),s={worker:new self.Worker(i),objectURL:i,clientCount:1};return Nr[Fr]=s,s}());const{worker:t}=this.workerContext;t.addEventListener("message",this.onWorkerMessage),t.addEventListener("error",this.onWorkerError),t.postMessage({instanceNo:this.instanceNo,cmd:"init",typeSupported:h,id:e,config:Ue(o)})}catch(s){i.warn(`Error setting up "${e}" Web Worker, fallback to inline`,s),this.terminateWorker(),this.error=null,this.transmuxer=new Xn(this.observer,h,o,"",e,t.logger)}return}}this.transmuxer=new Xn(this.observer,h,o,"",e,t.logger)}reset(){if(this.frag=null,this.part=null,this.workerContext){const t=this.instanceNo;this.instanceNo=ea++;const e=this.hls.config,i=Te(e.preferManagedMediaSource);this.workerContext.worker.postMessage({instanceNo:this.instanceNo,cmd:"reset",resetNo:t,typeSupported:i,id:this.id,config:Ue(e)})}}terminateWorker(){if(this.workerContext){const{worker:t}=this.workerContext;this.workerContext=null,t.removeEventListener("message",this.onWorkerMessage),t.removeEventListener("error",this.onWorkerError),function(t){const e=Nr[t||Fr];if(e&&1===e.clientCount--){const{worker:i,objectURL:s}=e;delete Nr[t||Fr],s&&self.URL.revokeObjectURL(s),i.terminate()}}(this.hls.config.workerPath)}}destroy(){if(this.workerContext)this.terminateWorker(),this.onWorkerMessage=this.onWorkerError=null;else{const t=this.transmuxer;t&&(t.destroy(),this.transmuxer=null)}const t=this.observer;t&&t.removeAllListeners(),this.frag=null,this.part=null,this.observer=null,this.hls=null}push(t,e,i,s,r,n,a,o,l,h){var d,c;l.transmuxing.start=self.performance.now();const{instanceNo:u,transmuxer:f}=this,g=n?n.start:r.start,m=r.decryptdata,p=this.frag,v=!p||r.cc!==p.cc,y=!p||l.level!==p.level,E=p?l.sn-p.sn:-1,T=this.part?l.part-this.part.index:-1,S=0===E&&l.id>1&&l.id===(null==p?void 0:p.stats.chunkCount),b=!y&&(1===E||0===E&&(1===T||S&&T<=0)),A=self.performance.now();(y||E||0===r.stats.parsing.start)&&(r.stats.parsing.start=A),!n||!T&&b||(n.stats.parsing.start=A);const L=!(p&&(null==(d=r.initSegment)?void 0:d.url)===(null==(c=p.initSegment)?void 0:c.url)),I=new ta(v,b,o,y,g,L);if(!b||v||L){this.hls.logger.log(`[transmuxer-interface]: Starting new transmux session for ${r.type} sn: ${l.sn}${l.part>-1?" part: "+l.part:""} ${this.id} playlist: ${l.level} id: ${l.id}\n discontinuity: ${v}\n trackSwitch: ${y}\n contiguous: ${b}\n accurateTimeOffset: ${o}\n timeOffset: ${g}\n initSegmentChange: ${L}`);const t=new Jn(i,s,e,a,h);this.configureTransmuxer(t)}if(this.frag=r,this.part=n,this.workerContext)this.workerContext.worker.postMessage({instanceNo:u,cmd:"demux",data:t,decryptdata:m,chunkMeta:l,state:I},t instanceof ArrayBuffer?[t]:[]);else if(f){const e=f.push(t,m,l,I);Zn(e)?e.then(t=>{this.handleTransmuxComplete(t)}).catch(t=>{this.transmuxerError(t,l,"transmuxer-interface push error")}):this.handleTransmuxComplete(e)}}flush(t){t.transmuxing.start=self.performance.now();const{instanceNo:e,transmuxer:i}=this;if(this.workerContext)this.workerContext.worker.postMessage({instanceNo:e,cmd:"flush",chunkMeta:t});else if(i){const e=i.flush(t);Zn(e)?e.then(e=>{this.handleFlushResult(e,t)}).catch(e=>{this.transmuxerError(e,t,"transmuxer-interface flush error")}):this.handleFlushResult(e,t)}}transmuxerError(t,e,i){this.hls&&(this.error=t,this.hls.trigger(a.ERROR,{type:r.MEDIA_ERROR,details:n.FRAG_PARSING_ERROR,chunkMeta:e,frag:this.frag||void 0,part:this.part||void 0,fatal:!1,error:t,err:t,reason:i}))}handleFlushResult(t,e){t.forEach(t=>{this.handleTransmuxComplete(t)}),this.onFlush(e)}configureTransmuxer(t){const{instanceNo:e,transmuxer:i}=this;this.workerContext?this.workerContext.worker.postMessage({instanceNo:e,cmd:"configure",config:t}):i&&i.configure(t)}handleTransmuxComplete(t){t.chunkMeta.transmuxing.end=self.performance.now(),this.onTransmuxComplete(t)}}class sa extends U{constructor(t,e){super(e,t.logger),this.hls=void 0,this.canLoad=!1,this.timer=-1,this.loadingSync=!1,this.hls=t}destroy(){this.clearTimer(),this.hls=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(t,e,i){const s=null==e?void 0:e.renditionReports;if(s){let r=-1;for(let i=0;i<s.length;i++){const n=s[i];let a;try{a=new self.URL(n.URI,e.url).href}catch(t){this.warn(`Could not construct new URL for Rendition Report: ${t}`),a=n.URI||""}if(a===t){r=i;break}a===t.substring(0,a.length)&&(r=i)}if(-1!==r){const t=s[r],n=parseInt(t["LAST-MSN"])||e.lastPartSn;let a=parseInt(t["LAST-PART"])||e.lastPartIndex;if(this.hls.config.lowLatencyMode){const t=Math.min(e.age-e.partTarget,e.targetduration);a>=0&&t>e.partTarget&&(a+=1)}const o=i&&Oe(i);return new Fe(n,a>=0?a:void 0,o)}}}loadPlaylist(t){this.clearTimer()}loadingPlaylist(t,e){this.clearTimer()}shouldLoadPlaylist(t){return this.canLoad&&!!t&&!!t.url&&(!t.details||t.details.live)}getUrlWithDirectives(t,e){if(e)try{return e.addDirectives(t)}catch(t){this.warn(`Could not construct new URL with HLS Delivery Directives: ${t}`)}return t}playlistLoaded(t,e,i){const{details:s,stats:o}=e,l=s.fragments,h=self.performance.now(),d=o.loading.first?Math.max(0,Math.floor(h-o.loading.first)):0;s.advancedDateTime=Date.now()-d;const c=this.hls.config.timelineOffset;if(c!==s.appliedTimelineOffset){const t=Math.max(c||0,0);s.appliedTimelineOffset=t,l.forEach(e=>{null==e||e.setStart(e.playlistOffset+t)})}if(s.live||null!=i&&i.live){var u;const c="levelInfo"in e?e.levelInfo:e.track;s.reloaded(i);const f=null==(u=l[l.length-1])?void 0:u.type;if(s.misses>=this.hls.config.liveMaxUnchangedPlaylistRefresh){const t=new Error(`${f} playlist ${c.id} hit max allowed unchanged reloads.`);this.warn(t);const{networkDetails:i,context:l}=e;return void this.hls.trigger(a.ERROR,{type:r.NETWORK_ERROR,details:n.PLAYLIST_UNCHANGED_ERROR,fatal:!1,url:s.url,error:t,reason:t.message,level:e.level,parent:f,context:l,networkDetails:i,stats:o})}if(i){ir(i,s,this);const t=s.playlistParsingError;if(t){this.warn(t);const i=this.hls;if(!i.config.ignorePlaylistParsingErrors){const{networkDetails:l}=e;return void i.trigger(a.ERROR,{type:r.NETWORK_ERROR,details:n.LEVEL_PARSING_ERROR,fatal:!1,url:s.url,error:t,reason:t.message,level:e.level,parent:f,networkDetails:l,stats:o})}s.playlistParsingError=null}}-1===s.requestScheduled&&(s.requestScheduled=o.loading.start);const g=this.hls.mainForwardBufferInfo,m=g?g.end-g.len:0,p=nr(s,1e3*(s.edge-m));s.requestScheduled+p<h?s.requestScheduled=h:s.requestScheduled<=h&&(s.requestScheduled+=p);const v=e.deliveryDirectives;if(this.log(`live playlist ${t} ${s.advanced?`REFRESHED ${s.lastPartSn} - ${s.lastPartIndex}`:s.updated?"UPDATED":`MISSED (received ${s.lastPartSn} - ${s.lastPartIndex}${v?` | requested ${v.msn} - ${v.part}`:""})`}`),!this.canLoad||!s.live)return;let y,E,T;if(s.canBlockReload&&s.advanced){const t=this.hls.config.lowLatencyMode,r=s.lastPartSn,n=s.endSN,a=s.lastPartIndex,o=r===n;-1!==a?o?(E=n+1,T=t?0:a):(E=r,T=t?a+1:s.maxPartIndex):E=n+1;const l=s.age,d=l+s.ageHeader;let u=Math.min(d-s.partTarget,1.5*s.targetduration);if(u>0){if(d>3*s.targetduration)this.log(`Playlist last advanced ${l.toFixed(2)}s ago. Omitting segment and part directives.`),E=void 0,T=void 0;else if(null!=i&&i.tuneInGoal&&d-s.partTarget>i.tuneInGoal)this.warn(`CDN Tune-in goal increased from: ${i.tuneInGoal} to: ${u} with playlist age: ${s.age}`),u=0;else{const t=Math.floor(u/s.targetduration);if(E+=t,void 0!==T){T+=Math.round(u%s.targetduration/s.partTarget)}this.log(`CDN Tune-in age: ${s.ageHeader}s last advanced ${l.toFixed(2)}s goal: ${u} skip sn ${t} to part ${T}`)}s.tuneInGoal=u}if(y=this.getDeliveryDirectives(s,e.deliveryDirectives,E,T),t||!o)return s.requestScheduled=h,void this.loadingPlaylist(c,y)}else(s.canBlockReload||s.canSkipUntil)&&(y=this.getDeliveryDirectives(s,e.deliveryDirectives,E,T));y&&void 0!==E&&s.canBlockReload&&(s.requestScheduled=o.loading.first+Math.max(p-2*d,p/2)),this.scheduleLoading(c,y,s)}else this.clearTimer()}scheduleLoading(t,e,i){const s=i||t.details;if(!s)return void this.loadingPlaylist(t,e);const r=self.performance.now(),n=s.requestScheduled;if(r>=n&&!this.loadingSync)return this.loadingSync=!0,this.loadingPlaylist(t,e),void(this.loadingSync=!1);const a=Math.max(n-r,0);this.log(`reload live playlist ${t.name||t.bitrate+"bps"} in ${Math.round(a)} ms`),this.clearTimer(),this.timer=self.setTimeout(()=>this.loadingPlaylist(t,e),a)}getDeliveryDirectives(t,e,i,s){let r=Oe(t);return null!=e&&e.skip&&t.deltaUpdateFailed&&(i=e.msn,s=e.part,r=Ce),new Fe(i,s,r)}checkRetry(t){const e=t.details,i=D(t),s=t.errorAction,{action:r,retryCount:n=0,retryConfig:a}=s||{},o=!!s&&!!a&&(r===oi||!s.resolved&&r===ni);if(o){var l;if(n>=a.maxNumRetry)return!1;if(i&&null!=(l=t.context)&&l.deliveryDirectives)this.warn(`Retrying playlist loading ${n+1}/${a.maxNumRetry} after "${e}" without delivery-directives`),this.loadPlaylist();else{var h;const i=F(null==(h=t.response)?void 0:h.code);if(this.clearTimer(),i)this.log("Waiting for connection (offline)"),t.reason="offline",this.timer=self.setTimeout(()=>this.checkOfflineStatus(),1e3);else{const t=x(a,n);this.warn(`Retrying playlist loading ${n+1}/${a.maxNumRetry} after "${e}" in ${t}ms`),this.timer=self.setTimeout(()=>this.loadPlaylist(),t)}}t.levelRetry=!0,s.resolved=!0}return o}checkOfflineStatus(){this.clearTimer(),F(0)?this.timer=self.setTimeout(()=>this.checkOfflineStatus(),1e3):(this.log("Connection restored (online)"),this.loadPlaylist())}}function ra(t,e){if(t.length!==e.length)return!1;for(let i=0;i<t.length;i++)if(!na(t[i].attrs,e[i].attrs))return!1;return!0}function na(t,e,i){const s=t["STABLE-RENDITION-ID"];return s&&!i?s===e["STABLE-RENDITION-ID"]:!(i||["LANGUAGE","NAME","CHARACTERISTICS","AUTOSELECT","DEFAULT","FORCED","ASSOC-LANGUAGE"]).some(i=>t[i]!==e[i])}class aa{constructor(t){this.hls=null,this.autoLevelCapping=void 0,this.media=void 0,this.restrictedLevels=void 0,this.timer=void 0,this.observer=void 0,this.clientRect=void 0,this.streamController=void 0,this.hls=t,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.media=null,this.restrictedLevels=[],this.clientRect=null,this.registerListeners()}setStreamController(t){this.streamController=t}destroy(){this.hls&&this.unregisterListener(),(this.timer||this.observer)&&this.stopCapping(),this.media=this.clientRect=this.hls=null,this.streamController=void 0}registerListeners(){const{hls:t}=this;t&&(t.on(a.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),t.on(a.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(a.MANIFEST_PARSED,this.onManifestParsed,this),t.on(a.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(a.BUFFER_CODECS,this.onBufferCodecs,this),t.on(a.MEDIA_DETACHING,this.onMediaDetaching,this))}unregisterListener(){const{hls:t}=this;t&&(t.off(a.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),t.off(a.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(a.MANIFEST_PARSED,this.onManifestParsed,this),t.off(a.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(a.BUFFER_CODECS,this.onBufferCodecs,this),t.off(a.MEDIA_DETACHING,this.onMediaDetaching,this))}onFpsDropLevelCapping(t,e){if(!this.hls)return;const i=this.hls.levels[e.droppedLevel];this.isLevelAllowed(i)&&this.restrictedLevels.push({bitrate:i.bitrate,height:i.height,width:i.width})}onMediaAttaching(t,e){const i=e.media;this.clientRect=null,this.hls&&(i instanceof HTMLVideoElement?(this.media=i,this.hls.config.capLevelToPlayerSize&&this.observe()):this.media=null,(this.timer||this.observer)&&this.hls.levels.length>1&&this.detectPlayerSize())}onManifestParsed(t,e){this.restrictedLevels=[],e.video&&this.startCapping(),this.onLevelsUpdated()}onLevelsUpdated(){if(this.hls)if((this.timer||this.observer)&&(e(this.autoLevelCapping)||this.clientRect))this.detectPlayerSize();else if(void 0===this.observer&&void 0===this.timer){const t=this.hls.levels;t.length>1&&t.some(t=>!!t.videoCodec)&&this.startCapping()}}onBufferCodecs(t,e){e.video&&this.startCapping()}onMediaDetaching(){this.stopCapping(),this.media=null}detectPlayerSize(){if(this.media){if(this.mediaHeight<=0||this.mediaWidth<=0||!this.hls)return void(this.clientRect=null);const t=this.hls.levels;if(t.length>1){const e=this.hls,i=this.getMaxLevel(t.length-1);i!==this.autoLevelCapping&&e.logger.log(`Setting autoLevelCapping to ${i}: ${t[i].height}p@${t[i].bitrate} for media ${this.mediaWidth}x${this.mediaHeight}`),e.autoLevelCapping=i,e.autoLevelEnabled&&e.autoLevelCapping>this.autoLevelCapping&&this.streamController&&this.streamController.nextLevelSwitch(),this.autoLevelCapping=e.autoLevelCapping}else 1===t.length&&this.stopCapping()}}getMaxLevel(t){if(!this.hls)return-1;const e=this.hls.levels;if(!e.length)return-1;const i=e.filter((e,i)=>this.isLevelAllowed(e)&&i<=t);return this.observer||(this.clientRect=null),aa.getMaxLevelByMediaSize(i,this.mediaWidth,this.mediaHeight)}observe(){const t=self.ResizeObserver;t&&(this.observer=new t(t=>{var e;const i=null==(e=t[0])?void 0:e.contentRect;i&&(this.clientRect=i,this.detectPlayerSize())})),this.observer&&this.media&&this.observer.observe(this.media)}startCapping(){var t;this.timer||this.observer||null==(t=this.hls)||!t.config.capLevelToPlayerSize||(self.clearInterval(this.timer),this.timer=void 0,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.observe(),this.observer||(this.timer=self.setInterval(this.detectPlayerSize.bind(this),1e3)),this.detectPlayerSize())}stopCapping(){this.restrictedLevels=[],this.autoLevelCapping=Number.POSITIVE_INFINITY,this.timer&&(self.clearInterval(this.timer),this.timer=void 0),this.observer&&(this.observer.disconnect(),this.observer=void 0)}getDimensions(){if(this.clientRect)return this.clientRect;const t=this.media,e={width:0,height:0};if(t){const i=t.getBoundingClientRect();e.width=i.width,e.height=i.height,e.width||e.height||(e.width=i.right-i.left||t.width||0,e.height=i.bottom-i.top||t.height||0)}return this.clientRect=e,e}get mediaWidth(){return this.getDimensions().width*this.contentScaleFactor}get mediaHeight(){return this.getDimensions().height*this.contentScaleFactor}get contentScaleFactor(){let t=1;if(!this.hls)return t;const{ignoreDevicePixelRatio:e,maxDevicePixelRatio:i}=this.hls.config;if(!e)try{t=self.devicePixelRatio}catch(t){}return Math.min(t,i)}isLevelAllowed(t){return!this.restrictedLevels.some(e=>t.bitrate===e.bitrate&&t.width===e.width&&t.height===e.height)}static getMaxLevelByMediaSize(t,e,i){if(null==t||!t.length)return-1;const s=(t,e)=>!e||(t.width!==e.width||t.height!==e.height);let r=t.length-1;const n=Math.max(e,i);for(let e=0;e<t.length;e+=1){const i=t[e];if((i.width>=n||i.height>=n)&&s(i,t[e+1])){r=e;break}}return r}}var oa=class t{constructor(e,i){Array.isArray(e)&&(e=e.map(e=>e instanceof t?e:new t(e))),this.value=e,this.params=i}};function la(t,e,i,s){return new Error(`failed to ${t} "${r=e,Array.isArray(r)?JSON.stringify(r):r instanceof Map?"Map{}":r instanceof Set?"Set{}":"object"==typeof r?JSON.stringify(r):String(r)}" as ${i}`,{cause:s});var r}const ha="Bare Item";const da=/[\x00-\x1f\x7f]+/;var ca=class{constructor(t){this.description=t}};function ua(t,e,i){return la("serialize",t,e,i)}function fa(t){if(!1===ArrayBuffer.isView(t))throw ua(t,"Byte Sequence");return`:${e=t,btoa(String.fromCharCode(...e))}:`;var e}function ga(t){if(function(t){return t<-999999999999999||999999999999999<t}(t))throw ua(t,"Integer");return t.toString()}function ma(t){const e=J(t,3);if(Math.floor(Math.abs(e)).toString().length>12)throw ua(t,"Decimal");const i=e.toString();return i.includes(".")?i:`${i}.0`}function pa(t){const e=(i=t).description||i.toString().slice(7,-1);var i;if(!1===/^([a-zA-Z*])([!#$%&'*+\-.^_`|~\w:/]*)$/.test(e))throw ua(e,"Token");return e}function va(t){switch(typeof t){case"number":if(!e(t))throw ua(t,ha);return Number.isInteger(t)?ga(t):ma(t);case"string":return function(t){if(da.test(t))throw ua(t,"String");return`"${t.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}(t);case"symbol":return pa(t);case"boolean":return function(t){if("boolean"!=typeof t)throw ua(t,"Boolean");return t?"?1":"?0"}(t);case"object":if(t instanceof Date)return function(t){return`@${ga(t.getTime()/1e3)}`}(t);if(t instanceof Uint8Array)return fa(t);if(t instanceof ca)return pa(t);default:throw ua(t,ha)}}function ya(t){if(!1===/^[a-z*][a-z0-9\-_.*]*$/.test(t))throw ua(t,"Key");return t}function Ea(t){return null==t?"":Object.entries(t).map(([t,e])=>!0===e?`;${ya(t)}`:`;${ya(t)}=${va(e)}`).join("")}function Ta(t){return t instanceof oa?`${va(t.value)}${Ea(t.params)}`:va(t)}function Sa(t,e={whitespace:!0}){if("object"!=typeof t||null==t)throw ua(t,"Dict");const i=t instanceof Map?t.entries():Object.entries(t),s=null!=e&&e.whitespace?" ":"";return Array.from(i).map(([t,e])=>{e instanceof oa==!1&&(e=new oa(e));let i=ya(t);var s;return!0===e.value?i+=Ea(e.params):(i+="=",Array.isArray(e.value)?i+=`(${(s=e).value.map(Ta).join(" ")})${Ea(s.params)}`:i+=Ta(e)),i}).join(`,${s}`)}function ba(t,e){return Sa(t,e)}const Aa=["url"],La=["version","eventTargets","sid","transmissionMode"],Ia=["customData","headers"],Ra=t=>t instanceof oa?new oa(Math.round(t.value),t.params):Math.round(t),ka=t=>Array.isArray(t)?t.map(Ra):Ra(t),_a=(t,e)=>Array.isArray(t)?t.map(t=>_a(t,e)):t instanceof oa&&"string"==typeof t.value?new oa(_a(t.value,e),t.params):(e.baseUrl&&(t=function(t,e){let i;try{i=new URL(t)}catch(e){return t}const s=new URL(e);if(i.origin!==s.origin)return t;const r=i.pathname.split("/").slice(1),n=s.pathname.split("/").slice(1,-1),a=Math.min(r.length,n.length);for(let t=0;t<a&&r[t]===n[t];t++)r.shift(),n.shift();for(;n.length;)n.shift(),r.unshift("..");return r.join("/")+i.search+i.hash}(t,function(t){const e="string"==typeof t?new URL(t):t;return e.origin+e.pathname.substring(0,e.pathname.lastIndexOf("/")+1)}(e.baseUrl))),1===e.version?encodeURIComponent(t):t),Da=t=>t instanceof oa?new oa(100*Math.round(t.value/100),t.params):100*Math.round(t/100),wa=t=>Array.isArray(t)?t.map(Da):Da(t),Pa={br:ka,d:ka,bl:wa,dl:wa,mtp:wa,nor:(t,e)=>{let i=t;return e.version>=2&&(t instanceof oa&&"string"==typeof t.value?i=new oa([t]):"string"==typeof t&&(i=[t])),_a(i,e)},rtp:wa,tb:ka},Ca=2,xa="rr",Ma="bc",Oa="e",Fa=xa,Na="ce",$a=new Map([["ps","sta"],["pr","pr"],["c","cid"],["b","bg"],["bc","br"]]),Ba="event",Ua="request",Ga=["cen","e","h","ts"],Ka=["ab","bg","bl","br","bs","bsa","bsd","bsda","cdn","cid","cs","d","dfa","dl","ec","lab","lb","ltc","msd","mtp","nor","nr","ot","pb","pr","pt","rtp","sf","sid","sn","st","sta","su","tab","tb","tbl","tpb","v"],Va=/^[a-zA-Z0-9-.]+-[a-zA-Z0-9-.]+$/;function ja(t){return Va.test(t)}const Ha=new Set(Ka);function qa(t){return Ha.has(t)||ja(t)}const Ya=["cmsdd","cmsds","rc","smrt","ttfb","ttfbb","ttlb","url"],Wa=new Set(Ya);function za(t){return Wa.has(t)}const Xa=new Set(Ga);const Qa=new Set(["ab","bl","br","bsa","bsd","bsda","lab","lb","mtp","pb","tab","tb","tbl","tpb"]),Za=["bl","br","bs","cid","d","dl","mtp","nor","nrr","ot","pr","rtp","sf","sid","st","su","tb","v"],Ja=new Set(Za);function to(t){return Ja.has(t)||ja(t)}const eo=new Set(["ot","sf","st","e","sta"]);function io(t){return eo.has(t)}function so(t){return"number"==typeof t?e(t):null!=t&&""!==t&&!1!==t}const ro={[Ba]:function(t){return qa(t)||za(t)||Xa.has(t)},[Ua]:qa};function no(t,e){if(Array.isArray(t)){let i;return e&&(i=t.find(t=>{var i;return(null==(i=t.params)?void 0:i.ot)===e})),i||(i=t[0]),no(i)}return t instanceof oa?t.value:t}function ao(t,i={}){const s={};if(null==t||"object"!=typeof t)return s;const r=i.version||t.v||Ca,n=i.reportingMode||Ua,a=1===r?function(t){const e={};for(const[s,r]of Object.entries(t))if(null!=r)if("nor"===s){const t=(Array.isArray(r)?r:[r])[0];var i;t instanceof oa?(e.nor=t.value,null!=(i=t.params)&&i.r&&(e.nrr=t.params.r)):e.nor=t}else Qa.has(s)?e[s]=no(r,t.ot):e[s]=r;else e[s]=r;return e}(t):t,o=1===r?to:ro[n];let l=Object.keys(a).filter(o);a.e&&a.e!==xa&&(l=l.filter(t=>!za(t)));const h=i.filter;"function"==typeof h&&(l=l.filter(h));const d=n===Ba;if(d){const t=a.e;l.includes("e")||null==t||l.push("e"),l.includes("ts")||l.push("ts"),l.includes("cen")||null==a.cen||"ce"!==t||l.push("cen");const e=t?$a.get(t):void 0;e&&null!=a[e]&&!l.includes(e)&&l.push(e)}if(0===l.length)return s;r>1&&!l.includes("v")&&l.push("v");const c={version:r,reportingMode:n,baseUrl:i.baseUrl};l.sort();for(const t of l){var u,f;let n=a[t];const o=null!=(u=null==(f=i.formatters)?void 0:f[t])?u:Pa[t];if("function"==typeof o&&(n=o(n,c)),"v"===t){if(1===r)continue;n=r}if("pr"===t&&1===n&&(!d||"pr"!==a.e))continue;d&&"ts"===t&&!e(n)&&(n=Date.now());const l=d&&!1===n&&"bg"===t&&"b"===a.e;(so(n)||l)&&(io(t)&&"string"==typeof n&&(n=new ca(n)),s[t]=n)}return s}const oo="CMCD-Object",lo="CMCD-Request",ho="CMCD-Session",co="CMCD-Status",uo=lo,fo={ab:oo,br:oo,d:oo,lab:oo,lb:oo,ot:oo,tab:oo,tb:oo,tpb:oo,bl:lo,cs:lo,dfa:lo,dl:lo,ltc:lo,mtp:lo,nor:lo,nrr:lo,pb:lo,sn:lo,sta:lo,su:lo,tbl:lo,cid:ho,msd:ho,sf:ho,sid:ho,st:ho,v:ho,bg:co,bs:co,bsa:co,bsd:co,bsda:co,cdn:co,ec:co,nr:co,pr:co,pt:co,rtp:co};function go(t,e){const i={};if(!t)return i;const s=Object.keys(t),r=e?(n=e,Object.keys(n).reduce((t,e)=>{var i;return null==(i=n[e])||i.forEach(i=>t[i]=e),t},{})):{};var n;for(const e of s){var a;const s=fo[e]||r[e]||uo;(null!=(a=i[s])?a:i[s]={})[e]=t[e]}return i}const mo="CMCD";function po(t){return ba(t,{whitespace:!1})}const vo=[...Za,...Ka,...Ya,...Ga].filter((t,e,i)=>i.indexOf(t)===e),yo="m",Eo="a",To="v",So="av",bo="i",Ao="tt",Lo="s",Io="p",Ro="k",ko="r",_o="a",Do="e",wo="f",Po="d",Co="query",xo="headers";function Mo(t,e,i){var s;const r=new Set(null!=(s=e.enabledKeys)?s:[]);return{version:e.version||Ca,reportingMode:t,filter:t=>r.has(t),baseUrl:i}}const Oo=Object.is,Fo=t=>t,No=Array.from($a,([t,e])=>"br"===e?{event:t,field:e,equal:(t,e)=>void 0===t||void 0===e?t===e:function(t,e){if(t===e)return!0;if(t.length!==e.length)return!1;for(let i=0;i<t.length;i++){const s=t[i],r=e[i];if(s===r)continue;if("number"==typeof s||"number"==typeof r)return!1;if(s.value!==r.value)return!1;const n=s.params,a=r.params,o=n&&Object.keys(n)[0],l=a&&Object.keys(a)[0];if(o!==l)return!1;if(void 0!==o&&void 0!==l&&n&&a&&n[o]!==a[l])return!1}return!0}(t,e),snapshot:t=>t.slice()}:{event:t,field:e,equal:Oo,snapshot:Fo}),$o=new Map(No.map(t=>[t.event,t]));function Bo(t){const{url:e}=t,i=_(t,Aa);return fetch(e,i)}var Uo=class{constructor(t,e=Bo){var i;this.timeOrigin=performance.timeOrigin||(null==(i=performance.timing)?void 0:i.fetchStart)||Date.now()-performance.now(),this.data={},this.msd=NaN,this.eventTargets=new Map,this.lastEmitted={},this.requestTarget={sn:0,msdSent:!1},this.config=function(t){const{version:e=Ca,eventTargets:i=[],sid:s=tt(),transmissionMode:r=Co}=t;return k(k({},_(t,La)),{},{version:e,transmissionMode:r,sid:s,eventTargets:i.reduce((t,e)=>{var i,s,r;return null!=e&&e.url&&null!=(i=e.events)&&i.length&&t.push({version:e.version||Ca,enabledKeys:(null==(s=e.enabledKeys)?void 0:s.slice())||[],url:e.url,events:e.events.slice(),interval:null!=(r=e.interval)?r:30,batchSize:e.batchSize||1}),t},[])})}(t),this.data={cid:this.config.cid,sid:this.config.sid,v:this.config.version},this.requester=e;for(const t of this.config.eventTargets)this.eventTargets.set(t,{intervalId:void 0,sn:0,msdSent:!1,queue:[]})}start(){this.eventTargets.forEach((t,e)=>{if(this.disarmInterval(t),0===e.interval||!e.events.includes("t"))return;const i=()=>{this.recordTargetEvent(t,e,"t"),this.processEventTargets()};t.intervalId=setInterval(i,1e3*e.interval),i()})}stop(t=!1){t&&this.flush(),this.eventTargets.forEach(t=>{this.disarmInterval(t)})}flush(){this.processEventTargets(!0)}update(t){t.sid&&t.sid!==this.data.sid&&this.resetSession(),t.msd&&!isNaN(t.msd)&&(this.msd=t.msd),this.data=k(k(k({},this.data),t),{},{msd:void 0});for(const e of No)e.field in t&&!e.equal(this.data[e.field],this.lastEmitted[e.field])&&this.recordEvent(e.event)}recordEvent(t,e={}){const i=$o.get(t);if(i){const t=i.field,s=e[t];void 0!==s&&I(this.data,{[t]:s});const r=this.data[t];if(void 0===r)return;if(i.equal(r,this.lastEmitted[t]))return;I(this.lastEmitted,{[t]:i.snapshot(r)})}this.eventTargets.forEach((i,s)=>{this.recordTargetEvent(i,s,t,e)}),this.processEventTargets()}recordTargetEvent(t,e,i,s={}){var r;if(!e.events.includes(i))return;const n=k(k(k({},this.data),s),{},{e:i,ts:null!=(r=s.ts)?r:Date.now(),sn:t.sn++});isNaN(this.msd)||t.msdSent||(n.msd=this.msd,t.msdSent=!0),t.queue.push(n)}recordResponseReceived(t,e={}){var i,s,r;const{request:n}=t,a=null!=(i=e.url)?i:null==n?void 0:n.url;if(!a)return;const o=new URL(a);o.searchParams.delete(mo);const l={url:o.toString(),rc:t.status},h=t.resourceTiming;h&&(null!=h.startTime&&(l.ts=Math.round(this.timeOrigin+h.startTime),null!=h.responseStart&&(l.ttfb=Math.round(h.responseStart-h.startTime))),null!=h.duration&&(l.ttlb=Math.round(h.duration)));const d=null!=(s=null==(r=n.customData)?void 0:r.cmcd)?s:{};this.recordEvent(xa,k(k(k({},d),l),e))}applyRequestReport(t){var e;return null!=(e=this.createRequestReport(t))?e:t}isRequestReportingEnabled(){var t;return!(null==(t=this.config.enabledKeys)||!t.length)}createRequestReport(t,e){var i;const{customData:s={},headers:r={}}=t,n=k(k({},_(t,Ia)),{},{headers:k({},r),customData:k(k({},s),{},{cmcd:{}})});if(null==(i=this.config.enabledKeys)||!i.length||!n.url)return n;const a=new URL(n.url),o=k(k(k({},this.data),e),{},{sn:this.requestTarget.sn++}),l=Mo(Ua,this.config,n.url);isNaN(this.msd)||this.requestTarget.msdSent||(o.msd=this.msd,this.requestTarget.msdSent=!0);const h=n.customData.cmcd=ao(o,l);switch(this.config.transmissionMode){case Co:const t=po(h);t&&(a.searchParams.set(mo,t),n.url=a.toString());break;case xo:I(n.headers,function(t,e){const i={},s=go(t,e);for(const[t,e]of Object.entries(s)){const s=ba(e,{whitespace:!1});s&&(i[t]=s)}return i}(h,l.customHeaderMap))}return n}processEventTargets(t=!1){let e=!1;this.eventTargets.forEach((i,s)=>{const{queue:r}=i;if(!r.length)return;if(r.length<s.batchSize&&!t)return;const n=t?r.length:s.batchSize,a=r.splice(0,n);this.sendEventReport(s,a).catch(()=>{i.queue.unshift(...a)}),e||(e=r.length>0)}),e&&this.processEventTargets()}async sendEventReport(t,e){const i=Mo(Ba,t),{status:s}=await this.requester({url:t.url,method:"POST",headers:{"Content-Type":"application/cmcd"},body:e.map(t=>function(t,e={}){return t?po(ao(t,e)):""}(t,i)).join("\n")+"\n"});if(410===s)this.disposeEventTarget(t);else if(429===s||s>499&&s<600)throw new Error(`Event report failed with status ${s}`)}disarmInterval(t){clearInterval(t.intervalId),t.intervalId=void 0}disposeEventTarget(t){const e=this.eventTargets.get(t);e&&(this.disarmInterval(e),this.eventTargets.delete(t))}resetSession(){this.eventTargets.forEach(t=>t.sn=0),this.requestTarget.sn=0,this.lastEmitted={}}};const Go="h",Ko="v",Vo="l",jo="ll";new Set(Za),new Set(vo);const Ho=["includeKeys"];function qo(t){return Object.keys(t).every(ja)}function Yo(t,e,i,s){t&&Object.keys(e).forEach(r=>{const n=t.filter(t=>t.groupId===r).map(t=>{const n=I({},t);return n.details=void 0,n.attrs=new ls(n.attrs),n.url=n.attrs.URI=Wo(t.url,t.attrs["STABLE-RENDITION-ID"],"PER-RENDITION-URIS",i),n.groupId=n.attrs["GROUP-ID"]=e[r],n.attrs["PATHWAY-ID"]=s,n});t.push(...n)})}function Wo(t,e,i,s){if(e){const{[i]:t}=s;if(t){const i=t[e];if(i)return i}}const{HOST:r,PARAMS:n}=s,a=new self.URL(t);return r&&(a.hostname=r),n&&Object.keys(n).sort().forEach(t=>{t&&De(a,t,n[t])}),a.href}class zo{constructor(){this.status="initialized",this.requestErrors=[],this.licenseXhr=void 0,this.onmessage=void 0,this.onkeystatuseschange=void 0,this.emitter=new Or,this.error=void 0,this.ok=void 0}get errored(){return this.error}set errored(t){this.error=t,this.emitter.eventNames().length&&this.emitter.emit("error",t)}get hasListeners(){return this.emitter.eventNames().length>0}get resolved(){return this.ok}resolve(){this.ok=!0,this.emitter.emit("resolved")}get useable(){return this.ok?Promise.resolve():this.error?Promise.reject(this.error):new Promise((t,e)=>{this.emitter.on("error",e),this.emitter.on("resolved",t)})}reset(){this.emitter.removeAllListeners();const t=this.licenseXhr;t&&(t.readyState!==XMLHttpRequest.DONE&&t.abort(),this.licenseXhr=void 0),this.onmessage=this.onkeystatuseschange=void 0}}class Xo extends Error{constructor(t,e){super(e),this.data=void 0,t.error||(t.error=new Error(e)),this.data=t,t.err=t.error}}class Qo extends U{constructor(t){super("eme",t.logger),this.hls=void 0,this.config=void 0,this.media=null,this.mediaResolved=void 0,this.keyFormatPromise=null,this.keySystemAccessPromises={},this.sessionSetupByUri={},this.mediaKeySessions=[],this.activeKeys={},this.mediaKeys=null,this.setMediaKeysChain=Qo.CDMCleanupPromise||Promise.resolve(),this.onMediaEncrypted=t=>{const{initDataType:e,initData:i}=t,s=`"${t.type}" event: init data type: "${e}"`;if(this.log(s),null!==i){if(!this.keyFormatPromise){let t=Object.keys(this.keySystemAccessPromises);t.length||(t=_s(this.config));const e=t.map(ks).filter(t=>!!t);this.keyFormatPromise=this.getKeyFormatPromise(e)}this.keyFormatPromise.then(r=>{let n;const a=Is(r),o=this.activeLevelKeys();if(a===Ts.FAIRPLAY&&"sinf"===e)try{const t=yt(new Uint8Array(i)),e=Gt(vt(JSON.parse(t).sinf));if(!e)throw new Error("'schm' box missing or not cbcs/cenc with schi > tenc");n=new Uint8Array(e.subarray(8,24))}catch(t){return void this.warn(`${s} Failed to parse sinf: ${t}`)}else if(a===Ts.PLAYREADY)n=Ps(new Uint8Array(i));else if(a===Ts.WIDEVINE){const t=Qt(i).filter(t=>t.systemId===Rs);if(t.length){var l;const e=t[0];n=null!=(l=e.kids)&&l.length?e.kids[0]:null}}let h;if(n){const t=mt(n);for(let s=0;s<o.length;s++){const r=o[s];if(r.keyId&&(us(n,r.keyId)||-1!==r.uri.replace(/-/g,"").indexOf(t))){r.pssh||(r.scheme=e,r.pssh=new Uint8Array(i),r.keyId=n,xs.setKeyIdForUri(r.uri,n)),h=this.getSessionForKey(r,"encrypted-event-key-match");break}}}if(!h){var d,c;if(o.length)return(d=o[0]).scheme||(d.scheme=e),(c=o[0]).pssh||(c.pssh=new Uint8Array(i)),this.getSessionForKey(o[0],"encrypted-event-no-match");if(n)throw new Error(`Key ID ${mt(n)} not encountered in playlist`);this.log(`Ignoring "${t.type}" event - could not determine keyId`)}return h}).catch(t=>this.handleError(t))}},this.onWaitingForKey=t=>{this.log(`"${t.type}" event`)},this.hls=t,this.config=t.config,this.registerListeners()}destroy(){this.onDestroying(),this.onMediaDetached();const t=this.config;t.requestMediaKeySystemAccessFunc=null,t.licenseXhrSetup=t.licenseResponseCallback=void 0,t.drmSystems=t.drmSystemOptions={},this.hls=this.config=null,this.onMediaEncrypted=this.onWaitingForKey=null}registerListeners(){const{hls:t}=this;t&&(t.on(a.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(a.MEDIA_DETACHED,this.onMediaDetached,this),t.on(a.MANIFEST_LOADING,this.onManifestLoading,this),t.on(a.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(a.DESTROYING,this.onDestroying,this))}unregisterListeners(){const{hls:t}=this;t&&(t.off(a.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(a.MEDIA_DETACHED,this.onMediaDetached,this),t.off(a.MANIFEST_LOADING,this.onManifestLoading,this),t.off(a.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(a.DESTROYING,this.onDestroying,this))}attemptKeySystemAccess(t){if(!this.hls)return Promise.reject(new Error("destroyed"));const e=this.hls.levels,i=(t,e,i)=>!!t&&i.indexOf(t)===e,s=e.map(t=>t.audioCodec).filter(i),a=e.map(t=>t.videoCodec).filter(i);return s.length+a.length===0&&a.push("avc1.42e01e"),new Promise((e,i)=>{const o=t=>{const l=t.shift();this.getMediaKeysPromise(l,s,a).then(t=>e({keySystem:l,mediaKeys:t})).catch(e=>{t.length?o(t):i(e instanceof Xo?e:new Xo({type:r.KEY_SYSTEM_ERROR,details:n.KEY_SYSTEM_NO_ACCESS,error:e,fatal:!0},e.message))})};o(t)})}requestMediaKeySystemAccess(t,e){const{requestMediaKeySystemAccessFunc:i}=this.config;if("function"!=typeof i){let t=`Configured requestMediaKeySystemAccess is not a function ${i}`;return null===Ds&&"http:"===self.location.protocol&&(t=`navigator.requestMediaKeySystemAccess is not available over insecure protocol ${location.protocol}`),Promise.reject(new Error(t))}return i(t,e)}getMediaKeysPromise(t,e,i){var s;const r=function(t,e,i,s){let r;switch(t){case Ts.FAIRPLAY:r=["cenc","sinf"];break;case Ts.WIDEVINE:case Ts.PLAYREADY:r=["cenc"];break;case Ts.CLEARKEY:r=["cenc","keyids"];break;default:throw new Error(`Unknown key-system: ${t}`)}return function(t,e,i,s){return[{initDataTypes:t,persistentState:s.persistentState||"optional",distinctiveIdentifier:s.distinctiveIdentifier||"optional",sessionTypes:s.sessionTypes||[s.sessionType||"temporary"],audioCapabilities:e.map(t=>({contentType:`audio/mp4; codecs=${t}`,robustness:s.audioRobustness||"",encryptionScheme:s.audioEncryptionScheme||null})),videoCapabilities:i.map(t=>({contentType:`video/mp4; codecs=${t}`,robustness:s.videoRobustness||"",encryptionScheme:s.videoEncryptionScheme||null}))}]}(r,e,i,s)}(t,e,i,this.config.drmSystemOptions||{});let n=this.keySystemAccessPromises[t],a=null==(s=n)?void 0:s.keySystemAccess;if(!a){this.log(`Requesting encrypted media "${t}" key-system access with config: ${Ue(r)}`),a=this.requestMediaKeySystemAccess(t,r);const e=n=this.keySystemAccessPromises[t]={keySystemAccess:a};return a.catch(e=>{this.log(`Failed to obtain access to key-system "${t}": ${e}`)}),a.then(i=>{this.throwIfDestroyed(),this.log(`Access for key-system "${i.keySystem}" obtained`);const s=this.fetchServerCertificate(t);this.log(`Create media-keys for "${t}"`);const r=e.mediaKeys=i.createMediaKeys().then(i=>(this.log(`Media-keys created for "${t}"`),e.createdMediaKeys=i,s.then(e=>e?this.setMediaKeysServerCertificate(i,t,e):i)));return r.catch(e=>{this.error(`Failed to create media-keys for "${t}"}: ${e}`)}),r})}return a.then(()=>n.mediaKeys)}getMediaKeySessionContext(t,e,i,s){const{mediaKeySessions:r}=this,n=` key-session "${t}" keyId: ${mt(i.keyId||[])} keyUri: ${i.uri} for "${s}"`;for(let t=0;t<r.length;t++){const e=r[t];if(!e.initialized&&e.createdFor.levelKey.uri===i.uri)return this.log(`Reusing${n}`),e}this.log(`Creating${n}`);const a=e.createSession(),o={keySystem:t,mediaKeys:e,mediaKeysSession:a,keyRequests:{},keyStatuses:{},createdFor:{levelKey:i,reason:s},initialized:!1};return r.push(o),o}resetMediaKeys(){var t;const e=null==(t=this.mediaKeySessions[0])?void 0:t.keySystem,i=this.keySystemAccessPromises[e];i&&(this.log("reset mediaKeys"),this.mediaKeys=null,delete i.createdMediaKeys,delete i.mediaKeys,delete this.keySystemAccessPromises[e])}updateKeySession(t,e,i){const s=t.mediaKeysSession;return this.log(`Updating key-session "${s.sessionId}" for keyId ${mt(e.keyId||[])}\n } (data length: ${i.byteLength})`),s.update(i)}getSelectedKeySystemFormats(){return Object.keys(this.keySystemAccessPromises).map(t=>({keySystem:t,hasMediaKeys:!!this.keySystemAccessPromises[t].createdMediaKeys})).filter(({hasMediaKeys:t})=>!!t).map(({keySystem:t})=>ks(t)).filter(t=>!!t)}getKeySystemAccess(t){return this.getKeySystemSelectionPromise(t).then(({keySystem:t,mediaKeys:e})=>this.attemptSetMediaKeys(t,e))}selectKeySystem(t){return this.getKeySystemSelectionPromise(t).then(({keySystem:t})=>{const e=ks(t);if(!e)throw new Error(`Unable to find format for key-system "${t}"`);return e})}selectKeySystemFormat(t){const e=Object.keys(t.levelkeys||{});return this.keyFormatPromise||(this.log(`Selecting key-system from fragment (sn: ${t.sn} ${t.type}: ${t.level}) key formats ${e.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(e)),this.keyFormatPromise}getKeyFormatPromise(t){const e=_s(this.config),i=t.map(Is).filter(t=>!!t&&-1!==e.indexOf(t));return this.selectKeySystem(i)}loadClear(t,e,i){if(this.config.emeEnabled&&!this.getSelectedKeySystemFormats().length){if(e.length)for(let s=0,r=e.length;s<r;s++){const n=e[s];if(t.cc<=n.cc&&(!y(t)||!y(n)||t.sn<n.sn)||!i&&s==r-1)return this.selectKeySystemFormat(n).then(t=>{if(!this.hls)return;n.setKeyFormat(t);const e=Is(t);return e?this.getKeySystemAccess([e]):void 0})}if(this.config.requireKeySystemAccessOnStart){const t=_s(this.config);if(t.length)return this.getKeySystemAccess(t)}}return null}getKeyStatus(t){const{mediaKeySessions:e}=this;for(let i=0;i<e.length;i++){const s=Zo(t,e[i]);if(s)return s}}loadKey(t){const e=t.decryptdata,i=this.getKeyStatus(e);if("internal-error"===i){const s=Jo(i,e);return s.data.frag=t,this.error(`${s.message} (${mt(e.keyId||[])})`),Promise.reject(s)}const s=t.type,r=this.activeKeys,n=r[s];n&&!e.matches(n.decryptdata)&&(r.previous||(r.previous=[]),r.previous.push(n),delete r[s]),r[s]||(r[s]=t);for(let t=this.mediaKeySessions.length;t--;){const i=this.mediaKeySessions[t];if(e.keyId&&"expired"===i.keyStatuses[mt(e.keyId)])return this.renewKeySession(e,i)}return this.updateUsablePromise(e,"playlist-key",t)}renewKeySession(t,e){return this.resetMediaKeys(),this.removeSession(e).then(()=>(this.throwIfDestroyed(),this.updateUsablePromise(t,"expired")))}updateUsablePromise(t,e,i){const s=this.getSessionForKey(t,e);return s.catch(t=>this.handleError(t,i)),s.then(e=>t)}getSessionForKey(t,e){const i=this.findContextForKey(t);if(void 0!==i)return Promise.resolve(i);const s=t.uri,r=this.sessionSetupByUri[s];let n;n=void 0===r?this.resolveSessionForKey(t,e):r.catch(()=>{}).then(()=>(this.throwIfDestroyed(),this.resolveSessionForKey(t,e))),this.sessionSetupByUri[s]=n;const a=()=>{this.sessionSetupByUri[s]===n&&delete this.sessionSetupByUri[s]};return n.then(a,a),n}findContextForKey(t){const{mediaKeySessions:e}=this;for(let i=e.length;i--;){const s=e[i];if(Zo(t,s))return s}}resolveSessionForKey(t,e){return this.getKeySystemForKeyPromise(t).then(({keySystem:i,mediaKeys:s})=>{this.throwIfDestroyed();for(let i=this.mediaKeySessions.length;i--;){const s=this.mediaKeySessions[i];if(Zo(t,s))return s;const r=this.getUsableKeyPromise(s,t,e);if(r)return r}return this.attemptSetMediaKeys(i,s).then(()=>(this.throwIfDestroyed(),this.getMediaKeySessionContext(i,s,t,e))).then(i=>{this.throwIfDestroyed();const s=t.scheme||"cenc",r=t.pssh?t.pssh.buffer:null;return this.generateRequestWithPreferredKeySession(i,t,s,r,e)})})}getUsableKeyPromise(t,e,i){const s=t.keyRequests[e.uri];if(s)return this.log(`Waiting for usable key (${i} keyId: ${function(t){if(t.keyFormat===bs)return t.uri;if(null===t.keyId)throw new Error("keyId is null");return mt(t.keyId)}(e)} format: "${e.keyFormat}" URI: ${e.uri})`),s.useable.then(()=>t)}throwIfDestroyed(t="Invalid state"){if(!this.hls)throw new Error("invalid state")}handleError(t,e){if(this.hls)if(t instanceof Xo){e&&(t.data.frag=e);const i=t.data.decryptdata;this.error(`${t.message}${i?` (${mt(i.keyId||[])})`:""}`),this.hls.trigger(a.ERROR,t.data)}else this.error(t.message),this.hls.trigger(a.ERROR,{type:r.KEY_SYSTEM_ERROR,details:n.KEY_SYSTEM_NO_KEYS,error:t,fatal:!0,reason:`${t.name}: ${t.message}`})}getKeySystemForKeyPromise(t){const e=Is(t.keyFormat),i=e?[e]:_s(this.config);return this.attemptKeySystemAccess(i)}getKeySystemSelectionPromise(t){if(t.length||(t=_s(this.config)),0===t.length)throw new Xo({type:r.KEY_SYSTEM_ERROR,details:n.KEY_SYSTEM_NO_CONFIGURED_LICENSE,fatal:!0},`Missing key-system license configuration options ${Ue({drmSystems:this.config.drmSystems})}`);return this.attemptKeySystemAccess(t)}activeLevelKeys(){const t=this.activeKeys,e=(t.previous||[]).map(t=>t.decryptdata);return t.audio&&e.unshift(t.audio.decryptdata),t.main&&e.unshift(t.main.decryptdata),e}queueSetMediaKeys(t){const e=this.setMediaKeysChain.then(t);return this.setMediaKeysChain=e.catch(t=>{this.log(`setMediaKeys failed: ${t}`)}),e}attemptSetMediaKeys(t,e){return this.mediaKeys===e?Promise.resolve():(this.log(`Setting media-keys for "${t}"`),this.mediaKeys=e,this.queueSetMediaKeys(()=>this.media?this.media.setMediaKeys(e):new Promise((t,i)=>{this.mediaResolved=()=>{if(this.mediaResolved=void 0,!this.media)return i(new Error("Attempted to set mediaKeys without media element attached"));this.mediaKeys=e,this.media.setMediaKeys(e).then(t).catch(i)}})).then(()=>{this.log(`Media-keys set for "${t}"`)},t=>{throw this.mediaKeys===e&&(this.mediaKeys=null),t}))}filterInitData(t,e,i,s,r){var n;const a=null==(n=this.config.drmSystems)||null==(n=n[t.keySystem])?void 0:n.generateRequest;if(a)try{const n=a.call(this.hls,i,s,I({},t,{decryptdata:e,reason:r}),r);if(!n)throw new Error("Invalid response from configured generateRequest filter");e.scheme=n.initDataType?n.initDataType:"cenc";const o=n.initData?n.initData:null;return e.pssh=o?new Uint8Array(o):null,n}catch(t){var o;if(this.warn(t.message),null!=(o=this.hls)&&o.config.debug)throw t}return{initDataType:i,initData:s}}generateRequestWithPreferredKeySession(t,e,i,s,r){const n=this.getUsableKeyPromise(t,e,r);if(n)return n;const a=this.filterInitData(t,e,i,s,r);if(a&&(s=a.initData?a.initData:null,i=a.initDataType),null===s)return r.startsWith("encrypted-event")?Promise.reject(new Error(`missing initialization data for "${r}"`)):(this.log(`Skipping key-session request for "${r}" (no initData)`),Promise.resolve(t));const o=e.uri,l=new zo;t.keyRequests[o]=l;const h=i=>{const s=t.mediaKeysSession;if(!s){const t=new Error("invalid state");return void(l.errored=t)}const{messageType:r,message:n}=i;l.status=r,this.log(`"${r}" message event for session "${s.sessionId}" message size: ${n.byteLength}`),"license-request"===r||"license-renewal"===r?this.renewLicense(t,e,n).catch(e=>{l.errored=e,l.hasListeners||this.handleError(e),this.removeSession(t)}):"license-release"===r?t.keySystem===Ts.FAIRPLAY&&this.updateKeySession(t,e,ps("acknowledged")).then(()=>this.removeSession(t)).catch(t=>this.handleError(t)):this.warn(`unhandled media key message type "${r}"`)};l.onmessage=h,Ti(t.mediaKeysSession,"message",h);return this.generateRequest(t,e,i,s,r,!1)}generateRequest(t,e,i,s,a,o){if(o){const r=this.filterInitData(t,e,i,s,a);r&&(s=r.initData?r.initData:s,i=r.initDataType)}const l=e.uri,h=t.keyRequests[l],d=mt(e.keyId||[]),c=t=>{let i;t.startsWith("usable")?h.resolve():"internal-error"===t||"output-restricted"===t||"output-downscaled"===t?i=Jo(t,e):"expired"===t?i=new Error(`key expired (keyId: ${d})`):"released"===t?i=new Error("key released"):"status-pending"===t||this.warn(`unhandled key status change "${t}" (keyId: ${d})`),i&&(h.errored=i,h.hasListeners||this.handleError(i))},u=i=>{if(!t.mediaKeysSession){const t=new Error("invalid state");return void(h.errored=t)}const s=t.keyStatuses=this.getKeyStatuses(t);if(!Object.keys(s).some(t=>"status-pending"!==s[t]))return;const r=this.activeLevelKeys();for(let i=0;i<r.length;i++){const a=mt(r[i].keyId||[]);if("expired"===s[a]){var n;this.log(`Expired key ${Ue(s)} in key-session "${null==(n=t.mediaKeysSession)?void 0:n.sessionId}"`),this.renewKeySession(e,t).catch(t=>this.handleError(t));break}}let a=s[d];if(a)c(a);else{var o;const i=1e3;t.keyStatusTimeouts||(t.keyStatusTimeouts={}),(o=t.keyStatusTimeouts)[d]||(o[d]=self.setTimeout(()=>{var s;if(!t.mediaKeysSession)return;const r=this.getKeyStatus(e);var n;if(r&&"status-pending"!==r)return this.log(`No status for keyId ${d} in key-session "${null==(n=t.mediaKeysSession)?void 0:n.sessionId}". Using session key-status ${r} from other session.`),c(r);this.log(`key status for ${d} in key-session "${null==(s=t.mediaKeysSession)?void 0:s.sessionId}" timed out after ${i}ms`),a="internal-error",c(a)},i)),this.log(`No status for keyId ${d} (${Ue(s)}).`)}};h.onkeystatuseschange=u,Ti(t.mediaKeysSession,"keystatuseschange",u);const f=h.useable;return this.log(`Generating key-session request for "${a}" keyId: ${d} URI: ${l} (init data type: ${i} length: ${s.byteLength})`),h.status="started",t.initialized=!0,t.mediaKeysSession.generateRequest(i,s).then(()=>{var e;h.status="generated",this.log(`Request generated for key-session "${null==(e=t.mediaKeysSession)?void 0:e.sessionId}" keyId: ${d} URI: ${l}`)}).catch(t=>{throw this.log(`mediaKeysSession.generateRequest failed: ${t}`),new Xo({type:r.KEY_SYSTEM_ERROR,details:n.KEY_SYSTEM_NO_SESSION,error:t,decryptdata:e,fatal:!1},`Error generating key-session request: ${t}`)}).then(()=>f).catch(e=>{var i;this.log(`mediaKeysSession.generateRequest failed: ${e}`);const s=null==(i=e.data)?void 0:i.details;return s!==n.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED&&s!==n.KEY_SYSTEM_STATUS_INTERNAL_ERROR||!Object.keys(t.keyStatuses).some(e=>"usable"===t.keyStatuses[e])?this.removeSession(t).then(()=>{throw e}):(this.handleError(e),t)}).then(()=>t)}getKeyStatuses(t){const e={},i=t.mediaKeysSession.sessionId;return t.mediaKeysSession.keyStatuses.forEach((s,r)=>{if("string"==typeof r&&"object"==typeof s){const t=r;r=s,s=t}const n="buffer"in r?new Uint8Array(r.buffer,r.byteOffset,r.byteLength):new Uint8Array(r);if(t.keySystem===Ts.PLAYREADY&&16===n.length){const t=mt(n);e[t]=s,vs(n)}const a=mt(n);this.log(`key status change "${s}" for keyStatuses keyId: ${a} key-session "${i}"`),e[a]=s}),e}fetchServerCertificate(t){const e=this.config,i=new(0,e.loader)(e),s=function(t,e){const{drmSystems:i}=e,s=null==i?void 0:i[t];if(s)return s.serverCertificateUrl}(t,e);return s?(this.log(`Fetching server certificate for "${t}"`),new Promise((a,o)=>{const l={type:u.SERVER_CERTIFICATE,responseType:"arraybuffer",url:s},h=e.certLoadPolicy.default,d={loadPolicy:h,timeout:h.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},c={onSuccess:(t,e,i,s)=>{a(t.data)},onError:(e,i,a,h)=>{o(new Xo({type:r.KEY_SYSTEM_ERROR,details:n.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:a,response:k({url:l.url,data:void 0},e)},`"${t}" certificate request failed (${s}). Status: ${e.code} (${e.text})`))},onTimeout:(e,i,a)=>{o(new Xo({type:r.KEY_SYSTEM_ERROR,details:n.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:a,response:{url:l.url,data:void 0}},`"${t}" certificate request timed out (${s})`))},onAbort:(t,e,i)=>{o(new Error("aborted"))}};i.load(l,d,c)})):(this.log(`No Server Certificate in config.drmSystems["${t}"]`),Promise.resolve())}setMediaKeysServerCertificate(t,e,i){return new Promise((s,a)=>{t.setServerCertificate(i).then(r=>{this.log(`setServerCertificate ${r?"success":"not supported by CDM"} (${i.byteLength}) on "${e}"`),s(t)}).catch(t=>{a(new Xo({type:r.KEY_SYSTEM_ERROR,details:n.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED,error:t,fatal:!0},t.message))})})}renewLicense(t,e,i){return this.requestLicense(t,e,new Uint8Array(i)).then(i=>this.updateKeySession(t,e,new Uint8Array(i)).catch(t=>{throw new Xo({type:r.KEY_SYSTEM_ERROR,details:n.KEY_SYSTEM_SESSION_UPDATE_FAILED,decryptdata:e,error:t,fatal:!1},t.message)}))}unpackPlayReadyKeyMessage(t,e){const i=yt(new Uint16Array(e.buffer));if(!i.includes("PlayReadyKeyMessage"))return t.setRequestHeader("Content-Type","text/xml; charset=utf-8"),e;const s=(new DOMParser).parseFromString(i,"application/xml"),r=s.querySelectorAll("HttpHeader");if(r.length>0){let e;for(let i=0,s=r.length;i<s;i++){var n,a;e=r[i];const s=null==(n=e.querySelector("name"))?void 0:n.textContent,o=null==(a=e.querySelector("value"))?void 0:a.textContent;s&&o&&t.setRequestHeader(s,o)}}const o=s.querySelector("Challenge"),l=null==o?void 0:o.textContent;if(!l)throw new Error("Cannot find <Challenge> in key message");return ps(atob(l))}setupLicenseXHR(t,e,i,s,r){const n=this.config.licenseXhrSetup;return n?Promise.resolve().then(()=>(this.throwIfDestroyed(),n.call(this.hls,t,e,k(k({},i),{},{decryptdata:s}),r))).catch(a=>{if(!i.mediaKeysSession)throw a;return t.open("POST",e,!0),n.call(this.hls,t,e,k(k({},i),{},{decryptdata:s}),r)}).then(i=>{t.readyState||t.open("POST",e,!0);return{xhr:t,licenseChallenge:i||r}}):(t.open("POST",e,!0),Promise.resolve({xhr:t,licenseChallenge:r}))}requestLicense(t,e,i){return new Promise((s,a)=>{const o=function(t,e){const{drmSystems:i,widevineLicenseUrl:s}=e,r=null==i?void 0:i[t];if(r)return r.licenseUrl;if(t===Ts.WIDEVINE&&s)return s}(t.keySystem,this.config);if(!o)return a(new Error(`no license server URL configured for key-system "${t.keySystem}"`));const l=t.keyRequests[e.uri];if(!l)return a(new Error("License emitter removed"));this.log(`Sending license request to URL: ${o}`);const h=this.config.keyLoadPolicy.default,d=new XMLHttpRequest;d.responseType="arraybuffer",d.onreadystatechange=()=>{if(!this.hls||!t.mediaKeysSession)return a(new Error("invalid state"));if(4===d.readyState)if(200===d.status){l.requestErrors=[];let i=d.response;this.log(`License received ${i instanceof ArrayBuffer?i.byteLength:i}`);const r=this.config.licenseResponseCallback;if(r)try{i=r.call(this.hls,d,o,k(k({},t),{},{decryptdata:e}))}catch(t){this.error(t)}s(i)}else{const c=h.errorRetry,u=c?c.maxNumRetry:0;if(l.requestErrors.push({status:d.status,message:d.statusText}),l.requestErrors.length>u||d.status>=400&&d.status<500)a(new Xo({type:r.KEY_SYSTEM_ERROR,details:n.KEY_SYSTEM_LICENSE_REQUEST_FAILED,decryptdata:e,fatal:!0,networkDetails:d,response:{url:o,data:void 0,code:d.status,text:d.statusText}},`License Request XHR failed (${o}). Status: ${d.status} (${d.statusText})`));else{const r=u-l.requestErrors.length;this.warn(`Retrying license request, ${r} attempts left`),this.requestLicense(t,e,i).then(s,a)}}},l.licenseXhr&&l.licenseXhr.readyState!==XMLHttpRequest.DONE&&l.licenseXhr.abort(),l.licenseXhr=d,this.setupLicenseXHR(d,o,t,e,i).then(({xhr:e,licenseChallenge:i})=>{t.keySystem==Ts.PLAYREADY&&(i=this.unpackPlayReadyKeyMessage(e,i)),e.send(i)}).catch(a)})}onDestroying(){this.unregisterListeners(),this._clear()}onMediaAttached(t,e){if(!this.config.emeEnabled)return;const i=e.media;this.media=i,Ti(i,"encrypted",this.onMediaEncrypted),Ti(i,"waitingforkey",this.onWaitingForKey);const s=this.mediaResolved;s?s():this.mediaKeys=i.mediaKeys}onMediaDetached(){const t=this.media;t&&(Si(t,"encrypted",this.onMediaEncrypted),Si(t,"waitingforkey",this.onWaitingForKey),this.media=null,this.mediaKeys=null)}_clear(t=!1){this.keyFormatPromise=null,t||(this.keySystemAccessPromises={}),this.activeKeys={},this.sessionSetupByUri={};const e=this.mediaResolved;if(e&&e(),!this.mediaKeys&&!this.mediaKeySessions.length)return;const i=this.media,s=t&&this.config.reuseKeySessions,o=s?[]:this.mediaKeySessions.slice();s||(this.mediaKeySessions=[],xs.clearKeyUriToKeyIdMap()),t||(this.mediaKeys=null);const l=o.length,h=i&&!t?this.queueSetMediaKeys(()=>i.setMediaKeys(null)).catch(t=>{this.log(`Could not clear media keys: ${t}`),this.hls&&this.hls.trigger(a.ERROR,{type:r.OTHER_ERROR,details:n.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR,fatal:!1,error:new Error(`Could not clear media keys: ${t}`)})}):Promise.resolve();Qo.CDMCleanupPromise=Promise.all(o.map(t=>this.removeSession(t)).concat(h)).catch(t=>{this.log(`Could not close sessions and clear media keys: ${t}`),this.hls&&this.hls.trigger(a.ERROR,{type:r.OTHER_ERROR,details:n.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error(`Could not close sessions and clear media keys: ${t}`)})}).then(()=>{l&&this.log("finished closing key sessions and clearing media keys")})}onManifestLoading(){var t;const e=null==(t=this.hls)||null==(t=t.media)?void 0:t.mediaKeys,i=!!e&&Object.keys(this.keySystemAccessPromises).some(t=>{var i;return t!==Ts.FAIRPLAY&&(null==(i=this.keySystemAccessPromises[t])?void 0:i.createdMediaKeys)===e});this._clear(i),this.keyFormatPromise=null}onManifestLoaded(t,{sessionKeys:e}){if(e&&this.config.emeEnabled&&!this.keyFormatPromise){const t=e.reduce((t,e)=>(-1===t.indexOf(e.keyFormat)&&t.push(e.keyFormat),t),[]);this.log(`Selecting key-system from session-keys ${t.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(t),this.keyFormatPromise.catch(()=>{})}}removeSession(t){const{mediaKeysSession:e}=t;if(e){this.log(`Remove licenses and keys and close session "${e.sessionId}"`),Object.keys(t.keyRequests).forEach(i=>{const s=t.keyRequests[i];s.onmessage&&e.removeEventListener("message",s.onmessage),s.onkeystatuseschange&&e.removeEventListener("keystatuseschange",s.onkeystatuseschange),s.reset(),t.keyRequests[i]=void 0}),t.mediaKeysSession=void 0;const i=this.mediaKeySessions.indexOf(t);i>-1&&this.mediaKeySessions.splice(i,1);const{keyStatusTimeouts:s}=t;s&&Object.keys(s).forEach(t=>self.clearTimeout(s[t]));const{drmSystemOptions:o}=this.config,l=function(t){var e;return!(!t||"persistent-license"!==t.sessionType&&(null==(e=t.sessionTypes)||!e.some(t=>"persistent-license"===t)))}(o)?new Promise((t,i)=>{self.setTimeout(()=>i(new Error("MediaKeySession.remove() timeout")),8e3),e.remove().then(t).catch(i)}):Promise.resolve();return l.catch(t=>{this.log(`Could not remove session: ${t}`),this.hls&&this.hls.trigger(a.ERROR,{type:r.OTHER_ERROR,details:n.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR,fatal:!1,error:new Error(`Could not remove session: ${t}`)})}).then(()=>e.close()).then(()=>e.closed).catch(t=>{this.log(`Could not close session: ${t}`),this.hls&&this.hls.trigger(a.ERROR,{type:r.OTHER_ERROR,details:n.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error(`Could not close session: ${t}`)})})}return Promise.resolve()}}function Zo(t,e){const i=t.keyId,s=e.mediaKeysSession;if(i&&s){const t=e.mediaKeysSession.keyStatuses;if(t.size)return t.has(i)?t.get(i):e.keyStatuses[mt(i)]}}function Jo(t,e){const i="output-restricted"===t,s=i?n.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:n.KEY_SYSTEM_STATUS_INTERNAL_ERROR;return new Xo({type:r.KEY_SYSTEM_ERROR,details:s,fatal:!1,decryptdata:e},i?"HDCP level output restricted":`key status changed to "${t}"`)}Qo.CDMCleanupPromise=void 0;var tl=function(){if(null!=Es&&Es.VTTCue)return self.VTTCue;const t=["","lr","rl"],e=["start","middle","end","left","right"];function i(t,e){if("string"!=typeof e)return!1;if(!Array.isArray(t))return!1;const i=e.toLowerCase();return!!~t.indexOf(i)&&i}function s(t){return i(e,t)}function r(t,...e){let i=1;for(;i<arguments.length;i++){const e=arguments[i];for(const i in e)t[i]=e[i]}return t}function n(e,n,a){const o=this,l={enumerable:!0};o.hasBeenReset=!1;let h="",d=!1,c=e,u=n,f=a,g=null,m="",p=!0,v="auto",y="start",E=50,T="middle",S=50,b="middle";Object.defineProperty(o,"id",r({},l,{get:function(){return h},set:function(t){h=""+t}})),Object.defineProperty(o,"pauseOnExit",r({},l,{get:function(){return d},set:function(t){d=!!t}})),Object.defineProperty(o,"startTime",r({},l,{get:function(){return c},set:function(t){if("number"!=typeof t)throw new TypeError("Start time must be set to a number.");c=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"endTime",r({},l,{get:function(){return u},set:function(t){if("number"!=typeof t)throw new TypeError("End time must be set to a number.");u=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"text",r({},l,{get:function(){return f},set:function(t){f=""+t,this.hasBeenReset=!0}})),Object.defineProperty(o,"region",r({},l,{get:function(){return g},set:function(t){g=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"vertical",r({},l,{get:function(){return m},set:function(e){const s=function(e){return i(t,e)}(e);if(!1===s)throw new SyntaxError("An invalid or illegal string was specified.");m=s,this.hasBeenReset=!0}})),Object.defineProperty(o,"snapToLines",r({},l,{get:function(){return p},set:function(t){p=!!t,this.hasBeenReset=!0}})),Object.defineProperty(o,"line",r({},l,{get:function(){return v},set:function(t){if("number"!=typeof t&&"auto"!==t)throw new SyntaxError("An invalid number or illegal string was specified.");v=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"lineAlign",r({},l,{get:function(){return y},set:function(t){const e=s(t);if(!e)throw new SyntaxError("An invalid or illegal string was specified.");y=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"position",r({},l,{get:function(){return E},set:function(t){if(t<0||t>100)throw new Error("Position must be between 0 and 100.");E=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"positionAlign",r({},l,{get:function(){return T},set:function(t){const e=s(t);if(!e)throw new SyntaxError("An invalid or illegal string was specified.");T=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"size",r({},l,{get:function(){return S},set:function(t){if(t<0||t>100)throw new Error("Size must be between 0 and 100.");S=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"align",r({},l,{get:function(){return b},set:function(t){const e=s(t);if(!e)throw new SyntaxError("An invalid or illegal string was specified.");b=e,this.hasBeenReset=!0}})),o.displayState=void 0}return n.prototype.getCueAsHTML=function(){return self.WebVTT.convertCueToDOMTree(self,this.text)},n}();class el{decode(t,e){if(!t)return"";if("string"!=typeof t)throw new Error("Error - expected string data.");return decodeURIComponent(encodeURIComponent(t))}}function il(t){function e(t,e,i,s){return 3600*(0|t)+60*(0|e)+(0|i)+parseFloat(s||0)}const i=t.match(/^(?:(\d+):)?(\d{2}):(\d{2})(\.\d+)?/);return i?parseFloat(i[2])>59?e(i[2],i[3],0,i[4]):e(i[1],i[2],i[3],i[4]):null}class sl{constructor(){this.values=Object.create(null)}set(t,e){this.get(t)||""===e||(this.values[t]=e)}get(t,e,i){return i?this.has(t)?this.values[t]:e[i]:this.has(t)?this.values[t]:e}has(t){return t in this.values}alt(t,e,i){for(let s=0;s<i.length;++s)if(e===i[s]){this.set(t,e);break}}integer(t,e){/^-?\d+$/.test(e)&&this.set(t,parseInt(e,10))}percent(t,e){if(/^([\d]{1,3})(\.[\d]*)?%$/.test(e)){const i=parseFloat(e);if(i>=0&&i<=100)return this.set(t,i),!0}return!1}}function rl(t,e,i,s){const r=s?t.split(s):[t];for(const t in r){if("string"!=typeof r[t])continue;const s=r[t].split(i);if(2!==s.length)continue;e(s[0],s[1])}}const nl=new tl(0,0,""),al="middle"===nl.align?"middle":"center";function ol(t,e,i){const s=t;function r(){const e=il(t);if(null===e)throw new Error("Malformed timestamp: "+s);return t=t.replace(/^[^\sa-zA-Z-]+/,""),e}function n(){t=t.replace(/^\s+/,"")}if(n(),e.startTime=r(),n(),"--\x3e"!==t.slice(0,3))throw new Error("Malformed time stamp (time stamps must be separated by '--\x3e'): "+s);t=t.slice(3),n(),e.endTime=r(),n(),function(t,e){const s=new sl;rl(t,function(t,e){let r;switch(t){case"region":for(let r=i.length-1;r>=0;r--)if(i[r].id===e){s.set(t,i[r].region);break}break;case"vertical":s.alt(t,e,["rl","lr"]);break;case"line":r=e.split(","),s.integer(t,r[0]),s.percent(t,r[0])&&s.set("snapToLines",!1),s.alt(t,r[0],["auto"]),2===r.length&&s.alt("lineAlign",r[1],["start",al,"end"]);break;case"position":r=e.split(","),s.percent(t,r[0]),2===r.length&&s.alt("positionAlign",r[1],["start",al,"end","line-left","line-right","auto"]);break;case"size":s.percent(t,e);break;case"align":s.alt(t,e,["start",al,"end","left","right"])}},/:/,/\s/),e.region=s.get("region",null),e.vertical=s.get("vertical","");let r=s.get("line","auto");"auto"===r&&-1===nl.line&&(r=-1),e.line=r,e.lineAlign=s.get("lineAlign","start"),e.snapToLines=s.get("snapToLines",!0),e.size=s.get("size",100),e.align=s.get("align",al);let n=s.get("position","auto");"auto"===n&&50===nl.position&&(n="start"===e.align||"left"===e.align?0:"end"===e.align||"right"===e.align?100:50),e.position=n}(t,e)}function ll(t){return t.replace(/<br(?: \/)?>/gi,"\n")}class hl{constructor(){this.state="INITIAL",this.buffer="",this.decoder=new el,this.regionList=[],this.cue=null,this.oncue=void 0,this.onparsingerror=void 0,this.onflush=void 0}parse(t){const e=this;function i(){let t=e.buffer,i=0;for(t=ll(t);i<t.length&&"\r"!==t[i]&&"\n"!==t[i];)++i;const s=t.slice(0,i);return"\r"===t[i]&&++i,"\n"===t[i]&&++i,e.buffer=t.slice(i),s}function s(t){rl(t,function(t,e){},/:/)}t&&(e.buffer+=e.decoder.decode(t,{stream:!0}));try{let t="";if("INITIAL"===e.state){if(!/\r\n|\n/.test(e.buffer))return this;t=i();const s=t.match(/^()?WEBVTT([ \t].*)?$/);if(null==s||!s[0])throw new Error("Malformed WebVTT signature.");e.state="HEADER"}let r=!1;for(;e.buffer;){if(!/\r\n|\n/.test(e.buffer))return this;switch(r?r=!1:t=i(),e.state){case"HEADER":/:/.test(t)?s(t):t||(e.state="ID");continue;case"NOTE":t||(e.state="ID");continue;case"ID":if(/^NOTE($|[ \t])/.test(t)){e.state="NOTE";break}if(!t)continue;if(e.cue=new tl(0,0,""),e.state="CUE",-1===t.indexOf("--\x3e")){e.cue.id=t;continue}case"CUE":if(!e.cue){e.state="BADCUE";continue}try{ol(t,e.cue,e.regionList)}catch(t){e.cue=null,e.state="BADCUE";continue}e.state="CUETEXT";continue;case"CUETEXT":{const i=-1!==t.indexOf("--\x3e");if(!t||i&&(r=!0)){e.oncue&&e.cue&&e.oncue(e.cue),e.cue=null,e.state="ID";continue}if(null===e.cue)continue;e.cue.text&&(e.cue.text+="\n"),e.cue.text+=t}continue;case"BADCUE":t||(e.state="ID")}}}catch(t){"CUETEXT"===e.state&&e.cue&&e.oncue&&e.oncue(e.cue),e.cue=null,e.state="INITIAL"===e.state?"BADWEBVTT":"BADCUE"}return this}flush(){const t=this;try{if((t.cue||"HEADER"===t.state)&&(t.buffer+="\n\n",t.parse()),"INITIAL"===t.state||"BADWEBVTT"===t.state)throw new Error("Malformed WebVTT signature.")}catch(e){t.onparsingerror&&t.onparsingerror(e)}return t.onflush&&t.onflush(),this}}function dl(t){let e=5381,i=t.length;for(;i;)e=33*e^t.charCodeAt(--i);return(e>>>0).toString()}const cl=/\r\n|\n\r|\n|\r/g,ul="Missing initPTS for VTT ";function fl(t,e,i){return dl(t.toString())+dl(e.toString())+dl(i)}function gl(t,i,s,r,n,a,o){const l=new hl,h=ot(new Uint8Array(t)).trim().replace(cl,"\n").split("\n"),d=[],c=i?function(t,e=1){return Nn(t,9e4,1/e)}(i.baseTime,i.timescale):0;let u,f="00:00.000",g=0,m=0,p=!1,v=!0;l.oncue=function(t){const e=s[r];let a=s.ccOffset;const o=(g-c)/9e4;if(p){if(null!=e&&e.new&&(a=s.ccOffset=e.start),o){if(!i)return void(u=new Error(ul+"MPEGTS"));a=o-s.presentationOffset}}else{if(!i)return void(u=new Error(ul+"without X-TIMESTAMP-MAP"));a=-i.baseTime/i.timescale}const l=t.endTime-t.startTime,h=Vn(9e4*(t.startTime+a-m),9e4*n)/9e4;t.startTime=Math.max(h,0),t.endTime=Math.max(h+l,0);const f=t.text.replace(/^[ \t\r\n\f]+|[ \t\r\n\f]+$/g,"");t.text=decodeURIComponent(encodeURIComponent(f)),t.id?r&&(t.id=`hlsjscc${r}_${t.id}`):t.id=fl(t.startTime,t.endTime,f.trim()),t.endTime>0&&d.push(t)},l.onparsingerror=function(t){u=t},l.onflush=function(){u?o(u):a(d)},h.forEach(t=>{if(v){if(t.startsWith("X-TIMESTAMP-MAP=")){v=!1,p=!0,t.slice(16).split(",").forEach(t=>{t.startsWith("LOCAL:")?f=t.slice(6):t.startsWith("MPEGTS:")&&(g=parseInt(t.slice(7)))});try{m=function(t){let i=parseInt(t.slice(-3));const s=parseInt(t.slice(-6,-4)),r=parseInt(t.slice(-9,-7)),n=t.length>9?parseInt(t.substring(0,t.indexOf(":"))):0;if(!(e(i)&&e(s)&&e(r)&&e(n)))throw Error(`Malformed X-TIMESTAMP-MAP: Local:${t}`);return i+=1e3*s,i+=6e4*r,i+=36e5*n,i}(f)/1e3}catch(t){u=t}return}""===t&&(v=!1)}l.parse(t+"\n")}),l.flush()}const ml="stpp.ttml.im1t",pl=/^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/,vl=/^(\d*(?:\.\d*)?)(h|m|s|ms|f|t)$/,yl={left:"start",center:"center",right:"end",start:"start",end:"end"};function El(t,e,i,s){const r=Pt(new Uint8Array(t),["mdat"]);if(0===r.length)return void s(new Error("Could not parse IMSC1 mdat"));const n=r.map(t=>ot(t)),a=function(t,e,i=1,s=!1){return Nn(t,e,1/i,s)}(e.baseTime,1,e.timescale);try{n.forEach(t=>i(function(t,e){const i=(new DOMParser).parseFromString(t,"text/xml"),s=i.getElementsByTagName("tt")[0];if(!s)throw new Error("Invalid ttml");const r={frameRate:30,subFrameRate:1,tickRate:1},n=Object.keys(r).reduce((t,e)=>(t[e]=s.getAttribute(`ttp:${e}`)||r[e],t),{}),a=(s.getAttribute("ttp:frameRateMultiplier")||"").trim().split(/\s+/).map(Number);2===a.length&&a[0]>0&&a[1]>0&&(n.frameRate=Number(n.frameRate)*a[0]/a[1]);!s.getAttribute("ttp:tickRate")&&s.getAttribute("ttp:frameRate")&&(n.tickRate=Number(n.frameRate)*Number(n.subFrameRate));const o="preserve"!==s.getAttribute("xml:space"),l=Sl(Tl(s,"styling","style")),h=Sl(Tl(s,"layout","region")),d=Tl(s,"body","[begin]");return[].map.call(d,t=>{const i=function(t,e){const i=bl(t,e);if(!e)return i;return i.split("\n").map(t=>t.replace(/ {2,}/g," ").trim()).join("\n")}(t,o);if(!i||!t.hasAttribute("begin"))return null;const s=Il(t.getAttribute("begin"),n),r=Il(t.getAttribute("dur"),n);let a=Il(t.getAttribute("end"),n);if(null===s)throw Ll(t);if(null===a){if(null===r)throw Ll(t);a=s+r}const d=new tl(s-e,a-e,i);d.id=fl(d.startTime,d.endTime,d.text);const c=function(t,e,i){const s="http://www.w3.org/ns/ttml#styling";let r=null;const n=["displayAlign","textAlign","color","backgroundColor","fontSize","fontFamily"],a=null!=t&&t.hasAttribute("style")?t.getAttribute("style"):null;a&&i.hasOwnProperty(a)&&(r=i[a]);return n.reduce((i,n)=>{const a=Al(e,s,n)||Al(t,s,n)||Al(r,s,n);return a&&(i[n]=a),i},{})}(h[t.getAttribute("region")],l[t.getAttribute("style")],l),{textAlign:u}=c;if(u){const t=yl[u];t&&(d.lineAlign=t),d.align=u}return I(d,c),d}).filter(t=>null!==t)}(t,a)))}catch(t){s(t)}}function Tl(t,e,i){const s=t.getElementsByTagName(e)[0];return s?[].slice.call(s.querySelectorAll(i)):[]}function Sl(t){return t.reduce((t,e)=>{const i=e.getAttribute("xml:id");return i&&(t[i]=e),t},{})}function bl(t,e){return[].slice.call(t.childNodes).reduce((t,i,s)=>{var r;return"br"===i.nodeName&&s?t+"\n":null!=(r=i.childNodes)&&r.length?t+bl(i,e):t+(e?i.textContent.replace(/\s+/g," "):i.textContent)},"")}function Al(t,e,i){return t&&t.hasAttributeNS(e,i)?t.getAttributeNS(e,i):null}function Ll(t){return new Error(`Could not parse ttml timestamp ${t}`)}function Il(t,e){if(!t)return null;if(pl.test(t))return function(t,e){const i=pl.exec(t),s=(0|i[4])+(0|i[5])/e.subFrameRate;return 3600*(0|i[1])+60*(0|i[2])+(0|i[3])+s/e.frameRate}(t,e);let i=il(t);return null===i&&vl.test(t)&&(i=function(t,e){const i=vl.exec(t),s=Number(i[1]);switch(i[2]){case"h":return 3600*s;case"m":return 60*s;case"ms":return s/1e3;case"f":return s/e.frameRate;case"t":return s/e.tickRate}return s}(t,e)),i}function Rl(t,e,i,s="",r="disabled"){const n=t.ownerDocument.createElement("track");return n.kind=e,n.label=i,s&&(n.srclang=s),n.src="data:,WEBVTT",n.track.mode=r,t.appendChild(n),n}function kl(t){return t.forced&&(te.indexOf("Apple")>-1||/iPhone|iPad|iPod/.test(Jt))?"forced":t.characteristics&&/transcribes-spoken-dialog/gi.test(t.characteristics)&&/describes-music-and-sound/gi.test(t.characteristics)?"captions":"subtitles"}function _l(t,e){const i=t.mode;if("disabled"===i&&(t.mode="hidden"),t.cues&&!t.cues.getCueById(e.id))try{if(t.addCue(e),!t.cues.getCueById(e.id))throw new Error(`addCue is failed for: ${e}`)}catch(i){q.debug(`[texttrack-utils]: ${i}`);try{const i=new self.TextTrackCue(e.startTime,e.endTime,e.text);i.id=e.id,t.addCue(i)}catch(t){q.debug(`[texttrack-utils]: Legacy TextTrackCue fallback failed: ${t}`)}}"disabled"===i&&(t.mode=i)}function Dl(t,e,i,s){const r=t.mode;if("disabled"===r&&(t.mode="hidden"),t.cues&&t.cues.length>0){const r=function(t,e,i){const s=[],r=function(t,e){if(e<=t[0].startTime)return 0;const i=t.length-1;if(e>t[i].endTime)return-1;let s,r=0,n=i;for(;r<=n;)if(s=Math.floor((n+r)/2),e<t[s].startTime)n=s-1;else{if(!(e>t[s].startTime&&r<i))return s;r=s+1}return t[r].startTime-e<e-t[n].startTime?r:n}(t,e);if(r>-1)for(let n=r,a=t.length;n<a;n++){const r=t[n];if(r.startTime>=e&&r.endTime<=i)s.push(r);else if(r.startTime>i)return s}return s}(t.cues,e,i);for(let e=0;e<r.length;e++)s&&!s(r[e])||t.removeCue(r[e])}"disabled"===r&&(t.mode=r)}function wl(t,e){const i=Pl(t.main);if(i&&i.start<=e)return i;const s=Pl(t.audio);return s&&s.start<=e?s:null}function Pl(t){if(!t)return null;switch(t.state){case vr:case pr:case Lr:case Ir:return null}return t.frag}function Cl(t,e){return e.getAppendedFrag(t,f.MAIN)||e.getPartialFragment(t)}function xl(t,e,i,s){const r=s.latestLevelDetails,n=Cl(e,i);if(wr(s.config)&&!t.nextStart&&r&&n&&s.interstitialsManager){const i="type"in n?n:n.fragment,a=si(r,i.sn);(null==a?void 0:a.level)===i.level&&Dr(a,s.interstitialsManager.playerQueue,e)&&(t.nextStart=a.start)}}function Ml(){if("undefined"!=typeof self)return self.VTTCue||self.TextTrackCue}function Ol(t,e,i,s,r){let n=new t(e,i,"");try{n.value=s,r&&(n.type=r)}catch(a){n=new t(e,i,Ue(r?k({type:r},s):s))}return n}const Fl=(()=>{const t=Ml();try{t&&new t(0,Number.POSITIVE_INFINITY,"")}catch(t){return Number.MAX_VALUE}return Number.POSITIVE_INFINITY})();function Nl(){return self.SourceBuffer||self.WebKitSourceBuffer}function $l(){if(!Y())return!1;const t=Nl();return!t||t.prototype&&"function"==typeof t.prototype.appendBuffer&&"function"==typeof t.prototype.remove}var Bl=0,Ul=1,Gl=2;class Kl extends _r{constructor(t,i,s){super(t,i,s,"stream-controller",f.MAIN),this.audioCodecSwap=!1,this.level=-1,this._forceStartLoad=!1,this._hasEnoughToStart=!1,this.altAudio=Bl,this.audioOnly=!1,this._couldBacktrack=!1,this._backtrackFragment=void 0,this.audioCodecSwitch=!1,this.videoBuffer=null,this.onMediaPlaying=()=>{this.tick()},this.onMediaSeeked=()=>{const t=this.media,i=t?t.currentTime:null;if(null===i||!e(i))return;if(this.log(`Media seeked to ${i}`),!this.getBufferedFrag(i))return;const s=this.getFwdBufferInfoAtPos(t,i,f.MAIN,0);s&&0!==s.len?this.tick():this.log(`Main buffer empty at ${i} on "seeked" event: ${s?s.len:s}`)},this.registerListeners()}registerListeners(){super.registerListeners();const{hls:t}=this;t.on(a.MANIFEST_PARSED,this.onManifestParsed,this),t.on(a.LEVEL_LOADING,this.onLevelLoading,this),t.on(a.LEVEL_LOADED,this.onLevelLoaded,this),t.on(a.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),t.on(a.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.on(a.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),t.on(a.BUFFER_CREATED,this.onBufferCreated,this),t.on(a.BUFFER_FLUSHED,this.onBufferFlushed,this),t.on(a.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(a.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){super.unregisterListeners();const{hls:t}=this;t.off(a.MANIFEST_PARSED,this.onManifestParsed,this),t.off(a.LEVEL_LOADED,this.onLevelLoaded,this),t.off(a.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),t.off(a.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.off(a.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),t.off(a.BUFFER_CREATED,this.onBufferCreated,this),t.off(a.BUFFER_FLUSHED,this.onBufferFlushed,this),t.off(a.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(a.FRAG_BUFFERED,this.onFragBuffered,this)}onHandlerDestroying(){this.onMediaPlaying=this.onMediaSeeked=null,this.unregisterListeners(),super.onHandlerDestroying()}startLoad(t,e){if(this.levels){const{lastCurrentTime:i,hls:s}=this;if(this.stopLoad(),this.setInterval(100),this.level=-1,!this.startFragRequested){let t=s.startLevel;-1===t&&(s.config.testBandwidth&&this.levels.length>1?(t=0,this.bitrateTest=!0):t=s.firstAutoLevel),s.nextLoadLevel=t,this.level=s.loadLevel,this._hasEnoughToStart=!!e}i>0&&-1===t&&!e&&this.initPTS.length&&(this.log(`Override startPosition with lastCurrentTime @${i}`),t=i),this.state=vr,this.nextLoadPosition=this.lastCurrentTime=t+this.timelineOffset,this.startPosition=e?-1:t,e||this.fragmentTracker.hasFragments(this.playlistType)||(this._hasEnoughToStart=this.startFragRequested=!1),this.tick()}else this._forceStartLoad=!0,this.state=pr}stopLoad(){this._forceStartLoad=!1,super.stopLoad()}doTick(){switch(this.state){case kr:{const{levels:t,level:e}=this,i=null==t?void 0:t[e],s=null==i?void 0:i.details;if(s&&(!s.live||this.levelLastLoaded===i&&!this.waitForLive(i))){if(this.waitForCdnTuneIn(s))break;this.state=vr;break}if(this.hls.nextLoadLevel!==this.level){this.state=vr;break}break}case Tr:this.checkRetryDate()}this.state===vr&&this.doTickIdle(),this.onTickEnd()}onTickEnd(){super.onTickEnd(),this.checkFragmentChanged()}doTickIdle(){const{hls:t,levelLastLoaded:e,levels:i,media:s}=this;if(null===e||!s&&!this.primaryPrefetch&&(this.startFragRequested||!t.config.startFragPrefetch))return;if(this.altAudio&&this.audioOnly)return;const r=this.buffering?t.nextLoadLevel:t.loadLevel;if(null==i||!i[r])return;const n=i[r],o=this.getMainFwdBufferInfo();if(null===o)return;const l=this.getLevelDetails();if(l&&this._streamEnded(o,l)&&this.altAudio!==Ul){const t={type:this.targetBufferType()};return this.hls.trigger(a.BUFFER_EOS,t),void(this.state=Lr)}if(!this.buffering)return;t.loadLevel!==r&&-1===t.manualLevel&&this.log(`Adapting to level ${r} from level ${this.level}`),this.level=t.nextLoadLevel=r;const h=n.details;if(!h||this.state===kr||this.waitForLive(n))return this.level=r,this.state=kr,void(this.startFragRequested=!1);const d=o.len,c=this.getMaxBufferLength(n.maxBitrate);if(d>=c)return;this.backtrackFragment&&this.backtrackFragment.start>o.end&&(this.backtrackFragment=void 0);const u=this.backtrackFragment?this.backtrackFragment.start:o.end;let p=this.getNextFragment(u,h);if(this.couldBacktrack&&!this.fragPrevious&&p&&y(p)&&this.fragmentTracker.getState(p)!==Fi){var v;const t=(null!=(v=this.backtrackFragment)?v:p).sn-h.startSN,e=h.fragments[t-1];e&&p.cc===e.cc&&(p=e,this.fragmentTracker.removeFragment(e))}else this.backtrackFragment&&o.len&&(this.backtrackFragment=void 0);if(p&&this.isLoopLoading(p,u)){if(!p.gap){const t=this.audioOnly&&!this.altAudio?g:m,e=(t===m?this.videoBuffer:this.mediaBuffer)||this.media;e&&this.afterBufferFlushed(e,t)}p=this.getNextFragmentLoopLoading(p,h,o,f.MAIN,c)}p&&(this.exceedsMaxBuffer(o,c,p)||this.loadFragment(p,n,u))}loadFragment(t,e,i){const s=this.fragmentTracker.getState(t);s===xi||s===Oi?this.bitrateTest?(this.log(`Fragment ${t.sn} of level ${t.level} is being downloaded to test bitrate and will not be buffered`),this._loadBitrateTestFrag(t,e)):super.loadFragment(t,e,i):this.clearTrackerIfNeeded(t)}immediateLevelSwitch(){if(this.abortCurrentFrag(),this.flushMainBuffer(0,Number.POSITIVE_INFINITY),this.altAudio!==Bl){var t;((null==(t=this.getLevelDetails())?void 0:t.fragmentStart)||0)>this.lastCurrentTime&&super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio")}}getBufferOutput(){return this.mediaBuffer&&this.altAudio===Gl?this.mediaBuffer:this.media}checkFragmentChanged(){const t=this.fragPlaying;if(!this.checkFragPlaying())return!1;const e=this.fragPlaying;if(e){const i=e.level;this.hls.trigger(a.FRAG_CHANGED,{frag:e,previousFrag:t}),(null==t?void 0:t.level)!==i&&this.hls.trigger(a.LEVEL_SWITCHED,{level:i})}return!0}get backtrackFragment(){return this._backtrackFragment}set backtrackFragment(t){this._backtrackFragment=t}get couldBacktrack(){return this._couldBacktrack}set couldBacktrack(t){this._couldBacktrack=t}abortCurrentFrag(){this.backtrackFragment=void 0,super.abortCurrentFrag()}flushMainBuffer(t,e){super.flushMainBuffer(t,e,this.targetBufferType())}targetBufferType(){return this.altAudio!==Gl||this.audioOnly?null:"video"}onMediaAttached(t,e){super.onMediaAttached(t,e);const i=e.media;Ti(i,"playing",this.onMediaPlaying),Ti(i,"seeked",this.onMediaSeeked)}onMediaDetaching(t,e){const{media:i}=this;i&&(Si(i,"playing",this.onMediaPlaying),Si(i,"seeked",this.onMediaSeeked)),this.videoBuffer=null,super.onMediaDetaching(t,e);!!e.transferMedia||(this._hasEnoughToStart=!1)}onManifestLoading(){super.onManifestLoading(),this.log("Trigger BUFFER_RESET"),this.hls.trigger(a.BUFFER_RESET,void 0),this.couldBacktrack=!1,this.backtrackFragment=void 0,this.altAudio=Bl,this.audioOnly=!1}onManifestParsed(t,e){let i=!1,s=!1;for(let t=0;t<e.levels.length;t++){const r=e.levels[t].audioCodec;r&&(i=i||-1!==r.indexOf("mp4a.40.2"),s=s||-1!==r.indexOf("mp4a.40.5"))}this.audioCodecSwitch=i&&s&&!function(){var t;const e=Nl();return"function"==typeof(null==e||null==(t=e.prototype)?void 0:t.changeType)}(),this.audioCodecSwitch&&this.log("Both AAC/HE-AAC audio found in levels; declaring level codec as HE-AAC"),this.levels=e.levels,this.startFragRequested=!1}onLevelLoading(t,e){const{levels:i}=this;if(!i||this.state!==vr)return;const s=e.levelInfo;(!s.details||s.details.live&&(this.levelLastLoaded!==s||s.details.expired)||this.waitForCdnTuneIn(s.details))&&(this.state=kr)}onLevelLoaded(t,e){var i;const{levels:s,startFragRequested:r}=this,n=e.level,o=e.details,l=o.totalduration;if(!s)return void this.warn(`Levels were reset while loading level ${n}`);this.log(`Level ${n} loaded [${o.startSN},${o.endSN}]${o.lastPartSn?`[part-${o.lastPartSn}-${o.lastPartIndex}]`:""}, cc [${o.startCC}, ${o.endCC}] duration:${l}`);const h=e.levelInfo,d=this.fragCurrent;!d||this.state!==Er&&this.state!==Tr||d.level!==e.level&&d.loader&&this.abortCurrentFrag();let c=0;if(o.live||null!=(i=h.details)&&i.live){var u;if(this.checkLiveUpdate(o),o.deltaUpdateFailed)return;c=this.alignPlaylists(o,h.details,null==(u=this.levelLastLoaded)?void 0:u.details)}if(h.details=o,this.levelLastLoaded=h,r||this.setStartPosition(o,c),this.hls.trigger(a.LEVEL_UPDATED,{details:o,level:n}),this.state===kr){if(this.waitForCdnTuneIn(o))return;this.state=vr}r&&o.live&&this.synchronizeToLiveEdge(o),this.initPTS.some((t,e)=>{if(e>=o.startCC)return!0;delete this.initPTS[e]}),this.tick()}synchronizeToLiveEdge(t){const{config:e,media:i}=this;if(!i)return;const s=this.hls.liveSyncPosition,r=this.playhead,n=t.fragmentStart,a=t.edge,o=r>=n-e.maxFragLookUpTolerance&&r<=a;if(null!==s&&i.duration>s&&(r<s||!o)){const n=void 0!==e.liveMaxLatencyDuration?e.liveMaxLatencyDuration:e.liveMaxLatencyDurationCount*t.targetduration;if((!o&&i.readyState<4||r<a-n)&&(this._hasEnoughToStart||(this.nextLoadPosition=s),i.readyState))if(this.warn(`Playback: ${r} is located too far from the end of live sliding playlist: ${a}, reset currentTime to : ${s}`),"buffered"===this.config.liveSyncMode){var l;const t=Ei.bufferInfo(i,s,0);if(null==(l=t.buffered)||!l.length)return void(i.currentTime=s);if(t.start<=r)return void(i.currentTime=s);const{nextStart:e}=Ei.bufferedInfo(t.buffered,r,0);e&&(i.currentTime=e)}else i.currentTime=s}}_handleFragmentLoadProgress(t){var e;const i=t.frag,{part:s,payload:r}=t,{levels:n}=this;if(!n)return void this.warn(`Levels were reset while fragment load was in progress. Fragment ${i.sn} of level ${i.level} will not be buffered`);const a=n[i.level];if(!a)return void this.warn(`Level ${i.level} not found on progress`);const o=a.details;if(!o)return this.warn(`Dropping fragment ${i.sn} of level ${i.level} after level details were reset`),void this.fragmentTracker.removeFragment(i);const l=a.videoCodec,h=o.PTSKnown||!o.live,d=null==(e=i.initSegment)?void 0:e.data,c=this._getAudioCodec(a),u=this.transmuxer=this.transmuxer||new ia(this.hls,f.MAIN,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)),g=s?s.index:-1,m=-1!==g,{decryptRange:p,byteRange:v}=Xi(i,s,this.iframesOnly),y=new ts(i.level,i.sn,i.stats.chunkCount,v?v.end-v.start:r.byteLength,g,m,i.duration,this.iframesOnly,p),E=this.initPTS[i.cc];u.push(r,d,c,l,i,s,o.totalduration,h,y,E)}onAudioTrackSwitching(t,e){const i=this.hls,s=this.altAudio!==Bl;if(We(e.url,i))this.altAudio=Ul;else{if(this.mediaBuffer!==this.media){this.log("Switching on main audio, use media.buffered to schedule main fragment loading"),this.mediaBuffer=this.media;const t=this.fragCurrent;t&&(this.log("Switching to main audio track, cancel main fragment load"),t.abortRequests(),this.fragmentTracker.removeFragment(t)),this.resetTransmuxer(),this.resetLoadingState()}else this.audioOnly&&this.resetTransmuxer();if(s)return this.altAudio=Bl,this.fragmentTracker.removeAllFragments(),i.once(a.BUFFER_FLUSHED,()=>{this.hls&&this.hls.trigger(a.AUDIO_TRACK_SWITCHED,e)}),void i.trigger(a.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:null});i.trigger(a.AUDIO_TRACK_SWITCHED,e)}}onAudioTrackSwitched(t,e){const i=We(e.url,this.hls);if(i){const t=this.videoBuffer;t&&this.mediaBuffer!==t&&(this.log("Switching on alternate audio, use video.buffered to schedule main fragment loading"),this.mediaBuffer=t)}this.altAudio=i?Gl:Bl,this.tick()}onBufferCreated(t,e){const i=e.tracks;let s,r,n=!1;for(const t in i){const e=i[t];if("main"===e.id){if(r=t,s=e,"video"===t){const e=i[t];e&&(this.videoBuffer=e.buffer)}}else n=!0}n&&s?(this.log(`Alternate track found, use ${r}.buffered to schedule main fragment loading`),this.mediaBuffer=s.buffer):this.mediaBuffer=this.media}onFragBuffered(t,e){const{frag:i,part:s}=e,r=i.type===f.MAIN;if(r){if(this.fragContextChanged(i))return this.warn(`Fragment ${i.sn}${s?" p: "+s.index:""} of level ${i.level} finished buffering, but was aborted. state: ${this.state}`),void(this.state===Ar&&(this.state=vr));let t=!1;if(y(i)&&(t=!!i.gap&&!i.tagList.some(t=>"GAP"===t[0])),this.fragBufferedComplete(i,s),t){var n;i.stats.retry++;const t=null==(n=this.levels)?void 0:n[i.level];t&&t.fragmentError++}}const a=this.media;a&&(!this._hasEnoughToStart&&Ei.getBuffered(a).length&&(this.seekToStartPos(),this._hasEnoughToStart=!0),r&&this.tick())}get hasEnoughToStart(){return this._hasEnoughToStart}onError(t,e){var i;if(e.fatal)this.state=Ir;else switch(e.details){case n.FRAG_GAP:case n.FRAG_PARSING_ERROR:case n.FRAG_DECRYPT_ERROR:case n.FRAG_LOAD_ERROR:case n.FRAG_LOAD_TIMEOUT:case n.KEY_LOAD_ERROR:case n.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(f.MAIN,e);break;case n.LEVEL_LOAD_ERROR:case n.LEVEL_LOAD_TIMEOUT:case n.LEVEL_PARSING_ERROR:e.levelRetry||this.state!==kr||(null==(i=e.context)?void 0:i.type)!==u.LEVEL||(this.state=vr);break;case n.BUFFER_APPEND_NO_PROGRESS:if("main"!==e.parent)return;e.frag&&(e.appendsWithoutProgress||0)>=this.config.appendErrorMaxRetry&&(this.warn(`Marking fragment ${e.frag.sn} of level ${e.frag.level} as a gap after ${e.appendsWithoutProgress} appends without buffered range growth, to prevent loop loading`),this.fragmentTracker.addAsGap(e.frag));break;case n.MEDIA_SOURCE_REQUIRES_RESET:this.onSourceBufferError(f.MAIN,e);break;case n.BUFFER_ADD_CODEC_ERROR:case n.BUFFER_APPEND_ERROR:if("main"!==e.parent)return;this.reduceLengthAndFlushBuffer(e)&&this.resetLoadingState();break;case n.BUFFER_FULL_ERROR:if("main"!==e.parent)return;if(this.reduceLengthAndFlushBuffer(e)){!this.config.interstitialsController&&this.config.assetPlayerId?this._hasEnoughToStart=!0:this.flushMainBuffer(0,Number.POSITIVE_INFINITY)}break;case n.INTERNAL_EXCEPTION:this.recoverWorkerError(e)}}onFragLoadEmergencyAborted(){this.state=vr,this._hasEnoughToStart||(this.startFragRequested=!1,this.nextLoadPosition=this.lastCurrentTime),this.tickImmediate()}onBufferFlushed(t,{type:e}){if(e!==g||!this.altAudio){const t=(e===m?this.videoBuffer:this.mediaBuffer)||this.media;t&&(this.afterBufferFlushed(t,e),this.tick())}}onLevelsUpdated(t,e){this.level>-1&&this.fragCurrent&&(this.level=this.fragCurrent.level,-1===this.level&&this.resetWhenMissingContext(this.fragCurrent)),this.levels=e.levels}swapAudioCodec(){this.audioCodecSwap=!this.audioCodecSwap}seekToStartPos(){const{media:t}=this;if(!t)return;const e=t.currentTime;let i=this.startPosition;if(i>=0&&e<i){if(t.seeking)return void this.log(`could not seek to ${i}, already seeking at ${e}`);const s=this.timelineOffset;s&&i&&(i+=s);const r=this.getLevelDetails(),n=Ei.getBuffered(t),a=n.length?n.start(0):0,o=a-i,l=Math.max(this.config.maxBufferHole,this.config.maxFragLookUpTolerance);(this.config.startOnSegmentBoundary||o>0&&(o<l||this.loadingParts&&o<2*((null==r?void 0:r.partTarget)||0)))&&(this.log(`adjusting start position by ${o} to match buffer start`),i+=o,this.startPosition=i),e<i&&(this.log(`seek to target start position ${i} from current time ${e} buffer start ${a}`),t.currentTime=i)}}_getAudioCodec(t){let e=this.config.defaultAudioCodec||t.audioCodec;return this.audioCodecSwap&&e&&(this.log("Swapping audio codec"),e=-1!==e.indexOf("mp4a.40.5")?"mp4a.40.2":"mp4a.40.5"),e}_loadBitrateTestFrag(t,e){t.bitrateTest=!0,this._doFragLoad(t,e).then(t=>{const{hls:i}=this,s=null==t?void 0:t.frag;if(!s||this.fragContextChanged(s))return;e.fragmentError=0,this.state=vr,this.startFragRequested=!1,this.bitrateTest=!1;const r=s.stats;r.parsing.start=r.parsing.end=r.buffering.start=r.buffering.end=self.performance.now(),i.trigger(a.FRAG_LOADED,t),s.bitrateTest=!1}).catch(e=>{this.state!==pr&&this.state!==Ir&&(this.warn(e),this.resetFragmentLoading(t))})}_handleTransmuxComplete(t){const i=this.playlistType,{hls:s}=this,{remuxResult:r,chunkMeta:n}=t,o=this.getCurrentContext(n);if(!o)return void this.resetWhenMissingContext(n);const{frag:l,part:h,level:d}=o,{video:c,text:u,id3:f,initSegment:m}=r,{details:p}=d,v=this.altAudio?void 0:r.audio;if(this.fragContextChanged(l))this.fragmentTracker.removeFragment(l);else{if(this.state=br,m){const t=m.tracks;if(t){const e=l.initSegment||l;if(this.unhandledEncryptionError(m,l))return;this._bufferInitSegment(d,t,e,n),s.trigger(a.FRAG_PARSING_INIT_SEGMENT,{frag:e,id:i,tracks:t})}const r=m.initPTS,o=m.timescale,h=this.initPTS[l.cc];if(e(r)&&(!h||h.baseTime!==r||h.timescale!==o)){const t=m.trackId;this.initPTS[l.cc]={baseTime:r,timescale:o,trackId:t};const e=this.initPTS.slice(0);s.trigger(a.INIT_PTS_FOUND,{timestampOffsets:e,frag:l,id:i,initPTS:r,timescale:o,trackId:t})}}if(c&&p){v&&"audiovideo"===c.type&&this.logMuxedErr(l);const t=p.fragments[l.sn-1-p.startSN],e=l.sn===p.startSN,i=!t||l.cc>t.cc;if(!1!==r.independent){const{startPTS:t,endPTS:s,startDTS:r,endDTS:a}=c;if(h)h.elementaryStreams[c.type]={startPTS:t,endPTS:s,startDTS:r,endDTS:a};else if(c.firstKeyFrame&&c.independent&&1===n.id&&!i&&(this.couldBacktrack=!0),c.dropped&&c.independent){const r=this.getMainFwdBufferInfo(),n=(r?r.end:this.getLoadPosition())+this.config.maxBufferHole,o=c.firstKeyFramePTS?c.firstKeyFramePTS:t;if(!e&&n<o-this.config.maxBufferHole&&!i)return void this.backtrack(l);i&&(l.gap=!0),l.setElementaryStreamInfo(c.type,l.start,s,l.start,a,!0)}else e&&t-(p.appliedTimelineOffset||0)>2&&(l.gap=!0);l.setElementaryStreamInfo(c.type,t,s,r,a),this.backtrackFragment&&(this.backtrackFragment=l),this.bufferFragmentData(c,l,h,n,e||i)}else{if(!e&&!i)return void this.backtrack(l);l.gap=!0}}if(v){const{startPTS:t,endPTS:e,startDTS:i,endDTS:s}=v;h&&(h.elementaryStreams[g]={startPTS:t,endPTS:e,startDTS:i,endDTS:s}),l.setElementaryStreamInfo(g,t,e,i,s),this.bufferFragmentData(v,l,h,n)}if(p&&null!=f&&f.samples.length){const t={id:i,frag:l,details:p,samples:f.samples};s.trigger(a.FRAG_PARSING_METADATA,t)}if(p&&u){const t={id:i,frag:l,details:p,samples:u.samples};s.trigger(a.FRAG_PARSING_USERDATA,t)}}}logMuxedErr(t){this.warn(`${y(t)?"Media":"Init"} segment with muxed audiovideo where only video expected: ${t.url}`)}_bufferInitSegment(t,e,i,s){if(this.state!==br)return;this.audioOnly=!!e.audio&&!e.video,this.altAudio&&!this.audioOnly&&(delete e.audio,e.audiovideo&&this.logMuxedErr(i));const{audio:r,video:n,audiovideo:o}=e;if(r){const i=t.audioCodec;let s=ve(r.codec,i);if("mp4a"===s&&(s="mp4a.40.5"),this.audioCodecSwitch){s&&(s=-1!==s.indexOf("mp4a.40.5")?"mp4a.40.2":"mp4a.40.5");const t=r.metadata;t&&"channelCount"in t&&1!==(t.channelCount||1)&&!function(){if(void 0===ie){const t=Jt.match(/Firefox\/(\d+)/i);ie=t?parseInt(t[1]):0}return ie}()&&(s="mp4a.40.5")}s&&-1!==s.indexOf("mp4a.40.5")&&/Android/.test(Jt)&&"audio/mpeg"!==r.container&&(s="mp4a.40.2",this.log(`Android: force audio codec to ${s}`)),i&&i!==s&&this.log(`Swapping manifest audio codec "${i}" for "${s}"`),r.levelCodec=s,r.id=f.MAIN,this.log(`Init audio buffer, container:${r.container}, codecs[selected/level/parsed]=[${s||""}/${i||""}/${r.codec}]`),delete e.audiovideo}if(n){n.levelCodec=t.videoCodec,n.id=f.MAIN;const i=n.codec;if(4===(null==i?void 0:i.length))switch(i){case"hvc1":case"hev1":n.codec="hvc1.1.6.L120.90";break;case"av01":n.codec="av01.0.04M.08";break;case"avc1":n.codec="avc1.42e01e"}this.log(`Init video buffer, container:${n.container}, codecs[level/parsed]=[${t.videoCodec||""}/${i}]${n.codec!==i?" parsed-corrected="+n.codec:""}${n.supplemental?" supplemental="+n.supplemental:""}`),delete e.audiovideo}o&&(this.iframesOnly&&this.logMuxedErr(i),this.log(`Init audiovideo buffer, container:${o.container}, codecs[level/parsed]=[${t.codecs}/${o.codec}]`),delete e.video,delete e.audio);const l=Object.keys(e);if(l.length){if(this.hls.trigger(a.BUFFER_CODECS,e),!this.hls)return;l.forEach(t=>{const r=e[t].initSegment;null!=r&&r.byteLength&&this.hls.trigger(a.BUFFER_APPENDING,{type:t,data:r,frag:i,part:null,chunkMeta:s,parent:i.type})})}this.tickImmediate()}getMainFwdBufferInfo(){const t=this.getBufferOutput();return this.getFwdBufferInfo(t,f.MAIN)}get maxBufferLength(){const{levels:t,level:e}=this,i=null==t?void 0:t[e];return i?this.getMaxBufferLength(i.maxBitrate):this.config.maxBufferLength}backtrack(t){this.couldBacktrack=!0,this.backtrackFragment=t,this.resetTransmuxer(),this.flushBufferGap(t),this.fragmentTracker.removeFragment(t),this.fragPrevious=null,this.nextLoadPosition=t.start,this.state=vr}get nextLevel(){const t=this.nextBufferedFrag;return t?t.level:-1}get currentFrag(){var t;if(this.fragPlaying)return this.fragPlaying;const i=(null==(t=this.media)?void 0:t.currentTime)||this.lastCurrentTime;return e(i)?this.getAppendedFrag(i):null}get currentProgramDateTime(){var t;const i=(null==(t=this.media)?void 0:t.currentTime)||this.lastCurrentTime;if(e(i)){const t=this.getLevelDetails(),e=this.currentFrag||(t?Je(null,t.fragments,i):null);if(e){const t=e.programDateTime;if(null!==t){const s=t+1e3*(i-e.start);return new Date(s)}}}return null}get currentLevel(){const t=this.currentFrag;return t?t.level:-1}get nextBufferedFrag(){const t=this.currentFrag;return t?this.followingBufferedFrag(t):null}get forceStartLoad(){return this._forceStartLoad}}class Vl extends Kl{constructor(...t){super(...t),this.currentOp=void 0,this.nextOp=void 0,this.cached=[],this.cachedSize=0,this.cacheFragmentData=!0,this.initDetails=void 0,this.onBufferedToEnd=()=>{const t=this.media;null!=t&&t.seeking&&(t.currentTime=t.currentTime)},this.onMediaSeeking=()=>{}}setInitPts(t){this.initPTS=t.slice()}loadMediaAt(t,e){if(!this.hls)return;const{seekOnAppend:i}=e,s=t+this.timelineOffset;switch(this.nextLoadPosition=this.lastCurrentTime=s,this.startPosition=t,this.state){case pr:case Lr:case Ir:this.state=vr}this.state===vr?(this.hls.resumeBuffering(),this.tick(),this.currentOp=[s,e]):this.nextOp=[s,e],this.hls.off(a.BUFFERED_TO_END,this.onBufferedToEnd);const r=this.media;if(i&&r){this.seekTo(s)&&(this.currentOp=[s,e],this.nextOp=void 0,this.flushPipeline(s,!0))}}seekTo(t){const e=this.media;if(e){var i;const s=null==(i=this.getLevelDetails())?void 0:i.edge,r=void 0!==s?s:e.duration;t>=r&&(t=r-.01);if(Ei.bufferInfo(e,t,0).len>0&&this.getBufferedAt(t))return e.currentTime=t,!0}return!1}getBufferedAt(t){return this.fragmentTracker.getBufferedFrag(t,f.MAIN)}cacheSet(t,e){if(!this.hls)return;t.data=e;const i=this.cached;i.push(t),this.cachedSize+=e.buffer.byteLength;const s=this.hls.config.iframeCacheLimit;for(;this.cachedSize>s&&i.length>1;){const t=i.shift();if(!t.data){this.cached=i.filter(t=>!!t.data),this.cachedSize=i.reduce((t,{data:e})=>e?e.buffer.byteLength:0,0);break}this.cachedSize-=t.data.byteLength,t.data=void 0}}onHandlerDestroying(){this.cached.length=0,this.cachedSize=0,super.onHandlerDestroying()}_handleFragmentLoadProgress(t){const e=t.frag,{part:i,payload:s}=t;this.cacheFragmentData&&!i&&null!=s&&s.byteLength&&!e.data&&y(e)&&this.cacheSet(e,new Uint8Array(s.slice(0))),super._handleFragmentLoadProgress(t)}loadFragment(t,e,i){const s=this.fragmentTracker.getState(t);s!==xi&&s!==Oi||!this.canReplayCached(t)?super.loadFragment(t,e,i):this.replayCachedFragment(t)}canReplayCached(t){var e;if(!this.cacheFragmentData||null==(e=t.data)||!e.byteLength)return!1;const i=t.decryptdata;return"identity"!==(null==i?void 0:i.keyFormat)||!!i.key}replayCachedFragment(t){const e=t.data.slice().buffer;this.log(`Buffering cached ${t.type} sn: ${t.sn} of level ${t.level} (${e.byteLength} bytes)`),this.fragCurrent=t,this.startFragRequested=!0;const i=t.stats=new c;i.loading.start=i.loading.first=i.loading.end=self.performance.now(),i.loaded=i.total=e.byteLength,i.chunkCount=1,this.state=Er;const s={frag:t,part:null,payload:e,networkDetails:null};this._handleFragmentLoadProgress(s),this.hls.trigger(a.FRAG_LOADED,s),this._handleFragmentLoadComplete(s)}fragBufferedComplete(t,e){super.fragBufferedComplete(t,e);const{currentOp:i,nextOp:s}=this;this.currentOp=this.nextOp=void 0,this.state=pr,null!=i&&i[1].seekOnAppend&&(this.flushPipeline(i[0],!s),this.seekTo(i[0])||this.log(`Could not seek to ${i[0]} after fragment buffered (superseded or flushed) buffer: ${this.media?bi(Ei.getBuffered(this.media)):"none"}`)),s&&this.loadMediaAt.apply(this,s)}flushPipeline(t,e){if(e){const e=this.media;if(e){const i=Ei.bufferInfo(e,t,0),s=i.len?i.nextStart:0;s&&(this.fragmentTracker.removeFragmentsInRange(s,1/0,f.MAIN),this.flushMainBuffer(s,1/0))}this.hls.once(a.BUFFERED_TO_END,this.onBufferedToEnd)}this.hls.trigger(a.BUFFER_EOS,{type:"video"})}get playhead(){return this.nextLoadPosition}startLoad(){if(!this.startFragRequested){const t=this.hls;t.nextLoadLevel=-1===t.startLevel?0:t.firstAutoLevel}}seekToStartPos(){}setStartPosition(){}alignPlaylists(t,e,i){const s=this.initDetails;return this.initDetails=null,super.alignPlaylists(t,e,i||s||void 0)}getMainFwdBufferInfo(){const t=this.playhead,e=this.getBufferedAt(t);if(e){const i=e.duration;return{len:i,start:t,end:t+i,bufferedIndex:-1}}return{len:0,start:t,end:t,bufferedIndex:-1}}_streamEnded(){const t=this.playhead,e=this.fragmentTracker.getBufferedFrag(t,f.MAIN);return!(null==e||!e.endList)}}class jl extends Vl{constructor(...t){super(...t),this._img=void 0,this.queued=void 0,this.cacheFragmentData=!1}get image(){return this._img}set image(t){var e;const i=null==(e=this._img)?void 0:e.src;i&&self.URL.revokeObjectURL(i),this._img=t}loadMediaAt(t){if(!this.hls)return;const e=t+this.timelineOffset;switch(this.nextLoadPosition=this.lastCurrentTime=e,this.startPosition=t,this.state){case pr:case Lr:case Ir:this.state=vr}if(this.state===vr){if(this.hls.resumeBuffering(),this.media||(this.media={}),this.tick(),this.state===vr){const e=this.getBufferedAt(t);e&&(this.fragCurrent=e,this.updateImage(e,null))}}else{const i=this.fragCurrent;(!i||t>=i.start&&t<i.end)&&(this.queued=[e])}}updateImage(t,e,i){const s=t.data;s||this.fragmentTracker.removeFragment(t);const r=this._img;if(r&&s){const n=self.performance.now();(e?e.stats:t.stats).buffering.start=t.stats.buffering.start=n,r.onload=()=>{if(!this.hls)return;const s=this.hls.levels[t.level];null!=s&&s.fragmentError&&(s.fragmentError=0,t.stats.retry=0);const r=self.performance.now(),n=e?e.stats:t.stats;n.buffering.end=t.stats.buffering.end=r,this.hls.trigger(a.FRAG_BUFFERED,{frag:t,part:e,stats:n,id:t.type,chunkMeta:i})},r.onerror=()=>{this.handleError("Image decode error",t,e,i)};const o=r.src;o&&self.URL.revokeObjectURL(o);const l=new Blob([s],{type:"image/jpeg"});r.src=self.URL.createObjectURL(l)}else this.state=pr,this.processQueued()}processQueued(){const t=this.queued;this.queued=void 0,t&&this.loadMediaAt.apply(this,t)}handleError(t,e,i,s){if(!this.hls)return;const o=new Error(t);this.hls.trigger(a.ERROR,{type:r.MEDIA_ERROR,details:n.FRAG_PARSING_ERROR,chunkMeta:s,frag:e,part:i,fatal:!1,error:o,err:o})}_bufferInitSegment(){}bufferFragmentData(t,e,i,s){super.bufferFragmentData(t,e,i,s,!0);const r=Pt(new Uint8Array(t.data1),["mdat"]);if(0===r.length)return void this.handleError("Could not find I-Frame mdat",e,i,s);const n=e;this.cacheSet(n,r[0]),this.updateImage(n,i,s)}fragBufferedComplete(t,e){this.fragmentTracker.fragBuffered(t,!0),super.fragBufferedComplete(t,e),this.processQueued()}checkFragPlaying(){var t;const e=null==(t=this.fragPrevious)?void 0:t.start;if(void 0!==e){const t=this.getAppendedFrag(e);if(t&&!E(t,this.fragPlaying))return this.fragPlaying=t,!0}return!1}getMainFwdBufferInfo(){return{len:0,start:this.playhead,end:this.playhead,bufferedIndex:-1}}}const Hl="Image I-Frame player does not accept HTMLMediaElements",ql={seekOnAppend:!0};let Yl,Wl;const zl=.025;let Xl=function(t){return t[t.Point=0]="Point",t[t.Range=1]="Range",t}({});function Ql(t,e,i){return`${t.identifier}-${i+1}-${dl(e)}`}class Zl{constructor(t,e){this.base=void 0,this._duration=null,this._timelineStart=null,this.appendInPlaceDisabled=void 0,this.appendInPlaceStarted=void 0,this.dateRange=void 0,this.hasPlayed=!1,this.cumulativeDuration=0,this.resumeOffset=NaN,this.playoutLimit=NaN,this.restrictions={skip:!1,jump:!1},this.snapOptions={out:!1,in:!1},this.assetList=[],this.assetListLoader=void 0,this.assetListResponse=null,this.resumeAnchor=void 0,this.error=void 0,this.resetOnResume=void 0,this.base=e,this.dateRange=t,this.setDateRange(t)}setDateRange(t){this.dateRange=t,this.resumeOffset=t.attr.optionalFloat("X-RESUME-OFFSET",this.resumeOffset),this.playoutLimit=t.attr.optionalFloat("X-PLAYOUT-LIMIT",this.playoutLimit),this.restrictions=t.attr.enumeratedStringList("X-RESTRICT",this.restrictions),this.snapOptions=t.attr.enumeratedStringList("X-SNAP",this.snapOptions)}reset(){var t;this.appendInPlaceStarted=!1,null==(t=this.assetListLoader)||t.destroy(),this.assetListLoader=void 0,this.supplementsPrimary||(this.assetListResponse=null,this.assetList=[],this._duration=null)}isAssetPastPlayoutLimit(t){var e;if(t>0&&t>=this.assetList.length)return!0;const i=this.playoutLimit;if(t<=0||isNaN(i))return!1;if(0===i)return!0;return((null==(e=this.assetList[t])?void 0:e.startOffset)||0)>i}findAssetIndex(t){return this.assetList.indexOf(t)}get identifier(){return this.dateRange.id}get startDate(){return this.dateRange.startDate}get startTime(){const t=this.dateRange.startTime;if(this.snapOptions.out){const e=this.dateRange.tagAnchor;if(e)return th(e,t)?Jl(t,e):t}return t}get startOffset(){return this.cue.pre?0:this.startTime}get startIsAligned(){if(0===this.startTime||this.snapOptions.out)return!0;const t=this.dateRange.tagAnchor;if(t){const e=this.dateRange.startTime;return e-Jl(e,t)<.1}return!1}get resumptionOffset(){const t=this.resumeOffset,i=e(t)?t:this.duration;return this.cumulativeDuration+i}get resumeTime(){const t=this.startOffset+this.resumptionOffset;if(this.snapOptions.in){const e=this.resumeAnchor;if(e)return th(e,t)?Jl(t,e):t}return t}get appendInPlace(){return!!this.appendInPlaceStarted||!this.appendInPlaceDisabled&&!(this.cue.once||this.cue.pre||!this.startIsAligned||!(isNaN(this.playoutLimit)&&isNaN(this.resumeOffset)||this.resumeOffset&&this.duration&&Math.abs(this.resumeOffset-this.duration)<zl))}set appendInPlace(t){this.appendInPlaceStarted?this.resetOnResume=!t:this.appendInPlaceDisabled=!t}get timelineStart(){return null!==this._timelineStart?this._timelineStart:this.startTime}set timelineStart(t){this._timelineStart=t}get duration(){const t=this.playoutLimit;let e;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(t){this._duration=t}get cue(){return this.dateRange.cue}get timelineOccupancy(){return"RANGE"===this.dateRange.attr["X-TIMELINE-OCCUPIES"]?Xl.Range:Xl.Point}get supplementsPrimary(){return"PRIMARY"===this.dateRange.attr["X-TIMELINE-STYLE"]}get contentMayVary(){return"NO"!==this.dateRange.attr["X-CONTENT-MAY-VARY"]}get assetUrl(){return this.dateRange.attr["X-ASSET-URI"]}get assetListUrl(){return this.dateRange.attr["X-ASSET-LIST"]}get baseUrl(){return this.base.url}get assetListLoaded(){return this.assetList.length>0||null!==this.assetListResponse}toString(){return`["${(t=this).identifier}" ${t.cue.pre?"<pre>":t.cue.post?"<post>":""}${t.timelineStart.toFixed(2)}-${t.resumeTime.toFixed(2)}]`;var t}}function Jl(t,e){return t-e.start<e.duration/2&&!(Math.abs(t-(e.start+e.duration))<zl)?e.start:e.start+e.duration}function th(t,e){return e>t.start-zl&&e<t.start+t.duration+zl}function eh(t,e,i){const s=new self.URL(t,i);return"data:"!==s.protocol&&De(s,"_HLS_primary_id",e),s}function ih(t,e){for(;null!=(i=t.assetList[++e])&&i.error;)var i;return e}function sh(t){const e=t.timelineStart,i=t.duration||0;return`["${t.identifier}" ${e.toFixed(2)}-${(e+i).toFixed(2)}]`}class rh{constructor(t,e,i,s){this.hls=void 0,this.interstitial=void 0,this.assetItem=void 0,this.tracks=null,this.hasDetails=!1,this.mediaAttached=null,this._currentTime=void 0,this._bufferedEosTime=void 0,this.checkPlayout=()=>{this.reachedPlayout(this.currentTime)&&this.hls&&this.hls.trigger(a.PLAYOUT_LIMIT_REACHED,{})};const r=this.hls=new t(e);this.interstitial=i,this.assetItem=s;const n=()=>{this.hasDetails=!0};r.once(a.LEVEL_LOADED,n),r.once(a.AUDIO_TRACK_LOADED,n),r.once(a.SUBTITLE_TRACK_LOADED,n),r.on(a.MEDIA_ATTACHING,(t,{media:e})=>{this.removeMediaListeners(),this.mediaAttached=e;this.interstitial.playoutLimit&&(e.addEventListener("timeupdate",this.checkPlayout),this.appendInPlace&&r.on(a.BUFFER_APPENDED,()=>{const t=this.bufferedEnd;this.reachedPlayout(t)&&(this._bufferedEosTime=t,r.trigger(a.BUFFERED_TO_END,void 0))}))})}get appendInPlace(){return this.interstitial.appendInPlace}loadSource(){const t=this.hls;if(t)if(t.url)t.levels.length&&!t.started&&t.startLoad(-1,!0);else{let e=this.assetItem.uri;try{e=eh(e,t.config.primarySessionId||"").href}catch(t){}t.loadSource(e)}}bufferedInPlaceToEnd(t,e){var i;if(!this.appendInPlace)return!1;if(null!=(i=this.hls)&&i.bufferedToEnd)return!0;if(!t)return!1;const s=Math.min(this._bufferedEosTime||1/0,this.duration),r=this.timelineOffset+(e||0),n=Ei.bufferInfo(t,r,.02);return this.getAssetTime(n.end)>=s-.02}reachedPlayout(t){const e=this.interstitial.playoutLimit;return this.startOffset+t>=e}get destroyed(){var t;return!(null!=(t=this.hls)&&t.userConfig)}get assetId(){return this.assetItem.identifier}get interstitialId(){return this.assetItem.parentIdentifier}get media(){var t;return(null==(t=this.hls)?void 0:t.media)||null}get bufferedEnd(){const t=this.media||this.mediaAttached;if(!t)return this._bufferedEosTime?this._bufferedEosTime:this.currentTime;const e=Ei.bufferInfo(t,t.currentTime,.001);return this.getAssetTime(e.end)}get currentTime(){const t=this.media||this.mediaAttached;return t?this.getAssetTime(t.currentTime):this._currentTime||0}get duration(){const t=this.assetItem.duration;if(!t)return 0;const e=this.interstitial.playoutLimit;if(e){const i=e-this.startOffset;if(i>0&&i<t)return i}return t}get remaining(){const t=this.duration;return t?Math.max(0,t-this.currentTime):0}get startOffset(){return this.assetItem.startOffset}get timelineOffset(){var t;return(null==(t=this.hls)?void 0:t.config.timelineOffset)||0}set timelineOffset(t){const e=this.timelineOffset;if(t!==e){const i=t-e;if(Math.abs(i)>1/9e4&&this.hls){if(this.hasDetails)throw new Error("Cannot set timelineOffset after playlists are loaded");this.hls.config.timelineOffset=t}}}getAssetTime(t){const e=this.timelineOffset,i=this.duration;return Math.min(Math.max(0,t-e),i)}removeMediaListeners(){const t=this.mediaAttached;t&&(this._currentTime=t.currentTime,this.bufferSnapShot(),t.removeEventListener("timeupdate",this.checkPlayout))}bufferSnapShot(){var t;this.mediaAttached&&(null!=(t=this.hls)&&t.bufferedToEnd&&(this._bufferedEosTime=this.bufferedEnd))}destroy(){this.removeMediaListeners(),this.hls&&this.hls.destroy(),this.hls=null,this.tracks=this.mediaAttached=this.checkPlayout=null}attachMedia(t){var e;this.loadSource(),null==(e=this.hls)||e.attachMedia(t)}detachMedia(){var t;this.removeMediaListeners(),this.mediaAttached=null,null==(t=this.hls)||t.detachMedia()}resumeBuffering(){var t;null==(t=this.hls)||t.resumeBuffering()}pauseBuffering(){var t;null==(t=this.hls)||t.pauseBuffering()}transferMedia(){var t;return this.bufferSnapShot(),(null==(t=this.hls)?void 0:t.transferMedia())||null}resetDetails(){const t=this.hls;if(t&&this.hasDetails){t.stopLoad();const e=t=>delete t.details;t.levels.forEach(e),t.allAudioTracks.forEach(e),t.allSubtitleTracks.forEach(e),this.hasDetails=!1}}on(t,e,i){var s;null==(s=this.hls)||s.on(t,e)}once(t,e,i){var s;null==(s=this.hls)||s.once(t,e)}off(t,e,i){var s;null==(s=this.hls)||s.off(t,e)}toString(){var t;return`HlsAssetPlayer: ${sh(this.assetItem)} ${null==(t=this.hls)?void 0:t.sessionId} ${this.appendInPlace?"append-in-place":""}`}}const nh=.033;class ah extends U{constructor(t,e){super("interstitials-sched",e),this.onScheduleUpdate=void 0,this.eventMap={},this.events=null,this.items=null,this.durations={primary:0,playout:0,integrated:0},this.onScheduleUpdate=t}destroy(){this.reset(),this.onScheduleUpdate=null}reset(){this.eventMap={},this.setDurations(0,0,0),this.events&&this.events.forEach(t=>t.reset()),this.events=this.items=null}resetErrorsInRange(t,e){return this.events?this.events.reduce((i,s)=>t<=s.startOffset&&e>s.startOffset?(delete s.error,i+1):i,0):0}get duration(){const t=this.items;return t?t[t.length-1].end:0}get length(){return this.items?this.items.length:0}getEvent(t){return t&&this.eventMap[t]||null}hasEvent(t){return t in this.eventMap}findItemIndex(t,e){if(t.event)return this.findEventIndex(t.event.identifier);let i=-1;t.nextEvent?i=this.findEventIndex(t.nextEvent.identifier)-1:t.previousEvent&&(i=this.findEventIndex(t.previousEvent.identifier)+1);const s=this.items;if(s)for(s[i]||(void 0===e&&(e=t.start),i=this.findItemIndexAtTime(e));i>=0&&null!=(r=s[i])&&r.event;){var r;i--}return i}findItemIndexAtTime(t,e){const i=this.items;if(i)for(let s=0;s<i.length;s++){let r=i[s];e&&"primary"!==e&&(r=r[e]);const n=r.start,a=i[s].event,o=null!=a&&a.cue.pre?a.duration:r.end;if(t===n||t>n&&t<o)return s}return-1}findJumpRestrictedIndex(t,e){const i=this.items;if(i)for(let s=t;s<=e&&i[s];s++){const t=i[s].event;if(null!=t&&t.restrictions.jump&&!t.appendInPlace)return s}return-1}findEventIndex(t){const e=this.items;if(e)for(let s=e.length;s--;){var i;if((null==(i=e[s].event)?void 0:i.identifier)===t)return s}return-1}findAssetIndex(t,e){const i=t.assetList,s=i.length;if(s>1)for(let t=0;t<s;t++){const r=i[t];if(!r.error){const i=r.timelineStart;if(e===i||e>i&&(e<i+(r.duration||0)||t===s-1))return t}}return 0}get assetIdAtEnd(){var t;const e=null==(t=this.items)||null==(t=t[this.length-1])?void 0:t.event;if(e){const t=e.assetList,i=t[t.length-1];if(i)return i.identifier}return null}parseInterstitialDateRanges(t,e,i=0){const s=t.main.details,{dateRanges:r}=s,n=this.events,a=this.parseDateRanges(r,{url:s.url},e),o=Object.keys(r),l=n?n.filter(t=>-1===o.indexOf(t.identifier)):[];a.length&&a.sort((t,e)=>{const i=t.cue.pre,s=t.cue.post,r=e.cue.pre,n=e.cue.post;if(i&&!r)return-1;if(r&&!i)return 1;if(s&&!n)return 1;if(n&&!s)return-1;if(!(i||r||s||n)){const i=t.startTime,s=e.startTime;if(i!==s)return i-s}return t.dateRange.tagOrder-e.dateRange.tagOrder}),this.events=a,l.forEach(t=>{this.removeEvent(t)}),this.updateSchedule(t,l,i)}updateSchedule(t,e=[],i=0,s=!1){const r=this.events||[];if(r.length||e.length||this.length<2){const n=this.items,a=this.parseSchedule(r,t,i);(s||e.length||(null==n?void 0:n.length)!==a.length||a.some((t,e)=>Math.abs(t.playout.start-n[e].playout.start)>.005||Math.abs(t.playout.end-n[e].playout.end)>.005))&&(this.items=a,this.onScheduleUpdate(e,n))}}parseDateRanges(t,e,i){const s=[],r=Object.keys(t);for(let n=0;n<r.length;n++){const a=r[n],o=t[a];if(o.isInterstitial){let t=this.eventMap[a];t?t.setDateRange(o):(t=new Zl(o,e),this.eventMap[a]=t,!1===i&&(t.appendInPlace=i)),s.push(t)}}return s}parseSchedule(t,e,i=0){const s=[],r=e.main.details,n=r.live?1/0:r.edge;let a=0;if((t=t.filter(t=>!(t.error||t.cue.once&&t.hasPlayed))).length){this.resolveOffsets(t,e);let l=0,h=0;if(t.forEach((e,o)=>{const d=e.cue.pre,c=e.cue.post,u=t[o-1]||null,f=e.appendInPlace,g=c?n:e.startOffset,m=e.duration,p=e.timelineOccupancy===Xl.Range?m:0,v=d&&r.live?i+(e.resumeOffset||0):0,y=v||e.resumptionOffset,E=(null==u?void 0:u.startTime)===g,T=g+e.cumulativeDuration;let S=f?T+m:g+y;if(d||!c&&g<=0){const t=h;h+=p,e.timelineStart=T;const i=a;a+=m,s.push({event:e,start:T,end:S,playout:{start:i,end:a},integrated:{start:t,end:h}})}else{if(!(g<=n))return;{if(!E){const i=g-l;if(i>nh){const r=l,n=h;h+=i;const d=a;a+=i;const c={previousEvent:t[o-1]||null,nextEvent:e,start:r,end:r+i,playout:{start:d,end:a},integrated:{start:n,end:h}};s.push(c)}else i>0&&u&&(u.cumulativeDuration+=i,s[s.length-1].end=g)}c&&(S=T),e.timelineStart=T;const i=h;h+=p;const r=a;a+=m,s.push({event:e,start:T,end:S,playout:{start:r,end:a},integrated:{start:i,end:h}})}}const b=v||e.resumeTime;l=c||b>n?n:!d&&S&&e.appendInPlaceStarted&&b-S>nh?S:b}),l<n){var o;const t=l,e=h,i=n-l;h+=i;const r=a;a+=i,s.push({previousEvent:(null==(o=s[s.length-1])?void 0:o.event)||null,nextEvent:null,start:l,end:t+i,playout:{start:r,end:a},integrated:{start:e,end:h}})}this.setDurations(n,a,h)}else{const t=0;s.push({previousEvent:null,nextEvent:null,start:t,end:n,playout:{start:t,end:n},integrated:{start:t,end:n}}),this.setDurations(n,n,n)}return s}setDurations(t,e,i){this.durations={primary:t,playout:e,integrated:i}}resolveOffsets(t,i){const s=i.main.details,r=s.live?1/0:s.edge;let n=0,a=-1;t.forEach((o,l)=>{const h=o.cue.pre,d=o.cue.post,c=h?0:d?r:o.startTime;this.updateAssetDurations(o);if(a===c?o.cumulativeDuration=n:(n=0,a=c),!d&&o.snapOptions.in&&(o.resumeAnchor=Je(null,s.fragments,o.startOffset+o.resumptionOffset,0,0)||void 0),o.appendInPlace&&!o.appendInPlaceStarted){this.primaryCanResumeInPlaceAt(o,i)||(o.appendInPlace=!1)}if(!o.appendInPlace&&l+1<t.length){t[l+1].startTime-t[l].resumeTime<nh&&(t[l+1].appendInPlace=!1,t[l+1].appendInPlace&&this.warn(`Could not change append strategy for abutting event ${o}`))}const u=e(o.resumeOffset)?o.resumeOffset:o.duration;n+=u})}primaryCanResumeInPlaceAt(t,e){const i=t.resumeTime,s=t.startTime+t.resumptionOffset;if(Math.abs(i-s)>zl)return this.log(`"${t.identifier}" resumption ${i} not aligned with estimated timeline end ${s}`),!1;return!Object.keys(e).some(s=>{const r=e[s].details,n=r.edge;if(i>=n)return this.log(`"${t.identifier}" resumption ${i} past ${s} playlist end ${n}`),!1;const a=Je(null,r.fragments,i);if(!a)return this.log(`"${t.identifier}" resumption ${i} does not align with any fragments in ${s} playlist (${r.fragStart}-${r.fragmentEnd})`),!0;const o="audio"===s?.175:0;return!(Math.abs(a.start-i)<zl+o||Math.abs(a.end-i)<zl+o)&&(this.log(`"${t.identifier}" resumption ${i} not aligned with ${s} fragment bounds (${a.start}-${a.end} sn: ${a.sn} cc: ${a.cc})`),!0)})}updateAssetDurations(t){if(!t.assetListLoaded)return;const e=t.timelineStart;let i=0,s=!1,r=!1;for(let n=0;n<t.assetList.length;n++){const a=t.assetList[n],o=e+i;a.startOffset=i,a.timelineStart=o,s||(s=null===a.duration),r||(r=!!a.error);i+=a.error?0:a.duration||0}t.duration=s&&!r?Math.max(i,t.duration):i}removeEvent(t){t.reset(),delete this.eventMap[t.identifier]}}function oh(t){return`[${t.event?'"'+t.event.identifier+'"':"primary"}: ${t.start.toFixed(2)}-${t.end.toFixed(2)}]`}class lh{constructor(t){this.hls=void 0,this.hls=t}destroy(){this.hls=null}loadAssetList(t,e){const i=t.assetListUrl;let s;try{s=eh(i,this.hls.sessionId,t.baseUrl)}catch(e){const s=this.assignAssetListError(t,n.ASSET_LIST_LOAD_ERROR,e,i);return void this.hls.trigger(a.ERROR,s)}e&&"data:"!==s.protocol&&De(s,"_HLS_start_offset",""+e);const r=this.hls.config,o=new(0,r.loader)(r),l={type:u.INTERSTITIAL_ASSET_LIST,responseType:"json",url:s.href},h=r.interstitialAssetListLoadPolicy.default,d={loadPolicy:h,timeout:h.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},c={onSuccess:(e,i,s,r)=>{const o=e.data,l=null==o?void 0:o.ASSETS;if(!Array.isArray(l)){const e=this.assignAssetListError(t,n.ASSET_LIST_PARSING_ERROR,new Error("Invalid interstitial asset list"),s.url,i,r);return void this.hls.trigger(a.ERROR,e)}t.assetListResponse=o,this.hls.trigger(a.ASSET_LIST_LOADED,{event:t,assetListResponse:o,networkDetails:r})},onError:(e,i,s,r)=>{const o=this.assignAssetListError(t,n.ASSET_LIST_LOAD_ERROR,new Error(`Error loading X-ASSET-LIST: HTTP status ${e.code} ${e.text} (${i.url})`),i.url,r,s);this.hls.trigger(a.ERROR,o)},onTimeout:(e,i,s)=>{const r=this.assignAssetListError(t,n.ASSET_LIST_LOAD_TIMEOUT,new Error(`Timeout loading X-ASSET-LIST (${i.url})`),i.url,e,s);this.hls.trigger(a.ERROR,r)}};return o.load(l,d,c),this.hls.trigger(a.ASSET_LIST_LOADING,{event:t}),o}assignAssetListError(t,e,i,s,n,a){return t.error=i,{type:r.NETWORK_ERROR,details:e,fatal:!1,interstitial:t,url:s,error:i,networkDetails:a,stats:n}}}function hh(t){var e;null==t||null==(e=t.play())||e.catch(()=>{})}function dh(t,e){return`[${t}] Advancing timeline position to ${e}`}class ch{constructor(t){this.buffered=void 0;const e=(e,i,s)=>{if((i>>>=0)>s-1)throw new DOMException(`Failed to execute '${e}' on 'TimeRanges': The index provided (${i}) is greater than the maximum bound (${s})`);return t[i][e]};this.buffered={get length(){return t.length},end:i=>e("end",i,t.length),start:i=>e("start",i,t.length)}}}const uh={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},fh=t=>String.fromCharCode(uh[t]||t),gh=15,mh=42,ph={17:1,18:3,21:5,22:7,23:9,16:11,19:12,20:14},vh={17:2,18:4,21:6,22:8,23:10,19:13,20:15},yh={25:1,26:3,29:5,30:7,31:9,24:11,27:12,28:14},Eh={25:2,26:4,29:6,30:8,31:10,27:13,28:15},Th=["white","green","blue","cyan","red","yellow","magenta","black","transparent"];class Sh{constructor(){this.time=null,this.verboseLevel=0}log(t,e){if(this.verboseLevel>=t){const i="function"==typeof e?e():e;q.log(`${this.time} [${t}] ${i}`)}}}const bh=function(t){const e=[];for(let i=0;i<t.length;i++)e.push(t[i].toString(16));return e},Ah=Object.freeze({foreground:"white",underline:!1,italics:!1,background:"black",flash:!1});class Lh{constructor(){this.styles=Ah}get foreground(){return this.styles.foreground}set foreground(t){const e=this.styles;this.styles={foreground:t,underline:e.underline,italics:e.italics,background:e.background,flash:e.flash}}get underline(){return this.styles.underline}set underline(t){const e=this.styles;this.styles={foreground:e.foreground,underline:t,italics:e.italics,background:e.background,flash:e.flash}}get italics(){return this.styles.italics}set italics(t){const e=this.styles;this.styles={foreground:e.foreground,underline:e.underline,italics:t,background:e.background,flash:e.flash}}get background(){return this.styles.background}set background(t){const e=this.styles;this.styles={foreground:e.foreground,underline:e.underline,italics:e.italics,background:t,flash:e.flash}}get flash(){return this.styles.flash}set flash(t){const e=this.styles;this.styles={foreground:e.foreground,underline:e.underline,italics:e.italics,background:e.background,flash:t}}reset(){this.styles=Ah}setStyles(t){const e=this.styles,i=Object.prototype.hasOwnProperty;this.styles={foreground:i.call(t,"foreground")?t.foreground:e.foreground,underline:i.call(t,"underline")?t.underline:e.underline,italics:i.call(t,"italics")?t.italics:e.italics,background:i.call(t,"background")?t.background:e.background,flash:i.call(t,"flash")?t.flash:e.flash}}toString(){return"color="+this.foreground+", underline="+this.underline+", italics="+this.italics+", background="+this.background+", flash="+this.flash}}class Ih{constructor(){this.uchar=" ",this.penState=new Lh}reset(){this.uchar=" ",this.penState.reset()}setChar(t,e){this.uchar=t,this.penState.styles=e.styles}setPenState(t){this.penState.styles=t.styles}copy(t){this.uchar=t.uchar,this.penState.styles=t.penState.styles}}class Rh{constructor(t){this.chars=[],this.pos=0,this.currPenState=new Lh,this.cueStartTime=null,this.logger=void 0;for(let t=0;t<mh;t++)this.chars.push(new Ih);this.logger=t}equals(t){const e=this.chars,i=t.chars;for(let t=0;t<mh;t++){const s=e[t],r=i[t];if(s.uchar!==r.uchar)return!1;const n=s.penState.styles,a=r.penState.styles;if(n!==a&&(n.foreground!==a.foreground||n.underline!==a.underline||n.italics!==a.italics||n.background!==a.background||n.flash!==a.flash))return!1}return!0}copy(t){for(let e=0;e<mh;e++)this.chars[e].copy(t.chars[e])}isEmpty(){const t=this.chars;for(let e=0;e<mh;e++){const i=t[e];if(" "!==i.uchar)return!1;const s=i.penState.styles;if(s!==Ah&&("white"!==s.foreground||s.underline||s.italics||"black"!==s.background||s.flash))return!1}return!0}setCursor(t){this.pos!==t&&(this.pos=t),this.pos<0?(this.logger.log(3,"Negative cursor position "+this.pos),this.pos=0):this.pos>=mh&&(this.logger.log(3,"Too large cursor position "+this.pos),this.pos=41)}moveCursor(t){const e=Math.min(this.pos+t,mh);if(t>1)for(let t=this.pos+1;t<e;t++)this.chars[t].setPenState(this.currPenState);this.setCursor(e)}backSpace(){this.moveCursor(-1),this.chars[this.pos].setChar(" ",this.currPenState)}insertChar(t){t>=144&&this.backSpace();const e=fh(t);this.pos>=mh?this.logger.log(0,()=>"Cannot insert "+t.toString(16)+" ("+e+") at position "+this.pos+". Skipping it!"):(this.chars[this.pos].setChar(e,this.currPenState),this.moveCursor(1))}clearFromPos(t){let e;for(e=t;e<mh;e++)this.chars[e].reset()}clear(){this.clearFromPos(0),this.pos=0,this.currPenState.reset()}clearToEndOfRow(){this.clearFromPos(this.pos)}getTextString(){const t=[];let e=!0;for(let i=0;i<mh;i++){const s=this.chars[i].uchar;" "!==s&&(e=!1),t.push(s)}return e?"":t.join("")}setPenStyles(t){this.currPenState.setStyles(t);this.chars[this.pos].setPenState(this.currPenState)}}class kh{constructor(t){this.rows=[],this.currRow=14,this.nrRollUpRows=null,this.lastOutputScreen=null,this.logger=void 0;for(let e=0;e<gh;e++)this.rows.push(new Rh(t));this.logger=t}reset(){for(let t=0;t<gh;t++)this.rows[t].clear();this.currRow=14}equals(t){let e=!0;for(let i=0;i<gh;i++)if(!this.rows[i].equals(t.rows[i])){e=!1;break}return e}copy(t){for(let e=0;e<gh;e++){const i=this.rows[e].chars,s=t.rows[e].chars;for(let t=0;t<mh;t++){const e=i[t],r=s[t];e.uchar=r.uchar,e.penState.styles=r.penState.styles}}}isEmpty(){let t=!0;for(let e=0;e<gh;e++)if(!this.rows[e].isEmpty()){t=!1;break}return t}backSpace(){this.rows[this.currRow].backSpace()}clearToEndOfRow(){this.rows[this.currRow].clearToEndOfRow()}insertChar(t){this.rows[this.currRow].insertChar(t)}setPen(t){this.rows[this.currRow].setPenStyles(t)}moveCursor(t){this.rows[this.currRow].moveCursor(t)}setCursor(t){this.logger.log(2,"setCursor: "+t);this.rows[this.currRow].setCursor(t)}setPAC(t){this.logger.log(2,()=>"pacData = "+Ue(t));let e=t.row-1;if(this.nrRollUpRows&&e<this.nrRollUpRows-1&&(e=this.nrRollUpRows-1),this.nrRollUpRows&&this.currRow!==e){for(let t=0;t<gh;t++)this.rows[t].clear();const t=this.currRow+1-this.nrRollUpRows,i=this.lastOutputScreen;if(i){const s=i.rows[t].cueStartTime,r=this.logger.time;if(null!==s&&null!==r&&s<r)for(let s=0;s<this.nrRollUpRows;s++)this.rows[e-this.nrRollUpRows+s+1].copy(i.rows[t+s])}}this.currRow=e;const i=this.rows[this.currRow];if(null!==t.indent){const e=t.indent,s=Math.max(e-1,0);i.setCursor(t.indent),t.color=i.chars[s].penState.foreground}const s={foreground:t.color,underline:t.underline,italics:t.italics,background:"black",flash:!1};this.setPen(s)}setBkgData(t){this.logger.log(2,()=>"bkgData = "+Ue(t)),this.backSpace(),this.setPen(t),this.insertChar(32)}setRollUpRows(t){this.nrRollUpRows=t}rollUp(){if(null===this.nrRollUpRows)return void this.logger.log(3,"roll_up but nrRollUpRows not set yet");this.logger.log(1,()=>this.getDisplayText());const t=this.currRow+1-this.nrRollUpRows,e=this.rows.splice(t,1)[0];e.clear(),this.rows.splice(this.currRow,0,e),this.logger.log(2,"Rolling up")}getDisplayText(t){t=t||!1;const e=[];let i="",s=-1;for(let i=0;i<gh;i++){const r=this.rows[i].getTextString();r&&(s=i+1,t?e.push("Row "+s+": '"+r+"'"):e.push(r.trim()))}return e.length>0&&(i=t?"["+e.join(" | ")+"]":e.join("\n")),i}getTextAndFormat(){return this.rows}}class _h{constructor(t,e,i){this.chNr=void 0,this.outputFilter=void 0,this.mode=void 0,this.verbose=void 0,this.displayedMemory=void 0,this.nonDisplayedMemory=void 0,this.lastOutputScreen=void 0,this.currRollUpRow=void 0,this.writeScreen=void 0,this.cueStartTime=void 0,this.logger=void 0,this.chNr=t,this.outputFilter=e,this.mode=null,this.verbose=0,this.displayedMemory=new kh(i),this.nonDisplayedMemory=new kh(i),this.lastOutputScreen=new kh(i),this.currRollUpRow=this.displayedMemory.rows[14],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null,this.logger=i}reset(){this.mode=null,this.displayedMemory.reset(),this.nonDisplayedMemory.reset(),this.lastOutputScreen.reset(),this.outputFilter.reset(),this.currRollUpRow=this.displayedMemory.rows[14],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null}getHandler(){return this.outputFilter}setHandler(t){this.outputFilter=t}setPAC(t){this.writeScreen.setPAC(t)}setBkgData(t){this.writeScreen.setBkgData(t)}setMode(t){t!==this.mode&&(this.mode=t,this.logger.log(2,()=>"MODE="+t),"MODE_POP-ON"===this.mode?this.writeScreen=this.nonDisplayedMemory:(this.writeScreen=this.displayedMemory,this.writeScreen.reset()),"MODE_ROLL-UP"!==this.mode&&(this.displayedMemory.nrRollUpRows=null,this.nonDisplayedMemory.nrRollUpRows=null),this.mode=t)}insertChars(t){for(let e=0;e<t.length;e++)this.writeScreen.insertChar(t[e]);const e=this.writeScreen===this.displayedMemory?"DISP":"NON_DISP";this.logger.log(2,()=>e+": "+this.writeScreen.getDisplayText(!0)),"MODE_PAINT-ON"!==this.mode&&"MODE_ROLL-UP"!==this.mode||(this.logger.log(1,()=>"DISPLAYED: "+this.displayedMemory.getDisplayText(!0)),this.outputDataUpdate())}ccRCL(){this.logger.log(2,"RCL - Resume Caption Loading"),this.setMode("MODE_POP-ON")}ccBS(){this.logger.log(2,"BS - BackSpace"),"MODE_TEXT"!==this.mode&&(this.writeScreen.backSpace(),this.writeScreen===this.displayedMemory&&this.outputDataUpdate())}ccAOF(){}ccAON(){}ccDER(){this.logger.log(2,"DER- Delete to End of Row"),this.writeScreen.clearToEndOfRow(),this.outputDataUpdate()}ccRU(t){this.logger.log(2,"RU("+t+") - Roll Up"),this.writeScreen=this.displayedMemory,this.setMode("MODE_ROLL-UP"),this.writeScreen.setRollUpRows(t)}ccFON(){this.logger.log(2,"FON - Flash On"),this.writeScreen.setPen({flash:!0})}ccRDC(){this.logger.log(2,"RDC - Resume Direct Captioning"),this.setMode("MODE_PAINT-ON")}ccTR(){this.logger.log(2,"TR"),this.setMode("MODE_TEXT")}ccRTD(){this.logger.log(2,"RTD"),this.setMode("MODE_TEXT")}ccEDM(){this.logger.log(2,"EDM - Erase Displayed Memory"),this.displayedMemory.reset(),this.outputDataUpdate(!0)}ccCR(){this.logger.log(2,"CR - Carriage Return"),this.writeScreen.rollUp(),this.outputDataUpdate(!0)}ccENM(){this.logger.log(2,"ENM - Erase Non-displayed Memory"),this.nonDisplayedMemory.reset()}ccEOC(){if(this.logger.log(2,"EOC - End Of Caption"),"MODE_POP-ON"===this.mode){const t=this.displayedMemory;this.displayedMemory=this.nonDisplayedMemory,this.nonDisplayedMemory=t,this.writeScreen=this.nonDisplayedMemory,this.logger.log(1,()=>"DISP: "+this.displayedMemory.getDisplayText())}this.outputDataUpdate(!0)}ccTO(t){this.logger.log(2,"TO("+t+") - Tab Offset"),this.writeScreen.moveCursor(t)}ccMIDROW(t){const e={flash:!1};if(e.underline=t%2==1,e.italics=t>=46,e.italics)e.foreground="white";else{const i=Math.floor(t/2)-16,s=["white","green","blue","cyan","red","yellow","magenta"];e.foreground=s[i]}this.logger.log(2,"MIDROW: "+Ue(e)),this.writeScreen.setPen(e)}outputDataUpdate(t=!1){const e=this.logger.time;null!==e&&this.outputFilter&&(null!==this.cueStartTime||this.displayedMemory.isEmpty()?this.displayedMemory.equals(this.lastOutputScreen)||(this.outputFilter.newCue(this.cueStartTime,e,this.lastOutputScreen),t&&this.outputFilter.dispatchCue&&this.outputFilter.dispatchCue(),this.cueStartTime=this.displayedMemory.isEmpty()?null:e):this.cueStartTime=e,this.lastOutputScreen.copy(this.displayedMemory))}cueSplitAtTime(t){this.outputFilter&&(this.displayedMemory.isEmpty()||(this.outputFilter.newCue&&this.outputFilter.newCue(this.cueStartTime,t,this.displayedMemory),this.cueStartTime=t))}}class Dh{constructor(t,e,i){this.channels=[null,null,null],this.currentChannel=0,this.cmdHistory={a:null,b:null},this.logger=void 0,this.field=void 0,this.outputFilters=void 0,this.logger=new Sh,this.field=t,this.outputFilters=[null,e,i]}getHandler(t){return this.outputFilters[t]}setHandler(t,e){var i;this.outputFilters[t]=e,null==(i=this.channels[t])||i.setHandler(e)}getChannel(t){let e=this.channels[t];return e||(e=this.channels[t]=new _h(this.field+t-1,this.outputFilters[t],this.logger)),e}addData(t,e){this.logger.time=t;for(let t=0;t<e.length;t+=2){const i=127&e[t],s=127&e[t+1];let r=!1,n=null;if(0===i&&0===s)continue;this.logger.log(3,()=>"["+bh([e[t],e[t+1]])+"] -> ("+bh([i,s])+")");const a=this.cmdHistory;if(i>=16&&i<=31){if(Ph(i,s,a)){wh(null,null,a),this.logger.log(3,()=>"Repeated command ("+bh([i,s])+") is dropped");continue}wh(i,s,this.cmdHistory),r=this.parseCmd(i,s),r||(r=this.parseMidrow(i,s)),r||(r=this.parsePAC(i,s)),r||(r=this.parseBackgroundAttributes(i,s))}else wh(null,null,a);if(!r&&(n=this.parseChars(i,s),n)){const t=this.currentChannel;if(t&&t>0){this.getChannel(t).insertChars(n)}else this.logger.log(2,"No channel found yet. TEXT-MODE?")}r||n||this.logger.log(2,()=>"Couldn't parse cleaned data "+bh([i,s])+" orig: "+bh([e[t],e[t+1]]))}}parseCmd(t,e){if(!((20===t||28===t||21===t||29===t)&&e>=32&&e<=47)&&!((23===t||31===t)&&e>=33&&e<=35))return!1;const i=20===t||21===t||23===t?1:2,s=this.getChannel(i);return 20===t||21===t||28===t||29===t?32===e?s.ccRCL():33===e?s.ccBS():34===e?s.ccAOF():35===e?s.ccAON():36===e?s.ccDER():37===e?s.ccRU(2):38===e?s.ccRU(3):39===e?s.ccRU(4):40===e?s.ccFON():41===e?s.ccRDC():42===e?s.ccTR():43===e?s.ccRTD():44===e?s.ccEDM():45===e?s.ccCR():46===e?s.ccENM():47===e&&s.ccEOC():s.ccTO(e-32),this.currentChannel=i,!0}parseMidrow(t,e){let i=0;if((17===t||25===t)&&e>=32&&e<=47){if(i=17===t?1:2,i!==this.currentChannel)return this.logger.log(0,"Mismatch channel in midrow parsing"),!1;const s=this.channels[i];return!!s&&(s.ccMIDROW(e),this.logger.log(3,()=>"MIDROW ("+bh([t,e])+")"),!0)}return!1}parsePAC(t,e){let i;if(!((t>=17&&t<=23||t>=25&&t<=31)&&e>=64&&e<=127)&&!((16===t||24===t)&&e>=64&&e<=95))return!1;const s=t<=23?1:2;i=e>=64&&e<=95?1===s?ph[t]:yh[t]:1===s?vh[t]:Eh[t];return this.getChannel(s).setPAC(this.interpretPAC(i,e)),this.currentChannel=s,!0}interpretPAC(t,e){let i;const s={color:null,italics:!1,indent:null,underline:!1,row:t};return i=e>95?e-96:e-64,s.underline=!(1&~i),i<=13?s.color=["white","green","blue","cyan","red","yellow","magenta","white"][Math.floor(i/2)]:i<=15?(s.italics=!0,s.color="white"):s.indent=4*Math.floor((i-16)/2),s}parseChars(t,e){let i,s=null,r=null;if(t>=25?(i=2,r=t-8):(i=1,r=t),r>=17&&r<=19){let t;t=17===r?e+80:18===r?e+112:e+144,this.logger.log(2,()=>"Special char '"+fh(t)+"' in channel "+i),s=[t]}else t>=32&&t<=127&&(s=0===e?[t]:[t,e]);return s&&this.logger.log(3,()=>"Char codes = "+bh(s).join(",")),s}parseBackgroundAttributes(t,e){if(!((16===t||24===t)&&e>=32&&e<=47)&&!((23===t||31===t)&&e>=45&&e<=47))return!1;let i;const s={};16===t||24===t?(i=Math.floor((e-32)/2),s.background=Th[i],e%2==1&&(s.background=s.background+"_semi")):45===e?s.background="transparent":(s.foreground="black",47===e&&(s.underline=!0));const r=t<=23?1:2;return this.getChannel(r).setBkgData(s),!0}reset(){for(let t=0;t<Object.keys(this.channels).length;t++){const e=this.channels[t];e&&e.reset()}wh(null,null,this.cmdHistory)}cueSplitAtTime(t){for(let e=0;e<this.channels.length;e++){const i=this.channels[e];i&&i.cueSplitAtTime(t)}}}function wh(t,e,i){i.a=t,i.b=e}function Ph(t,e,i){return i.a===t&&i.b===e}class Ch{constructor(t,e){this.timelineController=void 0,this.cueRanges=[],this.trackName=void 0,this.startTime=null,this.endTime=null,this.screen=null,this.timelineController=t,this.trackName=e}dispatchCue(){null!==this.startTime&&(this.timelineController.addCues(this.trackName,this.startTime,this.endTime,this.screen,this.cueRanges),this.startTime=null)}newCue(t,e,i){(null===this.startTime||this.startTime>t)&&(this.startTime=t),this.endTime=e,this.screen=i,this.timelineController.createCaptionsTrack(this.trackName)}reset(){this.cueRanges=[],this.startTime=null}}function xh(t,e,i,s){return Math.min(e,s)-Math.max(t,i)}const Mh=/\s/,Oh={newCue(t,e,i,s){const r=[];let n,a,o,l,h;const d=self.VTTCue||self.TextTrackCue;for(let u=0;u<s.rows.length;u++)if(n=s.rows[u],o=!0,l=0,h="",!n.isEmpty()){var c;for(let t=0;t<n.chars.length;t++)Mh.test(n.chars[t].uchar)&&o?l++:(h+=n.chars[t].uchar,o=!1);n.cueStartTime=e,e===i&&(i+=1e-4),l>=16?l--:l++;const s=ll(h.trim()),f=fl(e,i,s);null!=t&&null!=(c=t.cues)&&c.getCueById(f)||(a=new d(e,i,s),a.id=f,a.line=u+1,a.align="left",a.position=10+Math.min(80,10*Math.floor(8*l/32)),r.push(a))}return t&&r.length&&(r.sort((t,e)=>"auto"===t.line||"auto"===e.line?0:t.line>8&&e.line>8?e.line-t.line:t.line-e.line),r.forEach(e=>_l(t,e))),r}};class Fh{constructor(){this.requestTimeout=void 0,this.retryTimeout=void 0,this.retryDelay=0,this.config=null,this.callbacks=null,this.context=null,this.stats=new c}destroy(){this.callbacks=this.context=this.config=null,this.abortInternal(),this.stats=null}load(t,e,i){const s=this.stats;if(s.loading.start)throw new Error("Loader can only be used once.");s.loading.start=self.performance.now(),this.context=t,this.config=e,this.callbacks=i,this.loadInternal()}abort(){var t;this.abortInternal(),null!=(t=this.callbacks)&&t.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.getNetworkDetails())}loadtimeout(){if(!this.config)return;const t=this.config.loadPolicy.timeoutRetry;if(O(t,this.stats.retry,!0))this.retry(t);else{var e;q.warn(`timeout while loading ${null==(e=this.context)?void 0:e.url}`);const t=this.callbacks;t&&(this.abortInternal(),t.onTimeout(this.stats,this.context,this.getNetworkDetails()))}}retry(t){const{context:e,stats:i}=this;this.retryDelay=x(t,i.retry),i.retry++,q.warn(`${status?"HTTP Status "+status:"Timeout"} while loading ${null==e?void 0:e.url}, retrying ${i.retry}/${t.maxNumRetry} in ${this.retryDelay}ms`),this.abortInternal(),this.resetInternalLoader(),self.clearTimeout(this.retryTimeout),this.retryTimeout=self.setTimeout(()=>this.loadInternal(),this.retryDelay)}}const Nh=/(\d+)-(\d+)\/(\d+)/;class $h extends Fh{constructor(t){super(),this.fetchSetup=void 0,this.request=null,this.response=null,this.controller=null,this.fetchSetup=t.fetchSetup||Bh}destroy(){this.request=null,super.destroy(),this.response=null,this.controller=null,this.fetchSetup=null}abortInternal(){self.clearTimeout(this.retryTimeout),this.controller&&!this.stats.loading.end&&(this.stats.aborted=!0,this.controller.abort())}getNetworkDetails(){return this.response}resetInternalLoader(){this.response=null}loadInternal(){const{config:t,context:i,stats:s}=this;if(!t||!i)return;s.loading.first=0,s.loaded=0,s.aborted=!1,this.controller=new self.AbortController;const r=function(t,e){const i={method:"GET",mode:"cors",credentials:"same-origin",signal:e,headers:new self.Headers(I({},t.headers))};t.rangeEnd&&i.headers.set("Range","bytes="+t.rangeStart+"-"+String(t.rangeEnd-1));return i}(i,this.controller.signal),n="arraybuffer"===i.responseType,a=n?"byteLength":"length",{maxTimeToFirstByteMs:o,maxLoadTimeMs:l}=t.loadPolicy;this.request=this.fetchSetup(i,r),self.clearTimeout(this.requestTimeout),t.timeout=o&&e(o)?o:l,this.requestTimeout=self.setTimeout(()=>{this.loadtimeout()},t.timeout);(Zn(this.request)?this.request.then(self.fetch):self.fetch(this.request)).then(r=>{var a;this.response=r;const o=Math.max(self.performance.now(),s.loading.start);if(self.clearTimeout(this.requestTimeout),t.timeout=l,this.requestTimeout=self.setTimeout(()=>{this.loadtimeout()},l-(o-s.loading.start)),!r.ok){const{status:t,statusText:e}=r;throw new Uh(e||"fetch, bad network response",t,r)}s.loading.first=o,s.total=function(t){const i=t.get("Content-Range");if(i){const t=function(t){const e=Nh.exec(t);if(e)return parseInt(e[2])-parseInt(e[1])+1}(i);if(e(t))return t}const s=t.get("Content-Length");if(s)return parseInt(s)}(r.headers)||s.total;const h=null==(a=this.callbacks)?void 0:a.onProgress;return h&&e(t.highWaterMark)?this.loadProgressively(r,s,i,t.highWaterMark,h):n?r.arrayBuffer():"json"===i.responseType?r.json():r.text()}).then(r=>{var n,o;const l=this.response;if(!l)throw new Error("loader destroyed");self.clearTimeout(this.requestTimeout),s.loading.end=Math.max(self.performance.now(),s.loading.first);const h=r[a];h&&(s.loaded=s.total=h);const d={url:l.url,data:r,code:l.status},c=null==(n=this.callbacks)?void 0:n.onProgress;c&&!e(t.highWaterMark)&&c(s,i,r,l),null==(o=this.callbacks)||o.onSuccess(d,s,i,l)}).catch(e=>{if(self.clearTimeout(this.requestTimeout),s.aborted)return;const r=e&&e.code||0,n=e?e.message:null,a=t.loadPolicy.errorRetry;var o;O(a,s.retry,!1,{url:i.url,data:void 0,code:r})?this.retry(a):(q.error(`${r} while loading ${i.url}`),null==(o=this.callbacks)||o.onError({code:r,text:n},i,e?e.details:null,s))})}getCacheAge(){let t=null;if(this.response){const e=this.response.headers.get("age");t=e?parseFloat(e):null}return t}getResponseHeader(t){return this.response?this.response.headers.get(t):null}loadProgressively(t,e,i,s=0,r){const n=new Pr,a=t.body.getReader(),o=()=>a.read().then(a=>{if(a.done)return n.dataLength&&r(e,i,n.flush().buffer,t),Promise.resolve(new ArrayBuffer(0));const l=a.value,h=l.length;return e.loaded+=h,h<s||n.dataLength?(n.push(l),n.dataLength>=s&&r(e,i,n.flush().buffer,t)):r(e,i,l.buffer,t),o()}).catch(()=>Promise.reject());return o()}}function Bh(t,e){return new self.Request(t.url,e)}class Uh extends Error{constructor(t,e,i){super(t),this.code=void 0,this.details=void 0,this.code=e,this.details=i}}const Gh=/^age:\s*[\d.]+\s*$/im;class Kh extends Fh{constructor(t){super(),this.xhrSetup=void 0,this.loader=null,this.xhrSetup=t.xhrSetup||null}destroy(){super.destroy(),this.loader=null,this.xhrSetup=null}abortInternal(){const t=this.loader;self.clearTimeout(this.requestTimeout),self.clearTimeout(this.retryTimeout),t&&(t.onreadystatechange=null,t.onprogress=null,4!==t.readyState&&(this.stats.aborted=!0,t.abort()))}getNetworkDetails(){return this.loader}resetInternalLoader(){this.loader=null}loadInternal(){const{config:t,context:e}=this;if(!t||!e)return;const i=this.loader=new self.XMLHttpRequest,s=this.stats;s.loading.first=0,s.loaded=0,s.aborted=!1;const r=this.xhrSetup;r?Promise.resolve().then(()=>{if(this.loader===i&&!this.stats.aborted)return r.call(this,i,e.url,e)}).catch(t=>{if(this.loader===i&&!this.stats.aborted)return i.open("GET",e.url,!0),r.call(this,i,e.url,e)}).then(()=>{this.loader!==i||this.stats.aborted||this.openAndSendXhr(i,e,t)}).catch(t=>{var r;null==(r=this.callbacks)||r.onError({code:i.status,text:t.message},e,i,s)}):this.openAndSendXhr(i,e,t)}openAndSendXhr(t,i,s){t.readyState||t.open("GET",i.url,!0);const r=i.headers,{maxTimeToFirstByteMs:n,maxLoadTimeMs:a}=s.loadPolicy;if(r)for(const e in r)t.setRequestHeader(e,r[e]);i.rangeEnd&&t.setRequestHeader("Range",`bytes=${i.rangeStart}-${i.rangeEnd-1}`),t.onreadystatechange=this.readystatechange.bind(this),t.onprogress=this.loadprogress.bind(this),t.responseType=i.responseType,self.clearTimeout(this.requestTimeout),s.timeout=n&&e(n)?n:a,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),s.timeout),t.send()}readystatechange(){const{context:t,loader:e,stats:i}=this;if(!t||!e)return;const s=e.readyState,r=this.config;if(!i.aborted&&s>=2&&(0===i.loading.first&&(i.loading.first=Math.max(self.performance.now(),i.loading.start),r.timeout!==r.loadPolicy.maxLoadTimeMs&&(self.clearTimeout(this.requestTimeout),r.timeout=r.loadPolicy.maxLoadTimeMs,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),r.loadPolicy.maxLoadTimeMs-(i.loading.first-i.loading.start)))),4===s)){self.clearTimeout(this.requestTimeout),e.onreadystatechange=null,e.onprogress=null;const s=e.status,l="text"===e.responseType?e.responseText:null;if(s>=200&&s<300){const r=null!=l?l:e.response;if(null!=r){var n,a;i.loading.end=Math.max(self.performance.now(),i.loading.first);const o="arraybuffer"===e.responseType?r.byteLength:r.length;i.loaded=i.total=o,i.bwEstimate=8e3*i.total/(i.loading.end-i.loading.first);const l=null==(n=this.callbacks)?void 0:n.onProgress;l&&l(i,t,r,e);const h={url:e.responseURL,data:r,code:s};return t.rangeEnd&&o!==t.rangeEnd-t.rangeStart&&q.warn(`Payload length ${o} does not match requested Range: bytes=${t.rangeStart}-${t.rangeEnd-1}`),void(null==(a=this.callbacks)||a.onSuccess(h,i,t,e))}}const h=r.loadPolicy.errorRetry;var o;if(O(h,i.retry,!1,{url:t.url,data:void 0,code:s}))this.retry(h);else q.error(`${s} while loading ${t.url}`),null==(o=this.callbacks)||o.onError({code:s,text:e.statusText},t,e,i)}}loadprogress(t){const e=this.stats;e.loaded=t.loaded,t.lengthComputable&&(e.total=t.total)}getCacheAge(){let t=null;if(this.loader&&Gh.test(this.loader.getAllResponseHeaders())){const e=this.loader.getResponseHeader("age");t=e?parseFloat(e):null}return t}getResponseHeader(t){return this.loader&&new RegExp(`^${t}:\\s*[\\d.]+\\s*$`,"im").test(this.loader.getAllResponseHeaders())?this.loader.getResponseHeader(t):null}}const Vh=k(k({autoStartLoad:!0,startPosition:-1,defaultAudioCodec:void 0,debug:!1,capLevelOnFPSDrop:!1,capLevelToPlayerSize:!1,ignoreDevicePixelRatio:!1,maxDevicePixelRatio:Number.POSITIVE_INFINITY,preferManagedMediaSource:!1,initialLiveManifestSize:1,maxBufferLength:30,backBufferLength:1/0,frontBufferFlushThreshold:1/0,loopBackBufferFlush:void 0,startOnSegmentBoundary:!1,nextAudioTrackBufferFlushForwardOffset:.25,maxBufferSize:6e7,maxFragLookUpTolerance:.25,maxBufferHole:.1,detectStallWithCurrentTimeMs:1250,highBufferWatchdogPeriod:2,nudgeOffset:.1,nudgeMaxRetry:3,nudgeOnVideoHole:!0,skipBufferHolePadding:.1,liveSyncMode:"edge",liveSyncDurationCount:3,liveSyncOnStallIncrease:1,liveMaxLatencyDurationCount:1/0,liveMaxUnchangedPlaylistRefresh:1/0,liveSyncDuration:void 0,liveMaxLatencyDuration:void 0,maxLiveSyncPlaybackRate:1,liveDurationInfinity:!1,liveBackBufferLength:null,maxMaxBufferLength:600,enableWorker:!0,workerPath:null,enableSoftwareAES:!0,startLevel:void 0,startFragPrefetch:!1,fpsDroppedMonitoringPeriod:5e3,fpsDroppedMonitoringThreshold:.2,appendErrorMaxRetry:3,appendTimeout:1/0,ignorePlaylistParsingErrors:!1,loader:Kh,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,licenseXhrSetup:void 0,licenseResponseCallback:void 0,stretchShortVideoTrack:!1,maxAudioFramesDrift:1,forceKeyFrameOnDiscontinuity:!0,handleMpegTsVideoIntegrityErrors:"process",abrEwmaFastLive:3,abrEwmaSlowLive:9,abrEwmaFastVoD:3,abrEwmaSlowVoD:9,abrEwmaDefaultEstimate:5e5,abrEwmaDefaultEstimateMax:5e6,abrBandWidthFactor:.95,abrBandWidthUpFactor:.7,abrMaxWithRealBitrate:!1,abrSwitchInterval:0,maxStarvationDelay:4,maxLoadingDelay:4,minAutoBitrate:0,emeEnabled:!1,widevineLicenseUrl:void 0,drmSystems:{},drmSystemOptions:{},requestMediaKeySystemAccessFunc:Ds,requireKeySystemAccessOnStart:!1,reuseKeySessions:!1,testBandwidth:!0,progressive:!1,lowLatencyMode:!0,cmcd:void 0,enableDateRangeMetadataCues:!0,enableEmsgMetadataCues:!0,enableEmsgKLVMetadata:!1,enableID3MetadataCues:!0,emsgKLVSchemaUri:void 0,enableInterstitialPlayback:!0,interstitialAppendInPlace:!0,interstitialLiveLookAhead:10,iframeCacheLimit:2097152,useMediaCapabilities:!0,preserveManualLevelOnError:!1,errorPenaltyExpireMs:0,certLoadPolicy:{default:{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,streamController:Kl,abrController:class extends U{constructor(t){super("abr",t.logger),this.hls=void 0,this.lastLevelLoadSec=0,this.lastLoadedFragLevel=-1,this.firstSelection=-1,this.firstAutoFloor=-1,this._nextAutoLevel=-1,this.nextAutoLevelKey="",this.audioTracksByGroup=null,this.codecTiers=null,this.timer=-1,this.fragCurrent=null,this.partCurrent=null,this.bitrateTestDelay=0,this.rebufferNotice=-1,this.supportedCache={},this.bwEstimator=void 0,this._abandonRulesCheck=t=>{var i;const{fragCurrent:s,partCurrent:r,hls:n}=this;if(!n)return;const{autoLevelEnabled:o,media:l}=n;if(!s||!l)return;const h=performance.now(),d=r?r.stats:s.stats,c=r?r.duration:s.duration,u=h-d.loading.start,f=n.minAutoLevel,g=s.level,m=this._nextAutoLevel;if(d.aborted||d.loaded&&d.loaded===d.total||g<=f)return this.clearTimer(),void(this._nextAutoLevel=-1);if(!o)return;const p=m>-1&&m!==g,v=!!t||p;if(!v&&(l.paused||!l.playbackRate||!l.readyState))return;const y=n.mainForwardBufferInfo;if(!v&&null===y)return;const E=this.bwEstimator.getEstimateTTFB(),T=Math.abs(l.playbackRate);if(u<=Math.max(E,c/(2*T)*1e3))return;const S=y?y.len/T:0,b=d.loading.first?d.loading.first-d.loading.start:-1,A=d.loaded&&b>-1,L=this.getBwEstimate(),I=n.levels,R=I[g],k=Math.max(d.loaded,Math.round(c*(s.bitrate||R.averageBitrate)/8));let _=A?u-b:u;_<1&&A&&(_=Math.min(u,8*d.loaded/L));const D=A?1e3*d.loaded/_:0,w=E/1e3,P=D?(k-d.loaded)/D:8*k/L+w;if(P<=S)return;const C=D?8*D:L,x=!0===(null==(i=(null==t?void 0:t.details)||n.latestLevelDetails)?void 0:i.live),M=n.config.abrBandWidthUpFactor;let O,F=Number.POSITIVE_INFINITY;for(O=g-1;O>f;O--){const t=I[O].maxBitrate,e=!I[O].details||x;if(F=this.getTimeToLoadFrag(w,C,c*t,e),F<Math.min(S,c+w))break}if(F>=P)return;if(F>10*c)return;A?this.bwEstimator.sample(u-Math.min(E,b),d.loaded):this.bwEstimator.sampleTTFB(u);const N=I[O].maxBitrate;this.getBwEstimate()*M>N&&(this.firstAutoFloor=Math.min(O,n.firstLevel),this.resetEstimator(N));const $=this.findBestLevel(N,f,O,0,S,1,1);$>-1&&(O=$),this.warn(`Fragment ${s.sn}${r?" part "+r.index:""} of level ${g} is loading too slowly;\n Fragment duration: ${s.duration.toFixed(3)}\n Time to underbuffer: ${S.toFixed(3)} s\n Estimated load time for current fragment: ${P.toFixed(3)} s\n Estimated load time for down switch fragment: ${F.toFixed(3)} s\n TTFB estimate: ${0|b} ms\n Current BW estimate: ${e(L)?0|L:"Unknown"} bps\n New BW estimate: ${0|this.getBwEstimate()} bps\n Switching to level ${O} @ ${0|N} bps`),n.nextLoadLevel=n.nextAutoLevel=O,this.clearTimer();const B=()=>{this.clearTimer();const t=this.hls;if(this.fragCurrent===s&&t.loadLevel===O&&O>0){const e=this.getStarvationDelay();if(this.warn(`Aborting inflight request ${O>0?"and switching down":""}\n Fragment duration: ${s.duration.toFixed(3)} s\n Time to underbuffer: ${e.toFixed(3)} s`),s.abortRequests(),this.fragCurrent=this.partCurrent=null,O>f){let i=this.findBestLevel(t.levels[f].bitrate,f,O,0,e,1,1);-1===i&&(i=f),t.nextLoadLevel=t.nextAutoLevel=i,this.firstAutoFloor=Math.min(i,t.firstLevel),this.resetEstimator(t.levels[i].bitrate)}}};p||P>2*F?B():this.timer=self.setInterval(B,1e3*F),n.trigger(a.FRAG_LOAD_EMERGENCY_ABORTED,{frag:s,part:r,stats:d})},this.hls=t,this.bwEstimator=this.initEstimator(),this.registerListeners()}resetEstimator(t){this.hls&&(t&&(this.log(`setting initial bwe to ${t}`),this.hls.config.abrEwmaDefaultEstimate=t),this.firstSelection=-1,this.bwEstimator=this.initEstimator())}initEstimator(){const t=this.hls.config;return new B(t.abrEwmaSlowVoD,t.abrEwmaFastVoD,t.abrEwmaDefaultEstimate)}registerListeners(){const t=this.hls;t.on(a.MANIFEST_LOADING,this.onManifestLoading,this),t.on(a.FRAG_LOADING,this.onFragLoading,this),t.on(a.FRAG_LOADED,this.onFragLoaded,this),t.on(a.FRAG_BUFFERED,this.onFragBuffered,this),t.on(a.LEVEL_SWITCHING,this.onLevelSwitching,this),t.on(a.LEVEL_LOADED,this.onLevelLoaded,this),t.on(a.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(a.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),t.on(a.ERROR,this.onError,this)}unregisterListeners(){const{hls:t}=this;t&&(t.off(a.MANIFEST_LOADING,this.onManifestLoading,this),t.off(a.FRAG_LOADING,this.onFragLoading,this),t.off(a.FRAG_LOADED,this.onFragLoaded,this),t.off(a.FRAG_BUFFERED,this.onFragBuffered,this),t.off(a.LEVEL_SWITCHING,this.onLevelSwitching,this),t.off(a.LEVEL_LOADED,this.onLevelLoaded,this),t.off(a.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(a.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),t.off(a.ERROR,this.onError,this))}destroy(){this.unregisterListeners(),this.clearTimer(),this.hls=this._abandonRulesCheck=this.supportedCache=null,this.audioTracksByGroup=this.codecTiers=this.fragCurrent=this.partCurrent=null}onManifestLoading(t,e){this.lastLoadedFragLevel=-1,this.firstSelection=-1,this.firstAutoFloor=-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(t,e){const i=e.frag;if(!this.ignoreFragment(i)){var s;if(!i.bitrateTest)this.fragCurrent=i,this.partCurrent=null!=(s=e.part)?s:null;this.clearTimer(),this.timer=self.setInterval(this._abandonRulesCheck,100)}}onLevelSwitching(t,e){this.clearTimer()}onError(t,e){if(!e.fatal)switch(e.details){case n.BUFFER_ADD_CODEC_ERROR:case n.BUFFER_APPEND_ERROR:this.lastLoadedFragLevel=-1,this.firstSelection=-1;break;case n.FRAG_LOAD_TIMEOUT:{const t=e.frag,{fragCurrent:i,partCurrent:s}=this;if(t&&T(t,i)){const e=performance.now(),i=s?s.stats:t.stats,r=e-i.loading.start,n=i.loading.first?i.loading.first-i.loading.start:-1;if(i.loaded&&n>-1){const t=this.bwEstimator.getEstimateTTFB();this.bwEstimator.sample(r-Math.min(t,n),i.loaded)}else this.bwEstimator.sampleTTFB(r)}break}}}getTimeToLoadFrag(t,e,i,s){return t+i/e+(s?t+this.lastLevelLoadSec:0)}onLevelLoaded(t,i){const s=this.hls.config,{loading:r}=i.stats,n=r.end-r.first;e(n)&&(this.lastLevelLoadSec=n/1e3),i.details.live?this.bwEstimator.update(s.abrEwmaSlowLive,s.abrEwmaFastLive):this.bwEstimator.update(s.abrEwmaSlowVoD,s.abrEwmaFastVoD),this.timer>-1&&this._abandonRulesCheck(i.levelInfo)}onFragLoaded(t,e){var i;const{frag:s,part:r}=e,n=r?r.stats:s.stats;if(s.type===f.MAIN&&this.bwEstimator.sampleTTFB(n.loading.first-n.loading.start),!this.ignoreFragment(s)){if(this.clearTimer(),s.level===this._nextAutoLevel&&(this._nextAutoLevel=-1),this.firstSelection=-1,null!=(i=this.hls)&&i.config.abrMaxWithRealBitrate){const t=r?r.duration:s.duration,e=this.hls.levels[s.level],i=(e.loaded?e.loaded.bytes:0)+n.loaded,a=(e.loaded?e.loaded.duration:0)+t;e.loaded={bytes:i,duration:a},e.realBitrate=Math.round(8*i/a)}if(s.bitrateTest){const t={stats:n,frag:s,part:r,id:s.type};this.onFragBuffered(a.FRAG_BUFFERED,t),s.bitrateTest=!1}else this.lastLoadedFragLevel=s.level}}onFragBuffered(t,e){const{frag:i,part:s}=e,r=null!=s&&s.stats.loaded?s.stats:i.stats;if(r.aborted)return;if(this.ignoreFragment(i))return;const n=((i.bitrate||0)>=1e5?r.parsing.end:r.loading.end)-r.loading.start-Math.min(r.loading.first-r.loading.start,this.bwEstimator.getEstimateTTFB());this.bwEstimator.sample(n,r.loaded),r.bwEstimate=this.getBwEstimate(),i.bitrateTest?this.bitrateTestDelay=n/1e3:(this.bitrateTestDelay=0,this.firstAutoFloor>-1&&this.bwEstimator.canEstimate()&&(this.firstAutoFloor=-1))}ignoreFragment(t){return t.type!==f.MAIN||"initSegment"===t.sn}clearTimer(){this.timer>-1&&(self.clearInterval(this.timer),this.timer=-1)}get firstAutoLevel(){const{hls:t}=this;if(!t)return 0;const{maxAutoLevel:e,minAutoLevel:i}=t,s=this.getBwEstimate(),r=this.getStarvationDelay(),n=t.config.maxStarvationDelay,a=this.findBestLevel(s,i,e,r/2,n,1,1);if(a>-1)return a;const o=t.firstLevel,l=-1===this.firstAutoFloor?1/0:this.firstAutoFloor,h=Math.min(Math.max(o,i),e,l);return this.warn(`Could not find best starting auto level. Defaulting to first in playlist ${o} clamped to ${h}`),h}get forcedAutoLevel(){return this.nextAutoLevelKey?-1:this._nextAutoLevel}get nextAutoLevel(){if(!this.hls)return-1;const t=this.forcedAutoLevel,e=this.bwEstimator.canEstimate(),i=this.lastLoadedFragLevel>-1;if(!(-1===t||e&&i&&this.nextAutoLevelKey!==this.getAutoLevelKey()))return t;const s=e&&i?this.getNextABRAutoLevel():this.firstAutoLevel;if(-1!==t){const e=this.hls.levels;if(e.length>Math.max(t,s)&&e[t].loadError<=e[s].loadError)return t}return this._nextAutoLevel=s,this.nextAutoLevelKey=this.getAutoLevelKey(),s}getAutoLevelKey(){return`${this.getBwEstimate()}_${this.getStarvationDelay().toFixed(2)}`}getNextABRAutoLevel(){const{fragCurrent:t,partCurrent:e,hls:i}=this;if(!i)return-1;if(i.levels.length<=1)return i.loadLevel;const{maxAutoLevel:s,config:r,minAutoLevel:n}=i,a=e?e.duration:t?t.duration:0,o=this.getBwEstimate(),l=this.getStarvationDelay();let h=r.abrBandWidthFactor,d=r.abrBandWidthUpFactor;if(l){const t=this.findBestLevel(o,n,s,l,0,h,d);if(t>=0)return this.rebufferNotice=-1,t}let c=a?Math.min(a,r.maxStarvationDelay):r.maxStarvationDelay;if(!l){const t=this.bitrateTestDelay;if(t){c=(a?Math.min(a,r.maxLoadingDelay):r.maxLoadingDelay)-t,this.info(`bitrate test took ${Math.round(1e3*t)}ms, set first fragment max fetchDuration to ${Math.round(1e3*c)} ms`),h=d=1}}const u=this.findBestLevel(o,n,s,l,c,h,d);if(this.rebufferNotice!==u&&(this.rebufferNotice=u,this.info(`${l?"rebuffering expected":"buffer is empty"}, optimal quality level ${u}`)),u>-1)return u;const f=i.levels[n],g=i.loadLevelObj;return g&&(null==f?void 0:f.bitrate)<g.bitrate?n:i.loadLevel}getStarvationDelay(){const t=this.hls,e=null==t?void 0:t.media;if(!e)return 1/0;const i=e&&0!==e.playbackRate?Math.abs(e.playbackRate):1,s=t.mainForwardBufferInfo;return(s?s.len:0)/i}getBwEstimate(){return this.bwEstimator.getEstimate()}findBestLevel(t,i,s,r,n,a,o){const{hls:l,lastLoadedFragLevel:h,fragCurrent:d,partCurrent:c}=this;if(!l)return-1;const u=r+n,f=-1===h?l.firstLevel:h,{levels:g,allAudioTracks:m,loadLevel:p,latestLevelDetails:v,config:y}=l;if(1===g.length)return 0;const E=g[f],T=!(null==v||!v.live),S=-1===p||-1===h;let b,A="SDR",L=(null==E?void 0:E.frameRate)||0;const{audioPreference:I,videoPreference:R}=y,k=this.audioTracksByGroup||(this.audioTracksByGroup=Ke(m));let _=-1;if(S){if(-1!==this.firstSelection)return this.firstSelection;const r=this.codecTiers||(this.codecTiers=function(t,e,i,s){return t.slice(i,s+1).reduce((t,i,s)=>{if(!i.codecSet)return t;const r=i.audioGroups;let n=t[i.codecSet];n||(t[i.codecSet]=n={minBitrate:1/0,minHeight:1/0,minFramerate:1/0,minIndex:s,maxScore:0,videoRanges:{SDR:0},channels:{2:0},hasDefaultAudio:!r,fragmentError:0}),n.minBitrate=Math.min(n.minBitrate,i.bitrate);const a=Math.min(i.height,i.width);return n.minHeight=Math.min(n.minHeight,a),n.minFramerate=Math.min(n.minFramerate,i.frameRate),n.minIndex=Math.min(n.minIndex,s),n.maxScore=Math.max(n.maxScore,i.score),n.fragmentError+=i.fragmentError,n.videoRanges[i.videoRange]=(n.videoRanges[i.videoRange]||0)+1,r&&r.forEach(t=>{if(!t)return;const i=e.groups[t];i&&(n.hasDefaultAudio=n.hasDefaultAudio||e.hasDefaultAudio?i.hasDefault:i.hasAutoSelect||!e.hasDefaultAudio&&!e.hasAutoSelectAudio,Object.keys(i.channels).forEach(t=>{n.channels[t]=(n.channels[t]||0)+i.channels[t]}))}),t},{})}(g,k,i,s)),n=function(t,i,s,r,n){const a=Object.keys(t),o=null==r?void 0:r.channels,l=null==r?void 0:r.audioCodec,h=null==n?void 0:n.videoCodec,d=o&&2===parseInt(o);let c=!1,u=!1,f=1/0,g=1/0,m=1/0,p=1/0,v=0,y=[];const{preferHDR:E,allowedVideoRanges:T}=Be(i,n);for(let e=a.length;e--;){const i=t[a[e]];c||(c=i.channels[2]>0),f=Math.min(f,i.minHeight),g=Math.min(g,i.minFramerate),m=Math.min(m,i.minBitrate),T.filter(t=>i.videoRanges[t]>0).length>0&&(u=!0)}f=e(f)?f:0,g=e(g)?g:0;const S=Math.max(1080,f),b=Math.max(30,g);m=e(m)?m:s,s=Math.max(m,s),u||(i=void 0);const A=a.length>1;return{codecSet:a.reduce((e,i)=>{const r=t[i];if(i===e)return e;if(y=u?T.filter(t=>r.videoRanges[t]>0):[],A){if(r.minBitrate>s)return Ge(i,`min bitrate of ${r.minBitrate} > current estimate of ${s}`),e;if(!r.hasDefaultAudio)return Ge(i,"no renditions with default or auto-select sound found"),e;if(l&&i.indexOf(l.substring(0,4))%5!=0)return Ge(i,`audio codec preference "${l}" not found`),e;if(o&&!d){if(!r.channels[o])return Ge(i,`no renditions with ${o} channel sound found (channels options: ${Object.keys(r.channels)})`),e}else if((!l||d)&&c&&0===r.channels[2])return Ge(i,"no renditions with stereo sound found"),e;if(r.minHeight>S)return Ge(i,`min resolution of ${r.minHeight} > maximum of ${S}`),e;if(r.minFramerate>b)return Ge(i,`min framerate of ${r.minFramerate} > maximum of ${b}`),e;if(!y.some(t=>r.videoRanges[t]>0))return Ge(i,`no variants with VIDEO-RANGE of ${Ue(y)} found`),e;if(h&&i.indexOf(h.substring(0,4))%5!=0)return Ge(i,`video codec preference "${h}" not found`),e;if(r.maxScore<v)return Ge(i,`max score of ${r.maxScore} < selected max of ${v}`),e}return e&&(fe(i)>=fe(e)||r.fragmentError>t[e].fragmentError)?e:(p=r.minIndex,v=r.maxScore,i)},void 0),videoRanges:y,preferHDR:E,minFramerate:g,minBitrate:m,minIndex:p}}(r,A,t,I,R),{codecSet:a,videoRanges:o,minFramerate:l,minBitrate:h,minIndex:d,preferHDR:c}=n;_=d,b=a,A=c?o[o.length-1]:o[0],L=l,t=Math.max(t,h),this.log(`picked start tier ${Ue(n)}`)}else b=null==E?void 0:E.codecSet,A=null==E?void 0:E.videoRange;const D=c?c.duration:d?d.duration:0,w=this.bwEstimator.getEstimateTTFB()/1e3,P=[];for(let l=s;l>=i;l--){var C;const i=g[l],d=l>f;if(!i)continue;if(y.useMediaCapabilities&&!i.supportedResult&&!i.supportedPromise){const e=navigator.mediaCapabilities;"function"==typeof(null==e?void 0:e.decodingInfo)&&Ie(i,k,A,L,t,I)?(i.supportedPromise=Re(i,k,e,this.supportedCache),i.supportedPromise.then(t=>{if(!this.hls)return;i.supportedResult=t;const e=this.hls.levels,s=e.indexOf(i);t.error?this.warn(`MediaCapabilities decodingInfo error: "${t.error}" for level ${s} ${Ue(t)}`):t.supported?t.decodingInfoResults.some(t=>!1===t.smooth||!1===t.powerEfficient)&&this.log(`MediaCapabilities decodingInfo for level ${s} not smooth or powerEfficient: ${Ue(t)}`):(this.warn(`Unsupported MediaCapabilities decodingInfo result for level ${s} ${Ue(t)}`),s>-1&&e.length>1&&(this.log(`Removing unsupported level ${s}`),this.hls.removeLevel(s),-1===this.hls.loadLevel&&(this.hls.nextLoadLevel=0)))}).catch(t=>{this.warn(`Error handling MediaCapabilities decodingInfo: ${t}`)})):i.supportedResult=Ae}if((b&&i.codecSet!==b||A&&i.videoRange!==A||d&&L>i.frameRate||!d&&L>0&&L<i.frameRate||null!=(C=i.supportedResult)&&null!=(C=C.decodingInfoResults)&&C.some(t=>!1===t.smooth))&&(!S||l!==_)){P.push(l);continue}const m=i.details,v=(c?null==m?void 0:m.partTarget:null==m?void 0:m.averagetargetduration)||D||1;let E;E=d?o*t:a*t;const R=D&&r>=2*D&&0===n?i.averageBitrate:i.maxBitrate,x=this.getTimeToLoadFrag(w,E,R*v,!m||m.live);if(E>=R&&(l===h||0===i.loadError&&0===i.fragmentError||N(i,y.errorPenaltyExpireMs))&&(x<=w||!e(x)||T&&!this.bitrateTestDelay||x<u)){const t=this.forcedAutoLevel;return l===p||-1!==t&&t===p||(P.length&&this.trace(`Skipped level(s) ${P.join(",")} of ${s} max with CODECS and VIDEO-RANGE:"${g[P[0]].codecs}" ${g[P[0]].videoRange}; not compatible with "${b}" ${A}`),this.info(`switch candidate:${f}->${l} adjustedbw(${Math.round(E)})-bitrate=${Math.round(E-R)} ttfb:${w.toFixed(1)} avgDuration:${v.toFixed(1)} maxFetchDuration:${u.toFixed(1)} fetchDuration:${x.toFixed(1)} firstSelection:${S} codecSet:${i.codecSet} videoRange:${i.videoRange} hls.loadLevel:${p}`)),S&&(this.firstSelection=l),l}}return-1}set nextAutoLevel(t){const e=this.deriveNextAutoLevel(t);this._nextAutoLevel!==e&&(this.nextAutoLevelKey="",this._nextAutoLevel=e)}deriveNextAutoLevel(t){if(!this.hls)return-1;const{maxAutoLevel:e,minAutoLevel:i}=this.hls;return Math.min(Math.max(t,i),e)}},bufferController:class extends U{constructor(t,e){var i;super("buffer-controller",t.logger),this.hls=void 0,this.fragmentTracker=void 0,this.fragmentAppendProgress=Object.create(null),this.appendsWithoutProgress=Object.create(null),this.details=null,this._objectUrl=null,this.operationQueue=null,this.bufferCodecEventsTotal=0,this.media=null,this.mediaSource=null,this.lastMpegAudioChunk=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.appendError=void 0,this._quotaEvictionPending={},this.tracks={},this.sourceBuffers=[[null,null],[null,null]],this._onEndStreaming=t=>{var e;this.hls&&"open"===(null==(e=this.mediaSource)?void 0:e.readyState)&&this.media&&!this.media.seeking&&this.hls.pauseBuffering()},this._onStartStreaming=t=>{this.hls&&this.hls.resumeBuffering()},this._onMediaSourceOpen=t=>{const{media:e,mediaSource:i}=this;t&&this.log("Media source opened"),e&&i&&(Si(i,"sourceopen",this._onMediaSourceOpen),Si(e,"emptied",this._onMediaEmptied),this.updateDuration(),this.hls.trigger(a.MEDIA_ATTACHED,{media:e,mediaSource:i}),null!==this.mediaSource&&this.checkPendingTracks())},this._onMediaSourceClose=()=>{if(this.log("Media source closed"),this.media){if(this.isMediaSourceReplaced()){const{currentSrc:t}=this.media,e=t&&t!==this._objectUrl?t:this.mediaSrc;return this.warn(`MediaSource closed after media element switched to another source (${this._objectUrl} > ${e}) - detaching media`),void this.hls.detachMedia()}const t=this.media.error,{appendError:e,appendErrors:i}=this;let s=!1;if(!e&&t){s=Math.max(++i.audio,++i.video,++i.audiovideo)>=this.hls.config.appendErrorMaxRetry}const o=new Error(`MediaSource closed while media attached${Di(s,t)}`);this.warn(o),this.hls.trigger(a.ERROR,I({fatal:s},e,{type:r.MEDIA_ERROR,details:n.MEDIA_SOURCE_REQUIRES_RESET,error:o}))}},this._onMediaSourceEnded=()=>{this.log("Media source ended")},this._onMediaEmptied=()=>{const{mediaSrc:t,_objectUrl:e}=this;t!==e&&this.error(`Media element src was set while attaching MediaSource (${e} > ${t})`)},this._onMediaError=()=>{const{media:t}=this;var e,i;t&&this.log(`Media error (code: ${null==(e=t.error)?void 0:e.code}): ${null==(i=t.error)?void 0:i.message}`)},this.hls=t,this.fragmentTracker=e,this.appendSource=(i=Y(t.config.preferManagedMediaSource),"undefined"!=typeof self&&i===self.ManagedMediaSource),this.initTracks(),this.registerListeners()}hasSourceTypes(){return Object.keys(this.tracks).length>0}destroy(){this.unregisterListeners(),this.details=null,this.lastMpegAudioChunk=null,this.transferData=this.overrides=void 0,this.operationQueue&&(this.operationQueue.destroy(),this.operationQueue=null),this.hls=this.fragmentTracker=null,this._onMediaSourceOpen=this._onMediaSourceClose=null,this._onMediaSourceEnded=null,this._onStartStreaming=this._onEndStreaming=null,this._onMediaEmptied=this._onMediaError=null}registerListeners(){const{hls:t}=this;t.on(a.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(a.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(a.MANIFEST_LOADING,this.onManifestLoading,this),t.on(a.MANIFEST_PARSED,this.onManifestParsed,this),t.on(a.BUFFER_RESET,this.onBufferReset,this),t.on(a.BUFFER_APPENDING,this.onBufferAppending,this),t.on(a.BUFFER_CODECS,this.onBufferCodecs,this),t.on(a.BUFFER_EOS,this.onBufferEos,this),t.on(a.BUFFER_FLUSHING,this.onBufferFlushing,this),t.on(a.LEVEL_UPDATED,this.onLevelUpdated,this),t.on(a.FRAG_PARSED,this.onFragParsed,this),t.on(a.FRAG_CHANGED,this.onFragChanged,this),t.on(a.ERROR,this.onError,this)}unregisterListeners(){const{hls:t}=this;t.off(a.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(a.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(a.MANIFEST_LOADING,this.onManifestLoading,this),t.off(a.MANIFEST_PARSED,this.onManifestParsed,this),t.off(a.BUFFER_RESET,this.onBufferReset,this),t.off(a.BUFFER_APPENDING,this.onBufferAppending,this),t.off(a.BUFFER_CODECS,this.onBufferCodecs,this),t.off(a.BUFFER_EOS,this.onBufferEos,this),t.off(a.BUFFER_FLUSHING,this.onBufferFlushing,this),t.off(a.LEVEL_UPDATED,this.onLevelUpdated,this),t.off(a.FRAG_PARSED,this.onFragParsed,this),t.off(a.FRAG_CHANGED,this.onFragChanged,this),t.off(a.ERROR,this.onError,this)}transferMedia(){const{media:t,mediaSource:e}=this;if(!t)return null;const i={};if(this.operationQueue){const t=this.isUpdating();t||this.operationQueue.removeBlockers();const e=this.isQueued();(t||e)&&this.warn(`Transfering MediaSource with${e?" operations in queue":""}${t?" updating SourceBuffer(s)":""} ${this.operationQueue}`),this.operationQueue.destroy()}const s=this.transferData;return s&&!this.sourceBufferCount&&s.mediaSource===e?I(i,s.tracks):this.sourceBuffers.forEach(t=>{const[e]=t;e&&(i[e]=I({},this.tracks[e]),this.removeBuffer(e)),t[0]=t[1]=null}),{media:t,mediaSource:e,tracks:i}}initTracks(){this.resetAppendProgress(),this.sourceBuffers=[[null,null],[null,null]],this.tracks={},this.resetQueue(),this.lastMpegAudioChunk=null,this.lastVideoAppendEnd=0}onManifestLoading(){this.bufferCodecEventsTotal=0,this.details=null,this.resetAppendErrors(),this.resetAppendProgress()}onManifestParsed(t,e){var i;let s=2;(e.audio&&!e.video||!e.altAudio)&&(s=1),this.bufferCodecEventsTotal=s,this.log(`${s} bufferCodec event(s) expected.`),null!=(i=this.transferData)&&i.mediaSource&&this.sourceBufferCount&&s&&this.bufferCreated()}onMediaAttaching(t,e){const i=this.media=e.media;this.transferData=this.overrides=void 0;const s=Y(this.appendSource);if(s){const t=!!e.mediaSource;(t||e.overrides)&&(this.transferData=e,this.overrides=e.overrides);const n=this.mediaSource=e.mediaSource||new s;if(this.assignMediaSource(n),t)this._objectUrl=i.src,this.attachTransferred();else{var r;const t=this._objectUrl=self.URL.createObjectURL(n),e=this.hls.config,s=e.emeEnabled&&i.mediaKeys?null==(r=e.emeController)?void 0:r.CDMCleanupPromise:null;s?s.then(()=>{this.hls&&this.setSource(i,n,t)}).catch(()=>{}):this.setSource(i,n,t)}Ti(i,"emptied",this._onMediaEmptied),Ti(i,"error",this._onMediaError),this.appendSource&&Ti(i,"seeking",this._onStartStreaming)}}setSource(t,e,i){if(this.appendSource)try{t.removeAttribute("src");const s=self.ManagedMediaSource;t.disableRemotePlayback=t.disableRemotePlayback||s&&e instanceof s,ki(t),function(t,e){const i=self.document.createElement("source");i.type="video/mp4",i.src=e,t.appendChild(i)}(t,i),t.load()}catch(e){t.src=i}else t.src=i}assignMediaSource(t){var e,i;this.log(`${(null==(e=this.transferData)?void 0:e.mediaSource)===t?"transferred":"created"} media source: ${null==(i=t.constructor)?void 0:i.name}`),Ti(t,"sourceopen",this._onMediaSourceOpen),Ti(t,"sourceended",this._onMediaSourceEnded),Ti(t,"sourceclose",this._onMediaSourceClose),this.appendSource&&(Ti(t,"startstreaming",this._onStartStreaming),Ti(t,"endstreaming",this._onEndStreaming))}attachTransferred(){const t=this.media,e=this.transferData;if(!e||!t)return;const i=this.tracks,s=e.tracks,r=s?Object.keys(s):null,n=r?r.length:0,o=()=>{Promise.resolve().then(()=>{this.media&&this.mediaSourceOpenOrEnded&&this._onMediaSourceOpen()})};if(s&&r&&n){if(!this.tracksReady)return this.hls.config.startFragPrefetch=!0,void this.log("attachTransferred: waiting for SourceBuffer track info");if(this.log(`attachTransferred: (bufferCodecEventsTotal ${this.bufferCodecEventsTotal})\nrequired tracks: ${Ue(i,(t,e)=>"initSegment"===t?void 0:e)};\ntransfer tracks: ${Ue(s,(t,e)=>"initSegment"===t?void 0:e)}}`),!W(s,i)){e.mediaSource=null,e.tracks=void 0;const r=t.currentTime,n=this.details,o=Math.max(r,(null==n?void 0:n.fragments[0].start)||0);return o-r>1?void this.log(`attachTransferred: waiting for playback to reach new tracks start time ${r} -> ${o}`):(this.warn(`attachTransferred: resetting MediaSource for incompatible tracks ("${Object.keys(s)}"->"${Object.keys(i)}") start time: ${o} currentTime: ${r}`),this.onMediaDetaching(a.MEDIA_DETACHING,{}),this.onMediaAttaching(a.MEDIA_ATTACHING,e),void(t.currentTime=o))}this.transferData=void 0,r.forEach(t=>{const e=t,i=s[e];if(i){const t=i.buffer;if(t){const s=this.fragmentTracker,r=i.id;if(s.hasFragments(r)||s.hasParts(r)){const i=Ei.getBuffered(t);s.detectEvictedFragments(e,i,r,null,null,!0)}const n=_i(e),a=[e,t];this.sourceBuffers[n]=a,t.updating&&this.operationQueue&&this.operationQueue.prependBlocker(e),this.trackSourceBuffer(e,i)}}}),o(),this.bufferCreated()}else this.log("attachTransferred: MediaSource w/o SourceBuffers"),o()}get mediaSourceOpenOrEnded(){var t;const e=null==(t=this.mediaSource)?void 0:t.readyState;return"open"===e||"ended"===e}onMediaDetaching(t,e){const i=!!e.transferMedia;this.transferData=this.overrides=void 0;const{media:s,mediaSource:r,_objectUrl:n}=this;if(r){if(this.log("media source "+(i?"transferring":"detaching")),i)this.sourceBuffers.forEach(([t])=>{t&&this.removeBuffer(t)}),this.resetQueue();else{if(this.mediaSourceOpenOrEnded){const t="open"===r.readyState;try{const e=r.sourceBuffers;for(let i=e.length;i--;)t&&e[i].abort(),r.removeSourceBuffer(e[i]);t&&r.endOfStream()}catch(t){this.warn(`onMediaDetaching: ${t.message} while calling endOfStream`)}}this.sourceBufferCount&&this.onBufferReset()}Si(r,"sourceopen",this._onMediaSourceOpen),Si(r,"sourceended",this._onMediaSourceEnded),Si(r,"sourceclose",this._onMediaSourceClose),this.appendSource&&(Si(r,"startstreaming",this._onStartStreaming),Si(r,"endstreaming",this._onEndStreaming)),this.mediaSource=null,this._objectUrl=null}s&&(Si(s,"emptied",this._onMediaEmptied),Si(s,"error",this._onMediaError),Si(s,"seeking",this._onStartStreaming),i||(n&&self.URL.revokeObjectURL(n),this.mediaSrc!==n||this.isMediaSourceReplaced(n)?this.warn("media|source.src was changed by a third party - skip cleanup"):(s.removeAttribute("src"),this.appendSource&&ki(s),s.load())),this.media=null)}onBufferReset(){this.sourceBuffers.forEach(([t])=>{t&&this.resetBuffer(t)}),this.initTracks()}resetBuffer(t){var e;const i=null==(e=this.tracks[t])?void 0:e.buffer;if(this.removeBuffer(t),i)try{var s;null!=(s=this.mediaSource)&&s.sourceBuffers.length&&this.mediaSource.removeSourceBuffer(i)}catch(e){this.warn(`onBufferReset ${t}`,e)}delete this.tracks[t]}removeBuffer(t){this.removeBufferListeners(t),this.sourceBuffers[_i(t)]=[null,null];const e=this.tracks[t];e&&(this.clearBufferAppendTimeoutId(e),e.buffer=void 0)}resetQueue(){this.operationQueue&&this.operationQueue.destroy(),this.operationQueue=new Qe(this.tracks)}onBufferCodecs(t,e){var i;const s=this.tracks,r=Object.keys(e);this.log(`BUFFER_CODECS: "${r}" (current SB count ${this.sourceBufferCount})`);const n="audiovideo"in e&&(s.audio||s.video)||s.audiovideo&&("audio"in e||"video"in e),a=!n&&this.sourceBufferCount&&this.media&&r.some(t=>!s[t]);n||a?this.warn(`Unsupported transition between "${Object.keys(s)}" and "${r}" SourceBuffers`):(r.forEach(t=>{var i,r;const n=e[t],{id:a,codec:o,levelCodec:l,container:h,metadata:d,supplemental:c}=n;let u=s[t];const f=null==(i=this.transferData)||null==(i=i.tracks)?void 0:i[t],g=null!=f&&f.buffer?f:u,m=(null==g?void 0:g.pendingCodec)||(null==g?void 0:g.codec),p=null==g?void 0:g.levelCodec;u||(u=s[t]={buffer:void 0,listeners:[],codec:o,supplemental:c,container:h,levelCodec:l,metadata:d,id:a});const v=ve(m,p),y=null==v?void 0:v.replace(Ai,"$1");let E=ve(o,l);const T=null==(r=E)?void 0:r.replace(Ai,"$1");E&&v&&y!==T&&("audio"===t.slice(0,5)&&(E=pe(E,this.appendSource)),this.log(`switching codec ${m} to ${E}`),E!==(u.pendingCodec||u.codec)&&(u.pendingCodec=E),u.container=h,this.appendChangeType(t,h,E))}),(this.tracksReady||this.sourceBufferCount)&&(e.tracks=this.sourceBufferTracks),this.sourceBufferCount||(this.bufferCodecEventsTotal>1&&!this.tracks.video&&!e.video&&"main"===(null==(i=e.audio)?void 0:i.id)&&(this.log("Main audio-only"),this.bufferCodecEventsTotal=1),this.mediaSourceOpenOrEnded&&this.checkPendingTracks()))}get sourceBufferTracks(){return Object.keys(this.tracks).reduce((t,e)=>{const i=this.tracks[e];return t[e]={id:i.id,container:i.container,codec:i.codec,levelCodec:i.levelCodec},t},{})}appendChangeType(t,e,i){const s=`${e};codecs=${i}`,r={label:`change-type=${s}`,execute:()=>{const r=this.tracks[t];if(r){const n=r.buffer;null!=n&&n.changeType&&(this.log(`changing ${t} sourceBuffer type to ${s}`),n.changeType(s),r.codec=i,r.container=e)}this.shiftAndExecuteNext(t)},onStart:()=>{},onComplete:()=>{},onError:e=>{this.warn(`Failed to change ${t} SourceBuffer type`,e)}};this.append(r,t,this.isPending(this.tracks[t]))}blockAudio(t){var e;const i=t.start,s=i+.05*t.duration;if(!0===(null==(e=this.fragmentTracker.getAppendedFrag(i,f.MAIN))?void 0:e.gap))return;const r={label:"block-audio",execute:()=>{var t,e;(this.lastVideoAppendEnd>s||Ei.isBuffered(null==(t=this.tracks.video)?void 0:t.buffer,s)||!0===(null==(e=this.fragmentTracker.getAppendedFrag(s,f.MAIN))?void 0:e.gap))&&this.unblockAudio()},onStart:()=>{},onComplete:()=>{},onError:t=>{this.warn("Error executing block-audio operation",t)}};this.append(r,"audio",!0)}unblockAudio(){this.operationQueue&&this.operationQueue.unblockAudio()}onBufferAppending(t,i){const{tracks:s}=this,{data:o,type:l,parent:h,frag:d,part:c,chunkMeta:u,offset:f}=i,g=u.buffering[l],m=y(d)&&!c&&!d.gap&&!u.partial&&!u.iframe;let p=null,v=!1;const{sn:E,cc:T}=d,S=self.performance.now();g.start=S;const b=d.stats.buffering,A=c?c.stats.buffering:null;0===b.start&&(b.start=S),0===(null==A?void 0:A.start)&&(A.start=S);const L=s.audio;let I=!1;"audio"===l&&"audio/mpeg"===(null==L?void 0:L.container)&&(I=!this.lastMpegAudioChunk||1===u.id||this.lastMpegAudioChunk.sn!==u.sn,this.lastMpegAudioChunk=u);const R=s.video,k=null==R?void 0:R.buffer;if(k&&"initSegment"!==E&&void 0!==f){const t=null==L?void 0:L.buffer,e=c||d;if("audio"===l&&"main"!==h&&!R.ending&&!R.ended&&t&&Ei.getBuffered(t).length){const t=e.start+.05*e.duration,i=Ei.getBuffered(k),s=this.currentOp("video");i.length||s?!Ei.isBuffered(k,t)&&this.lastVideoAppendEnd<t&&this.blockAudio(e):this.blockAudio(e)}else if("video"===l){const t=e.end,i=this.lastVideoAppendEnd-t;this.lastVideoAppendEnd=t,i<0||i>e.duration?this.unblockAudio():this.isAudioBlocked()&&this.executeNext("audio")}}const _=(c||d).start,D={label:`append-${l}`,execute:()=>{var t;g.executeStart=self.performance.now();const i=null==(t=this.tracks[l])?void 0:t.buffer;i&&(m&&(p=Ei.timeRangesToArray(Ei.getBuffered(i)),v=Ci(Pi(p,d),d)),I?this.updateTimestampOffset(i,_,.1,l,E,T):void 0!==f&&e(f)&&this.updateTimestampOffset(i,f,1e-6,l,E,T)),this.appendExecutor(o,l)},onStart:()=>{},onComplete:()=>{this.clearBufferAppendTimeoutId(this.tracks[l]);const t=self.performance.now();g.executeEnd=g.end=t,0===b.first&&(b.first=t),0===(null==A?void 0:A.first)&&(A.first=t);const e={};if(this.sourceBuffers.forEach(([t,i])=>{t&&(e[t]=Ei.getBuffered(i))}),m){const t=this.getFragmentAppendProgress(d),i=e[l];if(i&&p){const e=Pi(Ei.timeRangesToArray(i),d);t.progressed||(t.progressed=e-Pi(p,d)>.001);const s=v&&Ci(e,d);t.fullyBuffered[l]=(void 0===t.fullyBuffered[l]||t.fullyBuffered[l])&&s}}this.hls.trigger(a.BUFFER_APPENDED,{type:l,frag:d,part:c,chunkMeta:u,parent:h,timeRanges:e})},onError:t=>{var e;this.clearBufferAppendTimeoutId(this.tracks[l]);const i=t.code===DOMException.QUOTA_EXCEEDED_ERR||"QuotaExceededError"==t.name||"quota"in t;if(i&&!this._quotaEvictionPending[l]){const t=this.getBackBufferEvictionTarget(l,o.byteLength,d.type);if(t>0){this._quotaEvictionPending[l]=!0,this.log(`QuotaExceededError on "${l}" append sn: ${E} - evicting back buffer to ${t.toFixed(3)}s and retrying`);const e=this.getFlushOp(l,0,t),i=this.getClearEvictionPendingOp(l);return void this.insertNext([e,D,i],l)}this.warn(`QuotaExceededError on "${l}" sn: ${E} - no back buffer available to evict`)}m&&(this.getFragmentAppendProgress(d).errored=!0);const s={type:r.MEDIA_ERROR,parent:h,details:n.BUFFER_APPEND_ERROR,sourceBufferName:l,frag:d,part:c,chunkMeta:u,error:t,err:t,fatal:!1},f=null==(e=this.media)?void 0:e.error;if(t.name!==Li||0!==this.sourceBufferCount||this.media&&0!==this.pendingTrackCount){var g;i&&(s.details=n.BUFFER_FULL_ERROR);const e=++this.appendErrors[l],r=this.hls.config.appendErrorMaxRetry;this.warn(`Failed ${e}/${r+1} times to append segment in "${l}" sourceBuffer with error: ${t.message}`),e>=r&&(s.fatal=!i);const a=null==(g=this.mediaSource)?void 0:g.readyState;"ended"!==a&&"closed"!==a&&!f||this.isMediaSourceReplaced()||(this.warn(`MediaSource readyState "${a}" during SourceBuffer${Di(s.fatal,f)}`),s.details=n.MEDIA_SOURCE_REQUIRES_RESET)}else s.errorAction=pi(!0);this.appendError=s,this.hls.trigger(a.ERROR,s),i&&this.hls&&this.trimBuffers(d.start,1)}};this.log(`queuing "${l}" append sn: ${E}${c?" p: "+c.index:""} of ${h} playlist ${d.level} cc: ${T} offset: ${f} bytes: ${o.byteLength}`),this.append(D,l,this.isPending(this.tracks[l]))}getClearEvictionPendingOp(t){return{label:"clear",execute:()=>{this._quotaEvictionPending[t]=!1,this.shiftAndExecuteNext(t)},onStart:()=>{},onComplete:()=>{},onError:()=>{}}}getFlushOp(t,e,i){return this.log(`queuing "${t}" remove ${e}-${i}`),{label:"remove",execute:()=>{this.removeExecutor(t,e,i)},onStart:()=>{},onComplete:()=>{var s;const r=null==(s=this.tracks[t])?void 0:s.buffer;this.log(`Remove request ${e}-${i} from ${t} Source Buffer complete > buffer: ${r?bi(Ei.getBuffered(r)):"(detached)"}`),this.hls.trigger(a.BUFFER_FLUSHED,{type:t,start:e,end:i})},onError:s=>{this.warn(`Failed to remove ${e}-${i} from "${t}" SourceBuffer`,s),this.hls.trigger(a.BUFFER_FLUSHED,{type:t,start:0,end:0,error:s})}}}onBufferFlushing(t,e){const{type:i,startOffset:s,endOffset:r}=e;i&&"audio"!==i||this.unblockAudio(),i?this.append(this.getFlushOp(i,s,r),i):this.sourceBuffers.forEach(([t])=>{t&&this.append(this.getFlushOp(t,s,r),t)})}onFragParsed(t,e){const{frag:i,part:s,chunkMeta:r}=e,n=[],o=s?s.elementaryStreams:i.elementaryStreams;o[p]?n.push("audiovideo"):(o[g]&&n.push("audio"),o[m]&&n.push("video"));0===n.length&&this.log(`Fragments must have at least one ElementaryStreamType set. ${i.type} ${i.level} ${s?`part: ${s.index} of `:""}sn: ${i.sn}`),this.blockBuffers(()=>{const t=self.performance.now();i.stats.buffering.end=t,s&&(s.stats.buffering.end=t);const e=s?s.stats:i.stats;this.checkAppendProgress(i,s,r,n),this.hls&&(this.hls.trigger(a.FRAG_BUFFERED,{frag:i,part:s,stats:e,id:i.type,chunkMeta:r}),!s&&i.gap&&e.retry&&this.log(`Nothing buffered for ${i.type} level: ${i.level} sn: ${i.sn} retries ${e.retry}`))},n).catch(t=>{this.warn(`Fragment buffered callback ${t.message}`),this.stepOperationQueue(this.sourceBufferTypes)})}onFragChanged(t,e){var i,s;const r=null==(i=this.hls)?void 0:i.config;if(!r)return;const{backBufferLength:n,frontBufferFlushThreshold:a}=r;this.trimBuffers(a,n,e.frag,e.previousFrag);const o=e.frag.elementaryStreams,{appendErrors:l}=this,h=null==(s=this.appendError)?void 0:s.sourceBufferName;Object.keys(o).forEach(t=>{o[t]&&(l[t]=0,t===h&&(this.appendError=void 0),"audio"===t||"video"===t?(l.audiovideo=0,"audiovideo"===h&&(this.appendError=void 0)):(l.audio=0,l.video=0,"audiovideo"!==h&&(this.appendError=void 0)))})}get bufferedToEnd(){return this.sourceBufferCount>0&&!this.sourceBuffers.some(([t])=>{if(t){const e=this.tracks[t];if(e)return!e.ended||e.ending}return!1})}onBufferEos(t,e){var i;this.sourceBuffers.forEach(([t])=>{if(t){const i=this.tracks[t];e.type&&e.type!==t||(i.ending=!0,i.ended||(i.ended=!0,this.log(`${t} buffer reached EOS`)))}});const s=!1!==(null==(i=this.overrides)?void 0:i.endOfStream);this.allTracksEnding?(this.unblockAudio(),s?(this.log("Queueing EOS"),this.blockUntilOpen(()=>{if(this.tracksEnded(),!this.allTracksEnding)return void this.log("EOS cancelled");const{mediaSource:t}=this;"open"===(null==t?void 0:t.readyState)?(this.log("Calling mediaSource.endOfStream()"),t.endOfStream(),this.hls.trigger(a.BUFFERED_TO_END,void 0)):t&&this.log(`Could not call mediaSource.endOfStream(). mediaSource.readyState: ${t.readyState}`)})):(this.tracksEnded(),this.hls.trigger(a.BUFFERED_TO_END,void 0))):"video"===e.type&&this.unblockAudio()}get allTracksEnding(){return this.sourceBufferCount>0&&!this.sourceBuffers.some(([t])=>{var e;return t&&!(null!=(e=this.tracks[t])&&e.ended)})}tracksEnded(){this.sourceBuffers.forEach(([t])=>{if(null!==t){const e=this.tracks[t];e&&(e.ending=!1)}})}onLevelUpdated(t,{details:e}){e.fragments.length&&(this.details=e,this.updateDuration())}updateDuration(){this.blockUntilOpen(()=>{const t=this.getDurationAndRange();t&&this.updateMediaSource(t)})}onError(t,i){if(i.details===n.BUFFER_APPEND_ERROR&&i.frag){var s;const t=null==(s=i.errorAction)?void 0:s.nextAutoLevel;e(t)&&t!==i.frag.level&&this.resetAppendErrors()}}getBackBufferEvictionTarget(t,e,i){const{media:s}=this;return s?this.fragmentTracker.getBackBufferEvictionEnd(s.currentTime,i,e):0}getFragmentAppendProgress(t){var e;const i=wi(t);let s=this.fragmentAppendProgress[i];return(null==(e=s)?void 0:e.stats)!==t.stats&&(s={stats:t.stats,progressed:!1,errored:!1,fullyBuffered:Object.create(null)},this.fragmentAppendProgress[i]=s),s}checkAppendProgress(t,e,i,s){if(e||!y(t)||t.gap||i.iframe||i.partial)return;const o=wi(t),l=this.fragmentAppendProgress[o];delete this.fragmentAppendProgress[o];const h=t.stats.buffering;if(h.start&&!h.first)return;const d=(null==l?void 0:l.stats)===t.stats?l:void 0;if(null!=d&&d.errored)return;const c=s.length>0&&s.every(t=>!0===(null==d?void 0:d.fullyBuffered[t]));if(null!=d&&d.progressed||c)return void delete this.appendsWithoutProgress[o];if(!d&&0===s.length)return;const u=(this.appendsWithoutProgress[o]||0)+1,f=this.hls;u>=f.config.appendErrorMaxRetry?delete this.appendsWithoutProgress[o]:this.appendsWithoutProgress[o]=u,this.warn(`Fragment ${t.sn} of ${t.type} playlist ${t.level} appended ${u} time${u>1?"s":""} without buffered range growth`),f.trigger(a.ERROR,{type:r.MEDIA_ERROR,details:n.BUFFER_APPEND_NO_PROGRESS,fatal:!1,frag:t,chunkMeta:i,parent:t.type,appendsWithoutProgress:u,error:new Error(`Fragment append did not increase buffered coverage (${u})`)})}resetAppendProgress(){this.fragmentAppendProgress=Object.create(null),this.appendsWithoutProgress=Object.create(null)}resetAppendErrors(){this.appendErrors={audio:0,video:0,audiovideo:0},this.appendError=void 0}trimBuffers(t,i,s,r){const{hls:n,details:a,media:o}=this;if(!o||null===a)return;if(!this.sourceBufferCount)return;const l=n.config,h=o.currentTime,d=a.levelTargetDuration;i=a.live&&null!==l.liveBackBufferLength?l.liveBackBufferLength:i;let c=-1/0;if(e(i)&&i>=0){const t=Math.max(i,d);c=Math.floor(h/d)*d-t}if(s){const t=this.getLoopBackBufferFlushEnd(s,null!=r?r:null);t>0&&(c=Math.max(c,t))}if(c>0&&this.flushBackBuffer(h,d,c),e(t)&&t>0){const e=Math.max(l.maxBufferLength,t),i=Math.max(e,d),s=Math.floor(h/d)*d+i;this.flushFrontBuffer(h,d,s)}}getLoopBackBufferFlushEnd(t,e){var i;const{media:s}=this;if(!1===(null==(i=this.hls)?void 0:i.config.loopBackBufferFlush)||null==s||!s.loop||!e||t.level<=e.level)return 0;const{video:r,audiovideo:n}=t.elementaryStreams;if(null!=r&&r.partial||null!=n&&n.partial)return 0;const a=this.getEarliestElementaryStreamStart(t)-.25;return a<=0?0:(this.log(`Flushing lower quality back buffer for loop: level ${t.level}, range [0-${a.toFixed(3)}]`),a)}getEarliestElementaryStreamStart(t){const{audio:e,video:i,audiovideo:s}=t.elementaryStreams;let r=t.start;return s?r=Math.min(r,s.startDTS):(e&&(r=Math.min(r,e.startDTS)),i&&(r=Math.min(r,i.startDTS))),r}flushBackBuffer(t,e,i){this.sourceBuffers.forEach(([t,e])=>{if(e){const o=Ei.getBuffered(e);if(o.length>0&&i>o.start(0)){var s,r,n;this.hls.trigger(a.BACK_BUFFER_REACHED,{bufferEnd:i});const e=this.tracks[t];if(null!=(s=this.details)&&s.live)this.hls.trigger(a.LIVE_BACK_BUFFER_REACHED,{bufferEnd:i});else if(null!=e&&e.ended&&(null==(r=this.media)||!r.loop||!1===(null==(n=this.hls)?void 0:n.config.loopBackBufferFlush)))return void this.log(`Cannot flush ${t} back buffer while SourceBuffer is in ended state`);this.hls.trigger(a.BUFFER_FLUSHING,{startOffset:0,endOffset:i,type:t})}}})}flushFrontBuffer(t,e,i){this.sourceBuffers.forEach(([e,s])=>{if(s){const r=Ei.getBuffered(s),n=r.length;if(n<2)return;const o=r.start(n-1),l=r.end(n-1);if(i>o||t>=o&&t<=l)return;this.hls.trigger(a.BUFFER_FLUSHING,{startOffset:o,endOffset:1/0,type:e})}})}getDurationAndRange(){var t;const{details:i,mediaSource:s}=this;if(!i||!this.media||"open"!==(null==s?void 0:s.readyState))return null;const r=i.edge;if(i.live&&this.hls.config.liveDurationInfinity){if(i.fragments.length&&s.setLiveSeekableRange){const t=Math.max(0,i.fragmentStart);return{duration:1/0,start:t,end:Math.max(t,r)}}return{duration:1/0}}const n=null==(t=this.overrides)?void 0:t.duration;if(n)return e(n)?{duration:n}:null;const a=this.media.duration;return r>(e(s.duration)?s.duration:0)&&r>a||!e(a)?{duration:r}:null}updateMediaSource({duration:t,start:i,end:s}){const r=this.mediaSource;r&&this.media&&"open"===r.readyState&&(r.duration!==t&&(e(t)&&this.log(`Updating MediaSource duration to ${t.toFixed(3)}`),r.duration=t),void 0!==i&&void 0!==s&&(this.log(`MediaSource duration is set to ${r.duration}. Setting seekable range to ${i}-${s}.`),r.setLiveSeekableRange(i,s)))}get tracksReady(){const t=this.pendingTrackCount;return t>0&&(t>=this.bufferCodecEventsTotal||this.isPending(this.tracks.audiovideo))}checkPendingTracks(){const{bufferCodecEventsTotal:t,pendingTrackCount:e,tracks:i}=this;if(this.log(`checkPendingTracks (pending: ${e} codec events expected: ${t}) ${Ue(i)}`),this.tracksReady){var s;const t=null==(s=this.transferData)?void 0:s.tracks;t&&Object.keys(t).length?this.attachTransferred():this.createSourceBuffers()}}bufferCreated(){if(this.sourceBufferCount){const t={};this.sourceBuffers.forEach(([e,i])=>{if(e){const s=this.tracks[e];t[e]={buffer:i,container:s.container,codec:s.codec,supplemental:s.supplemental,levelCodec:s.levelCodec,id:s.id,metadata:s.metadata}}}),this.hls.trigger(a.BUFFER_CREATED,{tracks:t}),this.log(`SourceBuffers created. Running queue: ${this.operationQueue}`),this.sourceBuffers.forEach(([t])=>{this.executeNext(t)})}else{const t=new Error("could not create source buffer for media codec(s)");this.hls.trigger(a.ERROR,{type:r.MEDIA_ERROR,details:n.BUFFER_INCOMPATIBLE_CODECS_ERROR,fatal:!0,error:t,reason:t.message})}}createSourceBuffers(){const{tracks:t,sourceBuffers:e,mediaSource:i}=this;if(!i)throw new Error("createSourceBuffers called when mediaSource was null");for(const o in t){const l=o,h=t[l];if(this.isPending(h)){const t=this.getTrackCodec(h,l),o=`${h.container};codecs=${t}`;h.codec=t,this.log(`creating sourceBuffer(${o})${this.currentOp(l)?" Queued":""} ${Ue(h)}`);try{const t=i.addSourceBuffer(o),s=_i(l),r=[l,t];e[s]=r,h.buffer=t}catch(t){var s;return this.error(`error while trying to add sourceBuffer: ${t.message}`),this.shiftAndExecuteNext(l),null==(s=this.operationQueue)||s.removeBlockers(),delete this.tracks[l],void this.hls.trigger(a.ERROR,{type:r.MEDIA_ERROR,details:n.BUFFER_ADD_CODEC_ERROR,fatal:!1,error:t,sourceBufferName:l,mimeType:o,parent:h.id})}this.trackSourceBuffer(l,h)}}this.bufferCreated()}clearBufferAppendTimeoutId(t){t&&(self.clearTimeout(t.bufferAppendTimeoutId),t.bufferAppendTimeoutId=void 0)}getTrackCodec(t,e){const i=t.supplemental;let s=t.codec;i&&("video"===e||"audiovideo"===e)&&he(i,"video")&&(s=function(t,e){const i=[];if(t){const e=t.split(",");for(let t=0;t<e.length;t++)le(e[t],"video")||i.push(e[t])}return e&&i.push(e),i.join(",")}(s,i));const r=ve(s,t.levelCodec);return r?"audio"===e.slice(0,5)?pe(r,this.appendSource):r:""}trackSourceBuffer(t,e){const i=e.buffer;if(!i)return;const s=this.getTrackCodec(e,t);this.tracks[t]={buffer:i,codec:s,container:e.container,levelCodec:e.levelCodec,supplemental:e.supplemental,metadata:e.metadata,id:e.id,listeners:[]},this.removeBufferListeners(t),this.addBufferListener(t,"updatestart",this.onSBUpdateStart),this.addBufferListener(t,"updateend",this.onSBUpdateEnd),this.addBufferListener(t,"error",this.onSBUpdateError),this.appendSource&&this.addBufferListener(t,"bufferedchange",(t,e)=>{const i=e.removedRanges;null!=i&&i.length&&(this.log(`${t} buffer removed ${bi(i)}`),this.hls.trigger(a.BUFFER_FLUSHED,{type:t,start:i.start(0),end:i.end(i.length-1)}))})}get mediaSrc(){var t;const e=this.media;if(!e)return;return(e.src?e:(null==(t=e.querySelector)?void 0:t.call(e,"source"))||e).src}isMediaSourceReplaced(t=this._objectUrl){var e;if(!t)return!1;const i=null==(e=this.media)?void 0:e.currentSrc,s=this.mediaSrc;return!!i&&i!==t||!!s&&s!==t}onSBUpdateStart(t){const e=this.currentOp(t);e&&e.onStart()}onSBUpdateEnd(t){var e,i;if("closed"===(null==(e=this.mediaSource)?void 0:e.readyState))return void this.resetBuffer(t);const s=this.currentOp(t);if(!s)return;s.onComplete();if(null==(i=this.tracks[t])||null==(i=i.buffer)?void 0:i.updating)return this.log(`${t} SourceBuffer updating on "updateend"`),void this.blockUntilOpen(()=>{this.shiftAndExecuteNext(t)});this.shiftAndExecuteNext(t)}onSBUpdateError(t,e){var i;const s=null==(i=this.mediaSource)?void 0:i.readyState,o=new Error(`${t} SourceBuffer error. MediaSource readyState: ${s}`);o.name=Ii,this.error(`${o.message}`,e),this.hls.trigger(a.ERROR,{type:r.MEDIA_ERROR,details:n.BUFFER_APPENDING_ERROR,sourceBufferName:t,error:o,fatal:!1});const l=this.currentOp(t);l&&l.onError(o)}updateTimestampOffset(t,e,i,s,r,n){const a=e-t.timestampOffset;Math.abs(a)>=i&&(this.log(`Updating ${s} SourceBuffer timestampOffset to ${e} (sn: ${r} cc: ${n})`),t.timestampOffset=e)}removeExecutor(t,i,s){const{media:r,mediaSource:n}=this,a=this.tracks[t],o=null==a?void 0:a.buffer;if(!r||!n||!o)throw new Error(`Attempting to remove from the ${t} SourceBuffer, but it does not exist`);const l=e(r.duration)?r.duration:1/0,h=e(n.duration)?n.duration:1/0,d=Math.max(0,i);var c;if(d>=h)return null==(c=this.currentOp(t))||c.onComplete(),void this.shiftAndExecuteNext(t);const u=Math.min(s,l,h);if(!(u>d)||a.ending&&!a.ended)throw new Error(`Cannot remove ${u<=d?`invalid range (${d} >= ${u}) `:""}from the ${t} SourceBuffer${a.ending?" while track ending":""}`);a.ended=!1,this.log(`Removing [${d},${u}] from the ${t} SourceBuffer`),o.remove(d,u)}appendExecutor(t,e){const i=this.tracks[e],s=null==i?void 0:i.buffer;if(!s)throw new Ri(`Attempting to append to the ${e} SourceBuffer, but it does not exist`);if(i.ending=!1,i.ended=!1,this.hls.config.appendTimeout!==1/0){const t=this.calculateAppendTimeoutTime(s);i.bufferAppendTimeoutId=self.setTimeout(()=>this.appendTimeoutHandler(e,s,t),t)}s.appendBuffer(t)}appendTimeoutHandler(t,e,i){this.log(`Received timeout after ${i}ms for append on ${t} source buffer. Aborting and triggering error.`);try{e.abort()}catch(e){this.log(`Failed to abort append on ${t} source buffer after timeout.`)}const s=this.currentOp(t);s&&s.onError(new Error(`${t}-append-timeout`))}calculateAppendTimeoutTime(t){let e=10;this.details&&(e=this.details.levelTargetDuration);let i=2*e*1e3;if(null===this.media)return i;const s=Ei.bufferInfo(t,this.media.currentTime,0);return s.len?(i=Math.max(1e3*s.len,i),Math.max(this.hls.config.appendTimeout,i)):i}blockUntilOpen(t){if(this.isUpdating()||this.isQueued())this.blockBuffers(t).catch(t=>{this.warn(`SourceBuffer blocked callback ${t}`),this.stepOperationQueue(this.sourceBufferTypes)});else try{t()}catch(t){this.warn(`Callback run without blocking ${this.operationQueue} ${t}`)}}isUpdating(){return this.sourceBuffers.some(([t,e])=>t&&e.updating)}isQueued(){return this.sourceBuffers.some(([t])=>t&&!!this.currentOp(t))}isPending(t){return!!t&&!t.buffer}isAudioBlocked(){var t;return"block-audio"===(null==(t=this.currentOp("audio"))?void 0:t.label)}isAudioBlocking(){return!!this.operationQueue&&this.operationQueue.audioBlocking()}blockBuffers(t,e=this.sourceBufferTypes){if(!e.length)return this.log("Blocking operation requested, but no SourceBuffers exist"),Promise.resolve().then(t);const{operationQueue:i}=this,s=2===e.length&&this.isAudioBlocking()?[this.appendBlocker("video")]:e.map(t=>this.appendBlocker(t));return Promise.all(s).then(e=>{i===this.operationQueue&&(t(),this.stepOperationQueue(this.sourceBufferTypes))})}stepOperationQueue(t){t.forEach(t=>{var e;const i=null==(e=this.tracks[t])?void 0:e.buffer;!i||i.updating||"audio"===t&&this.isAudioBlocked()||this.shiftAndExecuteNext(t)})}append(t,e,i){this.operationQueue&&this.operationQueue.append(t,e,i)}insertNext(t,e){this.operationQueue&&this.operationQueue.insertNext(t,e)}appendBlocker(t){if(this.operationQueue)return this.operationQueue.appendBlocker(t)}currentOp(t){return this.operationQueue?this.operationQueue.current(t):null}executeNext(t){t&&this.operationQueue&&this.operationQueue.executeNext(t)}shiftAndExecuteNext(t){this.operationQueue&&this.operationQueue.shiftAndExecuteNext(t)}get pendingTrackCount(){return Object.keys(this.tracks).reduce((t,e)=>t+(this.isPending(this.tracks[e])?1:0),0)}get sourceBufferCount(){return this.sourceBuffers.reduce((t,[e])=>t+(e?1:0),0)}get sourceBufferTypes(){return this.sourceBuffers.map(([t])=>t).filter(t=>!!t)}addBufferListener(t,e,i){const s=this.tracks[t];if(!s)return;const r=s.buffer;if(!r)return;const n=i.bind(this,t);s.listeners.push({event:e,listener:n}),Ti(r,e,n)}removeBufferListeners(t){const e=this.tracks[t];if(!e)return;const i=e.buffer;i&&(e.listeners.forEach(t=>{Si(i,t.event,t.listener)}),e.listeners.length=0)}},capLevelController:aa,errorController:class extends U{constructor(t){super("error-controller",t.logger),this.hls=void 0,this.playlistError=0,this.hls=t,this.registerListeners()}registerListeners(){const t=this.hls;t.on(a.ERROR,this.onError,this),t.on(a.MANIFEST_LOADING,this.onManifestLoading,this),t.on(a.LEVEL_UPDATED,this.onLevelUpdated,this)}unregisterListeners(){const t=this.hls;t&&(t.off(a.ERROR,this.onError,this),t.off(a.ERROR,this.onErrorOut,this),t.off(a.MANIFEST_LOADING,this.onManifestLoading,this),t.off(a.LEVEL_UPDATED,this.onLevelUpdated,this))}destroy(){this.unregisterListeners(),this.hls=null}startLoad(t){}stopLoad(){this.playlistError=0}getVariantLevelIndex(t){return(null==t?void 0:t.type)===f.MAIN?t.level:this.getVariantIndex()}getVariantIndex(){var t;const e=this.hls,i=e.currentLevel;return null!=(t=e.loadLevelObj)&&t.details||-1===i?e.loadLevel:i}variantHasKey(t,e){if(t){var i;if(null!=(i=t.details)&&i.hasKey(e))return!0;const s=t.audioGroups;if(s){return this.hls.allAudioTracks.filter(t=>s.indexOf(t.groupId)>=0).some(t=>{var i;return null==(i=t.details)?void 0:i.hasKey(e)})}}return!1}onManifestLoading(){this.playlistError=0}onLevelUpdated(){this.playlistError=0}onError(t,e){var i;if(e.fatal)return;const s=this.hls,a=e.context;switch(e.details){case n.FRAG_LOAD_ERROR:case n.FRAG_LOAD_TIMEOUT:case n.KEY_LOAD_ERROR:case n.KEY_LOAD_TIMEOUT:return void(e.errorAction=this.getFragRetryOrSwitchAction(e));case n.FRAG_PARSING_ERROR:if(null!=(i=e.frag)&&i.gap)return void(e.errorAction=pi());case n.FRAG_GAP:case n.FRAG_DECRYPT_ERROR:return e.errorAction=this.getFragRetryOrSwitchAction(e),void(e.errorAction.action=ni);case n.PLAYLIST_UNCHANGED_ERROR:case n.LEVEL_EMPTY_ERROR:case n.LEVEL_PARSING_ERROR:{var o;const t=e.parent===f.MAIN?e.level:s.loadLevel;e.details===n.LEVEL_EMPTY_ERROR&&null!=(o=e.context)&&null!=(o=o.levelDetails)&&o.live?e.errorAction=this.getPlaylistRetryOrSwitchAction(e,t):(e.levelRetry=!1,e.errorAction=this.getLevelSwitchAction(e,t))}return;case n.LEVEL_LOAD_ERROR:case n.LEVEL_LOAD_TIMEOUT:return void("number"==typeof(null==a?void 0:a.level)&&(e.errorAction=this.getPlaylistRetryOrSwitchAction(e,a.level)));case n.AUDIO_TRACK_LOAD_ERROR:case n.AUDIO_TRACK_LOAD_TIMEOUT:case n.SUBTITLE_LOAD_ERROR:case n.SUBTITLE_TRACK_LOAD_TIMEOUT:if(a){const t=s.loadLevelObj;if(t&&(a.type===u.AUDIO_TRACK&&t.hasAudioGroup(a.groupId)||a.type===u.SUBTITLE_TRACK&&t.hasSubtitleGroup(a.groupId)))return e.errorAction=this.getPlaylistRetryOrSwitchAction(e,s.loadLevel),e.errorAction.action=ni,void(e.errorAction.flags=hi)}return;case n.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:return void(e.errorAction={action:ni,flags:di});case n.KEY_SYSTEM_SESSION_UPDATE_FAILED:case n.KEY_SYSTEM_STATUS_INTERNAL_ERROR:case n.KEY_SYSTEM_NO_SESSION:return void(e.errorAction={action:ni,flags:ci});case n.BUFFER_ADD_CODEC_ERROR:case n.REMUX_ALLOC_ERROR:case n.BUFFER_APPEND_ERROR:return void(e.errorAction||(e.errorAction=this.getLevelSwitchAction(e,e.level)));case n.MEDIA_SOURCE_REQUIRES_RESET:return e.errorAction||(e.errorAction=this.getLevelSwitchAction(e,e.level)),void(e.errorAction.flags|=fi|ui);case n.INTERNAL_EXCEPTION:case n.BUFFER_APPENDING_ERROR:case n.BUFFER_APPEND_NO_PROGRESS:case n.BUFFER_FULL_ERROR:case n.LEVEL_SWITCH_ERROR:case n.BUFFER_STALLED_ERROR:case n.BUFFER_SEEK_OVER_HOLE:case n.BUFFER_NUDGE_ON_STALL:return void(e.errorAction=pi())}e.type===r.KEY_SYSTEM_ERROR&&(e.levelRetry=!1,e.errorAction=pi())}getPlaylistRetryOrSwitchAction(t,e){const i=C(this.hls.config.playlistLoadPolicy,t),s=this.playlistError++;if(O(i,s,D(t),t.response))return{action:oi,flags:li,retryConfig:i,retryCount:s};const r=this.getLevelSwitchAction(t,e);return i&&(r.retryConfig=i,r.retryCount=s),r}getFragRetryOrSwitchAction(t){const e=this.hls,i=this.getVariantLevelIndex(t.frag),s=e.levels[i],{fragLoadPolicy:r,keyLoadPolicy:a}=e.config,o=C(w(t)?a:r,t),l=e.levels.reduce((t,e)=>t+e.fragmentError,0);if(s&&(t.details!==n.FRAG_GAP&&s.fragmentError++,!P(t))){if(O(o,l,D(t),t.response))return{action:oi,flags:li,retryConfig:o,retryCount:l}}const h=this.getLevelSwitchAction(t,i);return o&&(h.retryConfig=o,h.retryCount=l),h}getLevelSwitchAction(t,e){const i=this.hls;null==e&&(e=i.loadLevel);const s=this.hls.levels[e];if(s){var r,a;const e=t.details;s.loadError++,s.loadErrorTime=self.performance.now(),e===n.BUFFER_APPEND_ERROR&&s.fragmentError++;let h=-1;const{levels:d,loadLevel:c,minAutoLevel:g,maxAutoLevel:m}=i;i.autoLevelEnabled||i.config.preserveManualLevelOnError||(i.loadLevel=-1);const p=null==(r=t.frag)?void 0:r.type,v=(p===f.AUDIO&&e===n.FRAG_PARSING_ERROR||"audio"===t.sourceBufferName&&gi(t))&&d.some(({audioCodec:t})=>s.audioCodec!==t),y="video"===t.sourceBufferName&&gi(t)&&d.some(({codecSet:t,audioCodec:e})=>s.codecSet!==t&&s.audioCodec===e),{type:E,groupId:T}=null!=(a=t.context)?a:{};for(let r=d.length;r--;){const a=(r+c)%d.length;if(a!==c&&a>=g&&a<=m&&(0===d[a].loadError||N(d[a],i.config.errorPenaltyExpireMs))){var o,l;const i=d[a];if(e===n.FRAG_GAP&&p===f.MAIN&&t.frag){const e=d[a].details;if(e){const i=Je(t.frag,e.fragments,t.frag.start);if(null!=i&&i.gap)continue}}else{if(E===u.AUDIO_TRACK&&i.hasAudioGroup(T)||E===u.SUBTITLE_TRACK&&i.hasSubtitleGroup(T))continue;if(p===f.AUDIO&&null!=(o=s.audioGroups)&&o.some(t=>i.hasAudioGroup(t))||p===f.SUBTITLE&&null!=(l=s.subtitleGroups)&&l.some(t=>i.hasSubtitleGroup(t))||v&&s.audioCodec===i.audioCodec||y&&s.codecSet===i.codecSet||!v&&s.audioCodec!==i.audioCodec)continue}h=a;break}}if(h>-1&&i.loadLevel!==h)return t.levelRetry=!0,this.playlistError=0,{action:ni,flags:li,nextAutoLevel:h}}return{action:ni,flags:hi}}onErrorOut(t,e){var i,s;switch(null==(i=e.errorAction)?void 0:i.action){case ri:break;case ni:this.sendAlternateToPenaltyBox(e),e.errorAction.resolved||e.details===n.FRAG_GAP||e.details===n.PLAYLIST_UNCHANGED_ERROR||mi(e)||(e.fatal=!0)}((null==(s=e.errorAction)?void 0:s.flags)||0)&fi&&this.hls.recoverMediaError(),e.fatal&&this.hls.stopLoad()}sendAlternateToPenaltyBox(t){const e=this.hls,i=t.errorAction;if(!i)return;let s=i.nextAutoLevel;if(i.flags===li)this.switchLevel(t,s);else if(i.flags&ui){const t=this.hls.levels;for(let e=t.length;e--;)"SDR"!==t[e].videoRange?(t[e].fragmentError++,t[e].loadError++):void 0===s&&(s=e)}else if(i.flags&di){const s=this.getVariantLevelIndex(t.frag),r=e.levels[s],n=null==r?void 0:r.attrs["HDCP-LEVEL"];i.hdcpLevel=n;const a="NONE"===n;n&&!a?(e.maxHdcpLevel=we[we.indexOf(n)-1],i.resolved=!0,this.warn(`Restricting playback to HDCP-LEVEL of "${e.maxHdcpLevel}" or lower`)):(a&&this.warn("HDCP policy resticted output with HDCP-LEVEL=NONE"),i.flags|=ci)}if(i.flags&ci){const e=t.decryptdata;if(e){const s=this.hls.levels,a=s.length;for(let i=a;i--;){var r,n;if(this.variantHasKey(s[i],e))this.log(`Banned key found in level ${i} (${s[i].bitrate}bps) or audio group "${null==(r=s[i].audioGroups)?void 0:r.join(",")}" (${null==(n=t.frag)?void 0:n.type} fragment) ${mt(e.keyId||[])}`),s[i].fragmentError++,s[i].loadError++,this.log(`Removing level ${i} with key error (${t.error})`),this.hls.removeLevel(i)}const o=t.frag;if(this.hls.levels.length<a)i.resolved=!0;else if(o&&o.type!==f.MAIN){const t=o.decryptdata;t&&!e.matches(t)&&(i.resolved=!0)}}}i.resolved||this.switchLevel(t,s)}switchLevel(t,e){if(void 0!==e&&t.errorAction&&(this.warn(`switching to level ${e} after ${t.details}`),this.hls.nextAutoLevel=e,t.errorAction.resolved=!0,this.hls.nextLoadLevel=this.hls.nextAutoLevel,t.details===n.BUFFER_ADD_CODEC_ERROR&&t.mimeType&&"audiovideo"!==t.sourceBufferName)){const e=Se(t.mimeType),i=this.hls.levels;for(let s=i.length;s--;)i[s][`${t.sourceBufferName}Codec`]===e&&(this.log(`Removing level ${s} for ${t.details} ("${e}" not supported)`),this.hls.removeLevel(s))}}},fpsController:class{constructor(t){this.hls=void 0,this.isVideoPlaybackQualityAvailable=!1,this.timer=void 0,this.media=null,this.lastTime=void 0,this.lastDroppedFrames=0,this.lastDecodedFrames=0,this.streamController=void 0,this.hls=t,this.registerListeners()}setStreamController(t){this.streamController=t}registerListeners(){this.hls.on(a.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.on(a.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListeners(){this.hls.off(a.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.off(a.MEDIA_DETACHING,this.onMediaDetaching,this)}destroy(){this.timer&&clearInterval(this.timer),this.unregisterListeners(),this.isVideoPlaybackQualityAvailable=!1,this.media=null}onMediaAttaching(t,e){const i=this.hls.config;if(i.capLevelOnFPSDrop){const t=e.media instanceof self.HTMLVideoElement?e.media:null;this.media=t,t&&"function"==typeof t.getVideoPlaybackQuality&&(this.isVideoPlaybackQualityAvailable=!0),self.clearInterval(this.timer),this.timer=self.setInterval(this.checkFPSInterval.bind(this),i.fpsDroppedMonitoringPeriod)}}onMediaDetaching(){this.media=null}checkFPS(t,e,i){const s=performance.now();if(e){if(this.lastTime){const t=s-this.lastTime,r=i-this.lastDroppedFrames,n=e-this.lastDecodedFrames,o=1e3*r/t,l=this.hls;if(l.trigger(a.FPS_DROP,{currentDropped:r,currentDecoded:n,totalDroppedFrames:i}),o>0&&r>l.config.fpsDroppedMonitoringThreshold*n){let t=l.currentLevel;l.logger.warn("drop FPS ratio greater than max allowed value for currentLevel: "+t),t>0&&(-1===l.autoLevelCapping||l.autoLevelCapping>=t)&&(t-=1,l.trigger(a.FPS_DROP_LEVEL_CAPPING,{level:t,droppedLevel:l.currentLevel}),l.autoLevelCapping=t,this.streamController.nextLevelSwitch())}}this.lastTime=s,this.lastDroppedFrames=i,this.lastDecodedFrames=e}}checkFPSInterval(){const t=this.media;if(t)if(this.isVideoPlaybackQualityAvailable){const e=t.getVideoPlaybackQuality();this.checkFPS(t,e.totalVideoFrames,e.droppedVideoFrames)}else this.checkFPS(t,t.webkitDecodedFrameCount,t.webkitDroppedFrameCount)}},id3TrackController:class{constructor(t){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(a.EVENT_CUE_ENTER,{})},this.hls=t,this._registerListeners()}destroy(){this._unregisterListeners(),this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.hls=this.onEventCueEnter=null}_registerListeners(){const{hls:t}=this;t&&(t.on(a.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(a.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(a.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(a.MANIFEST_LOADING,this.onManifestLoading,this),t.on(a.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),t.on(a.BUFFER_FLUSHING,this.onBufferFlushing,this),t.on(a.LEVEL_UPDATED,this.onLevelUpdated,this),t.on(a.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))}_unregisterListeners(){const{hls:t}=this;t&&(t.off(a.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(a.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(a.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(a.MANIFEST_LOADING,this.onManifestLoading,this),t.off(a.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),t.off(a.BUFFER_FLUSHING,this.onBufferFlushing,this),t.off(a.LEVEL_UPDATED,this.onLevelUpdated,this),t.off(a.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))}onMediaAttaching(t,e){this.media=e.media}onMediaAttached(){var t;const e=null==(t=this.hls)?void 0:t.latestLevelDetails;e&&this.updateDateRangeCues(e)}onMediaDetaching(t,e){this.media=null;!!e.transferMedia||(this.id3Track&&(this.id3Track.remove(),this.id3Track=null),this.dateRangeCuesAppended={})}onManifestLoading(){this.dateRangeCuesAppended={}}createTrack(t){return Rl(t,"metadata","id3","","hidden")}onFragParsingMetadata(t,e){if(!this.media||!this.hls)return;const{enableEmsgMetadataCues:i,enableID3MetadataCues:s}=this.hls.config;if(!i&&!s)return;const{samples:r}=e;this.id3Track||(this.id3Track=this.createTrack(this.media));const n=Ml();if(n)for(let t=0;t<r.length;t++){const e=r[t].type;if(e===qr.emsg&&!i||!s)continue;const a=ct(r[t].data),o=r[t].pts;let l=o+r[t].duration;l>Fl&&(l=Fl);l-o<=0&&(l=o+.25);for(let t=0;t<a.length;t++){const i=a[t];if(!ut(i)){this.updateId3CueEnds(o,e);const t=Ol(n,o,l,i,e);t&&this.id3Track.track.addCue(t)}}}}updateId3CueEnds(t,e){var i;const s=null==(i=this.id3Track)?void 0:i.track.cues;if(s)for(let i=s.length;i--;){const r=s[i];r.type===e&&r.startTime<t&&r.endTime===Fl&&(r.endTime=t)}}onBufferFlushing(t,{startOffset:e,endOffset:i,type:s}){const{id3Track:r,hls:n}=this;if(!n)return;const{config:{enableEmsgMetadataCues:a,enableID3MetadataCues:o}}=n;if(r&&(a||o)){let t;t="audio"===s?t=>t.type===qr.audioId3&&o:"video"===s?t=>t.type===qr.emsg&&a:t=>t.type===qr.audioId3&&o||t.type===qr.emsg&&a,Dl(r.track,e,i,t)}}onLevelUpdated(t,{details:e}){this.updateDateRangeCues(e,!0)}onLevelPtsUpdated(t,e){Math.abs(e.drift)>.01&&this.updateDateRangeCues(e.details)}updateDateRangeCues(t,i){if(!this.hls||!this.media)return;const{assetPlayerId:s,timelineOffset:r,enableDateRangeMetadataCues:n,interstitialsController:a}=this.hls.config;if(!n)return;const o=Ml();if(s&&r&&!a){const{fragmentStart:e,fragmentEnd:i}=t;let r=this.assetCue;r?(r.startTime=e,r.endTime=i):o&&(r=this.assetCue=Ol(o,e,i,{assetPlayerId:this.hls.config.assetPlayerId},"hlsjs.interstitial.asset"),r&&(r.id=s,this.id3Track||(this.id3Track=this.createTrack(this.media)),this.id3Track.track.addCue(r),r.addEventListener("enter",this.onEventCueEnter)))}if(!t.hasProgramDateTime)return;const{id3Track:l}=this,{dateRanges:h}=t,d=Object.keys(h);let c=this.dateRangeCuesAppended;var u;if(l&&i)if(null!=(u=l.track.cues)&&u.length){const t=Object.keys(c).filter(t=>-1===d.indexOf(t));for(let e=t.length;e--;){var f;const i=t[e],s=null==(f=c[i])?void 0:f.cues;delete c[i],s&&Object.keys(s).forEach(t=>{const e=s[t];if(e){e.removeEventListener("enter",this.onEventCueEnter);try{l.track.removeCue(e)}catch(t){}}})}}else c=this.dateRangeCuesAppended={};const g=t.fragments[t.fragments.length-1];if(0!==d.length&&e(null==g?void 0:g.programDateTime)){this.id3Track||(this.id3Track=this.createTrack(this.media));for(let t=0;t<d.length;t++){const e=d[t],i=h[e],s=i.startTime,r=c[e],n=(null==r?void 0:r.cues)||{};let l=(null==r?void 0:r.durationKnown)||!1,u=Fl;const{duration:f,endDate:g}=i;if(g&&null!==f)u=s+f,l=!0;else if(i.endOnNext&&!l){const t=d.reduce((t,e)=>{if(e!==i.id){const s=h[e];if(s.class===i.class&&s.startDate>i.startDate&&(!t||i.startDate<t.startDate))return s}return t},null);t&&(u=t.startTime,l=!0)}const m=Object.keys(i.attr);for(let t=0;t<m.length;t++){const h=m[t];if(!hs(h))continue;const d=n[h];if(d)!l||null!=r&&r.durationKnown?Math.abs(d.startTime-s)>.01&&(d.startTime=s,d.endTime=u):d.endTime=u;else if(o){let t=i.attr[h];ds(h)&&(t=pt(t));const r=Ol(o,s,u,{key:h,data:t},qr.dateRange);r&&(r.id=e,this.id3Track.track.addCue(r),n[h]=r,a&&("X-ASSET-LIST"!==h&&"X-ASSET-URL"!==h||r.addEventListener("enter",this.onEventCueEnter)))}}c[e]={cues:n,dateRange:i,durationKnown:l}}}}},gapController:class extends Ji{constructor(t,e){super("gap-controller",t.logger),this.hls=void 0,this.fragmentTracker=void 0,this.media=null,this.mediaSource=void 0,this.nudgeRetry=0,this.skipRetry=0,this.stallReported=!1,this.stalled=null,this.moved=!1,this.seeking=!1,this.buffered={},this.lastCurrentTime=void 0,this.ended=0,this.waiting=0,this.onMediaPlaying=()=>{this.ended=0,this.waiting=0},this.onMediaWaiting=()=>{var t;null!=(t=this.media)&&t.seeking||(this.waiting=self.performance.now(),this.tick())},this.onMediaEnded=()=>{var t;this.hls&&(this.ended=(null==(t=this.media)?void 0:t.currentTime)||1,this.hls.trigger(a.MEDIA_ENDED,{stalled:!1}))},this.hls=t,this.fragmentTracker=e,this.lastCurrentTime=this.getCurrentTime(),this.registerListeners()}registerListeners(){const{hls:t}=this;t&&(t.on(a.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(a.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(a.BUFFER_APPENDED,this.onBufferAppended,this))}unregisterListeners(){const{hls:t}=this;t&&(t.off(a.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(a.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(a.BUFFER_APPENDED,this.onBufferAppended,this))}destroy(){super.destroy(),this.unregisterListeners(),this.media=this.hls=this.fragmentTracker=null,this.mediaSource=void 0}onMediaAttached(t,e){this.setInterval(100),this.mediaSource=e.mediaSource;const i=this.media=e.media;Ti(i,"playing",this.onMediaPlaying),Ti(i,"waiting",this.onMediaWaiting),Ti(i,"ended",this.onMediaEnded)}onMediaDetaching(t,e){this.clearInterval();const{media:i}=this;i&&(Si(i,"playing",this.onMediaPlaying),Si(i,"waiting",this.onMediaWaiting),Si(i,"ended",this.onMediaEnded),this.media=null),this.mediaSource=void 0}onBufferAppended(t,e){this.buffered=e.timeRanges}get hasBuffered(){return Object.keys(this.buffered).length>0}getCurrentTime(){var t;const e=(null==(t=this.hls)?void 0:t.config.timelineOffset)||0;return this.media?Math.max(this.media.currentTime,e):e}tick(){var t;if(null==(t=this.media)||!t.readyState||!this.hasBuffered)return;const e=this.getCurrentTime();this.media.currentTime<e||(this.poll(e,this.lastCurrentTime),this.lastCurrentTime=e)}poll(t,e){var i,s;const r=null==(i=this.hls)?void 0:i.config;if(!r)return;const n=this.media;if(!n)return;const{seeking:o}=n,l=this.seeking&&!o,h=!this.seeking&&o,d=n.paused&&!o||n.ended||0===n.playbackRate;if(this.seeking=o,t!==e)return e&&(this.ended=0),this.moved=!0,o||(this.skipRetry=this.nudgeRetry=0,r.nudgeOnVideoHole&&!d&&t>e&&this.nudgeOnVideoHole(t,e)),void(0===this.waiting&&this.stallResolved(t));if(h||l)return void(l&&this.stallResolved(t));if(d)return this.skipRetry=this.nudgeRetry=0,this.stallResolved(t),void(!this.ended&&n.ended&&this.hls&&(this.ended=t||1,this.hls.trigger(a.MEDIA_ENDED,{stalled:!1})));if(!Ei.getBuffered(n).length)return void(this.skipRetry=this.nudgeRetry=0);const c=Ei.bufferInfo(n,t,0),u=this.fragmentTracker;u&&this.hls&&xl(c,t,u,this.hls);const f=c.nextStart||0;if(o&&u&&this.hls){const e=wl(this.hls.inFlightFragments,t),i=c.len>2,s=!f||e||f-t>2&&!u.getPartialFragment(t);if(i||s)return;this.moved=!1}const g=null==(s=this.hls)?void 0:s.latestLevelDetails;if(!this.moved&&null!==this.stalled&&u){if(!(c.len>0)&&!f)return;const e=Math.max(f,c.start||0)-t,i=!(null==g||!g.live)?2*g.targetduration:2,s=Cl(t,u);if(e>0&&(e<=i||s))return void(n.paused||this._trySkipBufferHole(s))}const m=r.detectStallWithCurrentTimeMs,p=self.performance.now(),v=this.waiting;let y=this.stalled;if(null===y){if(!(v>0&&p-v<m))return void(this.stalled=p);y=this.stalled=v}const E=p-y;if(!o&&(E>=m||v&&this.moved)&&this.hls){var T;if("ended"===(null==(T=this.mediaSource)?void 0:T.readyState)&&(null==g||!g.live)&&Math.abs(t-((null==g?void 0:g.edge)||0))<1){if(this.ended)return;return this.ended=t||1,void this.hls.trigger(a.MEDIA_ENDED,{stalled:!0})}if(this._reportStall(c),!this.media||!this.hls)return;if(n.currentTime!==t){const e=t;return t=n.currentTime,this.moved=!0,void this.log(`currentTime changed ${e} > ${t}`)}}const S=Ei.bufferInfo(n,t,r.maxBufferHole);this._tryFixBufferStall(S,E,t)}stallResolved(t){const e=this.stalled;if(e&&this.hls&&(this.stalled=null,this.stallReported)){const i=self.performance.now()-e;this.log(`playback not stuck anymore @${t}, after ${Math.round(i)}ms`),this.stallReported=!1,this.waiting=0,this.hls.trigger(a.STALL_RESOLVED,{})}}nudgeOnVideoHole(t,e){var i;const s=this.buffered.video;if(this.hls&&this.media&&this.fragmentTracker&&null!=(i=this.buffered.audio)&&i.length&&s&&s.length>1&&t>s.end(0)){const i=Ei.bufferedInfo(Ei.timeRangesToArray(this.buffered.audio),t,0);if(i.len>1&&e>=i.start){const i=Ei.timeRangesToArray(s),o=Ei.bufferedInfo(i,e,0).bufferedIndex;if(o>-1&&o<i.length-1){const e=Ei.bufferedInfo(i,t,0).bufferedIndex,s=i[o].end,l=i[o+1].start;if((-1===e||e>o)&&l-s<1&&t-s<2){const i=new Error(`nudging playhead to flush pipeline after video hole. currentTime: ${t} hole: ${s} -> ${l} buffered index: ${e}`);this.warn(i.message),this.media.currentTime+=1e-6;let o=Cl(t,this.fragmentTracker);o&&"fragment"in o?o=o.fragment:o||(o=void 0);const h=Ei.bufferInfo(this.media,t,0);this.hls.trigger(a.ERROR,{type:r.MEDIA_ERROR,details:n.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:i,reason:i.message,frag:o,buffer:h.len,bufferInfo:h})}}}}}_tryFixBufferStall(t,e,i){var s,r;const{fragmentTracker:n,media:a}=this,o=null==(s=this.hls)?void 0:s.config;if(!a||!n||!o)return;const l=null==(r=this.hls)?void 0:r.latestLevelDetails,h=Cl(i,n);if(h||null!=l&&l.live&&i<l.fragmentStart){if(this._trySkipBufferHole(h)||!this.media)return}const d=t.buffered,c=this.adjacentTraversal(t,i);(d&&d.length>1&&t.len>o.maxBufferHole||t.nextStart&&(t.nextStart-i<o.maxBufferHole||c))&&(e>1e3*o.highBufferWatchdogPeriod||this.waiting)&&(this.warn("Trying to nudge playhead over buffer-hole"),this._tryNudgeBuffer(t))}adjacentTraversal(t,e){const i=this.fragmentTracker,s=t.nextStart;if(i&&s){const t=i.getFragAtPos(e,f.MAIN),r=i.getFragAtPos(s,f.MAIN);if(t&&r)return r.sn-t.sn<2}return!1}_reportStall(t){const{hls:e,media:i,stallReported:s,stalled:o}=this;if(!s&&null!==o&&i&&e){this.stallReported=!0;const s=new Error(`Playback stalling at @${i.currentTime} due to low buffer (${Ue(t)})`);this.warn(s.message),e.trigger(a.ERROR,{type:r.MEDIA_ERROR,details:n.BUFFER_STALLED_ERROR,fatal:!1,error:s,buffer:t.len,bufferInfo:t,stalled:{start:o}})}}_trySkipBufferHole(t){const{fragmentTracker:e,media:i,hls:s}=this,o=null==s?void 0:s.config;if(!i||!e||!o)return 0;const l=i.currentTime,h=Ei.bufferInfo(i,l,0);xl(h,l,e,s);const d=l<h.start?h.start:h.nextStart;if(d){const u=h.len<=o.maxBufferHole,g=h.len>0&&h.len<1&&i.readyState<3,m=d-l;if(m>0&&(u||g)){if(m>o.maxBufferHole){let i=!1;if(0===l){const t=e.getAppendedFrag(0,f.MAIN);t&&d<t.end&&(i=!0)}if(!i&&t){var c;if(null==(c=s.loadLevelObj)||!c.details)return 0;if(wl(s.inFlightFragments,d))return 0;let i=!1,r=t.end;for(;r<d;){const t=Cl(r,e),s=t?t.duration:0;if(!(s>0)){i=!0;break}r+=s}if(i)return 0}}const{nudgeMaxRetry:u,skipBufferHolePadding:g}=o,p=++this.skipRetry>u,v=Math.max(d,l)+g;if(p||(this.warn(`skipping hole, adjusting currentTime from ${l} to ${v}`),this.moved=!0,i.currentTime=v),null==t||!t.gap||p){const e=new Error(p?`Playhead still not moving after seeking over buffer hole from ${l} to ${v} after ${o.nudgeMaxRetry} attempts.`:`fragment loaded with buffer holes, seeking from ${l} to ${v}`),i={type:r.MEDIA_ERROR,details:n.BUFFER_SEEK_OVER_HOLE,fatal:p,error:e,reason:e.message,buffer:h.len,bufferInfo:h};t&&("fragment"in t?i.part=t:i.frag=t),s.trigger(a.ERROR,i)}return v}}return 0}_tryNudgeBuffer(t){const{hls:e,media:i,nudgeRetry:s}=this,o=null==e?void 0:e.config;if(!i||!o)return 0;const l=i.currentTime;if(this.nudgeRetry++,s<o.nudgeMaxRetry){const h=l+(s+1)*o.nudgeOffset,d=new Error(`Nudging 'currentTime' from ${l} to ${h}`);this.warn(d.message),i.currentTime=h,e.trigger(a.ERROR,{type:r.MEDIA_ERROR,details:n.BUFFER_NUDGE_ON_STALL,error:d,fatal:!1,buffer:t.len,bufferInfo:t})}else{const i=new Error(`Playhead still not moving while enough data buffered @${l} after ${o.nudgeMaxRetry} nudges`);this.error(i.message),e.trigger(a.ERROR,{type:r.MEDIA_ERROR,details:n.BUFFER_STALLED_ERROR,error:i,fatal:!0,buffer:t.len,bufferInfo:t})}}},latencyController:class{constructor(t){this.hls=void 0,this.media=null,this.currentTime=0,this.stallCount=0,this._latency=null,this._targetLatencyUpdated=!1,this.onTimeupdate=()=>{var t;const{media:e}=this,i=this.levelDetails;if(!e||!i||!this.hls)return;this.currentTime=e.currentTime;const s=this.hls.config,r=this.computeLatency();if(null===r)return;this._latency=r;const{lowLatencyMode:n,maxLiveSyncPlaybackRate:a}=s;if(!n||1===a||!i.live)return;const o=this.targetLatency;if(null===o)return;const l=r-o,h=l<Math.min(this.maxLatency,o+i.targetduration),d=wr(s)&&!(null==(t=this.hls.interstitialsManager)||null==(t=t.playingItem)||!t.event);if(h&&l>.05&&this.forwardBufferLength>1&&!d){const t=Math.min(2,Math.max(1,a)),i=Math.round(2/(1+Math.exp(-.75*l-this.edgeStalled))*20)/20,s=Math.min(t,Math.max(1,i));this.changeMediaPlaybackRate(e,s)}else 1!==e.playbackRate&&0!==e.playbackRate&&this.changeMediaPlaybackRate(e,1)},this.hls=t,this.registerListeners()}get levelDetails(){var t;return(null==(t=this.hls)?void 0:t.latestLevelDetails)||null}get latency(){return this._latency||0}get maxLatency(){var t;const e=null==(t=this.hls)?void 0:t.config;if(!e)return 0;if(void 0!==e.liveMaxLatencyDuration)return e.liveMaxLatencyDuration;const i=this.levelDetails;return i?e.liveMaxLatencyDurationCount*i.targetduration:0}get targetLatency(){const t=this.levelDetails;if(null===t||!this.hls)return null;const e=this.hls.config,{holdBack:i,partHoldBack:s,targetduration:r}=t,{liveSyncDuration:n,liveSyncDurationCount:a,lowLatencyMode:o}=e,l=this.hls.userConfig;let h=o&&s||i;(this._targetLatencyUpdated||l.liveSyncDuration||l.liveSyncDurationCount||0===h)&&(h=void 0!==n?n:a*r);const d=r;return h+Math.min(this.stallCount*e.liveSyncOnStallIncrease,d)}set targetLatency(t){this.hls&&(this.stallCount=0,this.hls.config.liveSyncDuration=t,this._targetLatencyUpdated=!0)}get liveSyncPosition(){const t=this.estimateLiveEdge(),e=this.targetLatency;if(null===t||null===e||!this.hls)return null;const i=this.levelDetails;if(null===i)return null;const s=i.edge,r=t-e-this.edgeStalled,n=s-i.totalduration,a=s-(this.hls.config.lowLatencyMode&&i.partTarget||i.targetduration);return Math.min(Math.max(n,r),a)}get drift(){const t=this.levelDetails;return null===t?1:t.drift}get edgeStalled(){const t=this.levelDetails;if(null===t||!this.hls)return 0;const e=3*(this.hls.config.lowLatencyMode&&t.partTarget||t.targetduration);return Math.max(t.age-e,0)}get forwardBufferLength(){const{media:t}=this,e=this.levelDetails;if(!t||!e)return 0;const i=t.buffered.length;return(i?t.buffered.end(i-1):e.edge)-this.currentTime}destroy(){this.unregisterListeners(),this.onMediaDetaching(),this.hls=null}registerListeners(){const{hls:t}=this;t&&(t.on(a.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(a.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(a.MANIFEST_LOADING,this.onManifestLoading,this),t.on(a.LEVEL_UPDATED,this.onLevelUpdated,this),t.on(a.ERROR,this.onError,this),t.on(a.INTERSTITIAL_ASSET_STARTED,this.onAssetStarted,this))}unregisterListeners(){const{hls:t}=this;t&&(t.off(a.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(a.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(a.MANIFEST_LOADING,this.onManifestLoading,this),t.off(a.LEVEL_UPDATED,this.onLevelUpdated,this),t.off(a.ERROR,this.onError,this),t.off(a.INTERSTITIAL_ASSET_STARTED,this.onAssetStarted,this))}onMediaAttached(t,e){this.media=e.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(t,{details:e}){e.advanced&&this.onTimeupdate(),!e.live&&this.media&&this.media.removeEventListener("timeupdate",this.onTimeupdate)}onAssetStarted(t,e){var i;const s=this.hls,r=this.media||e.event.appendInPlace&&(null==s||null==(i=s.interstitialsManager)?void 0:i.playerQueue.reduce((t,e)=>t||e.media,null));s&&r&&r.playbackRate>1&&r.playbackRate<=s.config.maxLiveSyncPlaybackRate&&this.changeMediaPlaybackRate(r,1)}onError(t,e){var i;e.details===n.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(t,e){var i,s;t.playbackRate!==e&&(null==(i=this.hls)||i.logger.debug(`[latency-controller]: latency=${this.latency.toFixed(3)}, targetLatency=${null==(s=this.targetLatency)?void 0:s.toFixed(3)}, forwardBufferLength=${this.forwardBufferLength.toFixed(3)}: adjusting playback rate from ${t.playbackRate} to ${e}`),t.playbackRate=e)}estimateLiveEdge(){const t=this.levelDetails;return null===t?null:t.edge+t.age}computeLatency(){const t=this.estimateLiveEdge();return null===t?null:t-this.currentTime}}},{cueHandler:Oh,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 _r{constructor(t,e,i){super(t,e,i,"subtitle-stream-controller",f.SUBTITLE),this.currentTrackId=-1,this.tracksBuffered=[],this.mainDetails=null,this.registerListeners()}onHandlerDestroying(){this.unregisterListeners(),super.onHandlerDestroying(),this.mainDetails=null}registerListeners(){super.registerListeners();const{hls:t}=this;t.on(a.LEVEL_LOADED,this.onLevelLoaded,this),t.on(a.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.on(a.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),t.on(a.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.on(a.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),t.on(a.BUFFER_FLUSHING,this.onBufferFlushing,this)}unregisterListeners(){super.unregisterListeners();const{hls:t}=this;t.off(a.LEVEL_LOADED,this.onLevelLoaded,this),t.off(a.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.off(a.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),t.off(a.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.off(a.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),t.off(a.BUFFER_FLUSHING,this.onBufferFlushing,this)}startLoad(t,e){this.stopLoad(),this.state=vr,this.setInterval(500),this.nextLoadPosition=this.lastCurrentTime=t+this.timelineOffset,this.startPosition=e?-1:t,this.tick()}onManifestLoading(){super.onManifestLoading(),this.mainDetails=null}onMediaDetaching(t,e){this.tracksBuffered=[],super.onMediaDetaching(t,e)}onLevelLoaded(t,e){this.mainDetails=e.details}onSubtitleFragProcessed(t,e){var i,s;const{frag:r,part:n,success:a}=e;if(!a)return;const o=(i=this.tracksBuffered)[s=r.level]||(i[s]=[]);if(!o)return;let l;const h=(n||r).start;for(let t=0;t<o.length;t++)if(h>=o[t].start&&h<=o[t].end){l=o[t];break}const d=h+(n||r).duration;if(l?l.end=d:(l={start:h,end:d},o.push(l)),!n||d>=r.end-1e-6){const t=this.fragmentTracker.fragBuffered(r);n&&t&&(t.range.subs={time:[{startPTS:r.start,endPTS:d}],partial:!0}),y(r)&&!this.fragContextChanged(r)&&(this.fragPrevious=r),this.fragBufferedComplete(r,n),this.media&&this.tickImmediate()}}onBufferFlushing(t,e){const{startOffset:i,endOffset:s}=e;if(0===i&&s!==Number.POSITIVE_INFINITY){const t=s-1;if(t<=0)return;e.endOffsetSubtitles=Math.max(0,t),this.tracksBuffered.forEach(e=>{if(e)for(let i=0;i<e.length;)if(e[i].end<=t)e.shift();else{if(!(e[i].start<t))break;e[i].start=t,i++}}),this.fragmentTracker.removeFragmentsInRange(i,t,f.SUBTITLE)}}onError(t,e){const i=e.frag;(null==i?void 0:i.type)===f.SUBTITLE&&(e.details===n.FRAG_GAP&&this.fragmentTracker.addAsGap(i),this.fragCurrent&&this.fragCurrent.abortRequests(),this.state!==pr&&(this.state=vr))}onSubtitleTracksUpdated(t,{subtitleTracks:e}){this.levels&&ra(this.levels,e)?this.levels=e.map(t=>new Ne(t)):(this.tracksBuffered=[],this.levels=e.map(t=>new Ne(t)),this.fragmentTracker.removeFragmentsInRange(0,Number.POSITIVE_INFINITY,f.SUBTITLE),this.fragPrevious=null,this.mediaBuffer=null)}onSubtitleTrackSwitch(t,e){var i;if(this.currentTrackId=e.id,this.abortCurrentFrag(),null==(i=this.levels)||!i.length||-1===this.currentTrackId)return void this.clearInterval();const s=this.levels[this.currentTrackId];null!=s&&s.details?(this.mediaBuffer=this.mediaBufferTimeRanges,this.state!==pr&&this.setInterval(500)):this.mediaBuffer=null}onSubtitleTrackLoaded(t,e){var i;const{currentTrackId:s,levels:r}=this,{details:n,id:o}=e;if(!r)return void this.warn(`Subtitle tracks were reset while loading level ${o}`);const l=r[o];if(o>=r.length||!l)return;this.log(`Subtitle track ${o} loaded [${n.startSN},${n.endSN}]${n.lastPartSn?`[part-${n.lastPartSn}-${n.lastPartIndex}]`:""},duration:${n.totalduration}`),this.mediaBuffer=this.mediaBufferTimeRanges;const h=this.mainDetails;let d=0;if(n.live||null!=(i=l.details)&&i.live){if(n.deltaUpdateFailed)return;if(!h)return void(this.startFragRequested=!1);var c;if(l.details)d=this.alignPlaylists(n,l.details,null==(c=this.levelLastLoaded)?void 0:c.details);n.alignedSliding||(mr(h,n,this),d=n.fragmentStart)}l.details=n,this.levelLastLoaded=l,h&&!this.startFragRequested&&this.setStartPosition(h,d),o===s&&(this.hls.trigger(a.SUBTITLE_TRACK_UPDATED,{details:n,id:o,groupId:e.groupId}),this.tickImmediate())}_handleFragmentLoadProgress(t){const{frag:e,part:i,payload:s}=t;i&&null!=s&&s.byteLength&&this.shouldDecrypt(e)&&this.decryptPayload(s,e,i)}_handleFragmentLoadComplete(t){const{frag:e,payload:i}=t;!this.fragContextChanged(e)&&null!=i&&i.byteLength&&this.shouldDecrypt(e)&&this.decryptPayload(i,e,null)}shouldDecrypt(t){const e=t.decryptdata;return!!(null!=e&&e.key&&e.iv&&gs(e.method))}decryptPayload(t,e,i){const s=e.decryptdata,o=performance.now();this.decrypter.decrypt(new Uint8Array(t),s.key.buffer,s.iv.buffer,ms(s.method)).then(t=>{this.fragContextChanged(e)||this.hls.trigger(a.FRAG_DECRYPTED,{frag:e,part:i,payload:t,stats:{tstart:o,tdecrypt:performance.now()}})}).catch(t=>{this.hls.trigger(a.ERROR,{type:r.MEDIA_ERROR,details:n.FRAG_DECRYPT_ERROR,fatal:!1,error:t,reason:t.message,frag:e,part:i}),i||(this.warn(`${t.name}: ${t.message}`),this.state=vr)})}doTick(){if(this.state===vr&&this.levels){var t;if(!this.media&&!this.primaryPrefetch&&(this.startFragRequested||!this.config.startFragPrefetch))return;const{currentTrackId:i,levels:s}=this,r=s[i],n=null==r?void 0:r.details;if(!n||this.waitForLive(r)||this.waitForCdnTuneIn(n))return void(this.startFragRequested=!1);const{config:a}=this,o=this.playhead,l=Ei.bufferedInfo(this.tracksBuffered[i]||[],o,a.maxBufferHole),{end:h,len:d}=l;if(d>Math.max(this.hls.maxBufferLength+n.levelTargetDuration,(null==(t=this.hls.mainForwardBufferInfo)?void 0:t.len)||0)||d&&!this.buffering)return;let c=this.getNextFragment(h,n);if(!c)return;if(y(c)){var e;if(c.end===l.end)return;const t=c.sn-n.startSN,i=n.fragments[t-1];c.cc!==(null==i?void 0:i.cc)||null!=(e=n.partList)&&e.length||this.fragmentTracker.getState(i)!==xi||(c=i)}this.loadFragment(c,r,h)}}loadFragment(t,e,i){const s=this.fragmentTracker.getState(t);s!==xi&&s!==Oi||super.loadFragment(t,e,i)}get mediaBufferTimeRanges(){return new ch(this.tracksBuffered[this.currentTrackId]||[])}},subtitleTrackController:class extends sa{constructor(t){super(t,"subtitle-track-controller"),this.media=null,this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0,this.queuedDefaultTrack=-1,this.useTextTrackPolling=!1,this.subtitlePollingInterval=-1,this._subtitleDisplay=!0,this.asyncPollTrackChange=()=>this.pollTrackChange(0),this.onTextTracksChanged=()=>{if(this.useTextTrackPolling||self.clearInterval(this.subtitlePollingInterval),!this.media||!this.hls.config.renderTextTracksNatively)return;let t=-1,e=!1;if(this.currentTrack){var i;const s=null==(i=this.currentTrack.trackNode)?void 0:i.track.mode;"showing"===s?(t=this.trackId,e=!0):"hidden"===s&&(t=this.trackId)}if(!e)for(let e=0;e<this.tracksInGroup.length;e++){var s;const i=null==(s=this.tracksInGroup[e].trackNode)?void 0:s.track.mode;if("showing"===i){t=e;break}t<0&&"hidden"===i&&(t=e)}var r;t>-1&&(this._subtitleDisplay="showing"===(null==(r=this.tracksInGroup[t].trackNode)?void 0:r.track.mode));this.setSubtitleTrack(t,!0)},this.registerListeners()}destroy(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.currentTrack=null,this.onTextTracksChanged=this.asyncPollTrackChange=null,super.destroy()}get subtitleDisplay(){return this._subtitleDisplay}set subtitleDisplay(t){this._subtitleDisplay=t,this.trackId>-1&&this.toggleTrackModes()}registerListeners(){const{hls:t}=this;t.on(a.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(a.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(a.MANIFEST_LOADING,this.onManifestLoading,this),t.on(a.MANIFEST_PARSED,this.onManifestParsed,this),t.on(a.LEVEL_LOADING,this.onLevelLoading,this),t.on(a.LEVEL_SWITCHING,this.onLevelSwitching,this),t.on(a.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.on(a.ERROR,this.onError,this)}unregisterListeners(){const{hls:t}=this;t.off(a.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(a.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(a.MANIFEST_LOADING,this.onManifestLoading,this),t.off(a.MANIFEST_PARSED,this.onManifestParsed,this),t.off(a.LEVEL_LOADING,this.onLevelLoading,this),t.off(a.LEVEL_SWITCHING,this.onLevelSwitching,this),t.off(a.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.off(a.ERROR,this.onError,this)}createTracksInGroup(){var t;if(!this.media||!this.hls.config.renderTextTracksNatively)return;this.tracksInGroup.forEach(t=>{t.trackNode||(t.trackNode=Rl(this.media,kl(t),t.name,t.lang))});const e=null==(t=this.currentTrack)||null==(t=t.trackNode)?void 0:t.track;"disabled"===(null==e?void 0:e.mode)&&(e.mode=this._subtitleDisplay?"showing":"hidden")}onMediaAttached(t,e){const i=e.media;this.media=i;let s=this.trackId;this.queuedDefaultTrack>-1&&(s=this.queuedDefaultTrack,this.queuedDefaultTrack=-1),this.setSubtitleTrack(s),this.createTracksInGroup(),this.useTextTrackPolling=!(i.textTracks&&"onchange"in i.textTracks),this.useTextTrackPolling?this.pollTrackChange(500):i.textTracks.addEventListener("change",this.asyncPollTrackChange)}pollTrackChange(t){self.clearInterval(this.subtitlePollingInterval),this.subtitlePollingInterval=self.setInterval(this.onTextTracksChanged,t)}onMediaDetaching(t,e){const i=this.media;if(!i)return;const s=!!e.transferMedia;self.clearInterval(this.subtitlePollingInterval),this.useTextTrackPolling||i.textTracks.removeEventListener("change",this.asyncPollTrackChange),this.trackId>-1&&(this.queuedDefaultTrack=this.trackId,this.setSubtitleTrack(-1)),this.media=null,s||this.hls.config.renderTextTracksNatively&&this.tracksInGroup.forEach(t=>{const e=t.trackNode;e&&(e.track.mode="hidden",e.remove(),t.trackNode=void 0)})}onManifestLoading(){this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0}onManifestParsed(t,e){this.tracks=e.subtitleTracks}onSubtitleTrackLoaded(t,e){const{id:i,groupId:s,details:r}=e,n=this.tracksInGroup[i];if(!n||n.groupId!==s)return void this.warn(`Subtitle track with id:${i} and group:${s} not found in active group ${null==n?void 0:n.groupId}`);const a=n.details;n.details=e.details,this.log(`Subtitle track ${i} "${n.name}" lang:${n.lang} group:${s} loaded [${r.startSN}-${r.endSN}]`),i===this.trackId&&this.playlistLoaded(i,e,a)}onLevelLoading(t,e){this.switchLevel(e.level)}onLevelSwitching(t,e){this.switchLevel(e.level)}switchLevel(t){const e=this.hls.levels[t];if(!e)return;const i=e.subtitleGroups||null,s=this.groupIds;let r=this.currentTrack;if(!i||(null==s?void 0:s.length)!==(null==i?void 0:i.length)||null!=i&&i.some(t=>-1===(null==s?void 0:s.indexOf(t)))){this.groupIds=i;const t=[];if(this.tracks.forEach(e=>{(e.textCodec===ml?this.hls.config.enableIMSC1:this.hls.config.enableWebVTT)&&(!i||i.indexOf(e.groupId)>-1?(e.id=t.length,t.push(e)):e.trackNode&&(e.trackNode.remove(),e.trackNode=void 0))}),t.length===this.tracksInGroup.length){let e=!1;for(let i=0;i<t.length;i++)if(t[i]!==this.tracksInGroup[i]){e=!0;break}if(!e)return}t.length&&this.selectDefaultTrack&&!t.some(t=>t.default)&&(this.selectDefaultTrack=!1),this.tracksInGroup=t,this.trackId=-1,this.currentTrack=null;const e=this.hls.config.subtitlePreference;if(!r&&e){this.selectDefaultTrack=!1;const i=je(e,t);if(i>-1)r=t[i];else{const t=je(e,this.tracks);r=this.tracks[t]}}let s=this.findTrackId(r);-1===s&&r&&(s=this.findTrackId(null));const n={subtitleTracks:t};this.log(`Updating subtitle tracks, ${t.length} track(s) found in "${null==i?void 0:i.join(",")}" group-id`),this.hls.trigger(a.SUBTITLE_TRACKS_UPDATED,n),this.setSubtitleTrack(s),this.createTracksInGroup()}}findTrackId(t){const e=this.tracksInGroup,i=this.selectDefaultTrack;for(let s=0;s<e.length;s++){const r=e[s];if((!i||r.default)&&(i||t)&&(!t||He(r,t)))return s}if(t){for(let i=0;i<e.length;i++){const s=e[i];if(na(t.attrs,s.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return i}for(let i=0;i<e.length;i++){const s=e[i];if(na(t.attrs,s.attrs,["LANGUAGE"]))return i}}return-1}onError(t,e){!e.fatal&&e.context&&e.context.type===u.SUBTITLE_TRACK&&e.context.id===this.trackId&&ze(e.context.groupId,this.groupIds)&&this.checkRetry(e)}get allSubtitleTracks(){return this.tracks}get subtitleTracks(){return this.tracksInGroup}get subtitleTrack(){return this.trackId}set subtitleTrack(t){this.selectDefaultTrack=!1,this.setSubtitleTrack(t,!0)}setSubtitleOption(t){if(this.hls.config.subtitlePreference=t,t){if(-1===t.id)return this.setSubtitleTrack(-1,!0),null;const e=this.allSubtitleTracks;if(this.selectDefaultTrack=!1,e.length){const i=this.currentTrack;if(i&&He(t,i))return i;const s=je(t,this.tracksInGroup);if(s>-1){const t=this.tracksInGroup[s];return this.setSubtitleTrack(s,!0),t}if(i)return null;{const i=je(t,e);if(i>-1)return e[i]}}}return null}loadPlaylist(t){super.loadPlaylist(),this.shouldLoadPlaylist(this.currentTrack)&&this.scheduleLoading(this.currentTrack,t)}loadingPlaylist(t,e){super.loadingPlaylist(t,e);const i=t.id,s=t.groupId,r=this.getUrlWithDirectives(t.url,e),n=t.details,o=null==n?void 0:n.age;this.log(`Loading subtitle ${i} "${t.name}" lang:${t.lang} group:${s}${void 0!==(null==e?void 0:e.msn)?" at sn "+e.msn+" part "+e.part:""}${o&&n.live?" age "+o.toFixed(1)+(n.type&&" "+n.type||""):""} ${r}`),this.hls.trigger(a.SUBTITLE_TRACK_LOADING,{url:r,id:i,groupId:s,deliveryDirectives:e||null,track:t})}toggleTrackModes(){if(!this.media||!this.hls.config.renderTextTracksNatively)return;const t=this.currentTrack;this.tracksInGroup.forEach(e=>{if(e.trackNode){const i=e===t?this._subtitleDisplay?"showing":"hidden":"disabled",s=e.trackNode.track;s.mode!==i&&(s.mode=i)}})}setSubtitleTrack(t,i=!1){const s=this.tracksInGroup;if(this.media||(this.queuedDefaultTrack=t),t<-1||t>=s.length||!e(t))return void this.warn(`Invalid subtitle track id: ${t}`);const r=this.currentTrack,n=s[t]||null;if(this.trackId=t,this.currentTrack=n,i&&this.toggleTrackModes(),!n)return void(r&&this.hls.trigger(a.SUBTITLE_TRACK_SWITCH,{id:t}));const o=!!n.details&&!n.details.live;if(n===r&&o)return;this.log(`Switching to subtitle-track ${t}`+(n?` "${n.name}" lang:${n.lang} group:${n.groupId}`:""));const{id:l,groupId:h="",name:d,type:c,url:u}=n;this.hls.trigger(a.SUBTITLE_TRACK_SWITCH,{id:l,groupId:h,name:d,type:c,url:u});const f=this.switchParams(n.url,null==r?void 0:r.details,n.details);this.loadPlaylist(f)}},timelineController:class{constructor(t){this.hls=void 0,this.media=null,this.config=void 0,this.enabled=!0,this.Cues=void 0,this.tracks=[],this.initPTS=[],this.unparsedFrags=[],this.captionsTracks={},this.cueCache={},this.nonNativeCaptionsTracks={},this.cea608Parser1=void 0,this.cea608Parser2=void 0,this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs={ccOffset:0,presentationOffset:0,0:{start:0,prevCC:-1,new:!0}},this.captionsProperties=void 0,this.hls=t,this.config=t.config,this.Cues=t.config.cueHandler,this.cueCache={},this.captionsProperties={textTrack1:{label:this.config.captionsTextTrack1Label,languageCode:this.config.captionsTextTrack1LanguageCode},textTrack2:{label:this.config.captionsTextTrack2Label,languageCode:this.config.captionsTextTrack2LanguageCode},textTrack3:{label:this.config.captionsTextTrack3Label,languageCode:this.config.captionsTextTrack3LanguageCode},textTrack4:{label:this.config.captionsTextTrack4Label,languageCode:this.config.captionsTextTrack4LanguageCode}},t.on(a.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(a.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(a.MANIFEST_LOADING,this.onManifestLoading,this),t.on(a.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(a.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.on(a.FRAG_LOADING,this.onFragLoading,this),t.on(a.FRAG_LOADED,this.onFragLoaded,this),t.on(a.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),t.on(a.FRAG_DECRYPTED,this.onFragDecrypted,this),t.on(a.INIT_PTS_FOUND,this.onInitPtsFound,this),t.on(a.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),t.on(a.BUFFER_APPENDED,this.onBufferAppended,this),t.on(a.BUFFER_FLUSHING,this.onBufferFlushing,this)}destroy(){const{hls:t}=this;t.off(a.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(a.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(a.MANIFEST_LOADING,this.onManifestLoading,this),t.off(a.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(a.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.off(a.FRAG_LOADING,this.onFragLoading,this),t.off(a.FRAG_LOADED,this.onFragLoaded,this),t.off(a.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),t.off(a.FRAG_DECRYPTED,this.onFragDecrypted,this),t.off(a.INIT_PTS_FOUND,this.onInitPtsFound,this),t.off(a.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),t.off(a.BUFFER_APPENDED,this.onBufferAppended,this),t.off(a.BUFFER_FLUSHING,this.onBufferFlushing,this),this.hls=this.config=this.media=null,this.cea608Parser1=this.cea608Parser2=void 0}initCea608Parsers(){const t=new Ch(this,"textTrack1"),e=new Ch(this,"textTrack2"),i=new Ch(this,"textTrack3"),s=new Ch(this,"textTrack4");this.cea608Parser1=new Dh(1,t,e),this.cea608Parser2=new Dh(3,i,s)}addCues(t,e,i,s,r){let n=!1;for(let t=r.length;t--;){const s=r[t],a=xh(s[0],s[1],e,i);if(a>=0&&(s[0]=Math.min(s[0],e),s[1]=Math.max(s[1],i),n=!0,a/(i-e)>.5))return}if(n||r.push([e,i]),this.config.renderTextTracksNatively){const r=this.cueCache[t];if(r){const t=this.Cues.newCue(null,e,i,s);t.length&&r.push.apply(r,t)}else{const r=this.captionsTracks[t].track;this.Cues.newCue(r,e,i,s)}}else{var o;const r=this.Cues.newCue(null,e,i,s),n=null==(o=this.captionsProperties[t])?void 0:o.media;this.hls.trigger(a.CUES_PARSED,{type:"captions",cues:r,track:t,closedCaptions:n})}}onInitPtsFound(t,{id:e,timestampOffsets:i}){const{unparsedFrags:s}=this;e===f.MAIN&&(this.initPTS=i),s.length&&(this.unparsedFrags=[],s.forEach(t=>{this.initPTS[t.frag.cc]?this.onFragLoaded(a.FRAG_LOADED,t):this.hls.trigger(a.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:t.frag,part:null,error:new Error("Subtitle discontinuity domain does not match main")})}))}createCaptionsTrack(t){this.config.renderTextTracksNatively?this.createNativeTrack(t):this.createNonNativeTrack(t)}createNativeTrack(t){if(this.captionsTracks[t])return;const{captionsProperties:e,captionsTracks:i,cueCache:s,media:r}=this,{label:n,languageCode:a}=e[t];r&&(s[t]=[],i[t]=Rl(r,"captions",n,a,"hidden"))}createNonNativeTrack(t){if(this.nonNativeCaptionsTracks[t])return;const e=this.captionsProperties[t];if(!e)return;const i={_id:t,label:e.label,kind:"captions",default:!!e.media&&!!e.media.default,closedCaptions:e.media};this.nonNativeCaptionsTracks[t]=i,this.hls.trigger(a.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:[i]})}onMediaAttaching(t,e){this.media=e.media}onMediaDetaching(t,e){const i=!!e.transferMedia;if(this.media=null,!i){if(this.config.renderTextTracksNatively){const{captionsTracks:t,cueCache:e}=this;for(const i in t)t[i].remove(),delete e[i]}this.cueCache={},this.captionsTracks={},this.nonNativeCaptionsTracks={}}}onManifestLoading(){this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs={ccOffset:0,presentationOffset:0,0:{start:0,prevCC:-1,new:!0}},this.tracks=[],this.captionsTracks={},this.nonNativeCaptionsTracks={},this.unparsedFrags=[],this.initPTS=[],this.cea608Parser1&&this.cea608Parser2&&(this.cea608Parser1.reset(),this.cea608Parser2.reset())}onSubtitleTracksUpdated(t,e){const i=e.subtitleTracks||[];if(i.length&&!this.config.renderTextTracksNatively&&!ra(this.tracks,i)){const t=i.map(t=>({label:t.name,kind:t.type.toLowerCase(),default:t.default,subtitleTrack:t}));this.hls.trigger(a.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:t})}this.tracks=i}onManifestLoaded(t,e){this.config.enableCEA708Captions&&e.captions&&e.captions.forEach(t=>{const e=/(?:CC|SERVICE)([1-4])/.exec(t.instreamId);if(!e)return;const i=`textTrack${e[1]}`,s=this.captionsProperties[i];s&&(s.label=t.name,t.lang&&(s.languageCode=t.lang),s.media=t)})}closedCaptionsForLevel(t){const e=this.hls.levels[t.level];return null==e?void 0:e.attrs["CLOSED-CAPTIONS"]}onFragLoading(t,e){if(this.enabled&&e.frag.type===f.MAIN){var i,s;const{cea608Parser1:t,cea608Parser2:r,lastSn:n}=this,{cc:a,sn:o}=e.frag,l=null!=(i=null==(s=e.part)?void 0:s.index)?i:-1;t&&r&&(o!==n+1||o===n&&l!==this.lastPartIndex+1||a!==this.lastCc)&&(t.reset(),r.reset()),this.lastCc=a,this.lastSn=o,this.lastPartIndex=l}}onFragLoaded(t,e){const{frag:i,payload:s}=e;var r;if(i.level<this.tracks.length&&i.type===f.SUBTITLE)if(s.byteLength||null!=(r=i.initSegment)&&null!=(r=r.data)&&r.byteLength){const t=i.decryptdata,s="stats"in e;if(null==t||!t.encrypted||s){const t=this.tracks[i.level],s=this.vttCCs;s[i.cc]||(s[i.cc]={start:i.start,prevCC:this.prevCC,new:!0},this.prevCC=i.cc),(null==t?void 0:t.textCodec)===ml?this._parseIMSC1(e):this._parseVTTs(e)}}else{const t="part"in e?e.part:null;this.hls.trigger(a.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:i,part:t,error:new Error("Empty subtitle payload")})}}_parseIMSC1(t){const{frag:e,payload:i}=t,s="part"in t?t.part:null;if(!this.initPTS[e.cc])return void this.unparsedFrags.push(t);const r=this.hls;El(i,this.initPTS[e.cc],t=>{this._appendCues(t,e.level),r.trigger(a.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:e,part:s})},t=>{r.logger.log(`Cannot parse IMSC1 (sn: ${e.sn} @${e.start}): ${t}`),r.trigger(a.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:e,part:s,error:t})})}_parseVTTs(t){var e;const{frag:i,payload:s}=t,r="part"in t?t.part:null,{initPTS:n,unparsedFrags:o}=this,l=n.length-1;if(!n[i.cc]&&-1===l)return void o.push(t);const h=this.hls,d=null==(e=i.initSegment)?void 0:e.data;gl(d?Ht(d,new Uint8Array(s)).buffer:s,this.initPTS[i.cc],this.vttCCs,i.cc,(r&&!d?r:i).start,t=>{this._appendCues(t,i.level),h.trigger(a.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:i,part:r})},e=>{const s=e.message.startsWith("Missing initPTS");h.logger.log(`${s?"Deferred parsing of":"Cannot parse"} VTT cue (sn: ${i.sn} @${i.start}): ${e}`),s?o.push(t):(this.config.enableIMSC1&&this._fallbackToIMSC1(t),h.trigger(a.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:i,part:r,error:e}))})}_fallbackToIMSC1(t){const{frag:e,payload:i}=t,s=this.tracks[e.level];s.textCodec||El(i,this.initPTS[e.cc],()=>{s.textCodec=ml,this._parseIMSC1(t)},()=>{s.textCodec="wvtt"})}_appendCues(t,e){const i=this.hls;if(this.config.renderTextTracksNatively){var s;const i=null==(s=this.tracks[e].trackNode)?void 0:s.track;if(!i||"disabled"===i.mode)return;t.forEach(t=>_l(i,t))}else{const s=this.tracks[e];if(!s)return;const r=s.default?"default":"subtitles"+e;i.trigger(a.CUES_PARSED,{type:"subtitles",cues:t,track:r,subtitleTrack:s})}}onFragDecrypted(t,e){const{frag:i}=e;i.type===f.SUBTITLE&&this.onFragLoaded(a.FRAG_LOADED,e)}onSubtitleTracksCleared(){this.tracks=[],this.captionsTracks={}}onFragParsingUserdata(t,e){if(!this.enabled||!this.config.enableCEA708Captions)return;const{frag:i,samples:s}=e;if(i.type!==f.MAIN||"NONE"!==this.closedCaptionsForLevel(i))for(let t=0;t<s.length;t++){const e=s[t].bytes;if(e){this.cea608Parser1||this.initCea608Parsers();const i=this.extractCea608Data(e);this.cea608Parser1.addData(s[t].pts,i[0]),this.cea608Parser2.addData(s[t].pts,i[1])}}}onBufferAppended(t,e){if(this.config.renderTextTracksNatively){var i;const{type:t,timeRanges:s}=e;if("video"===t&&null!=(i=s[t])&&i.length){const{captionsTracks:t,cueCache:e}=this;Object.keys(e).forEach(i=>{var s;const r=null==(s=t[i])?void 0:s.track;if(r){const t=e[i];for(let e=0;e<t.length;e++)_l(r,t[e])}delete e[i]})}}}onBufferFlushing(t,e){const{startOffset:i,endOffset:s,endOffsetSubtitles:r,type:n}=e,{media:a}=this;if(a&&!(a.currentTime<s)){if(!n||"video"===n){const{captionsTracks:t,cueCache:e}=this;Object.keys(t).forEach(e=>Dl(t[e].track,i,s)),Object.keys(e).forEach(t=>{const r=e[t];for(let t=r.length;t--;){const e=r[t];e.startTime>=i&&e.endTime<=s&&r.splice(t,1)}})}this.config.renderTextTracksNatively&&0===i&&void 0!==r&&this.tracks.forEach(t=>{var e;const s=null==(e=t.trackNode)?void 0:e.track;s&&Dl(s,i,r)})}}extractCea608Data(t){const e=[[],[]],i=31&t[0];let s=2;for(let r=0;r<i;r++){const i=t[s++],r=127&t[s++],n=127&t[s++];if(0===r&&0===n)continue;if(!!(4&i)){const t=3&i;0!==t&&1!==t||(e[t].push(r),e[t].push(n))}}return e}},audioStreamController:class extends _r{constructor(t,e,i){super(t,e,i,"audio-stream-controller",f.AUDIO),this.mainAnchor=null,this.mainFragLoading=null,this.audioOnly=!1,this.bufferedTrack=null,this.switchingTrack=null,this.trackId=-1,this.nextTrackId=-1,this.waitingData=null,this.mainDetails=null,this.flushing=!1,this.bufferFlushed=!1,this.cachedTrackLoadedData=null,this.registerListeners()}onHandlerDestroying(){this.unregisterListeners(),super.onHandlerDestroying(),this.resetItem()}resetItem(){this.mainDetails=this.mainAnchor=this.mainFragLoading=this.bufferedTrack=this.switchingTrack=this.waitingData=this.cachedTrackLoadedData=null}registerListeners(){super.registerListeners();const{hls:t}=this;t.on(a.LEVEL_LOADED,this.onLevelLoaded,this),t.on(a.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),t.on(a.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.on(a.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),t.on(a.BUFFER_RESET,this.onBufferReset,this),t.on(a.BUFFER_CREATED,this.onBufferCreated,this),t.on(a.BUFFER_FLUSHING,this.onBufferFlushing,this),t.on(a.BUFFER_FLUSHED,this.onBufferFlushed,this),t.on(a.INIT_PTS_FOUND,this.onInitPtsFound,this),t.on(a.FRAG_LOADING,this.onFragLoading,this),t.on(a.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){const{hls:t}=this;t&&(super.unregisterListeners(),t.off(a.LEVEL_LOADED,this.onLevelLoaded,this),t.off(a.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),t.off(a.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.off(a.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),t.off(a.BUFFER_RESET,this.onBufferReset,this),t.off(a.BUFFER_CREATED,this.onBufferCreated,this),t.off(a.BUFFER_FLUSHING,this.onBufferFlushing,this),t.off(a.BUFFER_FLUSHED,this.onBufferFlushed,this),t.off(a.INIT_PTS_FOUND,this.onInitPtsFound,this),t.off(a.FRAG_LOADING,this.onFragLoading,this),t.off(a.FRAG_BUFFERED,this.onFragBuffered,this))}onInitPtsFound(t,e){const{frag:i,id:s,initPTS:r,timescale:n,trackId:a,timestampOffsets:o}=e;if(s===f.MAIN){const t=i.cc,e=this.fragCurrent;if(this.initPTS=o,this.log(`InitPTS for cc: ${t} found from main: ${r/n} (${r}/${n}) trackId: ${a}`),this.mainAnchor=i,this.state===Rr){const e=this.waitingData;(!e&&!this.loadingParts||e&&e.frag.cc!==t)&&this.syncWithAnchor(i,null==e?void 0:e.frag)}else!this.hls.hasEnoughToStart&&e&&e.cc!==t?(e.abortRequests(),this.syncWithAnchor(i,e)):this.state===vr&&this.tick()}}getLoadPosition(){var t;return!this.startFragRequested&&this.nextLoadPosition>=0&&!1!==(null==(t=this.switchingTrack)?void 0:t.flushImmediate)?this.nextLoadPosition:super.getLoadPosition()}syncWithAnchor(t,e){var i;const s=(null==(i=this.mainFragLoading)?void 0:i.frag)||null;if(e&&(null==s?void 0:s.cc)===e.cc)return;const r=(s||t).cc,n=ii(this.getLevelDetails(),r,this.getLoadPosition());n&&this.fragmentTracker.getState(n)!==Fi&&(this.log(`Syncing with main frag at ${n.start} cc ${n.cc}`),this.startFragRequested=!1,this.nextLoadPosition=n.start,this.resetLoadingState(),this.state===vr&&this.doTickIdle())}startLoad(t,e){if(!this.levels)return this.startPosition=t,void(this.state=pr);const i=this.lastCurrentTime;this.stopLoad(),this.setInterval(100),i>0&&-1===t&&!e&&this.initPTS.length&&(this.log(`Override startPosition with lastCurrentTime @${i.toFixed(3)}`),t=i),this.state=vr,this.nextLoadPosition=this.lastCurrentTime=t+this.timelineOffset,this.startPosition=e?-1:t,e||this.fragmentTracker.hasFragments(this.playlistType)||(this.startFragRequested=!1),this.tick()}doTick(){switch(this.state){case vr:this.doTickIdle();break;case Sr:{const{levels:t,trackId:e}=this,i=null==t?void 0:t[e],s=null==i?void 0:i.details;if(s&&!this.waitForLive(i)){if(this.waitForCdnTuneIn(s))break;this.state=Rr}break}case Tr:this.checkRetryDate();break;case Rr:{const t=this.waitingData;if(t){const{frag:e,part:i,cache:s,complete:r}=t,n=this.mainAnchor;if(void 0!==this.initPTS[e.cc]){this.waitingData=null,this.state=Er;const t={frag:e,part:i,payload:s.flush().buffer,networkDetails:null};this._handleFragmentLoadProgress(t),r&&super._handleFragmentLoadComplete(t)}else n&&n.cc!==t.frag.cc&&this.syncWithAnchor(n,t.frag)}else this.state=vr}}this.onTickEnd()}resetLoadingState(){const t=this.waitingData;t&&(this.fragmentTracker.removeFragment(t.frag),this.waitingData=null),super.resetLoadingState()}onTickEnd(){super.onTickEnd(),this.checkFragmentChanged()}doTickIdle(){var t;const{hls:e,levels:i,media:s,trackId:r}=this,n=e.config;if(!this.buffering||!s&&!this.primaryPrefetch&&(this.startFragRequested||!n.startFragPrefetch)||null==i||!i[r])return;const o=i[r],l=o.details;if(!l||this.waitForLive(o)||this.waitForCdnTuneIn(l))return this.state=Sr,void(this.startFragRequested=!1);const h=this.getBufferOutput();this.bufferFlushed&&h&&(this.bufferFlushed=!1,this.afterBufferFlushed(h,g));const d=this.getFwdBufferInfo();if(null===d)return;if(!this.switchingTrack&&this._streamEnded(d,l))return e.trigger(a.BUFFER_EOS,{type:"audio"}),void(this.state=Lr);const c=d.len,u=e.maxBufferLength,m=l.fragments,p=m[0].start,v=this.getLoadPosition(),E=this.flushing||this.switchingTrack&&!this.switchingTrack.flushImmediate?v:d.end;if(this.switchingTrack&&s){const t=v;l.PTSKnown&&t<p&&t>=this.timelineOffset&&(d.end>p||d.nextStart)&&(this.log(`Alt audio track ahead of main track, seek to start of alt audio track ${t} -> ${p} + 0.05`),s.currentTime=p+.05)}if(c>=u&&!this.switchingTrack&&E<m[m.length-1].start)return;let T=this.getNextFragment(E,l);if(T&&this.isLoopLoading(T,E)&&(T=this.getNextFragmentLoopLoading(T,l,d,f.MAIN,u)),!T)return void(this.bufferFlushed=!0);if(this.exceedsMaxBuffer(d,u,T))return;let S=(null==(t=this.mainFragLoading)?void 0:t.frag)||null;if(!this.audioOnly&&this.startFragRequested&&S&&y(T)&&!T.endList&&(!l.live||!this.loadingParts&&E<this.hls.liveSyncPosition)&&(this.fragmentTracker.getState(S)===Fi&&(this.mainFragLoading=S=null),S&&y(S))){if(T.start>S.end){const t=this.fragmentTracker.getFragAtPos(E,f.MAIN);t&&t.end>S.end&&(S=t,this.mainFragLoading={frag:t,targetBufferTime:null})}if(T.start>S.end)return}this.loadFragment(T,o,E)}onMediaDetaching(t,e){this.bufferFlushed=this.flushing=!1,super.onMediaDetaching(t,e)}onAudioTracksUpdated(t,{audioTracks:e}){this.resetTransmuxer(),this.levels=e.map(t=>new Ne(t))}onAudioTrackSwitching(t,e){const i=!!e.url;this.trackId=e.id;const{fragCurrent:s}=this;s&&(s.abortRequests(),this.removeUnbufferedFrags(s.start)),this.resetLoadingState(),i?(this.switchingTrack=e,e.flushImmediate||(this.nextTrackId=e.id,this.nextLevelSwitch()),this.flushAudioIfNeeded(e),this.state!==pr&&(this.setInterval(100),this.state=vr,this.tick())):(this.resetTransmuxer(),this.switchingTrack=null,this.bufferedTrack=e,this.clearInterval())}onManifestLoading(){super.onManifestLoading(),this.bufferFlushed=this.flushing=this.audioOnly=!1,this.resetItem(),this.trackId=-1}onLevelLoaded(t,e){this.mainDetails=e.details;const i=this.cachedTrackLoadedData;i&&(this.cachedTrackLoadedData=null,this.onAudioTrackLoaded(a.AUDIO_TRACK_LOADED,i))}onAudioTrackLoaded(t,e){var i;const{levels:s}=this,{details:r,id:n,groupId:o,track:l}=e;if(!s)return void this.warn(`Audio tracks reset while loading track ${n} "${l.name}" of "${o}"`);const h=this.mainDetails;if(!h||r.endCC>h.endCC||h.expired)return this.cachedTrackLoadedData=e,void(this.state!==pr&&(this.state=Sr));this.cachedTrackLoadedData=null,this.log(`Audio track ${n} "${l.name}" of "${o}" loaded [${r.startSN},${r.endSN}]${r.lastPartSn?`[part-${r.lastPartSn}-${r.lastPartIndex}]`:""},duration:${r.totalduration}`);const d=s[n];let c=0;if(r.live||null!=(i=d.details)&&i.live){if(this.checkLiveUpdate(r),r.deltaUpdateFailed)return;var u;if(d.details)c=this.alignPlaylists(r,d.details,null==(u=this.levelLastLoaded)?void 0:u.details);r.alignedSliding||(mr(h,r,this),c=r.fragmentStart)}d.details=r,this.levelLastLoaded=d,this.startFragRequested||this.setStartPosition(h,c),this.hls.trigger(a.AUDIO_TRACK_UPDATED,{details:r,id:n,groupId:e.groupId}),this.state!==Sr||this.waitForCdnTuneIn(r)||(this.state=vr),this.tick()}_handleFragmentLoadProgress(t){var e;const i=t.frag,{part:s,payload:r}=t,{config:n,trackId:a,levels:o}=this;if(!o)return void this.warn(`Audio tracks were reset while fragment load was in progress. Fragment ${i.sn} of level ${i.level} will not be buffered`);const l=o[a];if(!l)return void this.warn("Audio track is undefined on fragment load progress");const h=l.details;if(!h)return this.warn("Audio track details undefined on fragment load progress"),void this.removeUnbufferedFrags(i.start);const d=n.defaultAudioCodec||l.audioCodec||"mp4a.40.2";let c=this.transmuxer;c||(c=this.transmuxer=new ia(this.hls,f.AUDIO,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)));const u=this.initPTS[i.cc],g=null==(e=i.initSegment)?void 0:e.data;if(void 0!==u){const t=!1,e=s?s.index:-1,n=-1!==e,a=new ts(i.level,i.sn,i.stats.chunkCount,r.byteLength,e,n,i.duration);c.push(r,g,d,"",i,s,h.totalduration,t,a,u)}else{this.log(`Unknown video PTS for cc ${i.cc}, waiting for video PTS before demuxing audio frag ${i.sn} of [${h.startSN} ,${h.endSN}],track ${a}`);const{cache:t}=this.waitingData=this.waitingData||{frag:i,part:s,cache:new Pr,complete:!1};t.push(new Uint8Array(r)),this.state!==pr&&(this.state=Rr)}}_handleFragmentLoadComplete(t){this.waitingData?this.waitingData.complete=!0:super._handleFragmentLoadComplete(t)}onBufferReset(){this.mediaBuffer=null}onBufferCreated(t,e){this.bufferFlushed=this.flushing=!1;const i=e.tracks.audio;i&&(this.mediaBuffer=i.buffer||null)}onFragLoading(t,e){!this.audioOnly&&e.frag.type===f.MAIN&&y(e.frag)&&(this.mainFragLoading=e,this.state===vr&&this.tick())}onFragBuffered(t,e){const{frag:i,part:s}=e;if(i.type===f.AUDIO)if(this.fragContextChanged(i))this.warn(`Fragment ${i.sn}${s?" p: "+s.index:""} of level ${i.level} finished buffering, but was aborted. state: ${this.state}, audioSwitch: ${this.switchingTrack?this.switchingTrack.name:"false"}`);else{if(y(i)){const t=this.switchingTrack;t&&(this.bufferedTrack=t)}this.fragBufferedComplete(i,s),this.media&&this.tick()}else this.audioOnly||i.type!==f.MAIN||i.elementaryStreams.video||i.elementaryStreams.audiovideo||(this.audioOnly=!0,this.mainFragLoading=null)}getFwdBufferInfo(){const t=this.getBufferOutput();return super.getFwdBufferInfo(t,f.AUDIO)}getBufferOutput(){return this.mediaBuffer?this.mediaBuffer:this.media}checkFragmentChanged(){const t=this.fragPlaying;if(!this.checkFragPlaying())return!1;const{fragPlaying:e,switchingTrack:i}=this,s=!e||e.level!==(null==t?void 0:t.level);return s&&t&&this.cleanupBackBuffer(),i&&(s||(null==e?void 0:e.level)===i.id)&&this.completeAudioSwitch(i),!0}onError(t,e){var i;if(e.fatal)this.state=Ir;else switch(e.details){case n.FRAG_GAP:case n.FRAG_PARSING_ERROR:case n.FRAG_DECRYPT_ERROR:case n.FRAG_LOAD_ERROR:case n.FRAG_LOAD_TIMEOUT:case n.KEY_LOAD_ERROR:case n.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(f.AUDIO,e);break;case n.AUDIO_TRACK_LOAD_ERROR:case n.AUDIO_TRACK_LOAD_TIMEOUT:case n.LEVEL_PARSING_ERROR:e.levelRetry||this.state!==Sr||(null==(i=e.context)?void 0:i.type)!==u.AUDIO_TRACK||(this.state=vr);break;case n.BUFFER_APPEND_NO_PROGRESS:if("audio"!==e.parent)return;e.frag&&(e.appendsWithoutProgress||0)>=this.config.appendErrorMaxRetry&&(this.warn(`Marking fragment ${e.frag.sn} of track ${e.frag.level} as a gap after ${e.appendsWithoutProgress} appends without buffered range growth, to prevent loop loading`),this.fragmentTracker.addAsGap(e.frag));break;case n.MEDIA_SOURCE_REQUIRES_RESET:this.onSourceBufferError(f.AUDIO,e);break;case n.BUFFER_ADD_CODEC_ERROR:case n.BUFFER_APPEND_ERROR:if("audio"!==e.parent)return;this.reduceLengthAndFlushBuffer(e)||this.resetLoadingState();break;case n.BUFFER_FULL_ERROR:if("audio"!==e.parent)return;this.reduceLengthAndFlushBuffer(e)&&(this.bufferedTrack=null,super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"));break;case n.INTERNAL_EXCEPTION:this.recoverWorkerError(e)}}onBufferFlushing(t,{type:e}){e!==m&&(this.flushing=!0)}onBufferFlushed(t,{type:e}){if(e!==m){this.flushing=!1,this.bufferFlushed=!0,this.state===Lr&&(this.state=vr);const t=this.getBufferOutput();t&&(this.afterBufferFlushed(t,e),this.tick())}}_handleTransmuxComplete(t){var e;const i="audio",{hls:s}=this,{remuxResult:r,chunkMeta:n}=t,o=this.getCurrentContext(n);if(!o)return void this.resetWhenMissingContext(n);const{frag:l,part:h,level:d}=o,{details:c}=d,{audio:u,text:m,id3:p,initSegment:v}=r;if(this.fragContextChanged(l)||!c)return this.fragmentTracker.removeFragment(l),void(null!=v&&v.tracks&&this.resetTransmuxer());if(this.state=br,u&&this.switchingTrack&&!this.switchingTrack.flushImmediate){const{config:t}=this,e=t.nextAudioTrackBufferFlushForwardOffset,i=Math.max(this.getLoadPosition()+e,(h||l).start);super.flushMainBuffer(i,Number.POSITIVE_INFINITY,f.AUDIO)}if(null!=v&&v.tracks){const t=l.initSegment||l;if(this.unhandledEncryptionError(v,l))return;this._bufferInitSegment(d,v.tracks,t,n),s.trigger(a.FRAG_PARSING_INIT_SEGMENT,{frag:t,id:i,tracks:v.tracks})}if(u){const{startPTS:t,endPTS:e,startDTS:i,endDTS:s}=u;h&&(h.elementaryStreams[g]={startPTS:t,endPTS:e,startDTS:i,endDTS:s}),l.setElementaryStreamInfo(g,t,e,i,s),this.bufferFragmentData(u,l,h,n)}if(null!=p&&null!=(e=p.samples)&&e.length){const t=I({id:i,frag:l,details:c},p);s.trigger(a.FRAG_PARSING_METADATA,t)}if(m){const t=I({id:i,frag:l,details:c},m);s.trigger(a.FRAG_PARSING_USERDATA,t)}}_bufferInitSegment(t,e,i,s){if(this.state!==br)return;if(e.video&&delete e.video,e.audiovideo&&delete e.audiovideo,!e.audio)return;const r=e.audio;r.id=f.AUDIO;const n=t.audioCodec;this.log(`Init audio buffer, container:${r.container}, codecs[level/parsed]=[${n}/${r.codec}]`),1===(null==n?void 0:n.split(",").length)&&(r.levelCodec=n),this.hls.trigger(a.BUFFER_CODECS,e);const o=r.initSegment;if(null!=o&&o.byteLength){const t={type:"audio",frag:i,part:null,chunkMeta:s,parent:i.type,data:o};this.hls.trigger(a.BUFFER_APPENDING,t)}this.tickImmediate()}loadFragment(t,e,i){const s=this.fragmentTracker.getState(t);var r;if(this.switchingTrack||s===xi||s===Oi)if(null!=(r=e.details)&&r.live&&!this.initPTS[t.cc]){this.log(`Waiting for video PTS in continuity counter ${t.cc} of live stream before loading audio fragment ${t.sn} of level ${this.trackId}`),this.state=Rr;const i=this.mainDetails;i&&i.fragmentStart!==e.details.fragmentStart&&mr(i,e.details,this)}else super.loadFragment(t,e,i);else this.clearTrackerIfNeeded(t)}flushAudioIfNeeded(t){if(this.media&&this.bufferedTrack&&t.flushImmediate){const{name:e,lang:i,assocLang:s,characteristics:r,audioCodec:n,channels:a}=this.bufferedTrack;He({name:e,lang:i,assocLang:s,characteristics:r,audioCodec:n,channels:a},t,qe)||(We(t.url,this.hls)?(this.log("Switching audio track : flushing all audio"),super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"),this.bufferedTrack=null):this.bufferedTrack=t)}}completeAudioSwitch(t){const{hls:e}=this;this.bufferedTrack=t,this.switchingTrack=null,e.trigger(a.AUDIO_TRACK_SWITCHED,k({},t))}get nextAudioTrack(){return this.nextTrackId}},audioTrackController:class extends sa{constructor(t){super(t,"audio-track-controller"),this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0,this.registerListeners()}registerListeners(){const{hls:t}=this;t.on(a.MANIFEST_LOADING,this.onManifestLoading,this),t.on(a.MANIFEST_PARSED,this.onManifestParsed,this),t.on(a.LEVEL_LOADING,this.onLevelLoading,this),t.on(a.LEVEL_SWITCHING,this.onLevelSwitching,this),t.on(a.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),t.on(a.ERROR,this.onError,this)}unregisterListeners(){const{hls:t}=this;t.off(a.MANIFEST_LOADING,this.onManifestLoading,this),t.off(a.MANIFEST_PARSED,this.onManifestParsed,this),t.off(a.LEVEL_LOADING,this.onLevelLoading,this),t.off(a.LEVEL_SWITCHING,this.onLevelSwitching,this),t.off(a.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),t.off(a.ERROR,this.onError,this)}destroy(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.currentTrack=null,super.destroy()}onManifestLoading(){this.tracks=[],this.tracksInGroup=[],this.groupIds=null,this.currentTrack=null,this.trackId=-1,this.selectDefaultTrack=!0}onManifestParsed(t,e){this.tracks=e.audioTracks||[]}onAudioTrackLoaded(t,e){const{id:i,groupId:s,details:r}=e,n=this.tracksInGroup[i];if(!n||n.groupId!==s)return void this.warn(`Audio track with id:${i} and group:${s} not found in active group ${null==n?void 0:n.groupId}`);const a=n.details;n.details=e.details,this.log(`Audio track ${i} "${n.name}" lang:${n.lang} group:${s} loaded [${r.startSN}-${r.endSN}]`),i===this.trackId&&this.playlistLoaded(i,e,a)}onLevelLoading(t,e){this.switchLevel(e.level)}onLevelSwitching(t,e){this.switchLevel(e.level)}switchLevel(t){const e=this.hls.levels[t];if(!e)return;const i=e.audioGroups||null,s=this.groupIds;let o=this.currentTrack;if(!i||(null==s?void 0:s.length)!==(null==i?void 0:i.length)||null!=i&&i.some(t=>-1===(null==s?void 0:s.indexOf(t)))){this.groupIds=i,this.trackId=-1,this.currentTrack=null;const t=this.tracks.filter(t=>ze(t.groupId,i));if(t.length)this.selectDefaultTrack&&!t.some(t=>t.default)&&(this.selectDefaultTrack=!1),t.forEach((t,e)=>{t.id=e});else if(!o&&!this.tracksInGroup.length)return;this.tracksInGroup=t;const e=this.hls.config.audioPreference;if(!o&&e){const i=je(e,t,qe);if(i>-1)o=t[i];else{const t=je(e,this.tracks);o=this.tracks[t]}}let s=this.findTrackId(o);-1===s&&o&&(s=this.findTrackId(null));const h={audioTracks:t};this.log(`Updating audio tracks, ${t.length} track(s) found in group(s): ${null==i?void 0:i.join(",")}`),this.hls.trigger(a.AUDIO_TRACKS_UPDATED,h);const d=this.trackId;if(-1!==s&&-1===d)this.setAudioTrack(s);else if(t.length&&-1===d){var l;const e=new Error(`No audio track selected for current audio group-ID(s): ${null==(l=this.groupIds)?void 0:l.join(",")} track count: ${t.length}`);this.warn(e.message),this.hls.trigger(a.ERROR,{type:r.MEDIA_ERROR,details:n.AUDIO_TRACK_LOAD_ERROR,fatal:!0,error:e})}}}onError(t,e){!e.fatal&&e.context&&e.context.type===u.AUDIO_TRACK&&e.context.id===this.trackId&&ze(e.context.groupId,this.groupIds)&&this.checkRetry(e)}get allAudioTracks(){return this.tracks}get audioTracks(){return this.tracksInGroup}get audioTrack(){return this.trackId}set audioTrack(t){this.selectDefaultTrack=!1,this.setAudioTrack(t)}get nextAudioTrack(){return this.trackId}set nextAudioTrack(t){this.selectDefaultTrack=!1,this.setAudioTrack(t,!1)}setAudioOption(t){const e=this.hls;if(e.config.audioPreference=t,t){const i=this.allAudioTracks;if(this.selectDefaultTrack=!1,i.length){const s=this.currentTrack;if(s&&He(t,s,qe))return s;const r=je(t,this.tracksInGroup,qe);if(r>-1){const e=this.tracksInGroup[r];return this.setAudioTrack(r,"flushImmediate"in t&&t.flushImmediate),e}if(s){let s=e.loadLevel;-1===s&&(s=e.firstAutoLevel);const r=function(t,e,i,s,r){const n=e[s],a=e.reduce((t,e,i)=>{const s=e.uri;return(t[s]||(t[s]=[])).push(i),t},{})[n.uri];a.length>1&&(s=Math.max.apply(Math,a));const o=n.videoRange,l=n.frameRate,h=n.codecSet.substring(0,4),d=Ye(e,s,e=>{if(e.videoRange!==o||e.frameRate!==l||e.codecSet.substring(0,4)!==h)return!1;const s=e.audioGroups,n=i.filter(t=>ze(t.groupId,s));return je(t,n,r)>-1});return d>-1?d:Ye(e,s,e=>{const s=e.audioGroups,n=i.filter(t=>ze(t.groupId,s));return je(t,n,r)>-1})}(t,e.levels,i,s,qe);if(-1===r)return null;e.nextLoadLevel=r}if(t.channels||t.audioCodec){const e=je(t,i);if(e>-1)return i[e]}}}return null}setAudioTrack(t,e=!0){const i=this.tracksInGroup;if(t<0||t>=i.length)return void this.warn(`Invalid audio track id: ${t}`);this.selectDefaultTrack=!1;const s=this.currentTrack,r=i[t],n=r.details&&!r.details.live;if(t===this.trackId&&r===s&&n)return;if(this.log(`Switching to audio-track ${t} "${r.name}" lang:${r.lang} group:${r.groupId} channels:${r.channels}`),this.trackId=t,this.currentTrack=r,this.hls.trigger(a.AUDIO_TRACK_SWITCHING,k(k({},r),{},{flushImmediate:e})),n)return;const o=this.switchParams(r.url,null==s?void 0:s.details,r.details);this.loadPlaylist(o)}findTrackId(t){const e=this.tracksInGroup;for(let i=0;i<e.length;i++){const s=e[i];if((!this.selectDefaultTrack||s.default)&&(!t||He(t,s,qe)))return i}if(t){const{name:i,lang:s,assocLang:r,characteristics:n,audioCodec:a,channels:o}=t;for(let t=0;t<e.length;t++){if(He({name:i,lang:s,assocLang:r,characteristics:n,audioCodec:a,channels:o},e[t],qe))return t}for(let i=0;i<e.length;i++){const s=e[i];if(na(t.attrs,s.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return i}for(let i=0;i<e.length;i++){const s=e[i];if(na(t.attrs,s.attrs,["LANGUAGE"]))return i}}return-1}loadPlaylist(t){super.loadPlaylist();const e=this.currentTrack;this.shouldLoadPlaylist(e)&&We(e.url,this.hls)&&this.scheduleLoading(e,t)}loadingPlaylist(t,e){super.loadingPlaylist(t,e);const i=t.id,s=t.groupId,r=this.getUrlWithDirectives(t.url,e),n=t.details,o=null==n?void 0:n.age;this.log(`Loading audio-track ${i} "${t.name}" lang:${t.lang} group:${s}${void 0!==(null==e?void 0:e.msn)?" at sn "+e.msn+" part "+e.part:""}${o&&n.live?" age "+o.toFixed(1)+(n.type&&" "+n.type||""):""} ${r}`),this.hls.trigger(a.AUDIO_TRACK_LOADING,{url:r,id:i,groupId:s,deliveryDirectives:e||null,track:t})}},emeController:Qo,cmcdController:class{constructor(t){this.hls=void 0,this.config=void 0,this.media=void 0,this.initialized=!1,this.starved=!1,this.buffering=!0,this.playerState=void 0,this.reporter=void 0,this.playheadLevel=void 0,this.onWaiting=()=>{this.initialized&&(this.starved=!0,this.setPlayerState(ko)),this.buffering=!0},this.onPlay=()=>{this.initialized||this.setPlayerState(Lo)},this.onPlaying=()=>{this.initialized||(this.initialized=!0),this.buffering=!1,this.setPlayerState(Io)},this.onPause=()=>{this.media&&!this.media.ended&&this.setPlayerState(_o)},this.onSeeking=()=>{this.initialized&&this.setPlayerState(Ro)},this.onSeeked=()=>{var t;this.initialized&&null!=(t=this.media)&&t.paused&&this.setPlayerState(_o)},this.onRateChange=()=>{this.reporter&&this.media&&this.reporter.update({pr:this.media.playbackRate})},this.applyPlaylistData=t=>{try{this.apply(t,{ot:yo,su:!this.initialized})}catch(t){this.hls.logger.warn("Could not generate manifest CMCD data.",t)}},this.applyFragmentData=t=>{try{const{frag:a,part:o}=t,l=this.hls.levels[a.level],h=this.getObjectType(a,l),d={d:1e3*(o||a).duration,ot:h};if(h===To||h===Eo||h===So||null==h&&("main"===a.type||"audio"===a.type)){var i;const t=l.bitrate/1e3;d.br=[t];const{cmcd:r}=this.config,n=null!=(i=null==r?void 0:r.rtpSafetyFactor)?i:5;if(d.rtp=100*Math.round(t*n/100),h===So||null==h&&"main"===a.type){const t=this.getTopBandwidth()/1e3;e(t)&&(d.tb=[t]);const i=this.getLowestBandwidth()/1e3;e(i)&&(d.lb=[i])}const o=this.getBufferLength(a);if(e(o)){var s;d.bl=[o];const t=(null==(s=this.media)?void 0:s.playbackRate)||1;d.dl=100*Math.round(o/t/100)}this.playheadLevel&&(d.pb=[this.playheadLevel.bitrate/1e3]);const c=this.hls.maxAutoLevel;if(c>=0){const t=this.hls.levels[c];t&&(d.tpb=[t.bitrate/1e3])}}const c=o?this.getNextPart(o):this.getNextFrag(a);null!=c&&c.url&&c.url!==a.url&&(c.byteRange.length>0?d.nor=[(r=c.url,n={r:`${c.byteRange[0]}-${c.byteRange[1]}`},new oa(r,n))]:d.nor=[c.url]),this.apply(t,d)}catch(t){this.hls.logger.warn("Could not generate segment CMCD data.",t)}var r,n},this.recordFragmentResponse=(t,e,i)=>{var s;const{cmcd:r}=this.config,n=null==r||null==(s=r.eventTargets)?void 0:s.some(t=>{var e;return null==(e=t.events)?void 0:e.includes(Fa)});if(this.reporter&&i.loading.first>0&&n)try{this.reporter.recordResponseReceived({request:{url:t},status:e.code,resourceTiming:{startTime:i.loading.start,responseStart:i.loading.first,duration:i.loading.end-i.loading.start,encodedBodySize:i.total}})}catch(t){this.hls.logger.warn("Could not record fragment response CMCD data.",t)}},this.hls=t;const i=this.config=t.config,{cmcd:s}=i;null!=s&&(i.pLoader=this.createPlaylistLoader(),i.fLoader=this.createFragmentLoader(),this.registerListeners())}createReporter(){var t,e;const{cmcd:i}=this.config;if(null==i)return;const s=i.version||1;if(this.reporter=new Uo({sid:i.sessionId||this.hls.sessionId,cid:i.contentId,version:s,transmissionMode:!0===i.useHeaders?xo:Co,enabledKeys:null!=(t=i.includeKeys)?t:[...s>=Ca?vo:Za],eventTargets:(null!=(e=i.eventTargets)?e:[]).map(t=>{let{includeKeys:e}=t;return k(k({},_(t,Ho)),{},{enabledKeys:null!=e?e:vo})})},i.loader),this.reporter.update({sf:Go,sta:this.playerState}),i.reporterCallback){const t=this.reporter,e={updateCustomData:e=>{qo(e)&&t.update(e)},recordCustomEvent:(e,i={})=>{qo(i)&&t.recordEvent(Na,k({cen:e},i))}};i.reporterCallback(e)}this.reporter.start()}registerListeners(){const t=this.hls;t.on(a.MANIFEST_LOADING,this.onManifestLoading,this),t.on(a.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(a.MEDIA_DETACHED,this.onMediaDetached,this),t.on(a.MEDIA_ENDED,this.onMediaEnded,this),t.on(a.ERROR,this.onError,this),t.on(a.LEVEL_SWITCHING,this.onLevelSwitching,this),t.on(a.LEVEL_SWITCHED,this.onLevelSwitched,this),t.on(a.BUFFER_APPENDED,this.onBufferInfoChange,this),t.on(a.BUFFER_FLUSHED,this.onBufferInfoChange,this)}unregisterListeners(){const t=this.hls;t.off(a.MANIFEST_LOADING,this.onManifestLoading,this),t.off(a.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(a.MEDIA_DETACHED,this.onMediaDetached,this),t.off(a.MEDIA_ENDED,this.onMediaEnded,this),t.off(a.ERROR,this.onError,this),t.off(a.LEVEL_SWITCHING,this.onLevelSwitching,this),t.off(a.LEVEL_SWITCHED,this.onLevelSwitched,this),t.off(a.BUFFER_APPENDED,this.onBufferInfoChange,this),t.off(a.BUFFER_FLUSHED,this.onBufferInfoChange,this)}destroy(){this.unregisterListeners(),this.onMediaDetached(),this.reporter&&(this.reporter.stop(!0),this.reporter=void 0),this.hls=this.config=null,this.onWaiting=this.onPlay=this.onPlaying=this.onPause=null,this.onSeeking=this.onSeeked=this.onRateChange=this.media=null}onMediaAttaching(t,e){const i=this.media=e.media;this.setPlayerState(this.media.autoplay?Lo:Po),Ti(i,"waiting",this.onWaiting),Ti(i,"play",this.onPlay),Ti(i,"playing",this.onPlaying),Ti(i,"pause",this.onPause),Ti(i,"seeking",this.onSeeking),Ti(i,"seeked",this.onSeeked),Ti(i,"ratechange",this.onRateChange)}onMediaDetached(){const t=this.media;t&&(Si(t,"waiting",this.onWaiting),Si(t,"play",this.onPlay),Si(t,"playing",this.onPlaying),Si(t,"pause",this.onPause),Si(t,"seeking",this.onSeeking),Si(t,"seeked",this.onSeeked),Si(t,"ratechange",this.onRateChange),this.media=null)}onMediaEnded(t,e){this.setPlayerState(Do)}onManifestLoading(t,e){this.initialized=!1,this.starved=!1,this.buffering=!0,this.reporter&&(this.reporter.stop(!0),this.reporter=void 0),this.createReporter(),this.media||this.setPlayerState(Po)}onError(t,e){e.fatal&&(this.setPlayerState(wo),this.reporter&&this.reporter.recordEvent(Oa,{ec:[e.details]}))}onLevelSwitching(t,e){var i;if(!this.reporter)return;const s={br:[e.bitrate/1e3]},r=null==(i=e.details)?void 0:i.fragments[0];r&&(s.ot=this.getObjectType(r,e)),this.reporter.recordEvent(Ma,s)}onLevelSwitched(t,e){const i=this.hls.levels[e.level];i&&(this.playheadLevel=i)}setPlayerState(t){this.playerState=t,this.reporter&&this.reporter.update({sta:t})}getStreamType(){const t=this.hls.latestLevelDetails;if(t)return t.live?t.partList&&t.canBlockReload?jo:Vo:Ko}apply(t,e={}){var i;if(!this.reporter)return;this.reporter.update({mtp:[this.hls.bandwidthEstimate/1e3],pr:null==(i=this.media)?void 0:i.playbackRate,st:this.getStreamType()});const s=e.ot===bo||e.ot===To||e.ot===So;this.starved&&s&&(e.bs=!0,e.su=!0,this.starved=!1),null==e.su&&(e.su=this.buffering);const r=this.reporter.createRequestReport({url:t.url,headers:t.headers},e);t.url=r.url,t.headers=r.headers}getNextFrag(t){var e;const i=null==(e=this.hls.levels[t.level])?void 0:e.details;if(i){const e=t.sn-i.startSN;return i.fragments[e+1]}}getNextPart(t){var e;const{index:i,fragment:s}=t,r=null==(e=this.hls.levels[s.level])||null==(e=e.details)?void 0:e.partList;if(r){const{sn:t}=s;for(let e=r.length-1;e>=0;e--){const s=r[e];if(s.index===i&&s.fragment.sn===t)return r[e+1]}}}getObjectType(t,e){const{type:i}=t;if("subtitle"===i)return Ao;if("initSegment"===t.sn)return bo;if("audio"===i)return Eo;if("main"===i){if(t.hasStreams){const e=t.elementaryStreams;if(e.audiovideo)return So;if(e.video)return To;if(e.audio)return Eo}if(e){const{audioCodec:t,videoCodec:i}=e;if(!this.hls.audioTracks.length){if(t&&i)return So;if(t)return Eo}if(i)return To}}}getTopBandwidth(){let t=0;const e=this.hls,i=e.maxAutoLevel,s=i>-1?i+1:e.levels.length;return e.levels.slice(0,s).forEach(e=>{e.bitrate>t&&(t=e.bitrate)}),t>0?t:NaN}getLowestBandwidth(){let t=1/0;const i=this.hls,s=i.maxAutoLevel,r=s>-1?s+1:i.levels.length;return i.levels.slice(0,r).forEach(e=>{e.bitrate<t&&(t=e.bitrate)}),e(t)?t:NaN}getBufferLength(t){if(!this.media)return NaN;const e="audio"===t.type?this.hls.audioForwardBufferInfo:this.hls.mainForwardBufferInfo;return e?1e3*e.len:NaN}getEventBufferLength(){if(!this.media)return NaN;const t=this.hls.mainForwardBufferInfo,e=this.hls.audioForwardBufferInfo;if(t&&e)return 1e3*Math.min(t.len,e.len);const i=t||e;return i?1e3*i.len:NaN}onBufferInfoChange(t,i){if(!this.reporter)return;const s=this.getEventBufferLength();e(s)&&this.reporter.update({bl:[s]})}createPlaylistLoader(){const{pLoader:t}=this.config,e=this.applyPlaylistData,i=t||this.config.loader;return class{constructor(t){this.loader=void 0,this.loader=new i(t)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(t,i,s){e(t),this.loader.load(t,i,s)}}}createFragmentLoader(){const{fLoader:t}=this.config,e=this.applyFragmentData,i=this.recordFragmentResponse,s=t||this.config.loader;return class{constructor(t){this.loader=void 0,this.loader=new s(t)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(t,s,r){e(t);const{onSuccess:n}=r;this.loader.load(t,s,k(k({},r),{},{onSuccess:(e,s,r,a)=>{n(e,s,r,a),i(t.url,e,s)}}))}}}},contentSteeringController:class extends U{constructor(t){super("content-steering",t.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=t,this.registerListeners()}registerListeners(){const t=this.hls;t.on(a.MANIFEST_LOADING,this.onManifestLoading,this),t.on(a.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(a.MANIFEST_PARSED,this.onManifestParsed,this),t.on(a.ERROR,this.onError,this)}unregisterListeners(){const t=this.hls;t&&(t.off(a.MANIFEST_LOADING,this.onManifestLoading,this),t.off(a.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(a.MANIFEST_PARSED,this.onManifestParsed,this),t.off(a.ERROR,this.onError,this))}pathways(){return(this.levels||[]).reduce((t,e)=>(-1===t.indexOf(e.pathwayId)&&t.push(e.pathwayId),t),[])}get pathwayPriority(){return this._pathwayPriority}set pathwayPriority(t){this.updatePathwayPriority(t)}startLoad(){if(this.started=!0,this.clearTimeout(),this.enabled&&this.uri){if(this.updated){const t=1e3*this.timeToLoad-(performance.now()-this.updated);if(t>0)return void this.scheduleRefresh(this.uri,t)}this.loadSteeringManifest(this.uri)}}stopLoad(){this.started=!1,this.loader&&(this.loader.destroy(),this.loader=null),this.clearTimeout()}clearTimeout(){-1!==this.reloadTimer&&(self.clearTimeout(this.reloadTimer),this.reloadTimer=-1)}destroy(){this.unregisterListeners(),this.stopLoad(),this.hls=null,this.levels=this.audioTracks=this.subtitleTracks=null}removeLevel(t){const e=this.levels;e&&(this.levels=e.filter(e=>e!==t))}onManifestLoading(){this.stopLoad(),this.enabled=!0,this.timeToLoad=300,this.updated=0,this.uri=null,this.pathwayId=".",this.levels=this.audioTracks=this.subtitleTracks=null}onManifestLoaded(t,e){const{contentSteering:i}=e;null!==i&&(this.pathwayId=i.pathwayId,this.uri=i.uri,this.started&&this.startLoad())}onManifestParsed(t,e){this.audioTracks=e.audioTracks,this.subtitleTracks=e.subtitleTracks}onError(t,e){const{errorAction:i}=e;if((null==i?void 0:i.action)===ni&&i.flags&hi){const t=this.levels;let s=this._pathwayPriority,r=this.pathwayId;if(e.context){const{groupId:i,pathwayId:s,type:n}=e.context;i&&t?r=this.getPathwayForGroupId(i,n,r):s&&(r=s)}r in this.penalizedPathways||(this.penalizedPathways[r]=performance.now()),!s&&t&&(s=this.pathways()),s&&s.length>1&&(this.updatePathwayPriority(s),i.resolved=this.pathwayId!==r,i.resolved||e.details===n.BUFFER_APPEND_ERROR&&!e.fatal||this.warn(`Could not resolve ${e.details} ("${e.error.message}") with content-steering for Pathway: ${r} levels: ${t?t.length:t} priorities: ${Ue(s)} penalized: ${Ue(this.penalizedPathways)}`))}}filterParsedLevels(t){this.levels=t;let e=this.getLevelsForPathway(this.pathwayId);if(0===e.length){const i=t[0].pathwayId;this.log(`No levels found in Pathway ${this.pathwayId}. Setting initial Pathway to "${i}"`),e=this.getLevelsForPathway(i),this.pathwayId=i}return e.length!==t.length&&this.log(`Found ${e.length}/${t.length} levels in Pathway "${this.pathwayId}"`),e}getLevelsForPathway(t){return null===this.levels?[]:this.levels.filter(e=>t===e.pathwayId)}updatePathwayPriority(t){let e;this._pathwayPriority=t;const i=this.penalizedPathways,s=performance.now();Object.keys(i).forEach(t=>{s-i[t]>3e5&&delete i[t]});for(let s=0;s<t.length;s++){const r=t[s];if(r in i)continue;if(r===this.pathwayId)return;const n=this.hls.nextLoadLevel,o=this.hls.levels[n];if(e=this.getLevelsForPathway(r),e.length>0){this.log(`Setting Pathway to "${r}"`),this.pathwayId=r,hr(e),this.hls.trigger(a.LEVELS_UPDATED,{levels:e});const t=this.hls.levels[n];o&&t&&this.levels&&(t.attrs["STABLE-VARIANT-ID"]!==o.attrs["STABLE-VARIANT-ID"]&&t.bitrate!==o.bitrate&&this.log(`Unstable Pathways change from bitrate ${o.bitrate} to ${t.bitrate}`),this.hls.nextLoadLevel=n);break}}}getPathwayForGroupId(t,e,i){const s=this.getLevelsForPathway(i).concat(this.levels||[]);for(let i=0;i<s.length;i++)if(e===u.AUDIO_TRACK&&s[i].hasAudioGroup(t)||e===u.SUBTITLE_TRACK&&s[i].hasSubtitleGroup(t))return s[i].pathwayId;return i}clonePathways(t){const e=this.levels;if(!e)return;const i={},s={};t.forEach(t=>{const{ID:r,"BASE-ID":n,"URI-REPLACEMENT":a}=t;if(e.some(t=>t.pathwayId===r))return;const o=this.getLevelsForPathway(n).map(t=>{const e=new ls(t.attrs);e["PATHWAY-ID"]=r;const n=e.AUDIO&&`${e.AUDIO}_clone_${r}`,o=e.SUBTITLES&&`${e.SUBTITLES}_clone_${r}`;n&&(i[e.AUDIO]=n,e.AUDIO=n),o&&(s[e.SUBTITLES]=o,e.SUBTITLES=o);const l=Wo(t.uri,e["STABLE-VARIANT-ID"],"PER-VARIANT-URIS",a),h=new Ne({attrs:e,audioCodec:t.audioCodec,bitrate:t.bitrate,height:t.height,name:t.name,url:l,videoCodec:t.videoCodec,width:t.width});if(t.audioGroups)for(let e=1;e<t.audioGroups.length;e++)h.addGroupId("audio",`${t.audioGroups[e]}_clone_${r}`);if(t.subtitleGroups)for(let e=1;e<t.subtitleGroups.length;e++)h.addGroupId("text",`${t.subtitleGroups[e]}_clone_${r}`);return h});e.push(...o),Yo(this.audioTracks,i,a,r),Yo(this.subtitleTracks,s,a,r)})}loadSteeringManifest(t){const e=this.hls.config,i=e.loader;let s;this.loader&&this.loader.destroy(),this.loader=new i(e);try{s=new self.URL(t)}catch(e){return this.enabled=!1,void this.log(`Failed to parse Steering Manifest URI: ${t}`)}if("data:"!==s.protocol){const t=0|(this.hls.bandwidthEstimate||e.abrEwmaDefaultEstimate);De(s,"_HLS_pathway",this.pathwayId),De(s,"_HLS_throughput",""+t)}const r={type:u.STEERING_MANIFEST,responseType:"json",url:s.href},n=e.steeringManifestLoadPolicy.default,o=n.errorRetry||n.timeoutRetry||{},l={loadPolicy:n,timeout:n.maxLoadTimeMs,maxRetry:o.maxNumRetry||0,retryDelay:o.retryDelayMs||0,maxRetryDelay:o.maxRetryDelayMs||0},h={onSuccess:(t,e,i,r)=>{this.log(`Loaded steering manifest: "${s}"`);const n=t.data;if(1!==(null==n?void 0:n.VERSION))return void this.log(`Steering VERSION ${n.VERSION} not supported!`);this.updated=performance.now(),this.timeToLoad=n.TTL;const{"RELOAD-URI":o,"PATHWAY-CLONES":l,"PATHWAY-PRIORITY":h}=n;if(o)try{this.uri=new self.URL(o,s).href}catch(t){return this.enabled=!1,void this.log(`Failed to parse Steering Manifest RELOAD-URI: ${o}`)}this.scheduleRefresh(this.uri||i.url),l&&this.clonePathways(l);const d={steeringManifest:n,url:s.toString()};this.hls.trigger(a.STEERING_MANIFEST_LOADED,d),h&&this.updatePathwayPriority(h)},onError:(t,e,i,s)=>{if(this.log(`Error loading steering manifest: ${t.code} ${t.text} (${e.url})`),this.stopLoad(),410===t.code)return this.enabled=!1,void this.log(`Steering manifest ${e.url} no longer available`);let r=1e3*this.timeToLoad;if(429===t.code){const t=this.loader;if("function"==typeof(null==t?void 0:t.getResponseHeader)){const e=t.getResponseHeader("Retry-After");e&&(r=1e3*parseFloat(e))}return void this.log(`Steering manifest ${e.url} rate limited`)}this.scheduleRefresh(this.uri||e.url,r)},onTimeout:(t,e,i)=>{this.log(`Timeout loading steering manifest (${e.url})`),this.scheduleRefresh(this.uri||e.url)}};this.log(`Requesting steering manifest: ${s}`),this.loader.load(r,l,h)}scheduleRefresh(t,e=1e3*this.timeToLoad){this.clearTimeout(),this.reloadTimer=self.setTimeout(()=>{var e;const i=null==(e=this.hls)?void 0:e.media;!i||i.ended?this.scheduleRefresh(t,1e3*this.timeToLoad):this.loadSteeringManifest(t)},e)}},iframeController:class extends U{constructor(t,e){var i;super("iframes",t.logger),this.hls=void 0,this.stats=void 0,this.variableList=null,this.initPTS=[],this.iframeInstances=void 0,this.instanceCounter=0,Yl||(i=e,Yl=class extends i{constructor(t,e,i,s){t.streamController||(t.streamController=Vl),super(t),this._url=e,this.streamController.setInitPts(i),this.streamController.initDetails=s}loadSource(){}loadMediaAt(t,e=ql){if(t<0)return;const i=k(k({},ql),e);this.loadingEnabled||this.startLoad(t),this.streamController.loadMediaAt(t,i)}}),Wl||(Wl=function(t){return class extends t{constructor(t,e,i,s){t.cmcdController=void 0,t.emeController=void 0,t.streamController||(t.streamController=jl),t.capLevelController=void 0,t.bufferController=void 0,super(t,e,i,s)}attachImage(t){this.streamController.image=t}detachImage(){this.streamController.image=void 0}loadSource(){}attachMedia(){throw new Error(Hl)}detachMedia(){}recoverMediaError(){}transferMedia(){return null}loadMediaAt(t){if(t<0)return null;this.loadingEnabled||this.startLoad(t),this.streamController.loadMediaAt(t)}}}(Yl)),this.hls=t,this.iframeInstances=[],this.registerListeners()}registerListeners(){const t=this.hls;t&&(t.on(a.MANIFEST_LOADING,this.clearAsset,this),t.on(a.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(a.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(a.INIT_PTS_FOUND,this.onInitPtsFound,this),t.on(a.FRAG_BUFFERED,this.onFragBuffered,this),t.on(a.DESTROYING,this.onDestroying,this))}unregisterListeners(){const t=this.hls;t&&(t.off(a.MANIFEST_LOADING,this.clearAsset,this),t.off(a.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(a.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(a.INIT_PTS_FOUND,this.onInitPtsFound,this),t.off(a.FRAG_BUFFERED,this.onFragBuffered,this),t.off(a.DESTROYING,this.onDestroying,this))}clearAsset(){this.stats=void 0,this.variableList=null,this.initPTS=[],this.iframeInstances.forEach(t=>t.destroy()),this.iframeInstances.length=0}onDestroying(){this.unregisterListeners(),this.clearAsset(),this.hls=void 0}onManifestLoaded(t,e){this.stats=e.stats,this.variableList=e.variableList}onLevelsUpdated(t,{levels:e}){var i;const s=null==(i=this.hls)?void 0:i.pathwayPriority;e.length&&s&&this.iframeInstances.forEach(t=>{t.pathwayPriority=s})}onInitPtsFound(t,{id:e,timestampOffsets:i}){e===f.MAIN&&(this.initPTS=i)}onFragBuffered(t,e){var i;const s=this.hls;s&&s.hasEnoughToStart&&((null==(i=s.mainForwardBufferInfo)?void 0:i.len)||0)>10&&this.iframeInstances.forEach(t=>{var e;t.loadingEnabled||t.startLoad((null==(e=this.hls)||null==(e=e.media)?void 0:e.currentTime)||0)})}createIFramePlayer(t){var e;return this.createInstance(Yl,null==(e=this.hls)?void 0:e.iframeVariants,t)}createImageIFramePlayer(t){var e;const i=null==(e=this.hls)?void 0:e.iframeVariants.filter(t=>t.imageCodec);return this.createInstance(Wl,i,t,"image-")}createInstance(t,e,i,s){const{hls:r}=this;if(!r)return null;const{url:n,userConfig:o,latestLevelDetails:l,loadLevelObj:h,loadLevel:d,bandwidthEstimate:c,sessionId:u}=r,{stats:f,variableList:g}=this;if(null==e||!e.length||!f||!n)return null;const m=`${s||""}iframe-player-${this.instanceCounter++}`,p=r.levels,v=h||p[d],y=Xe(v,o.videoPreference),E=(null==v?void 0:v.pathwayId)||".",T=new t(k(k({},o),{},{loggerId:m,primarySessionId:u,videoPreference:y,abrEwmaDefaultEstimate:c,streamController:void 0,audioStreamController:void 0,audioTrackController:void 0,subtitleStreamController:void 0,subtitleTrackController:void 0,timelineController:void 0,id3TrackController:void 0,fpsController:void 0,gapController:void 0,iframeController:void 0,cmcd:void 0,interstitialsController:void 0,backBufferLength:1/0,maxMaxBufferLength:1,capLevelToPlayerSize:!0,enableWorker:!1,autoStartLoad:!1,startFragPrefetch:!1,testBandwidth:!1,progressive:!1},i),n,this.initPTS,l);return this.iframeInstances=this.iframeInstances.filter(t=>!t.url),this.iframeInstances.push(T),T.trigger(a.MANIFEST_LOADED,{levels:e,contentSteering:{uri:"",pathwayId:E},sessionKeys:null,audioTracks:[],iframeVariants:[],sessionData:null,startTimeOffset:null,stats:f,networkDetails:null,url:n,variableList:g}),T}},interstitialsController:class extends U{constructor(t,e){super("interstitials",t.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.bufferPastEdge=!1,this.shouldPlay=!1,this.onPlay=()=>{this.shouldPlay=!0},this.onPause=()=>{this.shouldPlay=!1},this.onSeeking=()=>{const t=this.currentTime;if(void 0===t||this.playbackDisabled||!this.schedule)return;const e=t-this.timelinePos;if(Math.abs(e)<1/7056e5)return;const i=e<=-.01;-1!==this.timelinePos||this.effectivePlayingItem||this.checkStart(),this.timelinePos=t,this.bufferedPos=t;const s=this.playingItem;if(!s)return void this.checkBuffer();if(i){this.schedule.resetErrorsInRange(t,t-e)&&this.updateSchedule(!0)}if(this.checkBuffer(),i&&t<s.start||t>=s.end){var r;const e=this.findItemIndex(s);let n=this.schedule.findItemIndexAtTime(t);if(-1===n&&(n=e+(i?-1:1),this.log(`seeked ${i?"back ":""}to position not covered by schedule ${t} (resolving from ${e} to ${n})`)),!this.isInterstitial(s)&&null!=(r=this.media)&&r.paused&&(this.shouldPlay=!1),!i&&n>e){const t=this.schedule.findJumpRestrictedIndex(e+1,n);if(t>e)return void this.setSchedulePosition(t)}return void this.setSchedulePosition(n)}const n=this.playingAsset;if(!n){if(this.playingLastItem&&this.isInterstitial(s)){const e=s.event.assetList[0];e&&(this.endedItem=this.playingItem,this.playingItem=null,this.setScheduleToAssetAtTime(t,e))}return}const a=n.timelineStart,o=n.duration||0;var l;(i&&t<a||t>=a+o)&&(null!=(l=s.event)&&l.appendInPlace&&(this.clearAssetPlayers(s.event,s),this.flushFrontBuffer(t)),this.setScheduleToAssetAtTime(t,n))},this.onTimeupdate=()=>{const t=this.currentTime;if(void 0===t||this.playbackDisabled)return;if(-1!==this.timelinePos||this.effectivePlayingItem||this.checkStart(),!(t>this.timelinePos))return;this.timelinePos=t,t>this.bufferedPos&&this.checkBuffer();const e=this.playingItem;if(!e||this.playingLastItem)return;if(t>=e.end){this.timelinePos=e.end;const t=this.findItemIndex(e);this.setSchedulePosition(t+1)}const i=this.playingAsset;if(!i)return;t>=i.timelineStart+(i.duration||0)&&this.setScheduleToAssetAtTime(t,i)},this.onScheduleUpdate=(t,e)=>{const i=this.schedule;if(!i)return;const s=this.playingItem,r=i.events||[],n=i.items||[],o=i.durations,l=t.map(t=>t.identifier),h=!(!r.length&&!l.length);(h||e)&&this.log(`INTERSTITIALS_UPDATED (${r.length}): ${r}\nSchedule: ${n.map(t=>oh(t))} pos: ${this.timelinePos}`),l.length&&this.log(`Removed events ${l}`);let d=null,c=null;s&&(d=this.updateItem(s,this.timelinePos),this.itemsMatch(s,d)?this.playingItem=d:this.waitingItem=null);const u=this.waitingItem;u&&(this.waitingItem=this.updateItem(u),this.waitingItem||s||(this.log(`INTERSTITIAL_ENDED unresolved ${oh(u)}`),this.hls.trigger(a.INTERSTITIAL_ENDED,{event:u.event,schedule:n.slice(0),scheduleIndex:-1})));const f=this.bufferingItem;if(f&&(c=this.updateItem(f,this.bufferedPos),this.itemsMatch(f,c)?this.bufferingItem=c:f.event&&(this.bufferingItem=this.playingItem,this.clearInterstitial(f.event,null))),t.forEach(t=>{t.assetList.forEach(t=>{this.clearAssetPlayer(t.identifier,null)})}),this.playerQueue.forEach(t=>{if(t.interstitial.appendInPlace){const e=t.assetItem.timelineStart,i=t.timelineOffset-e;if(i)try{t.timelineOffset=e}catch(s){Math.abs(i)>zl&&this.warn(`${s} ("${t.assetId}" ${t.timelineOffset}->${e})`)}}}),h||e){if(this.hls.trigger(a.INTERSTITIALS_UPDATED,{events:r.slice(0),schedule:n.slice(0),durations:o,removedIds:l}),this.isInterstitial(s)&&l.indexOf(s.event.identifier)>-1)return this.warn(`Interstitial "${s.event.identifier}" removed while playing`),void this.primaryFallback(s.event);s&&this.trimInPlace(d,s),f&&c!==d&&this.trimInPlace(c,f),this.checkBuffer()}},this.hls=t,this.HlsPlayerClass=e,this.assetListLoader=new lh(t),this.schedule=new ah(this.onScheduleUpdate,t.logger),this.registerListeners()}registerListeners(){const t=this.hls;t&&(t.on(a.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(a.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(a.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(a.MANIFEST_LOADING,this.onManifestLoading,this),t.on(a.LEVEL_UPDATED,this.onLevelUpdated,this),t.on(a.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.on(a.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),t.on(a.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),t.on(a.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),t.on(a.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),t.on(a.ASSET_LIST_LOADED,this.onAssetListLoaded,this),t.on(a.BUFFER_APPENDED,this.onBufferAppended,this),t.on(a.BUFFER_FLUSHED,this.onBufferFlushed,this),t.on(a.BUFFERED_TO_END,this.onBufferedToEnd,this),t.on(a.MEDIA_ENDED,this.onMediaEnded,this),t.on(a.ERROR,this.onError,this),t.on(a.DESTROYING,this.onDestroying,this))}unregisterListeners(){const t=this.hls;t&&(t.off(a.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(a.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(a.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(a.MANIFEST_LOADING,this.onManifestLoading,this),t.off(a.LEVEL_UPDATED,this.onLevelUpdated,this),t.off(a.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.off(a.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),t.off(a.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),t.off(a.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),t.off(a.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),t.off(a.ASSET_LIST_LOADED,this.onAssetListLoaded,this),t.off(a.BUFFER_CODECS,this.onBufferCodecs,this),t.off(a.BUFFER_APPENDED,this.onBufferAppended,this),t.off(a.BUFFER_FLUSHED,this.onBufferFlushed,this),t.off(a.BUFFERED_TO_END,this.onBufferedToEnd,this),t.off(a.MEDIA_ENDED,this.onMediaEnded,this),t.off(a.ERROR,this.onError,this),t.off(a.DESTROYING,this.onDestroying,this))}startLoad(){this.resumeBuffering()}stopLoad(){this.pauseBuffering()}resumeBuffering(){var t;null==(t=this.getBufferingPlayer())||t.resumeBuffering()}pauseBuffering(){var t;null==(t=this.getBufferingPlayer())||t.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=null,this.assetListLoader=null,this.onPlay=this.onPause=this.onSeeking=this.onTimeupdate=null,this.onScheduleUpdate=null}onDestroying(){const t=this.primaryMedia||this.media;t&&this.removeMediaListeners(t)}removeMediaListeners(t){Si(t,"play",this.onPlay),Si(t,"pause",this.onPause),Si(t,"seeking",this.onSeeking),Si(t,"timeupdate",this.onTimeupdate)}onMediaAttaching(t,e){const i=this.media=e.media;Ti(i,"seeking",this.onSeeking),Ti(i,"timeupdate",this.onTimeupdate),Ti(i,"play",this.onPlay),Ti(i,"pause",this.onPause)}onMediaAttached(t,e){const i=this.effectivePlayingItem,s=this.detachedData;if(this.detachedData=null,null===i)this.checkStart();else if(!s){this.clearScheduleState();const t=this.findItemIndex(i);this.setSchedulePosition(t)}}clearScheduleState(){this.log("clear schedule state"),this.playingItem=this.bufferingItem=this.waitingItem=this.endedItem=this.playingAsset=this.endedAsset=this.bufferingAsset=null}onMediaDetaching(t,e){const i=!!e.transferMedia,s=this.media;if(this.media=null,!i&&(s&&this.removeMediaListeners(s),this.detachedData)){const t=this.getBufferingPlayer();t&&(this.log(`Removing schedule state for detachedData and ${t}`),this.playingAsset=this.endedAsset=this.bufferingAsset=this.bufferingItem=this.waitingItem=this.detachedData=null,t.detachMedia()),this.shouldPlay=!1}}get interstitialsManager(){if(!this.hls)return null;if(this.manager)return this.manager;const t=this,e=()=>t.bufferingItem||t.waitingItem,i=e=>e?t.getAssetPlayer(e.identifier):e,s=(e,s,n,a,o)=>{if(e){let l=e[s].start;const h=e.event;if(h){if("playout"===s||h.timelineOccupancy!==Xl.Point){const t=i(n);(null==t?void 0:t.interstitial)===h&&(l+=t.assetItem.startOffset+t[o])}}else{l+=("bufferedPos"===a?r():t[a])-e.start}return l}return 0},r=()=>{const e=t.bufferedPos;return e===Number.MAX_VALUE?n("primary"):Math.max(e,0)},n=e=>{var i,s;return null!=(i=t.primaryDetails)&&i.live?t.primaryDetails.edge:(null==(s=t.schedule)?void 0:s.durations[e])||0},a=(e,r)=>{var n,a;const o=t.effectivePlayingItem;if(null!=o&&null!=(n=o.event)&&n.restrictions.skip||!t.schedule)return;t.log(`seek to ${e} "${r}"`);const l=t.effectivePlayingItem,h=t.schedule.findItemIndexAtTime(e,r),d=null==(a=t.schedule.items)?void 0:a[h],c=t.getBufferingPlayer(),u=null==c?void 0:c.interstitial,f=null==u?void 0:u.appendInPlace,g=l&&t.itemsMatch(l,d);if(l&&(f||g)){const n=i(t.playingAsset),a=(null==n?void 0:n.media)||t.primaryMedia;if(a){const i="primary"===r?a.currentTime:s(l,r,t.playingAsset,"timelinePos","currentTime"),o=e-i,h=(f?i:a.currentTime)+o;if(h>=0&&(!n||f||h<=n.duration))return void(a.currentTime=h)}}if(d){let i=e;if("primary"!==r){const t=e-d[r].start;i=d.start+t}const s=!t.isInterstitial(d);if(t.isInterstitial(l)&&!l.event.appendInPlace||!s&&!d.event.appendInPlace){if(l){const n=t.findItemIndex(l);if(h>n){const e=t.schedule.findJumpRestrictedIndex(n+1,h);if(e>n)return void t.setSchedulePosition(e)}let a=0;if(s)t.timelinePos=i,t.checkBuffer();else{const t=d.event.assetList,i=e-(d[r]||d).start;for(let e=t.length;e--;){const s=t[e];if(s.duration&&i>=s.startOffset&&i<s.startOffset+s.duration){a=e;break}}}t.setSchedulePosition(h,a)}}else{const e=t.media||(f?null==c?void 0:c.media:null);e&&(e.currentTime=i)}}},o=()=>{const i=t.effectivePlayingItem;if(t.isInterstitial(i))return i;const s=e();return t.isInterstitial(s)?s:null},l={get bufferedEnd(){const i=e(),r=t.bufferingItem;var n;return r&&r===i&&(s(r,"playout",t.bufferingAsset,"bufferedPos","bufferedEnd")-r.playout.start||(null==(n=t.bufferingAsset)?void 0:n.startOffset))||0},get currentTime(){const e=o(),i=t.effectivePlayingItem;return i&&i===e?s(i,"playout",t.effectivePlayingAsset,"timelinePos","currentTime")-i.playout.start:0},set currentTime(e){const i=o(),s=t.effectivePlayingItem;s&&s===i&&a(e+s.playout.start,"playout")},get duration(){const t=o();return t?t.playout.end-t.playout.start:0},get assetPlayers(){var e;const i=null==(e=o())?void 0:e.event.assetList;return i?i.map(e=>t.getAssetPlayer(e.identifier)):[]},get playingIndex(){var e;const i=null==(e=o())?void 0:e.event;return i&&t.effectivePlayingAsset?i.findAssetIndex(t.effectivePlayingAsset):-1},get scheduleItem(){return o()}};return this.manager={get events(){var e;return(null==(e=t.schedule)||null==(e=e.events)?void 0:e.slice(0))||[]},get schedule(){var e;return(null==(e=t.schedule)||null==(e=e.items)?void 0:e.slice(0))||[]},get interstitialPlayer(){return o()?l:null},get playerQueue(){return t.playerQueue.slice(0)},get bufferingAsset(){return t.bufferingAsset},get bufferingItem(){return e()},get bufferingIndex(){const i=e();return t.findItemIndex(i)},get playingAsset(){return t.effectivePlayingAsset},get playingItem(){return t.effectivePlayingItem},get playingIndex(){const e=t.effectivePlayingItem;return t.findItemIndex(e)},primary:{get bufferedEnd(){return r()},get currentTime(){const e=t.timelinePos;return e>0?e:0},set currentTime(t){a(t,"primary")},get duration(){return n("primary")},get seekableStart(){return t.seekableStart}},integrated:{get bufferedEnd(){return s(e(),"integrated",t.bufferingAsset,"bufferedPos","bufferedEnd")},get currentTime(){return s(t.effectivePlayingItem,"integrated",t.effectivePlayingAsset,"timelinePos","currentTime")},set currentTime(t){a(t,"integrated")},get duration(){return n("integrated")},get seekableStart(){return((e,i)=>{var s;if(0!==e&&"primary"!==i&&null!=(s=t.schedule)&&s.length){var r;const s=t.schedule.findItemIndexAtTime(e),n=null==(r=t.schedule.items)?void 0:r[s];if(n)return e+(n[i].start-n.start)}return e})(t.seekableStart,"integrated")}},skip:()=>{const e=t.effectivePlayingItem,i=null==e?void 0:e.event;if(i&&!i.restrictions.skip){const s=t.findItemIndex(e);if(i.appendInPlace){const t=e.playout.start+e.event.duration;a(t+.001,"playout")}else t.advanceAfterAssetEnded(i,s,1/0)}}}}get effectivePlayingItem(){return this.waitingItem||this.playingItem||this.endedItem}get effectivePlayingAsset(){return this.playingAsset||this.endedAsset}get playingLastItem(){var t;const e=this.playingItem,i=null==(t=this.schedule)?void 0:t.items;return!!(this.playbackStarted&&e&&i)&&this.findItemIndex(e)===i.length-1}get playbackStarted(){return null!==this.effectivePlayingItem}get currentTime(){var t,i;if(null===this.mediaSelection)return;const s=this.waitingItem||this.playingItem;if(this.isInterstitial(s)&&!s.event.appendInPlace)return;let r=this.media;!r&&null!=(t=this.bufferingItem)&&null!=(t=t.event)&&t.appendInPlace&&(r=this.primaryMedia);const n=null==(i=r)?void 0:i.currentTime;return void 0!==n&&e(n)?n:void 0}get primaryMedia(){var t;return this.media||(null==(t=this.detachedData)?void 0:t.media)||null}isInterstitial(t){return!(null==t||!t.event)}retreiveMediaSource(t,e){const i=this.getAssetPlayer(t);i&&this.transferMediaFromPlayer(i,e)}transferMediaFromPlayer(t,e){const i=t.interstitial.appendInPlace,s=t.media;if(i&&s===this.primaryMedia){if(this.bufferingAsset=null,(!e||this.isInterstitial(e)&&!e.event.appendInPlace)&&e&&s)return void(this.detachedData={media:s});const i=t.transferMedia();this.log(`transfer MediaSource from ${t} ${Ue(i)}`),this.detachedData=i}else e&&s&&(this.shouldPlay||(this.shouldPlay=!s.paused))}transferMediaTo(t,e){var i,s;if(t.media===e)return;let r=null;const n=this.hls,a=t!==n,o=a&&t.interstitial.appendInPlace,l=null==(i=this.detachedData)?void 0:i.mediaSource;let h;if(n.media)o&&(r=n.transferMedia(),this.detachedData=r),h="Primary";else{const t=this.getBufferingPlayer();t?(r=t.transferMedia(),this.detachedData=r,h=`${t}`):h=l?"detached MediaSource":"detached media"}if(!r)if(l)r=this.detachedData,this.log(`using detachedData: MediaSource ${Ue(r)}`);else if(!this.detachedData||n.media===e){const t=this.playerQueue;t.length>1&&t.forEach(t=>{if(a&&t.interstitial.appendInPlace!==o){const e=t.interstitial;this.clearInterstitial(t.interstitial,null),e.appendInPlace=!1,e.appendInPlace&&this.warn(`Could not change append strategy for queued assets ${e}`)}}),this.hls.detachMedia(),this.detachedData={media:e}}const d=r&&"mediaSource"in r&&"closed"!==(null==(s=r.mediaSource)?void 0:s.readyState);if(this.log(`${d?"transfering MediaSource":"attaching media"} to ${a?t:"Primary"} from ${h} (media.currentTime: ${e.currentTime})`),!d&&!a)return void t.attachMedia(e);const c=d&&r?k({},r):{media:e},u=this.schedule;if(u&&a){const e=t.assetId===u.assetIdAtEnd;c.overrides={duration:u.duration,endOfStream:e||!1===t.appendInPlace}}if(!d&&o){const e=t,i=e.assetItem.timelineStart;if(i){const t=e.hls,s=Math.max(this.timelinePos-i,Number.EPSILON);t.startPosition!==s&&(this.log(`Set ${e} startPosition: ${s}`),t.config.startPosition=s,t.loadingEnabled&&t.startLoad(s))}}t.attachMedia(c)}onInterstitialCueEnter(){this.onTimeupdate()}checkStart(){const t=this.schedule,e=null==t?void 0:t.events,i=this.hls;if(!e||this.playbackDisabled||!this.media||!i)return;-1===this.bufferedPos&&(this.bufferedPos=0);const s=this.timelinePos,r=this.effectivePlayingItem;if(-1===s){if(!i.loadingEnabled)return void this.log("waiting for startLoad( <startPosition> )");const s=i.startPosition;if(this.timelinePos=s,0===e.length)this.setSchedulePosition(0);else if(e[0].cue.pre){this.log(dh("checkStart (preroll)",s));const i=t.findEventIndex(e[0].identifier);this.setSchedulePosition(i)}else if(s>=0||!this.primaryLive){this.log(dh("checkStart",s));const e=this.timelinePos=s>0?s:0,i=t.findItemIndexAtTime(e);this.setSchedulePosition(i)}else 0===i.liveSyncPosition?this.setSchedulePosition(0):this.log("[checkStart] waiting for live start")}else if(r&&!this.playingItem){this.log(dh("checkStart (playing item)",r.start));const e=t.findItemIndex(r);this.setSchedulePosition(e)}}advanceAssetBuffering(t,e){const i=t.event,s=i.findAssetIndex(e),r=ih(i,s);if(i.isAssetPastPlayoutLimit(r)){if(this.schedule){var n;const e=this.getNextItemIndex(t,!0),i=null==(n=this.schedule.items)?void 0:n[e];i&&this.bufferedToItem(i)}}else this.bufferedToEvent(t,r)}livePrerollResumption(t,i){if(t.cue.pre&&this.primaryLive&&!e(t.resumeOffset)&&this.hls){const t=this.getLiveStartPos();if(i){const e=this.getBufferingPlayer();return t+(null!=e&&e.interstitial.cue.pre?e.remaining:0)}return t}}getNextItemIndex(t,e){if(this.schedule){const i=this.livePrerollResumption(t.event,e);if(void 0!==i)return this.log(`find next item index @${i}`),this.schedule.findItemIndexAtTime(i)}return this.findItemIndex(t)+1}advanceAfterAssetEnded(t,e,i){const s=ih(t,i);if(t.isAssetPastPlayoutLimit(s)){if(this.schedule){const i=this.schedule.items;if(i){const s=i[e],r=s.event?this.getNextItemIndex(s):e+1;if(r>=i.length)return void this.setSchedulePosition(-1);const n=t.resumeTime;this.timelinePos<n&&(this.log(dh("advanceAfterAssetEnded",n)),this.timelinePos=n,t.appendInPlace&&!i[r].event&&this.hls.startLoad(n+.01),this.checkBuffer(this.bufferedPos<n)),this.setSchedulePosition(r)}}}else{if(t.appendInPlace){const e=t.assetList[s];e&&this.advanceInPlace(e.timelineStart)}this.setSchedulePosition(e,s)}}setScheduleToAssetAtTime(t,e){const i=this.schedule;if(!i)return;const s=e.parentIdentifier,r=i.getEvent(s);if(r){const e=i.findEventIndex(s),n=i.findAssetIndex(r,t);this.advanceAfterAssetEnded(r,e,n-1)}}setSchedulePosition(t,e){var i;const s=null==(i=this.schedule)?void 0:i.items;if(!s||this.playbackDisabled)return;const r=t>=0?s[t]:null;this.log(`setSchedulePosition ${t}, ${e} (${r?oh(r):r}) pos: ${this.timelinePos}`);const n=this.waitingItem||this.playingItem,o=this.playingLastItem;if(this.isInterstitial(n)){const i=n.event,c=this.playingAsset,u=null==c?void 0:c.identifier,f=u?this.getAssetPlayer(u):null;if(f&&u&&(!this.eventItemsMatch(n,r)||void 0!==e&&u!==i.assetList[e].identifier)){var l;const e=i.findAssetIndex(c);if(this.log(`INTERSTITIAL_ASSET_ENDED ${e+1}/${i.assetList.length} ${sh(c)}`),this.endedAsset=c,this.playingAsset=null,this.hls.trigger(a.INTERSTITIAL_ASSET_ENDED,{asset:c,assetListIndex:e,event:i,schedule:s.slice(0),scheduleIndex:t,player:f}),n!==this.playingItem)return void(this.itemsMatch(n,this.playingItem)&&!this.playingAsset&&this.advanceAfterAssetEnded(i,this.findItemIndex(this.playingItem),e));this.retreiveMediaSource(u,r),!f.media||null!=(l=this.detachedData)&&l.mediaSource||f.detachMedia()}if(!this.eventItemsMatch(n,r)&&(this.endedItem=n,this.playingItem=this.waitingItem=null,this.log(`INTERSTITIAL_ENDED ${i} ${oh(n)}`),i.hasPlayed=!0,this.hls.trigger(a.INTERSTITIAL_ENDED,{event:i,schedule:s.slice(0),scheduleIndex:t}),i.cue.once&&this.hls)){var h;this.updateSchedule();const t=null==(h=this.schedule)?void 0:h.items;if(r&&t){const a=this.findItemIndex(r),l=this.livePrerollResumption(i);if(void 0!==l){let e=l;const r=this.getNextItemIndex(n);if(!this.isInterstitial(s[r])){var d;const t=null==(d=this.primaryDetails)?void 0:d.fragments;if(i.snapOptions.in&&t){const i=Je(null,t,l);i&&(e=Math.min(Math.max(s[r].start,Jl(e,i)),s[r].end))}}if(this.log(dh("live join (preroll)",e)),this.timelinePos=e,r!==a&&(r||0===r))return void this.advanceSchedule(r,t,void 0,n,o)}this.advanceSchedule(a,t,e,n,o)}return}}this.advanceSchedule(t,s,e,n,o)}advanceSchedule(t,e,i,s,r){const n=this.schedule;if(!n)return;const o=e[t]||null,l=this.primaryMedia,h=this.playerQueue;if(h.length&&h.forEach(e=>{const i=e.interstitial,s=n.findEventIndex(i.identifier);(s<t||s>t+1)&&this.clearInterstitial(i,o)}),this.isInterstitial(o)){this.timelinePos=Math.min(Math.max(this.timelinePos,o.start),o.end);const r=o.event;if(void 0===i){const e=ih(r,(i=r.cue.pre?0:n.findAssetIndex(r,this.timelinePos))-1);if(r.isAssetPastPlayoutLimit(e)||r.appendInPlace&&this.timelinePos===o.end)return void this.advanceAfterAssetEnded(r,t,i);i=e}const h=this.waitingItem;this.assetsBuffered(o,l)||this.setBufferingItem(o);let d=this.preloadAssets(r,i);if(this.eventItemsMatch(o,h||s)||(this.waitingItem=o,this.log(`INTERSTITIAL_STARTED ${oh(o)} ${r.appendInPlace?"append in place":""}`),r.hasPlayed=!1,this.hls.trigger(a.INTERSTITIAL_STARTED,{event:r,schedule:e.slice(0),scheduleIndex:t})),!r.assetListLoaded)return void this.log(`Waiting for ASSET-LIST to complete loading ${r}`);if(r.assetListLoader&&(r.assetListLoader.destroy(),r.assetListLoader=void 0),!l)return void this.log(`Waiting for attachMedia to start Interstitial ${r}`);this.waitingItem=this.endedItem=null,this.playingItem=o;const c=r.assetList[i];if(!c)return void this.advanceAfterAssetEnded(r,t,i||0);if(d||(d=this.getAssetPlayer(c.identifier)),null===d||d.destroyed){const t=r.assetList.length;this.warn(`asset ${i+1}/${t} player destroyed ${r}`),d=this.createAssetPlayer(r,c,i),d.loadSource()}if(!this.eventItemsMatch(o,this.bufferingItem)&&r.appendInPlace&&this.isAssetBuffered(c))return;this.startAssetPlayer(d,i,e,t,l),this.shouldPlay&&hh(d.media)}else o?(this.resumePrimary(o,t,s),this.shouldPlay&&hh(this.hls.media)):r&&this.isInterstitial(s)&&(this.endedItem=null,this.playingItem=s,s.event.appendInPlace||this.attachPrimary(n.durations.primary,null))}get playbackDisabled(){return!1===this.hls.config.enableInterstitialPlayback}get primaryDetails(){var t;return null==(t=this.mediaSelection)?void 0:t.main.details}get primaryLive(){var t;return!(null==(t=this.primaryDetails)||!t.live)}resumePrimary(t,e,i){var s,r;this.playingItem=t,this.playingAsset=this.endedAsset=null,this.waitingItem=null,this.bufferedToItem(t),this.endedItem=null,this.log(`resuming ${oh(t)}`);let n=this.timelinePos;if(null!=(s=this.detachedData)&&s.mediaSource?this.primaryLive&&this.startLoadingPrimaryAt(n):((n<t.start||n>=t.end||n<this.seekableStart)&&(n=this.getPrimaryResumption(t,e),this.log(dh("resumePrimary",n)),this.timelinePos=n),this.attachPrimary(n,t)),!i)return;const o=null==(r=this.schedule)?void 0:r.items;o&&(this.log(`INTERSTITIALS_PRIMARY_RESUMED ${oh(t)}`),this.hls.trigger(a.INTERSTITIALS_PRIMARY_RESUMED,{schedule:o.slice(0),scheduleIndex:e}),this.checkBuffer())}get seekableStart(){var t;return this.primaryLive&&(null==(t=this.primaryDetails)?void 0:t.fragmentStart)||0}getPrimaryResumption(t,e,i){const s=t.start;if(this.primaryLive){if(0===e)return this.hls.startPosition;const t=this.endedItem||this.playingItem,r=null!=t&&t.event?this.livePrerollResumption(t.event,i):void 0;if(void 0!==r)return r;const n=this.primaryDetails;if(n){const{fragmentStart:t,edge:e}=n;if(s<t||s>e&&!i){const i=this.hls.liveSyncPosition;return this.log(`primary resumption out of bounds (${s} [${t}-${e}]) snapping to liveSync ${i}`),i||t}}}return this.log(`primary resumption itemStart: ${s}`),s}getLiveStartPos(){var t;const e=this.hls.startPosition,i=this.hls.liveSyncPosition||0,s=3*((null==(t=this.primaryDetails)?void 0:t.targetduration)||10);return-1===e||i&&i-e<s?i||0:e}isAssetBuffered(t){const e=this.getAssetPlayer(t.identifier);if(null!=e&&e.hls)return e.hls.bufferedToEnd;return Ei.bufferInfo(this.primaryMedia,this.timelinePos,0).end+1>=t.timelineStart+(t.duration||0)}attachPrimary(t,e,i){e?this.setBufferingItem(e):this.bufferingItem=this.playingItem,this.bufferingAsset=null;const s=this.primaryMedia;if(!s)return;const r=this.hls;r.media?this.checkBuffer():(this.transferMediaTo(r,s),i&&this.startLoadingPrimaryAt(t,i)),i||(this.log(dh("attachPrimary",t)),this.timelinePos=t,this.startLoadingPrimaryAt(t,i))}startLoadingPrimaryAt(t,e){const i=this.hls,{loadingEnabled:s,bufferingEnabled:r,startPosition:n}=i,a=i.hasEnoughToStart;if(this.log(`Start loading primary @${t} bufferedPos: ${this.bufferedPos} startPosition: ${n} skip seek: ${e} has enough ${a} loadingEnabled: ${s} bufferingEnabled: ${r}`),!e&&a||!s||Math.abs(n-t)>.1){const s=this.primaryDetails;if(null!=s&&s.live&&t+.5>=s.edge){const e=this.bufferingItem;return this.log(`Resume primary loading when live passes ${t} buffering item: ${e?oh(e):null}`),i.pauseBuffering(),void(this.bufferPastEdge=!0)}i.startLoad(t,e)}else r||i.resumeBuffering()}onManifestLoading(){var t;this.stopLoad(),null==(t=this.schedule)||t.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(a.BUFFER_CODECS,this.onBufferCodecs,this),this.hls.on(a.BUFFER_CODECS,this.onBufferCodecs,this)}onLevelUpdated(t,e){if(-1===e.level||!this.schedule)return;const i=this.hls.levels[e.level];if(!i.details)return;const s=k(k({},this.mediaSelection||this.altSelection),{},{main:i});this.mediaSelection=s;const r=this.hls.startPosition;this.schedule.parseInterstitialDateRanges(s,this.hls.config.interstitialAppendInPlace,-1===r?0:r);if(this.schedule.items)if(this.effectivePlayingItem){if(this.bufferPastEdge){const t=this.primaryDetails,e=this.bufferedPos;if(null!=t&&t.live&&e+.5<t.edge){this.bufferPastEdge=!1;const i=this.bufferingItem;this.log(`Live edge ${t.edge} passed buffer: ${e} buffering item: ${i?oh(i):null}`);if((null==i?void 0:i.end)===1/0){const t=this.playingItem,s=this.isInterstitial(t)&&t.event.appendInPlace;this.hls.startLoad(Math.max(e,i.start),s)}else{const t=this.getBufferingPlayer();if(t){t.bufferedInPlaceToEnd(this.primaryMedia,t.currentTime)&&t.hls&&t.hls.trigger(a.BUFFERED_TO_END,void 0)}}}}}else this.checkStart()}onAudioTrackUpdated(t,e){const i=this.hls.audioTracks[e.id],s=this.mediaSelection;if(!s)return void(this.altSelection=k(k({},this.altSelection),{},{audio:i}));const r=k(k({},s),{},{audio:i});this.mediaSelection=r}onSubtitleTrackUpdated(t,e){const i=this.hls.subtitleTracks[e.id],s=this.mediaSelection;if(!s)return void(this.altSelection=k(k({},this.altSelection),{},{subtitles:i}));const r=k(k({},s),{},{subtitles:i});this.mediaSelection=r}onAudioTrackSwitching(t,e){const i=Ve(e);this.playerQueue.forEach(({hls:t})=>t&&(t.setAudioOption(e)||t.setAudioOption(i)))}onSubtitleTrackSwitch(t,e){const i=Ve(e);this.playerQueue.forEach(({hls:t})=>t&&(t.setSubtitleOption(e)||-1!==e.id&&t.setSubtitleOption(i)))}onBufferCodecs(t,e){const i=e.tracks;i&&(this.requiredTracks=i)}onBufferAppended(t,e){this.checkBuffer()}onBufferFlushed(t,e){const i=this.playingItem;if(i&&!this.itemsMatch(i,this.bufferingItem)&&!this.isInterstitial(i)){const t=this.timelinePos;this.bufferedPos=t,this.checkBuffer()}}onBufferedToEnd(t){if(!this.schedule)return;const e=this.schedule.events;if(this.bufferedPos<Number.MAX_VALUE&&e){for(let t=0;t<e.length;t++){const i=e[t];if(i.cue.post){const t=this.getEventItem(i.identifier);t&&this.eventItemsMatch(t,this.bufferingItem)&&this.bufferedToItem(t,0);break}}this.bufferedPos=Number.MAX_VALUE}}onMediaEnded(t){const e=this.playingItem;if(!this.playingLastItem&&e){const t=this.findItemIndex(e);this.setSchedulePosition(t+1)}else this.shouldPlay=!1}updateItem(t,e){var i;const s=null==(i=this.schedule)?void 0:i.items;if(t&&s){return s[this.findItemIndex(t,e)]||null}return null}trimInPlace(t,e){if(this.isInterstitial(t)&&t.event.appendInPlace&&e.end-t.end>.25){t.event.assetList.forEach((e,i)=>{t.event.isAssetPastPlayoutLimit(i)&&this.clearAssetPlayer(e.identifier,null)});const i=t.end+.25,s=Ei.bufferInfo(this.primaryMedia,i,0);if(s.end>i||(s.nextStart||0)>i){this.log(`trim buffered interstitial ${oh(t)} (was ${oh(e)})`);const s=!0;this.attachPrimary(i,null,s),this.flushFrontBuffer(i)}}}itemsMatch(t,e){return!!e&&(t===e||t.event&&e.event&&this.eventItemsMatch(t,e)||!t.event&&!e.event&&this.findItemIndex(t)===this.findItemIndex(e))}eventItemsMatch(t,e){var i;return!!e&&(t===e||t.event.identifier===(null==(i=e.event)?void 0:i.identifier))}findEventIndex(t){return this.schedule?this.schedule.findEventIndex(t):-1}getEventItem(t){if(this.schedule){var e;const i=null==(e=this.schedule.items)?void 0:e[this.findEventIndex(t)];if(this.isInterstitial(i)&&i.event.identifier===t)return i}}findItemIndex(t,e){return t&&this.schedule?this.schedule.findItemIndex(t,e):-1}updateSchedule(t=!1){var e,i;const s=this.mediaSelection;if(!s)return;const r=(null==(e=this.hls)?void 0:e.liveSyncPosition)||0;null==(i=this.schedule)||i.updateSchedule(s,[],r,t)}checkBuffer(t){var e;const i=null==(e=this.schedule)?void 0:e.items;if(!i)return;const s=Ei.bufferInfo(this.primaryMedia,this.timelinePos,0);t&&(this.bufferedPos=this.timelinePos),t||(t=s.len<1),this.updateBufferedPos(s.end,i,t)}updateBufferedPos(t,e,i){const s=this.schedule,r=this.bufferingItem;if(this.bufferedPos>t||!s)return;if(1===e.length&&this.itemsMatch(e[0],r))return void(this.bufferedPos=t);const n=this.playingItem,a=this.findItemIndex(n);let o=s.findItemIndexAtTime(t);if(this.bufferedPos<t){var l;const i=this.findItemIndex(r),s=Math.min(i+1,e.length-1),n=e[s];if((-1===o&&r&&t>=r.end||null!=(l=n.event)&&l.appendInPlace&&t+.01>=n.start)&&(o=s),this.isInterstitial(r)){const t=r.event;if(s-a>1&&!1===t.appendInPlace)return;if(0===t.assetList.length&&t.assetListLoader)return}if(this.bufferedPos=t,o>i&&o>a)this.bufferedToItem(n);else{const e=this.primaryDetails;this.primaryLive&&e&&t>e.edge-e.targetduration&&n.start<e.edge+this.hls.config.interstitialLiveLookAhead&&this.isInterstitial(n)&&this.preloadAssets(n.event,0)}}else i&&n&&!this.itemsMatch(n,r)&&(o===a?this.bufferedToItem(n):o===a+1&&this.bufferedToItem(e[o]))}assetsBuffered(t,e){return 0!==t.event.assetList.length&&!t.event.assetList.some(t=>{const i=this.getAssetPlayer(t.identifier);return!(null!=i&&i.bufferedInPlaceToEnd(e))})}setBufferingItem(t){const e=this.bufferingItem,i=this.schedule;if(!this.itemsMatch(t,e)&&i){const{items:s,events:r}=i;if(!s||!r)return e;const n=this.isInterstitial(t),o=this.getBufferingPlayer();this.bufferingItem=t,this.bufferedPos=Math.max(t.start,Math.min(t.end,this.timelinePos));const l=o?o.remaining:e?e.end-this.timelinePos:0;if(this.log(`INTERSTITIALS_BUFFERED_TO_BOUNDARY ${oh(t)}`+(e?` (${l.toFixed(2)} remaining)`:"")),!this.playbackDisabled)if(n){const e=i.findAssetIndex(t.event,this.bufferedPos);t.event.assetList.forEach((t,i)=>{const s=this.getAssetPlayer(t.identifier);s&&(i===e&&s.loadSource(),s.resumeBuffering())})}else this.hls.resumeBuffering(),this.playerQueue.forEach(t=>t.pauseBuffering());this.hls.trigger(a.INTERSTITIALS_BUFFERED_TO_BOUNDARY,{events:r.slice(0),schedule:s.slice(0),bufferingIndex:this.findItemIndex(t),playingIndex:this.findItemIndex(this.playingItem)})}else this.bufferingItem!==t&&(this.bufferingItem=t);return e}bufferedToItem(t,e=0){const i=this.setBufferingItem(t);if(!this.playbackDisabled)if(this.isInterstitial(t))this.bufferedToEvent(t,e);else if(null!==i){this.bufferingAsset=null;const e=this.getPrimaryResumption(t,this.findItemIndex(t),!0),i=this.bufferedPos=Math.max(e,Math.min(this.bufferedPos,t.end),this.timelinePos,t.start),s=this.detachedData;if(s)if(s.mediaSource){const e=!0;this.attachPrimary(i,t,e)}else this.startLoadingPrimaryAt(i);else{const t=this.playingItem,e=this.isInterstitial(t)&&t.event.appendInPlace;this.startLoadingPrimaryAt(i,e)}}}bufferedToEvent(t,e){const i=t.event,s=0===i.assetList.length&&!i.assetListLoader,r=i.cue.once;if(s||!r){const t=this.preloadAssets(i,e);if(null!=t&&t.interstitial.appendInPlace){const e=this.primaryMedia;e&&this.bufferAssetPlayer(t,e)}}}preloadAssets(t,e){const i=t.assetUrl,s=t.assetList.length,r=0===s&&!t.assetListLoader,n=t.cue.once;if(r){const r=t.timelineStart,n=this.playingItem,o=this.getBufferingPlayer();var a;if(t.appendInPlace)this.isInterstitial(n)||(null==n||null==(a=n.nextEvent)?void 0:a.identifier)!==t.identifier||this.flushFrontBuffer(r+.25);let l,h=0;if(o&&!o.interstitial.cue.pre||!this.primaryLive||(h=this.getLiveStartPos(),o&&(h+=o.remaining)),h&&!t.cue.pre&&!t.cue.post){const t=h-r;t>0&&(l=Math.round(1e3*t)/1e3)}if(this.log(`Load interstitial asset ${e+1}/${i?1:s} ${t}${h?` live-start: ${h} start-offset: ${l} (timeline-start: ${r})`:""}`),i)return this.createAsset(t,0,0,r,t.duration,i);const d=this.assetListLoader.loadAssetList(t,l);d&&(t.assetListLoader=d)}else if(!n&&s){for(let i=e;i<s;i++){const e=t.assetList[i],s=this.getAssetPlayerQueueIndex(e.identifier);-1!==s&&!this.playerQueue[s].destroyed||e.error||this.createAssetPlayer(t,e,i)}const i=t.assetList[e];if(i){const t=this.getAssetPlayer(i.identifier);return t&&t.loadSource(),t}}return null}flushFrontBuffer(t){const e=this.requiredTracks;if(!e)return;const i=this.primaryDetails;if(i&&t>=i.edge)return;this.log(`Removing front buffer starting at ${t}`);Object.keys(e).forEach(e=>{this.hls.trigger(a.BUFFER_FLUSHING,{startOffset:t,endOffset:1/0,type:e})})}getAssetPlayerQueueIndex(t){const e=this.playerQueue;for(let i=0;i<e.length;i++)if(t===e[i].assetId)return i;return-1}getAssetPlayer(t){const e=this.getAssetPlayerQueueIndex(t);return this.playerQueue[e]||null}getBufferingPlayer(){const{playerQueue:t,primaryMedia:e}=this;if(e)for(let i=0;i<t.length;i++)if(t[i].media===e)return t[i];return null}createAsset(t,e,i,s,r,n){const a={parentIdentifier:t.identifier,identifier:Ql(t,n,e),duration:r,startOffset:i,timelineStart:s,uri:n};return this.createAssetPlayer(t,a,e)}createAssetPlayer(t,e,i){const s=this.hls,o=s.userConfig,l=Xe(s.loadLevelObj||s.levels[s.currentLevel],o.videoPreference),h=s.audioTracks[s.audioTrack],d=s.subtitleTracks[s.subtitleTrack];let c=0;if(this.primaryLive||t.appendInPlace){const t=this.timelinePos-e.timelineStart;if(t>=0){const i=e.duration;i&&t<i&&(c=t)}}const u=e.identifier,f=k(k({},o),{},{maxMaxBufferLength:Math.min(15,s.config.maxMaxBufferLength),autoStartLoad:!0,startFragPrefetch:!0,primarySessionId:s.sessionId,assetPlayerId:u,abrEwmaDefaultEstimate:s.bandwidthEstimate,interstitialsController:void 0,startPosition:c,liveDurationInfinity:!1,testBandwidth:!1,videoPreference:l,audioPreference:h||o.audioPreference,subtitlePreference:d||o.subtitlePreference});t.appendInPlace&&(t.appendInPlaceStarted=!0,e.timelineStart&&(f.timelineOffset=e.timelineStart));const g=f.cmcd;null!=g&&g.sessionId&&g.contentId&&(f.cmcd=I({},g,{contentId:dl(e.uri)})),this.getAssetPlayer(u)&&this.warn(`Duplicate date range identifier ${t} and asset ${u}`);const m=new rh(this.HlsPlayerClass,f,t,e);this.playerQueue.push(m),t.assetList[i]=e;let p=!0;const v=s=>{if(s.live){const e=new Error(`Interstitials MUST be VOD assets ${t}`),s={fatal:!0,type:r.OTHER_ERROR,details:n.INTERSTITIAL_ASSET_ITEM_ERROR,error:e},a=this.findEventIndex(t.identifier);return void this.handleAssetItemError(s,t,a,i,e.message)}const a=s.edge-s.fragmentStart,o=e.duration;(p||null===o||a>o)&&(p=!1,this.log(`Interstitial asset "${u}" duration change ${o} > ${a}`),e.duration=a,this.updateSchedule())};m.on(a.LEVEL_UPDATED,(t,{details:e})=>v(e)),m.on(a.LEVEL_PTS_UPDATED,(t,{details:e})=>v(e)),m.on(a.EVENT_CUE_ENTER,()=>this.onInterstitialCueEnter());const y=(t,e)=>{const i=this.getAssetPlayer(u);if(i&&e.tracks){i.off(a.BUFFER_CODECS,y),i.tracks=e.tracks;const t=this.primaryMedia;this.bufferingAsset===i.assetItem&&t&&!i.media&&this.bufferAssetPlayer(i,t)}};m.on(a.BUFFER_CODECS,y);m.on(a.BUFFERED_TO_END,()=>{const e=this.getAssetPlayer(u);if(this.log(`buffered to end of asset ${e}`),!e||!this.schedule)return;const i=this.getEventItem(t.identifier);i&&this.advanceAssetBuffering(i,e.assetItem)});const E=e=>()=>{if(!this.getAssetPlayer(u)||!this.schedule)return;this.shouldPlay=!0;const i=this.findEventIndex(t.identifier);this.advanceAfterAssetEnded(t,i,e)};return m.once(a.MEDIA_ENDED,E(i)),m.once(a.PLAYOUT_LIMIT_REACHED,E(1/0)),m.on(a.ERROR,(e,s)=>{if(!this.schedule)return;const r=this.getAssetPlayer(u);if(s.details===n.BUFFER_STALLED_ERROR)return null!=r&&r.appendInPlace?void this.handleInPlaceStall(t):(this.onTimeupdate(),void this.checkBuffer(!0));s.details!==n.BUFFER_SEEK_OVER_HOLE&&this.handleAssetItemError(s,t,this.findEventIndex(t.identifier),i,`Asset player error ${s.error} ${t}`)}),m.on(a.DESTROYING,()=>{if(!this.getAssetPlayer(u)||!this.schedule)return;const e=new Error(`Asset player destroyed unexpectedly ${u}`),s={fatal:!0,type:r.OTHER_ERROR,details:n.INTERSTITIAL_ASSET_ITEM_ERROR,error:e};this.handleAssetItemError(s,t,this.findEventIndex(t.identifier),i,e.message)}),this.log(`INTERSTITIAL_ASSET_PLAYER_CREATED ${sh(e)}`),this.hls.trigger(a.INTERSTITIAL_ASSET_PLAYER_CREATED,{asset:e,assetListIndex:i,event:t,player:m}),m}clearInterstitial(t,e){this.clearAssetPlayers(t,e),t.reset()}clearAssetPlayers(t,e){t.assetList.forEach(t=>{this.clearAssetPlayer(t.identifier,e)})}resetAssetPlayer(t){const e=this.getAssetPlayerQueueIndex(t);if(-1!==e){this.log(`reset asset player "${t}" after error`);const i=this.playerQueue[e];this.transferMediaFromPlayer(i,null),i.resetDetails()}}clearAssetPlayer(t,e){const i=this.getAssetPlayerQueueIndex(t);if(-1!==i){const t=this.playerQueue[i];this.log(`clear ${t} toSegment: ${e?oh(e):e}`),this.transferMediaFromPlayer(t,e),this.playerQueue.splice(i,1),t.destroy()}}emptyPlayerQueue(){let t;for(;t=this.playerQueue.pop();)t.destroy();this.playerQueue=[]}startAssetPlayer(t,e,i,s,r){const{interstitial:n,assetItem:o,assetId:l}=t,h=n.assetList.length,d=this.playingAsset;this.endedAsset=null,this.playingAsset=o,(null==d?void 0:d.identifier)!==l&&(d&&(this.clearAssetPlayer(d.identifier,i[s]),delete d.error),this.log(`INTERSTITIAL_ASSET_STARTED ${e+1}/${h} ${sh(o)}`),this.hls.trigger(a.INTERSTITIAL_ASSET_STARTED,{asset:o,assetListIndex:e,event:n,schedule:i.slice(0),scheduleIndex:s,player:t})),this.bufferAssetPlayer(t,r)}bufferAssetPlayer(t,e){var i;if(!this.schedule)return;const{interstitial:s,assetItem:a}=t,o=this.getEventItem(s.identifier);if(!o)return;if(t.loadSource(),this.setBufferingItem(o),this.bufferingAsset=a,t.bufferedInPlaceToEnd(this.primaryMedia,t.currentTime))return void this.advanceAssetBuffering(o,a);const l=this.getBufferingPlayer();if(l===t)return;const h=s.appendInPlace;if(h&&!1===(null==l?void 0:l.interstitial.appendInPlace))return;const d=(null==l?void 0:l.tracks)||(null==(i=this.detachedData)?void 0:i.tracks)||this.requiredTracks;if(h&&a!==this.playingAsset){if(!t.tracks)return void this.log(`Waiting for track info before buffering ${t}`);if(d&&!W(d,t.tracks)){const e=new Error(`Asset ${sh(a)} SourceBuffer tracks ('${Object.keys(t.tracks)}') are not compatible with primary content tracks ('${Object.keys(d)}')`),i={fatal:!0,type:r.OTHER_ERROR,details:n.INTERSTITIAL_ASSET_ITEM_ERROR,error:e},o=s.findAssetIndex(a);return void this.handleAssetItemError(i,s,this.findEventIndex(s.identifier),o,e.message)}}this.transferMediaTo(t,e)}handleInPlaceStall(t){const e=this.schedule,i=this.primaryMedia;if(!e||!i)return;const s=i.currentTime,r=e.findAssetIndex(t,s),n=t.assetList[r];if(n){const a=this.getAssetPlayer(n.identifier);if(a){const o=a.currentTime||s-n.timelineStart,l=a.duration-o;if(this.warn(`Stalled at ${o} of ${o+l} in ${a} ${t} (media.currentTime: ${s})`),o&&(l/i.playbackRate<.5||a.bufferedInPlaceToEnd(i,a.currentTime))&&a.hls){const i=e.findEventIndex(t.identifier);this.advanceAfterAssetEnded(t,i,r)}}}}advanceInPlace(t){const e=this.primaryMedia;if(e&&e.currentTime<t){const i=`advance currentTime to ${t}, duration: ${e.duration}`;e.duration>t?(this.log(i),e.currentTime=t):this.log(`Cannot ${i}`)}}handleAssetItemError(t,e,i,s,r){if(t.details===n.BUFFER_STALLED_ERROR)return;const o=e.assetList[s]||null;if(this.warn(`INTERSTITIAL_ASSET_ERROR ${o?sh(o):o} ${t.error}`),!this.schedule)return;const l=(null==o?void 0:o.identifier)||"",h=this.getAssetPlayerQueueIndex(l),d=this.playerQueue[h]||null,c=this.schedule.items,u=I({},t,{fatal:!1,errorAction:pi(!0),asset:o,assetListIndex:s,event:e,schedule:c,scheduleIndex:i,player:d});if(this.hls.trigger(a.INTERSTITIAL_ASSET_ERROR,u),!t.fatal)return;const f=this.playingAsset,g=this.bufferingAsset,m=new Error(r);if(o&&(this.clearAssetPlayer(l,null),o.error=m),e.assetList.some(t=>!t.error))for(let t=s;t<e.assetList.length;t++)this.resetAssetPlayer(e.assetList[t].identifier);else e.error=m;this.updateSchedule(!0),e.error?this.primaryFallback(e):(null==f?void 0:f.identifier)===l?this.advanceAfterAssetEnded(e,i,s):(null==g?void 0:g.identifier)===l&&this.isInterstitial(this.bufferingItem)&&this.advanceAssetBuffering(this.bufferingItem,g)}primaryFallback(t){const e=t.timelineStart,i=this.effectivePlayingItem,s=this.playingItem,r=this.seekableStart,n=this.hls.startPosition;let a=this.timelinePos;if(this.isInterstitial(i)){this.log(`Fallback to primary from event "${t.identifier}" start: ${e} pos: ${a} playing: ${oh(i)} startPosition: ${n} seekableStart: ${r} error: ${t.error}`),-1===a&&(a=n),a=Math.max(a,r);const s=this.updateItem(i,a);this.itemsMatch(i,s)&&this.clearInterstitial(t,null),t.appendInPlace&&(this.attachPrimary(e,null),this.flushFrontBuffer(e))}else if(-1===a)return void this.checkStart();if(!this.schedule)return;if(s&&!this.isInterstitial(s))return;const o=this.schedule.findItemIndexAtTime(a);this.setSchedulePosition(o)}onAssetListLoaded(t,e){var i,s;const r=e.event,n=r.identifier,a=e.assetListResponse.ASSETS;if(null==(i=this.schedule)||!i.hasEvent(n))return;const o=r.timelineStart,l=r.duration;let h=0;a.forEach((t,e)=>{const i=parseFloat(t.DURATION);this.createAsset(r,e,h,o+h,i,t.URI),h+=i}),r.duration=h,this.log(`Loaded asset-list with duration: ${h} (was: ${l}) ${r}`);const d=this.waitingItem,c=(null==d?void 0:d.event.identifier)===n;this.updateSchedule();const u=null==(s=this.bufferingItem)?void 0:s.event;if(c){const t=this.findEventIndex(n),e=this.getEventItem(n);if(e){if(!this.playingItem&&this.timelinePos>e.end){if(this.schedule.findItemIndexAtTime(this.timelinePos)!==t)return r.error=new Error(`Interstitial ${a.length?"no longer within playback range":"asset-list is empty"} ${this.timelinePos} ${r}`),this.log(r.error.message),this.updateSchedule(!0),void this.primaryFallback(r)}this.setBufferingItem(e)}this.setSchedulePosition(t)}else if((null==u?void 0:u.identifier)===n){const t=r.assetList[0];if(t){const e=this.getAssetPlayer(t.identifier);if(u.appendInPlace){const t=this.primaryMedia;e&&t&&this.bufferAssetPlayer(e,t)}else e&&e.loadSource()}}}onError(t,e){if(this.schedule)switch(e.details){case n.ASSET_LIST_PARSING_ERROR:case n.ASSET_LIST_LOAD_ERROR:case n.ASSET_LIST_LOAD_TIMEOUT:{const t=e.interstitial;t&&(this.updateSchedule(!0),this.primaryFallback(t));break}case n.BUFFER_STALLED_ERROR:{const t=this.endedItem||this.waitingItem||this.playingItem;if(this.isInterstitial(t)&&t.event.appendInPlace)return void this.handleInPlaceStall(t.event);const e=this.primaryMedia;this.log(`Primary player stall @${this.timelinePos} currentTime: ${null==e?void 0:e.currentTime} bufferedPos: ${this.bufferedPos}`),this.onTimeupdate(),this.checkBuffer(!0);break}}}}});function jh(t,e,i){if((e.liveSyncDurationCount||e.liveMaxLatencyDurationCount)&&(e.liveSyncDuration||e.liveMaxLatencyDuration))throw new Error("Illegal hls.js config: don't mix up liveSyncDurationCount/liveMaxLatencyDurationCount and liveSyncDuration/liveMaxLatencyDuration");if(void 0!==e.liveMaxLatencyDurationCount&&(void 0===e.liveSyncDurationCount||e.liveMaxLatencyDurationCount<=e.liveSyncDurationCount))throw new Error('Illegal hls.js config: "liveMaxLatencyDurationCount" must be greater than "liveSyncDurationCount"');if(void 0!==e.liveMaxLatencyDuration&&(void 0===e.liveSyncDuration||e.liveMaxLatencyDuration<=e.liveSyncDuration))throw new Error('Illegal hls.js config: "liveMaxLatencyDuration" must be greater than "liveSyncDuration"');if(void 0!==e.liveMaxUnchangedPlaylistRefresh){const t=e.liveMaxUnchangedPlaylistRefresh,s=((t,e,i)=>Math.max(e,Math.min(t,i)))(t,2,1/0);s!==t&&i.warn(`hls.js config: "liveMaxUnchangedPlaylistRefresh" clamped from ${t} to ${s}.`),e.liveMaxUnchangedPlaylistRefresh=s}const s=Hh(t),r=["TimeOut","MaxRetry","RetryDelay","MaxRetryTimeout"];return["manifest","level","frag"].forEach(t=>{const n=`${"level"===t?"playlist":t}LoadPolicy`,a=void 0===e[n],o=[];r.forEach(i=>{const r=`${t}Loading${i}`,l=e[r];if(void 0!==l&&a){o.push(r);const t=s[n].default;switch(e[n]={default:t},i){case"TimeOut":t.maxLoadTimeMs=l,t.maxTimeToFirstByteMs=l;break;case"MaxRetry":t.errorRetry.maxNumRetry=l,t.timeoutRetry.maxNumRetry=l;break;case"RetryDelay":t.errorRetry.retryDelayMs=l,t.timeoutRetry.retryDelayMs=l;break;case"MaxRetryTimeout":t.errorRetry.maxRetryDelayMs=l,t.timeoutRetry.maxRetryDelayMs=l}}}),o.length&&i.warn(`hls.js config: "${o.join('", "')}" setting(s) are deprecated, use "${n}": ${Ue(e[n])}`)}),k(k({},s),e)}function Hh(t){return t&&"object"==typeof t?Array.isArray(t)?t.map(Hh):Object.keys(t).reduce((e,i)=>(e[i]=Hh(t[i]),e),{}):t}function qh(t,e){const i=t.loader;if(i!==$h&&i!==Kh)e.log("[config]: Custom loader detected, cannot enable progressive streaming"),t.progressive=!1;else{(function(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch(t){}return!1})()&&(t.loader=$h,t.progressive=!0,t.enableSoftwareAES=!0,e.log("[config]: Progressive streaming enabled, using FetchLoader"))}}class Yh extends sa{constructor(t,e){super(t,"level-controller"),this._levels=[],this._firstLevel=-1,this._maxAutoLevel=-1,this._startLevel=void 0,this.currentLevel=null,this.currentLevelIndex=-1,this.manualLevelIndex=-1,this.steering=void 0,this.lastABRSwitchTime=-1,this._iframeVariants=[],this.onParsedComplete=void 0,this.steering=e,this._registerListeners()}_registerListeners(){const{hls:t}=this;t.on(a.MANIFEST_LOADING,this.onManifestLoading,this),t.on(a.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(a.LEVEL_LOADED,this.onLevelLoaded,this),t.on(a.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(a.FRAG_BUFFERED,this.onFragBuffered,this),t.on(a.ERROR,this.onError,this)}_unregisterListeners(){const{hls:t}=this;t.off(a.MANIFEST_LOADING,this.onManifestLoading,this),t.off(a.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(a.LEVEL_LOADED,this.onLevelLoaded,this),t.off(a.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(a.FRAG_BUFFERED,this.onFragBuffered,this),t.off(a.ERROR,this.onError,this)}destroy(){this._unregisterListeners(),this.steering=null,this.resetLevels(),super.destroy()}stopLoad(){this._levels.forEach(t=>{t.loadError=0,t.fragmentError=0}),super.stopLoad()}resetLevels(){this._startLevel=void 0,this.manualLevelIndex=-1,this.currentLevelIndex=-1,this.currentLevel=null,this._levels=[],this._maxAutoLevel=-1,this._iframeVariants=[]}onManifestLoading(t,e){this.resetLevels()}onManifestLoaded(t,e){const i=this.hls.config.preferManagedMediaSource,s=[],r={},n={};let a=!1,o=!1,l=!1,h=!1;e.levels.forEach(t=>{const e=t.attrs,d=Xh(t,i),{audioCodec:c,videoCodec:u,imageCodec:f,width:g,height:m}=t;if(!d)return void this.log(`Some or all CODECS not supported "${e.CODECS}"`);a||(a=!(!g||!m)),o||(o=!!u),l||(l=!!c),h||(h=!!f);const{CODECS:p,"FRAME-RATE":v,"HDCP-LEVEL":y,"PATHWAY-ID":E,RESOLUTION:T,"VIDEO-RANGE":S}=e,b=`${`${E||"."}-`}${t.bitrate}-${T}-${v}-${p}-${S}-${y}`;if(r[b])if(r[b].uri===t.url||t.attrs["PATHWAY-ID"])t.iframes||(r[b].addGroupId("audio",e.AUDIO),r[b].addGroupId("text",e.SUBTITLES));else{const e=n[b]+=1;t.attrs["PATHWAY-ID"]=new Array(e+1).join(".");const i=this.createLevel(t);r[b]=i,s.push(i)}else{const e=this.createLevel(t);r[b]=e,n[b]=1,s.push(e)}}),this.filterAndSortMediaOptions(s,e,a,o,l,h)}createLevel(t){const e=new Ne(t),i=t.supplemental;if(null!=i&&i.videoCodec&&!zh(i.videoCodec,this.hls.config.preferManagedMediaSource)){const t=new Error(`SUPPLEMENTAL-CODECS not supported "${i.videoCodec}"`);this.log(t.message),e.supportedResult=Le(t,[])}return e}filterAndSortMediaOptions(t,e,i,s,o,l){var h;let d=[],c=[],u=t;const f=(null==(h=e.stats)?void 0:h.parsing)||{},g=this.hls.config.preferManagedMediaSource;if((i||s)&&o&&(u=u.filter(({videoCodec:t,videoRange:e,width:i,height:s})=>{return(!!t||!(!i||!s))&&(!!(r=e)&&Pe.indexOf(r)>-1);var r})),s&&l&&(u=u.filter(t=>!t.imageCodec)),0===u.length)return Promise.resolve().then(()=>{if(this.hls){let t="no level with compatible codecs found in manifest",i=t;e.levels.length&&(i=`one or more CODECS in variant not supported: ${Ue(e.levels.map(t=>t.attrs.CODECS).filter((t,e,i)=>i.indexOf(t)===e))}`,this.warn(i),t+=` (${i})`);const s=new Error(t);this.hls.trigger(a.ERROR,{type:r.MEDIA_ERROR,details:n.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:e.url,error:s,reason:i})}}),void(f.end=performance.now());e.audioTracks&&(d=e.audioTracks.filter(t=>!t.audioCodec||Wh(t.audioCodec,g)),Qh(d)),e.subtitles&&(c=e.subtitles,Qh(c));const m=u.slice(0);u.sort((t,e)=>{if(t.attrs["HDCP-LEVEL"]!==e.attrs["HDCP-LEVEL"])return(t.attrs["HDCP-LEVEL"]||"")>(e.attrs["HDCP-LEVEL"]||"")?1:-1;if(i&&t.height!==e.height)return t.height-e.height;if(t.frameRate!==e.frameRate)return t.frameRate-e.frameRate;if(t.videoRange!==e.videoRange)return Pe.indexOf(t.videoRange)-Pe.indexOf(e.videoRange);if(t.videoCodec!==e.videoCodec){const i=ue(t.videoCodec),s=ue(e.videoCodec);if(i!==s)return s-i}if(t.uri===e.uri&&t.codecSet!==e.codecSet){const i=fe(t.codecSet),s=fe(e.codecSet);if(i!==s)return s-i}return t.averageBitrate!==e.averageBitrate?t.averageBitrate-e.averageBitrate:0});let p=m[0];if(this.steering&&(u=this.steering.filterParsedLevels(u),u.length!==m.length))for(let t=0;t<m.length;t++)if(m[t].pathwayId===u[0].pathwayId){p=m[t];break}this._levels=u;for(let t=0;t<u.length;t++)if(u[t]===p){var v;this._firstLevel=t;const e=p.bitrate,i=this.hls.bandwidthEstimate;if(this.log(`manifest loaded, ${u.length} level(s) found, first bitrate: ${e}`),void 0===(null==(v=this.hls.userConfig)?void 0:v.abrEwmaDefaultEstimate)){const t=Math.min(e,this.hls.config.abrEwmaDefaultEstimateMax);t>i&&i===this.hls.abrEwmaDefaultEstimate&&(this.hls.bandwidthEstimate=t)}break}const y=e.iframeVariants.filter(t=>Xh(t,g));this._iframeVariants=y;const E=o&&!s,T=this.hls.config,S=!(!T.audioStreamController||!T.audioTrackController),b={levels:u,audioTracks:d,subtitleTracks:c,iframeVariants:y,sessionData:e.sessionData,sessionKeys:e.sessionKeys,firstLevel:this._firstLevel,stats:e.stats,audio:o,video:s,altAudio:S&&!E&&d.some(t=>!!t.url)};f.end=performance.now(),this.hls.trigger(a.MANIFEST_PARSED,b)}get iframeVariants(){return 0===this._iframeVariants.length?null:this._iframeVariants}get levels(){return 0===this._levels.length?null:this._levels}get loadLevelObj(){return this.currentLevel}get level(){return this.currentLevelIndex}set level(t){const e=this._levels;if(0===e.length)return;if(t<0||t>=e.length){const i=new Error("invalid level idx"),s=t<0;if(this.hls.trigger(a.ERROR,{type:r.OTHER_ERROR,details:n.LEVEL_SWITCH_ERROR,level:t,fatal:s,error:i,reason:i.message}),s)return;t=Math.min(t,e.length-1)}const i=this.currentLevelIndex,s=this.currentLevel,o=s?s.attrs["PATHWAY-ID"]:void 0,l=e[t],h=l.attrs["PATHWAY-ID"];if(this.currentLevelIndex=t,this.currentLevel=l,i===t&&s&&o===h)return;this.log(`Switching to level ${t} (${l.height?l.height+"p ":""}${l.videoRange?l.videoRange+" ":""}${l.codecSet?l.codecSet+" ":""}@${l.bitrate})${h?" with Pathway "+h:""} from level ${i}${o?" with Pathway "+o:""}`);const d={level:t,attrs:l.attrs,details:l.details,bitrate:l.bitrate,averageBitrate:l.averageBitrate,maxBitrate:l.maxBitrate,realBitrate:l.realBitrate,width:l.width,height:l.height,codecSet:l.codecSet,audioCodec:l.audioCodec,videoCodec:l.videoCodec,audioGroups:l.audioGroups,subtitleGroups:l.subtitleGroups,loaded:l.loaded,loadError:l.loadError,fragmentError:l.fragmentError,name:l.name,id:l.id,uri:l.uri,url:l.url,urlId:0,audioGroupIds:l.audioGroupIds,textGroupIds:l.textGroupIds};this.hls.trigger(a.LEVEL_SWITCHING,d);const c=l.details;if(!c||c.live){const t=this.switchParams(l.uri,null==s?void 0:s.details,c);this.loadPlaylist(t)}}get manualLevel(){return this.manualLevelIndex}set manualLevel(t){this.manualLevelIndex=t,void 0===this._startLevel&&(this._startLevel=t),-1!==t&&(this.level=t)}get firstLevel(){return this._firstLevel}set firstLevel(t){this._firstLevel=t}get startLevel(){if(void 0===this._startLevel){const t=this.hls.config.startLevel;return void 0!==t?t:this.hls.firstAutoLevel}return this._startLevel}set startLevel(t){this._startLevel=t}get pathways(){return this.steering?this.steering.pathways():[]}get pathwayPriority(){return this.steering?this.steering.pathwayPriority:null}set pathwayPriority(t){if(this.steering){const e=this.steering.pathways(),i=t.filter(t=>-1!==e.indexOf(t));if(t.length<1)return void this.warn(`pathwayPriority ${t} should contain at least one pathway from list: ${e}`);this.steering.pathwayPriority=i}}onError(t,e){!e.fatal&&e.context&&e.context.type===u.LEVEL&&e.context.level===this.level&&this.checkRetry(e)}onFragBuffered(t,{frag:e}){if(e.type===f.MAIN){const t=e.elementaryStreams;if(!Object.keys(t).some(e=>!!t[e]))return;const i=this._levels[e.level];null!=i&&i.loadError&&(this.log(`Resetting level error count of ${i.loadError} on frag buffered`),i.loadError=0)}}onLevelLoaded(t,e){var i;const{level:s,details:r}=e,n=e.levelInfo;var a;if(!n)return this.warn(`Invalid level index ${s}`),void(null!=(a=e.deliveryDirectives)&&a.skip&&(r.deltaUpdateFailed=!0));if(n===this.currentLevel||e.withoutMultiVariant){0===n.fragmentError&&(n.loadError=0);let t=n.details;t===e.details&&t.advanced&&(t=void 0),this.playlistLoaded(s,e,t)}else null!=(i=e.deliveryDirectives)&&i.skip&&(r.deltaUpdateFailed=!0)}loadPlaylist(t){super.loadPlaylist(),this.shouldLoadPlaylist(this.currentLevel)&&this.scheduleLoading(this.currentLevel,t)}loadingPlaylist(t,e){super.loadingPlaylist(t,e);const i=this.getUrlWithDirectives(t.uri,e),s=this.currentLevelIndex,r=t.attrs["PATHWAY-ID"],n=t.details,o=null==n?void 0:n.age;this.log(`Loading level index ${s}${void 0!==(null==e?void 0:e.msn)?" at sn "+e.msn+" part "+e.part:""}${r?" Pathway "+r:""}${o&&n.live?" age "+o.toFixed(1)+(n.type&&" "+n.type||""):""} ${i}`),this.hls.trigger(a.LEVEL_LOADING,{url:i,level:s,levelInfo:t,pathwayId:t.attrs["PATHWAY-ID"],id:0,deliveryDirectives:e||null})}get nextLoadLevel(){return-1!==this.manualLevelIndex?this.manualLevelIndex:this.hls.nextAutoLevel}set nextLoadLevel(t){const e=this.currentLevelIndex;if(-1===this.manualLevelIndex&&t!==e&&-1!==t){const i=this.hls.config.abrSwitchInterval;if(i>0){const s=performance.now(),r=s-this.lastABRSwitchTime,n=1e3*i;if(this.lastABRSwitchTime>-1&&r<n)return void this.warn(`Preventing ABR level switch: ${e} -> ${t} (${Math.round(r)}ms < ${n}ms / ${i}s)`);this.lastABRSwitchTime=s,this.log(`Allowing ABR level switch: ${e} -> ${t} (${Math.round(r)}ms >= ${n}ms / ${i}s)`)}}this.level=t,-1===this.manualLevelIndex&&(this.hls.nextAutoLevel=t)}removeLevel(t){var e;if(1===this._levels.length)return;const i=this._levels.filter((e,i)=>i!==t||(this.steering&&this.steering.removeLevel(e),e===this.currentLevel&&(this.currentLevel=null,this.currentLevelIndex=-1,e.details&&e.details.fragments.forEach(t=>t.level=-1)),!1));hr(i),this._levels=i,this.currentLevelIndex>-1&&null!=(e=this.currentLevel)&&e.details&&(this.currentLevelIndex=this.currentLevel.details.fragments[0].level),this.manualLevelIndex>-1&&(this.manualLevelIndex=this.currentLevelIndex);const s=i.length-1;this._firstLevel=Math.min(this._firstLevel,s),this._startLevel&&(this._startLevel=Math.min(this._startLevel,s)),this.hls.trigger(a.LEVELS_UPDATED,{levels:i})}onLevelsUpdated(t,{levels:e}){this._levels=e}checkMaxAutoUpdated(){const{autoLevelCapping:t,maxAutoLevel:e,maxHdcpLevel:i}=this.hls;this._maxAutoLevel!==e&&(this._maxAutoLevel=e,this.hls.trigger(a.MAX_AUTO_LEVEL_UPDATED,{autoLevelCapping:t,levels:this.levels,maxAutoLevel:e,minAutoLevel:this.hls.minAutoLevel,maxHdcpLevel:i}))}}function Wh(t,e){return he(t,"audio",e)}function zh(t,e){return he(t,"video",e)}function Xh(t,e){let{audioCodec:i,videoCodec:s}=t;i&&(t.audioCodec=i=pe(i,e)||void 0),s&&(s=t.videoCodec=function(t){const e=t.split(",");for(let t=0;t<e.length;t++){const i=e[t].split(".");i.length>2&&"avc1"===i[0]&&(e[t]=`avc1.${parseInt(i[1]).toString(16)}${("000"+parseInt(i[2]).toString(16)).slice(-4)}`)}return e.join(",")}(s));const{unknownCodecs:r}=t;return!((null==r?void 0:r.length)||0||i&&!Wh(i,e)||s&&!zh(s,e))}function Qh(t){const e={};t.forEach(t=>{const i=t.groupId||"";t.id=e[i]=e[i]||0,e[i]++})}class Zh extends U{constructor(t,e){super("key-loader",e),this.config=void 0,this.keyLoaderInfo={},this.emeController=null,this.config=t}abort(t){for(const i in this.keyLoaderInfo){const s=this.keyLoaderInfo[i].loader;if(s){var e;if(t&&t!==(null==(e=s.context)?void 0:e.frag.type))return;s.abort()}}}destroy(){for(const t in this.keyLoaderInfo){const e=this.keyLoaderInfo[t].loader;e&&e.destroy()}this.emeController=null,this.keyLoaderInfo={}}loadClear(t,e,i){return this.emeController?this.emeController.loadClear(t,e,i):null}load(t,e){return!t.decryptdata&&t.encrypted&&this.emeController&&this.config.emeEnabled?this.emeController.selectKeySystemFormat(t).then(i=>this.loadInternal(t,e,i)):this.loadInternal(t,e)}loadInternal(t,e,i){i&&t.setKeyFormat(i);const s=t.decryptdata;if(!s){const e=new Error(i?`Expected frag.decryptdata to be defined after setting format ${i}`:`Missing decryption data on fragment in onKeyLoading (emeEnabled with controller: ${this.emeController&&this.config.emeEnabled})`);return Promise.reject(Jh(t,n.KEY_LOAD_ERROR,e))}const r=t;switch(s.method){case"SAMPLE-AES":case"SAMPLE-AES-CENC":case"SAMPLE-AES-CTR":return"identity"===s.keyFormat?this.loadKeyHTTP(r):e?e.then(()=>this.loadKeyEME(r)):this.loadKeyEME(r);case"AES-128":case"AES-256":case"AES-256-CTR":return this.loadKeyHTTP(r);default:return Promise.reject(Jh(t,n.KEY_LOAD_ERROR,new Error(`Key supplied with unsupported METHOD: "${s.method}"`)))}}loadKeyEME(t){if(this.emeController&&this.config.emeEnabled){var e;if(!t.decryptdata.keyId&&null!=(e=t.initSegment)&&e.data){const e=function(t){const e=[];return Ut(t,t=>e.push(t.subarray(8,24))),e}(t.initSegment.data);if(e.length){let i=e[0];const s=t.decryptdata.uri;if(i.some(t=>0!==t))this.log(`Using keyId found in init segment ${mt(i)} keyUri: ${s}`),xs.setKeyIdForUri(s,i);else{const t=xs.addKeyIdForUri(s);this.log(`Patching empty keyId with ${mt(t)} keyUri: ${s}`),i=t}t.decryptdata.keyId=i}}return this.emeController.loadKey(t).then(()=>({frag:t,keyInfo:{decryptdata:t.decryptdata}}))}return Promise.reject(Jh(t,n.KEY_LOAD_ERROR,new Error(`emeEnabled with controller: ${this.emeController&&this.config.emeEnabled})`)))}loadKeyHTTP(t){const e=t.decryptdata,i=e.uri;if(!i)return Promise.reject(Jh(t,n.KEY_LOAD_ERROR,new Error(`Invalid key URI: "${i}"`)));const s=this.keyLoaderInfo[i];if(s){if(s.decryptdata.key)return e.key=s.decryptdata.key,s.keyLoadPromise=null,Promise.resolve({frag:t,keyInfo:s});if(s.keyLoadPromise)return s.keyLoadPromise.then(i=>(e.key=s.decryptdata.key,k(k({},i),{},{frag:t})))}this.log(`Loading${e.keyId?" keyId: "+mt(e.keyId):""} URI: ${e.uri} from ${t.type} ${t.level}`);const r=this.config,a=new(0,r.loader)(r);t.keyLoader=a;const o=this.keyLoaderInfo[i]={decryptdata:e,keyLoadPromise:null,loader:a};return o.keyLoadPromise=new Promise((e,s)=>{const l={type:u.KEY,keyInfo:o,frag:t,responseType:"arraybuffer",url:i},h=r.keyLoadPolicy.default,d={loadPolicy:h,timeout:h.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},c={onSuccess:(t,i,r,a)=>{const{frag:o,keyInfo:l,url:h}=r;if(!o.decryptdata||l!==this.keyLoaderInfo[h])return this.resetLoader(r),s(Jh(o,n.KEY_LOAD_ERROR,new Error("after key load, decryptdata unset or changed"),a));l.decryptdata.key=o.decryptdata.key=new Uint8Array(t.data),o.keyLoader=l.loader=l.keyLoadPromise=null,e({frag:o,keyInfo:l})},onError:(e,r,a,o)=>{this.resetLoader(r),s(Jh(t,n.KEY_LOAD_ERROR,new Error(`HTTP Error ${e.code} loading key ${e.text}`),a,k({url:i,data:void 0},e)))},onTimeout:(e,i,r)=>{this.resetLoader(i),s(Jh(t,n.KEY_LOAD_TIMEOUT,new Error("key loading timed out"),r))},onAbort:(e,i,r)=>{this.resetLoader(i),s(Jh(t,n.INTERNAL_ABORTED,new Error("key loading aborted"),r))}};a.load(l,d,c)})}resetLoader(t){const{frag:e,keyInfo:i,url:s}=t,r=i.loader;e.keyLoader===r&&(e.keyLoader=i.loader=i.keyLoadPromise=null),delete this.keyLoaderInfo[s],r&&r.destroy()}}function Jh(t,e=n.KEY_LOAD_ERROR,i,s,a){return new Zi({type:r.NETWORK_ERROR,details:e,fatal:!1,frag:t,response:a,error:i,networkDetails:s||null})}function td(t){const{type:e}=t;switch(e){case u.AUDIO_TRACK:return f.AUDIO;case u.SUBTITLE_TRACK:return f.SUBTITLE;default:return f.MAIN}}function ed(t,e){let i=t.url;return void 0!==i&&0!==i.indexOf("data:")||(i=e.url),i}class id{constructor(t){this.hls=void 0,this.loaders=Object.create(null),this.variableList=null,this.onManifestLoaded=this.checkAutostartLoad,this.hls=t,this.registerListeners()}startLoad(t){}stopLoad(){this.destroyInternalLoaders()}registerListeners(){const{hls:t}=this;t.on(a.MANIFEST_LOADING,this.onManifestLoading,this),t.on(a.LEVEL_LOADING,this.onLevelLoading,this),t.on(a.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),t.on(a.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),t.on(a.LEVELS_UPDATED,this.onLevelsUpdated,this)}unregisterListeners(){const{hls:t}=this;t.off(a.MANIFEST_LOADING,this.onManifestLoading,this),t.off(a.LEVEL_LOADING,this.onLevelLoading,this),t.off(a.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),t.off(a.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),t.off(a.LEVELS_UPDATED,this.onLevelsUpdated,this)}createInternalLoader(t){const e=this.hls.config,i=e.pLoader,s=e.loader,r=new(i||s)(e);return this.loaders[t.type]=r,r}getInternalLoader(t){return this.loaders[t.type]}resetInternalLoader(t){this.loaders[t]&&delete this.loaders[t]}destroyInternalLoaders(){for(const t in this.loaders){const e=this.loaders[t];e&&e.destroy(),this.resetInternalLoader(t)}}destroy(){this.variableList=null,this.unregisterListeners(),this.destroyInternalLoaders()}onManifestLoading(t,e){const{url:i}=e;this.variableList=null,this.load({id:null,level:0,responseType:"text",type:u.MANIFEST,url:i,deliveryDirectives:null,levelOrTrack:null})}onLevelLoading(t,e){const{id:i,level:s,pathwayId:r,url:n,deliveryDirectives:a,levelInfo:o}=e;this.load({id:i,level:s,pathwayId:r,responseType:"text",type:u.LEVEL,url:n,deliveryDirectives:a,levelOrTrack:o})}onAudioTrackLoading(t,e){const{id:i,groupId:s,url:r,deliveryDirectives:n,track:a}=e;this.load({id:i,groupId:s,level:null,responseType:"text",type:u.AUDIO_TRACK,url:r,deliveryDirectives:n,levelOrTrack:a})}onSubtitleTrackLoading(t,e){const{id:i,groupId:s,url:r,deliveryDirectives:n,track:a}=e;this.load({id:i,groupId:s,level:null,responseType:"text",type:u.SUBTITLE_TRACK,url:r,deliveryDirectives:n,levelOrTrack:a})}onLevelsUpdated(t,e){const i=this.loaders[u.LEVEL];if(i){const t=i.context;t&&!e.levels.some(e=>e===t.levelOrTrack)&&(i.abort(),delete this.loaders[u.LEVEL])}}load(t){var i;const s=this.hls.config;let r,n=this.getInternalLoader(t);if(n){const e=this.hls.logger,i=n.context;if((null==i?void 0:i.levelOrTrack)===t.levelOrTrack&&(i.url===t.url||i.deliveryDirectives&&!t.deliveryDirectives))return void(i.url===t.url?e.log(`[playlist-loader]: ignore ${t.url} ongoing request`):e.log(`[playlist-loader]: ignore ${t.url} in favor of ${i.url}`));e.log(`[playlist-loader]: aborting previous loader for type: ${t.type}`),n.abort()}if(r=t.type===u.MANIFEST?s.manifestLoadPolicy.default:I({},s.playlistLoadPolicy.default,{timeoutRetry:null,errorRetry:null}),n=this.createInternalLoader(t),e(null==(i=t.deliveryDirectives)?void 0:i.part)){let e;if(t.type===u.LEVEL&&null!==t.level?e=this.hls.levels[t.level].details:t.type===u.AUDIO_TRACK&&null!==t.id?e=this.hls.audioTracks[t.id].details:t.type===u.SUBTITLE_TRACK&&null!==t.id&&(e=this.hls.subtitleTracks[t.id].details),e){const t=e.partTarget,i=e.targetduration;if(t&&i){const e=1e3*Math.max(3*t,.8*i);r=I({},r,{maxTimeToFirstByteMs:Math.min(e,r.maxTimeToFirstByteMs),maxLoadTimeMs:Math.min(e,r.maxTimeToFirstByteMs)})}}}const a=r.errorRetry||r.timeoutRetry||{},o={loadPolicy:r,timeout:r.maxLoadTimeMs,maxRetry:a.maxNumRetry||0,retryDelay:a.retryDelayMs||0,maxRetryDelay:a.maxRetryDelayMs||0},l={onSuccess:(t,e,i,s)=>{const r=this.getInternalLoader(i);this.resetInternalLoader(i.type);const n=t.data;e.parsing.start=performance.now(),Us.isMediaPlaylist(n)||i.type!==u.MANIFEST?this.handleTrackOrLevelPlaylist(t,e,i,s||null,r):this.handleMasterPlaylist(t,e,i,s)},onError:(t,e,i,s)=>{this.handleNetworkError(e,i,!1,t,s)},onTimeout:(t,e,i)=>{this.handleNetworkError(e,i,!0,void 0,t)}};n.load(t,o,l)}checkAutostartLoad(){if(!this.hls)return;const{config:{autoStartLoad:t,startPosition:e},forceStartLoad:i}=this.hls;(t||i)&&(this.hls.logger.log(`${t?"auto":"force"} startLoad with configured startPosition ${e}`),this.hls.startLoad(e))}handleMasterPlaylist(t,e,i,s){const r=this.hls,n=t.data,o=ed(t,i),l=Us.parseMasterPlaylist(n,o);if(l.playlistParsingError)return e.parsing.end=performance.now(),void this.handleManifestParsingError(t,i,l.playlistParsingError,s,e);const{contentSteering:h,levels:d,iframeVariants:c,sessionData:u,sessionKeys:f,startTimeOffset:g,variableList:m}=l;this.variableList=m,d.forEach(t=>{const{unknownCodecs:e}=t;if(e){const{preferManagedMediaSource:i}=this.hls.config;let{audioCodec:s,videoCodec:r}=t;for(let n=e.length;n--;){const a=e[n];he(a,"audio",i)?(t.audioCodec=s=s?`${s},${a}`:a,oe.audio[s.substring(0,4)]=2,e.splice(n,1)):he(a,"video",i)&&(t.videoCodec=r=r?`${r},${a}`:a,oe.video[r.substring(0,4)]=2,e.splice(n,1))}}});const{AUDIO:p=[],SUBTITLES:v,"CLOSED-CAPTIONS":y}=Us.parseMasterPlaylistMedia(n,o,l);if(p.length){p.some(t=>!t.url)||!d[0].audioCodec||d[0].attrs.AUDIO||(this.hls.logger.log("[playlist-loader]: audio codec signaled in quality level, but no embedded audio track signaled, create one"),p.unshift({type:"main",name:"main",groupId:"main",default:!1,autoselect:!1,forced:!1,id:-1,attrs:new ls({}),bitrate:0,url:""}))}r.trigger(a.MANIFEST_LOADED,{levels:d,audioTracks:p,subtitles:v,iframeVariants:c,captions:y,contentSteering:h,url:o,stats:e,networkDetails:s,sessionData:u,sessionKeys:f,startTimeOffset:g,variableList:m})}handleTrackOrLevelPlaylist(t,i,s,r,n){const o=this.hls,{id:l,level:h,type:d}=s,c=ed(t,s),f=e(h)?h:e(l)?l:0,g=td(s),m=Us.parseLevelPlaylist(t.data,c,f,g,0,this.variableList);if(d===u.MANIFEST){const t={attrs:new ls({}),bitrate:0,details:m,name:"",url:c};m.requestScheduled=i.loading.start+nr(m,0),o.trigger(a.MANIFEST_LOADED,{levels:[t],audioTracks:[],iframeVariants:[],url:c,stats:i,networkDetails:r,sessionData:null,sessionKeys:null,contentSteering:null,startTimeOffset:null,variableList:null})}i.parsing.end=performance.now(),s.levelDetails=m,this.handlePlaylistLoaded(m,t,i,s,r,n)}handleManifestParsingError(t,e,i,s,o){this.hls.trigger(a.ERROR,{type:r.NETWORK_ERROR,details:n.MANIFEST_PARSING_ERROR,fatal:e.type===u.MANIFEST,url:t.url,err:i,error:i,reason:i.message,response:t,context:e,networkDetails:s,stats:o})}handleNetworkError(t,e,i=!1,s,o){let l=`A network ${i?"timeout":"error"+(s?" (status "+s.code+")":"")} occurred while loading ${t.type}`;t.type===u.LEVEL?l+=`: ${t.level} id: ${t.id}`:t.type!==u.AUDIO_TRACK&&t.type!==u.SUBTITLE_TRACK||(l+=` id: ${t.id} group-id: "${t.groupId}"`);const h=new Error(l);this.hls.logger.warn(`[playlist-loader]: ${l}`);let d=n.UNKNOWN,c=!1;const f=this.getInternalLoader(t);switch(t.type){case u.MANIFEST:d=i?n.MANIFEST_LOAD_TIMEOUT:n.MANIFEST_LOAD_ERROR,c=!0;break;case u.LEVEL:d=i?n.LEVEL_LOAD_TIMEOUT:n.LEVEL_LOAD_ERROR,c=!1;break;case u.AUDIO_TRACK:d=i?n.AUDIO_TRACK_LOAD_TIMEOUT:n.AUDIO_TRACK_LOAD_ERROR,c=!1;break;case u.SUBTITLE_TRACK:d=i?n.SUBTITLE_TRACK_LOAD_TIMEOUT:n.SUBTITLE_LOAD_ERROR,c=!1}f&&this.resetInternalLoader(t.type);const g={type:r.NETWORK_ERROR,details:d,fatal:c,url:t.url,loader:f,context:t,error:h,networkDetails:e,stats:o};if(s){let i=t.url;e&&"url"in e&&(i=e.url),g.response=k({url:i,data:void 0},s)}this.hls.trigger(a.ERROR,g)}handlePlaylistLoaded(t,e,i,s,o,l){const h=this.hls,{type:d,level:c,levelOrTrack:g,id:m,groupId:p,deliveryDirectives:v}=s,y=ed(e,s),E=td(s);let T="number"==typeof s.level&&E===f.MAIN?c:void 0;g&&"iframes"in g&&g.iframes&&!t.iframesOnly&&(t.playlistParsingError=new Error("EXT-X-I-FRAME-STREAM-INF media playlist MUST contain an EXT-X-I-FRAMES-ONLY tag"),t.iframesOnly=!0);const S=t.playlistParsingError;if(S){if(this.hls.logger.warn(`${S} ${t.url}`),!h.config.ignorePlaylistParsingErrors)return void h.trigger(a.ERROR,{type:r.NETWORK_ERROR,details:n.LEVEL_PARSING_ERROR,fatal:!1,url:y,error:S,reason:S.message,response:e,context:s,level:T,parent:E,networkDetails:o,stats:i});t.playlistParsingError=null}if(!t.fragments.length){const l=t.playlistParsingError=new Error("No Segments found in Playlist");return void h.trigger(a.ERROR,{type:r.NETWORK_ERROR,details:n.LEVEL_EMPTY_ERROR,fatal:!1,url:y,error:l,reason:l.message,response:e,context:s,level:T,parent:E,networkDetails:o,stats:i})}switch(t.live&&l&&(l.getCacheAge&&(t.ageHeader=l.getCacheAge()||0),l.getCacheAge&&!isNaN(t.ageHeader)||(t.ageHeader=0)),d){case u.MANIFEST:case u.LEVEL:if(T)if(g){if(g!==h.levels[T]){const t=h.levels.indexOf(g);t>-1&&(T=t)}}else T=0;h.trigger(a.LEVEL_LOADED,{details:t,levelInfo:g||h.levels[0],level:T||0,id:m||0,stats:i,networkDetails:o,deliveryDirectives:v,withoutMultiVariant:d===u.MANIFEST,context:s});break;case u.AUDIO_TRACK:h.trigger(a.AUDIO_TRACK_LOADED,{details:t,track:g,id:m||0,groupId:p||"",stats:i,networkDetails:o,deliveryDirectives:v,context:s});break;case u.SUBTITLE_TRACK:h.trigger(a.SUBTITLE_TRACK_LOADED,{details:t,track:g,id:m||0,groupId:p||"",stats:i,networkDetails:o,deliveryDirectives:v,context:s})}}}class sd{static get version(){return Fr}static isMSESupported(){return $l()}static isSupported(){return function(){if(!$l())return!1;const t=Y();return"function"==typeof(null==t?void 0:t.isTypeSupported)&&(["avc1.42E01E,mp4a.40.2","av01.0.01M.08","vp09.00.50.08"].some(e=>t.isTypeSupported(ce(e,"video")))||["mp4a.40.2","fLaC"].some(e=>t.isTypeSupported(ce(e,"audio"))))}()}static getMediaSource(){return Y()}static get Events(){return a}static get MetadataSchema(){return qr}static get ErrorTypes(){return r}static get ErrorDetails(){return n}static get DefaultConfig(){return sd.defaultConfig?sd.defaultConfig:Vh}static set DefaultConfig(t){sd.defaultConfig=t}constructor(t={}){this.config=void 0,this.userConfig=void 0,this.logger=void 0,this._url=null,this.streamController=void 0,this.coreComponents=void 0,this.networkControllers=void 0,this._emitter=new Or,this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.abrController=void 0,this.bufferController=void 0,this.capLevelController=void 0,this.latencyController=void 0,this.levelController=void 0,this.audioStreamController=void 0,this.subtititleStreamController=void 0,this.audioTrackController=void 0,this.subtitleTrackController=void 0,this.interstitialsController=void 0,this.iframeController=void 0,this.gapController=void 0,this.emeController=void 0,this.cmcdController=void 0,this._media=null,this._sessionId=void 0,this.triggeringException=void 0,this.started=!1;const e=this.logger=function(t,e,i){const s=V();if("object"==typeof console&&!0===t||"object"==typeof t){const r=["debug","log","info","warn","error"];r.forEach(e=>{s[e]=j(e,t,i)});try{s.log(`Debug logs enabled for "${e}" in hls.js version 1.7.4`)}catch(t){return V()}r.forEach(e=>{H[e]=j(e,t)})}else I(H,s);return s}(t.debug||!1,"Hls instance",t.loggerId||t.assetPlayerId),i=this.config=jh(sd.DefaultConfig,t,e);this.userConfig=t,i.progressive&&qh(i,e);const{streamController:s,abrController:r,bufferController:n,capLevelController:o,errorController:l,fpsController:h,id3TrackController:d,iframeController:c,gapController:u}=i,f=new l(this),g=this.abrController=new r(this),m=new Ni(this),p=i.interstitialsController,v=p?this.interstitialsController=new p(this,sd):null,y=n?this.bufferController=new n(this,m):null,E=o?this.capLevelController=new o(this):null,T=h?new h(this):null,S=i.cmcdController,b=S?this.cmcdController=new S(this):null,A=new id(this),L=i.contentSteeringController,R=L?new L(this):null,k=this.levelController=new Yh(this,R),_=d?new d(this):void 0,D=new Zh(this.config,this.logger),w=this.streamController=new s(this,m,D),P=this.gapController=u?new u(this,m):void 0;E&&E.setStreamController(w);const C=[A,k,w];v&&C.splice(1,0,v),R&&C.splice(1,0,R),this.networkControllers=C;const x=[g];y&&x.push(y),P&&x.push(P),E&&x.push(E),T&&(T.setStreamController(w),x.push(T)),_&&x.push(_),x.push(m),this.audioTrackController=this.createController(i.audioTrackController,C);const M=i.audioStreamController;M&&C.push(this.audioStreamController=new M(this,m,D)),this.subtitleTrackController=this.createController(i.subtitleTrackController,C);const O=i.subtitleStreamController;O&&C.push(this.subtititleStreamController=new O(this,m,D)),this.createController(i.timelineController,x),D.emeController=this.emeController=this.createController(i.emeController,x),b&&x.push(b),this.latencyController=this.createController(i.latencyController,x),this.coreComponents=x,this.iframeController=c?new c(this,sd):void 0,C.push(f);const F=f.onErrorOut;"function"==typeof F&&this.on(a.ERROR,F,f),this.on(a.MANIFEST_LOADED,A.onManifestLoaded,A)}createController(t,e){if(t){const i=new t(this);return e&&e.push(i),i}return null}on(t,e,i=this){this._emitter.on(t,e,i)}once(t,e,i=this){this._emitter.once(t,e,i)}removeAllListeners(t){this._emitter.removeAllListeners(t)}off(t,e,i=this,s){this._emitter.off(t,e,i,s)}listeners(t){return this._emitter.listeners(t)}emit(t,e,i){return this._emitter.emit(t,e,i)}trigger(t,e){if(this.config.debug)return this.emit(t,t,e);try{return this.emit(t,t,e)}catch(e){if(this.logger.error("An internal error happened while handling event "+t+'. Error message: "'+e.message+'". Here is a stacktrace:',e),!this.triggeringException){this.triggeringException=!0;const i=t===a.ERROR;this.trigger(a.ERROR,{type:r.OTHER_ERROR,details:n.INTERNAL_EXCEPTION,fatal:i,event:t,error:e}),this.triggeringException=!1}}return!1}listenerCount(t){return this._emitter.listenerCount(t)}destroy(){this.logger.log("destroy"),this.trigger(a.DESTROYING,void 0),this.detachMedia(),this.removeAllListeners(),this._autoLevelCapping=-1,this._url=null,this.networkControllers.forEach(t=>t.destroy()),this.networkControllers.length=0,this.coreComponents.forEach(t=>t.destroy()),this.coreComponents.length=0,this.iframeController=void 0;const t=this.config;t.xhrSetup=t.fetchSetup=void 0,this.userConfig=null}attachMedia(t){if(!t||"media"in t&&!t.media){const e=new Error(`attachMedia failed: invalid argument (${t})`);return void this.trigger(a.ERROR,{type:r.OTHER_ERROR,details:n.ATTACH_MEDIA_ERROR,fatal:!0,error:e})}this.logger.log("attachMedia"),this._media&&(this.logger.warn("media must be detached before attaching"),this.detachMedia());const e="media"in t,i=e?t.media:t,s=e?t:{media:i};this._media=i,this.trigger(a.MEDIA_ATTACHING,s)}detachMedia(){this.logger.log("detachMedia");const t={};this.trigger(a.MEDIA_DETACHING,t),this._media=null,this.trigger(a.MEDIA_DETACHED,t)}transferMedia(){var t;this._media=null;const e=(null==(t=this.bufferController)?void 0:t.transferMedia())||null,i={transferMedia:e};return this.trigger(a.MEDIA_DETACHING,i),this.trigger(a.MEDIA_DETACHED,i),e}loadSource(t){var e;this.stopLoad();const i=this.media,s=this._url,r=this._url=d.buildAbsoluteURL(self.location.href,t,{alwaysNormalize:!0});this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.logger.log(`loadSource:${r}`),i&&s&&(s!==r||null!=(e=this.bufferController)&&e.hasSourceTypes())&&(this.detachMedia(),this.attachMedia(i)),this.trigger(a.MANIFEST_LOADING,{url:t})}get url(){return this._url}get hasEnoughToStart(){return this.streamController.hasEnoughToStart}get startPosition(){return this.streamController.startPositionValue}startLoad(t=-1,e){this.logger.log(`startLoad(${t+(e?", <skip seek to start>":"")})`),this.started=!0,this.resumeBuffering();for(let i=0;i<this.networkControllers.length&&(this.networkControllers[i].startLoad(t,e),this.started&&this.networkControllers);i++);}stopLoad(){this.logger.log("stopLoad"),this.started=!1;for(let t=0;t<this.networkControllers.length&&(this.networkControllers[t].stopLoad(),!this.started&&this.networkControllers);t++);}get loadingEnabled(){return this.started&&this.streamController.state!==pr}get bufferingEnabled(){return this.streamController.bufferingEnabled}resumeBuffering(){this.bufferingEnabled||(this.logger.log("resume buffering"),this.networkControllers.forEach(t=>{t.resumeBuffering&&t.resumeBuffering()}))}pauseBuffering(){this.bufferingEnabled&&(this.logger.log("pause buffering"),this.networkControllers.forEach(t=>{t.pauseBuffering&&t.pauseBuffering()}))}get inFlightFragments(){const t={[f.MAIN]:this.streamController.inFlightFrag};return this.audioStreamController&&(t[f.AUDIO]=this.audioStreamController.inFlightFrag),this.subtititleStreamController&&(t[f.SUBTITLE]=this.subtititleStreamController.inFlightFrag),t}swapAudioCodec(){this.logger.log("swapAudioCodec"),this.streamController.swapAudioCodec()}recoverMediaError(){this.logger.log("recoverMediaError");const t=this._media,e=this.started,i=null==t?void 0:t.currentTime;this.detachMedia(),t&&(this.attachMedia(t),e&&(i?this.startLoad(i):this.config.autoStartLoad||this.startLoad()))}removeLevel(t){this.levelController.removeLevel(t)}get sessionId(){let t=this._sessionId;return t||(t=this._sessionId=tt()),t}get levels(){const t=this.levelController.levels;return t||[]}get latestLevelDetails(){return this.streamController.getLevelDetails()||null}get loadLevelObj(){return this.levelController.loadLevelObj}get currentLevel(){return this.streamController.currentLevel}set currentLevel(t){this.logger.log(`set currentLevel:${t}`),this.levelController.manualLevel=t,this.streamController.immediateLevelSwitch()}get nextLevel(){return this.streamController.nextLevel}set nextLevel(t){this.logger.log(`set nextLevel:${t}`),this.levelController.manualLevel=t,this.streamController.nextLevelSwitch()}get loadLevel(){return this.levelController.level}set loadLevel(t){this.logger.log(`set loadLevel:${t}`),this.levelController.manualLevel=t}get nextLoadLevel(){return this.levelController.nextLoadLevel}set nextLoadLevel(t){this.levelController.nextLoadLevel=t}get firstLevel(){return Math.max(this.levelController.firstLevel,this.minAutoLevel)}set firstLevel(t){this.logger.log(`set firstLevel:${t}`),this.levelController.firstLevel=t}get startLevel(){const t=this.levelController.startLevel;return-1===t&&this.abrController.forcedAutoLevel>-1?this.abrController.forcedAutoLevel:t}set startLevel(t){this.logger.log(`set startLevel:${t}`),-1!==t&&(t=Math.max(t,this.minAutoLevel)),this.levelController.startLevel=t}get capLevelToPlayerSize(){return this.config.capLevelToPlayerSize}set capLevelToPlayerSize(t){const e=this.capLevelController,i=!!t;e&&i!==this.config.capLevelToPlayerSize&&(i?e.startCapping():(e.stopCapping(),this.autoLevelCapping=-1,this.streamController.nextLevelSwitch()),this.config.capLevelToPlayerSize=i)}get autoLevelCapping(){return this._autoLevelCapping}get bandwidthEstimate(){const{bwEstimator:t}=this.abrController;return t?t.getEstimate():NaN}set bandwidthEstimate(t){this.abrController.resetEstimator(t)}get abrEwmaDefaultEstimate(){const{bwEstimator:t}=this.abrController;return t?t.defaultEstimate:NaN}get ttfbEstimate(){const{bwEstimator:t}=this.abrController;return t?t.getEstimateTTFB():NaN}set autoLevelCapping(t){this._autoLevelCapping!==t&&(this.logger.log(`set autoLevelCapping:${t}`),this._autoLevelCapping=t,this.levelController.checkMaxAutoUpdated())}get maxHdcpLevel(){return this._maxHdcpLevel}set maxHdcpLevel(t){(function(t){return we.indexOf(t)>-1})(t)&&this._maxHdcpLevel!==t&&(this._maxHdcpLevel=t,this.levelController.checkMaxAutoUpdated())}get autoLevelEnabled(){return-1===this.levelController.manualLevel}get manualLevel(){return this.levelController.manualLevel}get minAutoLevel(){const{levels:t,config:{minAutoBitrate:e}}=this;if(!t)return 0;const i=t.length;for(let s=0;s<i;s++)if(t[s].maxBitrate>=e)return s;return 0}get maxAutoLevel(){const{levels:t,autoLevelCapping:e,maxHdcpLevel:i}=this;let s;if(s=-1===e&&null!=t&&t.length?t.length-1:e,i)for(let e=s;e--;){const s=t[e].attrs["HDCP-LEVEL"];if(s&&s<=i)return e}return s}get firstAutoLevel(){return this.abrController.firstAutoLevel}get nextAutoLevel(){return this.abrController.nextAutoLevel}set nextAutoLevel(t){this.abrController.nextAutoLevel=t}get playingDate(){return this.streamController.currentProgramDateTime}get mainForwardBufferInfo(){return this.streamController.getMainFwdBufferInfo()}get audioForwardBufferInfo(){var t;return(null==(t=this.audioStreamController)?void 0:t.getFwdBufferInfo())||null}get maxBufferLength(){return this.streamController.maxBufferLength}setAudioOption(t){var e;return(null==(e=this.audioTrackController)?void 0:e.setAudioOption(t))||null}setSubtitleOption(t){var e;return(null==(e=this.subtitleTrackController)?void 0:e.setSubtitleOption(t))||null}get allAudioTracks(){const t=this.audioTrackController;return t?t.allAudioTracks:[]}get audioTracks(){const t=this.audioTrackController;return t?t.audioTracks:[]}get audioTrack(){const t=this.audioTrackController;return t?t.audioTrack:-1}set audioTrack(t){const e=this.audioTrackController;e&&(e.audioTrack=t)}get nextAudioTrack(){var t,e;return null!=(t=null==(e=this.audioStreamController)?void 0:e.nextAudioTrack)?t:-1}set nextAudioTrack(t){const{audioTrackController:e}=this;e&&(e.nextAudioTrack=t)}get allSubtitleTracks(){const t=this.subtitleTrackController;return t?t.allSubtitleTracks:[]}get subtitleTracks(){const t=this.subtitleTrackController;return t?t.subtitleTracks:[]}get subtitleTrack(){const t=this.subtitleTrackController;return t?t.subtitleTrack:-1}get media(){return this._media}set subtitleTrack(t){const e=this.subtitleTrackController;e&&(e.subtitleTrack=t)}get subtitleDisplay(){const t=this.subtitleTrackController;return!!t&&t.subtitleDisplay}set subtitleDisplay(t){const e=this.subtitleTrackController;e&&(e.subtitleDisplay=t)}get lowLatencyMode(){return this.config.lowLatencyMode}set lowLatencyMode(t){this.config.lowLatencyMode=t}get liveSyncPosition(){var t,e;return null!=(t=null==(e=this.latencyController)?void 0:e.liveSyncPosition)?t:null}get latency(){var t;return(null==(t=this.latencyController)?void 0:t.latency)||0}get maxLatency(){var t;return(null==(t=this.latencyController)?void 0:t.maxLatency)||0}get targetLatency(){var t;return(null==(t=this.latencyController)?void 0:t.targetLatency)||null}set targetLatency(t){this.latencyController&&(this.latencyController.targetLatency=t)}get drift(){var t;return(null==(t=this.latencyController)?void 0:t.drift)||null}get forceStartLoad(){return this.streamController.forceStartLoad}get pathways(){return this.levelController.pathways}get pathwayPriority(){return this.levelController.pathwayPriority}set pathwayPriority(t){this.levelController.pathwayPriority=t}get bufferedToEnd(){var t;return!(null==(t=this.bufferController)||!t.bufferedToEnd)}get interstitialsManager(){return this.interstitialsController?this.interstitialsController.interstitialsManager:null}get iframeVariants(){const t=this.levelController.iframeVariants;return t||[]}createIFramePlayer(t){return this._url&&this.iframeController?this.iframeController.createIFramePlayer(t):null}createImageIFramePlayer(t){return this._url&&this.iframeController?this.iframeController.createImageIFramePlayer(t):null}getMediaDecodingInfo(t,e=this.allAudioTracks){return Re(t,Ke(e),navigator.mediaCapabilities)}}function rd(t){const{baseUrl:e,apiKey:i,clientId:s,fetch:r,apiVersion:n}=t,a=r??globalThis.fetch;if(!a)throw new Error("No fetch implementation found. Provide one in SDKConfig.fetch for Node or custom environments.");const o={"Content-Type":"application/json","x-api-key":i},l=t=>function(t,e,i,s){if(/^https?:\/\//i.test(s))return s;const r=function(t){let e=t.length;for(;e>0&&"/"===t[e-1];)e--;return t.slice(0,e)}(t),n=s.replace(/^\/+/,"");return`${r}/b2b/${e}/subscription/${encodeURIComponent(i)}${n.startsWith("/")?n:`/${n}`}`}(e,function(t){const e=t.toLowerCase();return"v1"===e||"v2"===e?e:"v1"}(n),s,t),h=async(t,e,i,s)=>{const r={method:t,headers:{...o,...i?.headers},...i};void 0!==s&&(r.body=JSON.stringify(s));return async function(t){if(!t.ok){const e=await t.text().catch(()=>"");throw new Error(`HTTP ${t.status}: ${e||t.statusText}`)}if(204!==t.status)return t.json()}(await a(l(e),r))};return{get:(t,e)=>h("GET",t,e),post:(t,e,i)=>h("POST",t,i,e),put:(t,e,i)=>h("PUT",t,i,e),patch:(t,e,i)=>h("PATCH",t,i,e),delete:(t,e)=>h("DELETE",t,e)}}sd.defaultConfig=void 0;const nd=t=>void 0!==t?.subdomain?`?subdomain=${encodeURIComponent(t.subdomain)}`:"";const ad="https://api.jaaq.app";class od{constructor(t,e){"v2"===e?(this.videos=function(t){return{async getById(e){const i=`/videos/${encodeURIComponent(e)}`;return(await t.get(i)).video}}}(t),this.collections=function(t){return{list:async()=>(await t.get("/collections")).collections,async getById(e,i){const s=`/collections/${encodeURIComponent(e)}${nd(i)}`;return(await t.get(s)).collection},async getSummaryById(e,i){const s=`/collections/${encodeURIComponent(e)}/summary${nd(i)}`;return(await t.get(s)).collection}}}(t)):(this.videos=function(t){return{async getById(e){const i=`/videos/${encodeURIComponent(e)}`;return(await t.get(i)).video}}}(t),this.collections=function(t){return{list:async()=>(await t.get("/collections")).collections,async getById(e){const i=`/collections/${encodeURIComponent(e)}`;return(await t.get(i)).collection}}}(t))}static fromHttp(t,e){return new od(t,e)}static init(t){return ld(t)}}function ld(t){const{baseUrl:e=ad,apiKey:i,clientId:s,fetch:r,apiVersion:n="v1"}=t,a=rd({baseUrl:e,apiKey:i,clientId:s,fetch:r??globalThis.fetch,apiVersion:n});return od.fromHttp(a,n)}function hd(t,e,i){return Math.max(e,Math.min(i,t))}var dd=".jaaq-video-player {\n position: relative;\n width: 100%;\n max-width: none;\n margin: 0;\n background: #000;\n border-radius: 12px;\n overflow: hidden;\n box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);\n font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, sans-serif;\n aspect-ratio: 9 / 16;\n}\n\n.jaaq-video-player video {\n position: absolute;\n top: 0;\n left: 0;\n width: 100%;\n height: 100%;\n display: block;\n background: #000;\n object-fit: cover;\n}\n\n.jaaq-video-player.fullscreen {\n max-width: 100%;\n border-radius: 0;\n aspect-ratio: auto;\n}\n\n.jaaq-controls {\n position: absolute;\n bottom: 0;\n left: 0;\n right: 0;\n background: linear-gradient(to top, rgba(0, 0, 0, 0.8), transparent);\n padding: 40px 16px 16px;\n opacity: 1;\n z-index: 5;\n}\n\n.jaaq-progress-bar {\n width: 100%;\n flex: 1 1 0;\n min-width: 80px;\n height: 4px;\n background: rgba(255, 255, 255, 0.3);\n border-radius: 2px;\n cursor: pointer;\n position: relative;\n}\n\n.jaaq-progress-filled {\n height: 100%;\n background: #007bff;\n border-radius: 2px;\n width: 0%;\n transition: width 0.1s linear;\n}\n\n.jaaq-progress-bar:hover .jaaq-progress-filled {\n background: #0056b3;\n}\n\n.jaaq-controls-bottom {\n display: flex;\n align-items: center;\n justify-content: center;\n gap: 12px;\n color: white;\n}\n\n.jaaq-control-btn {\n background: transparent;\n border: none;\n color: white;\n cursor: pointer;\n padding: 8px;\n display: flex;\n align-items: center;\n justify-content: center;\n transition: transform 0.2s;\n font-size: 20px;\n line-height: 1;\n}\n\n.jaaq-control-btn:hover {\n transform: scale(1.1);\n}\n\n.jaaq-control-btn:disabled {\n opacity: 0.5;\n cursor: not-allowed;\n}\n\n.jaaq-loading {\n position: absolute;\n top: 50%;\n left: 50%;\n transform: translate(-50%, -50%);\n width: 50px;\n height: 50px;\n border: 4px solid rgba(255, 255, 255, 0.3);\n border-top-color: #007bff;\n border-radius: 50%;\n animation: jaaq-spin 1s linear infinite;\n}\n\n@keyframes jaaq-spin {\n to {\n transform: translate(-50%, -50%) rotate(360deg);\n }\n}\n\n.jaaq-error {\n position: absolute;\n top: 50%;\n left: 50%;\n transform: translate(-50%, -50%);\n background: rgba(220, 53, 69, 0.9);\n color: white;\n padding: 16px 24px;\n border-radius: 8px;\n max-width: 80%;\n text-align: center;\n font-size: 14px;\n}\n\n.jaaq-video-info {\n padding: 16px;\n background: #f8f9fa;\n border-radius: 0 0 12px 12px;\n margin-top: -12px;\n}\n\n.jaaq-video-info h3 {\n margin: 0 0 8px 0;\n color: #333;\n font-size: 18px;\n font-weight: 600;\n}\n\n.jaaq-video-info p {\n margin: 4px 0;\n color: #666;\n font-size: 14px;\n}\n\n.jaaq-video-info strong {\n color: #333;\n}\n\n.jaaq-logo {\n position: absolute;\n top: 20px;\n left: 22px;\n color: white;\n font-size: 16px;\n font-weight: 600;\n z-index: 10;\n font-family:\n 'Archivo',\n -apple-system,\n BlinkMacSystemFont,\n 'Segoe UI',\n Roboto,\n sans-serif;\n letter-spacing: 0.5px;\n pointer-events: none;\n}\n\n.jaaq-center-play-btn {\n position: absolute;\n top: 50%;\n left: 50%;\n transform: translate(-50%, -50%);\n width: 84px;\n height: 84px;\n background: transparent;\n border: none;\n cursor: pointer;\n z-index: 15;\n display: flex;\n align-items: center;\n justify-content: center;\n transition: transform 0.2s;\n padding: 0;\n}\n\n.jaaq-center-play-btn:hover {\n transform: translate(-50%, -50%) scale(1.1);\n}\n\n.jaaq-center-play-btn svg {\n width: 100%;\n height: 100%;\n filter: drop-shadow(0 4px 8px rgba(0, 0, 0, 0.3));\n}\n\n.jaaq-video-player.is-playing .jaaq-center-play-btn {\n display: none;\n}\n\n.jaaq-gradient-overlay {\n position: absolute;\n bottom: 0;\n left: 0;\n right: 0;\n background: linear-gradient(180deg, transparent 0%, #0f0f0f 100%);\n padding: 80px 22px 85px;\n pointer-events: none;\n z-index: 5;\n}\n\n.jaaq-caption-display {\n font-family:\n 'Archivo',\n -apple-system,\n BlinkMacSystemFont,\n 'Segoe UI',\n Roboto,\n sans-serif;\n font-weight: 400;\n font-size: 16px;\n line-height: 20px;\n color: white;\n background: rgba(0, 0, 0, 0.8);\n padding: 8px 16px;\n margin-bottom: 12px;\n border-radius: 4px;\n text-align: center;\n max-width: 90%;\n margin-left: auto;\n margin-right: auto;\n}\n\n.jaaq-video-title {\n font-family:\n 'Archivo',\n -apple-system,\n BlinkMacSystemFont,\n 'Segoe UI',\n Roboto,\n sans-serif;\n font-weight: 600;\n font-size: 18.695px;\n line-height: 21.5px;\n color: white;\n margin-bottom: 8px;\n letter-spacing: 0.37px;\n}\n\n.jaaq-video-author {\n font-family:\n 'Archivo',\n -apple-system,\n BlinkMacSystemFont,\n 'Segoe UI',\n Roboto,\n sans-serif;\n font-weight: 500;\n font-size: 14.021px;\n line-height: 16.825px;\n color: white;\n opacity: 0.7;\n margin-bottom: 8px;\n letter-spacing: -0.14px;\n}\n\n.jaaq-video-description {\n font-family:\n 'Archivo',\n -apple-system,\n BlinkMacSystemFont,\n 'Segoe UI',\n Roboto,\n sans-serif;\n font-weight: 400;\n font-size: 11px;\n line-height: 16px;\n color: #aaa8aa;\n letter-spacing: -0.11px;\n}\n\n.jaaq-description-text {\n color: #aaa8aa;\n}\n\n.jaaq-read-more {\n color: white;\n cursor: pointer;\n pointer-events: auto;\n}\n\n.jaaq-read-more:hover {\n text-decoration: underline;\n}\n\n.jaaq-progress-bar {\n background: rgba(255, 255, 255, 0.2);\n}\n\n.jaaq-progress-filled {\n background: white;\n}\n\n.jaaq-captions-btn {\n font-size: 14px;\n font-weight: 600;\n border: 1.5px solid white;\n border-radius: 3px;\n padding: 4px 6px;\n line-height: 1;\n}\n\n.jaaq-captions-btn.active {\n background: white;\n color: #000;\n}\n";class cd{constructor(t,e){if(this.client=null,this.hls=null,this.videoElement=null,this.listeners=new Map,this.captionCues=[],this.elements={},this.container="string"==typeof t?document.querySelector(t):t,!this.container)throw new Error("Container element not found");if(this.config=e,this.state={isPlaying:!1,currentTime:0,duration:0,volume:1,isMuted:!0===e.startMuted,isFullscreen:!1,isLoading:!0,error:null,videoData:null,captionsEnabled:!1},e.client)this.client=e.client;else{if(!e.apiKey||!e.clientId)throw new Error("Please provide either a client instance or apiKey and clientId");this.client=function(t){return ld(t)}({apiKey:e.apiKey,clientId:e.clientId,baseUrl:e.baseUrl})}this.init()}async init(){this.createDOM(),await this.loadVideo(),this.attachEventListeners(),!0===this.config.startMuted&&this.updateVolumeUI()}createDOM(){this.container.innerHTML="";const t=document.createElement("div");t.style.width=this.config.width||"100%",t.style.height=this.config.height||"auto";const e=document.createElement("div");e.className=`jaaq-video-player jaaq-vanilla-player ${this.config.className||""}`,this.elements.player=e;const i=document.createElement("video");this.videoElement=i,!0===this.config.startMuted&&(i.muted=!0,i.setAttribute("muted","")),e.appendChild(i);const s=document.createElement("div");s.className="jaaq-logo",s.innerHTML='\n <svg xmlns="http://www.w3.org/2000/svg" width="50" height="15" viewBox="0 0 50 15" fill="none">\n <path d="M48.0329 10.7826C48.7578 9.6622 49.1402 8.37108 49.1402 7.02322C49.1402 3.19784 46.0283 0.0859375 42.2029 0.0859375C38.3775 0.0859375 35.2656 3.19784 35.2656 7.02322C35.2656 10.8486 38.3753 13.9578 42.1985 13.9605C42.1991 13.9605 42.2002 13.9605 42.2007 13.9605H42.2029C43.8475 13.9605 45.4305 13.3687 46.6698 12.3285L49.9971 14.56V12.0999L48.0334 10.7826H48.0329ZM37.309 7.02322C37.309 4.32479 39.5045 2.12927 42.2035 2.12927C44.9024 2.12927 47.0974 4.32479 47.0974 7.02322C47.0974 7.96252 46.8345 8.862 46.3359 9.64475L43.9817 8.06561C43.4531 7.71378 42.8373 7.52778 42.2002 7.52778C40.4394 7.52778 39.0054 8.95036 38.9846 10.7062C37.9586 9.80839 37.3084 8.49053 37.3084 7.02322H37.309ZM42.2035 11.9172C42.2035 11.9172 42.2002 11.9172 42.1985 11.9172C41.5527 11.9161 41.0274 11.3903 41.0274 10.7439C41.0274 10.0975 41.5538 9.57056 42.2007 9.57056C42.4331 9.57056 42.6578 9.6382 42.8493 9.76584L44.8714 11.1224C44.0853 11.633 43.1586 11.9172 42.2029 11.9172H42.2035Z" fill="white"/>\n <path d="M31.0751 0.686201C30.9856 0.579834 30.8858 0.483286 30.7767 0.39983C30.4374 0.138004 30.0283 0 29.5946 0C29.161 0 28.7524 0.138549 28.4126 0.39983C28.2304 0.540561 28.0755 0.711838 27.9533 0.909844C27.8835 1.02276 27.8257 1.14003 27.7815 1.25785L23.1172 13.7317H25.4551L29.5946 2.66135L33.7342 13.7317H36.0721L31.4078 1.25785C31.3303 1.05003 31.218 0.858024 31.0745 0.686746L31.0751 0.686201Z" fill="white"/>\n <path d="M17.4969 0.686201C17.4075 0.579834 17.3076 0.483286 17.1986 0.39983C16.8593 0.138004 16.4502 0 16.0165 0C15.5829 0 15.1743 0.138549 14.8345 0.39983C14.6523 0.540561 14.4974 0.711838 14.3752 0.909844C14.3054 1.02276 14.2476 1.14003 14.2034 1.25785L9.53906 13.7317H11.8769L16.0165 2.66135L20.1561 13.7317H22.494L17.8302 1.25731C17.7527 1.04948 17.6404 0.857478 17.4969 0.686201Z" fill="white"/>\n <path d="M9.86046 0.511825V0.371094H7.82204V9.02333C7.82204 10.6248 6.51891 11.928 4.91741 11.928C3.47028 11.928 2.23261 10.849 2.03897 9.41771L2.01988 9.27807L1.88024 9.29716L0.13964 9.5328L0 9.5519L0.0190914 9.69154C0.348555 12.1292 2.45462 13.9669 4.91741 13.9669C7.64313 13.9669 9.86046 11.7496 9.86046 9.02388V0.511825Z" fill="white"/>\n </svg>\n ',this.elements.logo=s,e.appendChild(s);const r=document.createElement("button");r.className="jaaq-center-play-btn",r.innerHTML='\n <svg viewBox="0 0 84 84" fill="none">\n <circle cx="42" cy="42" r="42" fill="white" fill-opacity="0.9"/>\n <path d="M33 28L56 42L33 56V28Z" fill="#000"/>\n </svg>\n ',r.setAttribute("aria-label","Play video"),this.elements.centerPlayBtn=r,e.appendChild(r);const n=document.createElement("div");n.className="jaaq-gradient-overlay",this.elements.gradientOverlay=n;const a=document.createElement("div");a.className="jaaq-caption-display",a.style.display="none",this.elements.captionDisplay=a,n.appendChild(a);const o=document.createElement("div");o.className="jaaq-video-title",this.elements.videoTitle=o,n.appendChild(o);const l=document.createElement("div");l.className="jaaq-video-author",this.elements.videoAuthor=l,n.appendChild(l);const h=document.createElement("div");h.className="jaaq-video-description",this.elements.videoDescription=h,n.appendChild(h),e.appendChild(n);const d=document.createElement("div");d.className="jaaq-loading",this.elements.loading=d,e.appendChild(d);const c=document.createElement("div");c.className="jaaq-error",c.style.display="none",this.elements.error=c,e.appendChild(c);const u=document.createElement("div");u.className="jaaq-controls",this.elements.controls=u;const f=document.createElement("div");f.className="jaaq-controls-bottom";const g=document.createElement("button");g.className="jaaq-control-btn",g.textContent="▶",g.setAttribute("aria-label","Play"),this.elements.playPauseBtn=g,f.appendChild(g);const m=document.createElement("button");m.className="jaaq-control-btn",m.innerHTML='\n <svg xmlns="http://www.w3.org/2000/svg" width="22" height="20" viewBox="0 0 22 20" fill="none">\n <path d="M11.2168 19.9287L4.20801 13.7031H0V6.22559H4.20898L11.2168 0V19.9287ZM14.0215 0.150391C16.2405 0.150468 18.1409 1.39074 19.4385 3.17676C20.7365 4.9634 21.499 7.36811 21.499 9.96484C21.499 12.5613 20.7363 14.9654 19.4385 16.752C18.1409 18.538 16.2405 19.7792 14.0215 19.7793V17.1025C15.2032 17.1025 16.3824 16.4464 17.3135 15.165C18.2442 13.8839 18.8593 12.0493 18.8594 9.96484C18.8594 7.88034 18.2442 6.04581 17.3135 4.76465C16.3824 3.4832 15.2033 2.82723 14.0215 2.82715V0.150391ZM14.0215 5.75879C15.5701 5.75896 16.8252 7.64189 16.8252 9.96484C16.8251 12.2877 15.57 14.1707 14.0215 14.1709V5.75879Z" fill="white"/>\n </svg>\n ',m.setAttribute("aria-label","Mute"),this.elements.volumeBtn=m,f.appendChild(m);const p=document.createElement("div");p.className="jaaq-progress-bar",this.elements.progressBar=p;const v=document.createElement("div");v.className="jaaq-progress-filled",this.elements.progressFilled=v,p.appendChild(v),f.appendChild(p);const y=document.createElement("button");y.className="jaaq-control-btn jaaq-captions-btn",y.innerHTML="CC",y.setAttribute("aria-label","Captions"),this.elements.captionsBtn=y,f.appendChild(y);const E=document.createElement("button");E.className="jaaq-control-btn",E.textContent="⛶",E.setAttribute("aria-label","Fullscreen"),this.elements.fullscreenBtn=E,f.appendChild(E),u.appendChild(f),e.appendChild(u),t.appendChild(e),this.container.appendChild(t),this.updateControlsVisibility()}updateControlsVisibility(){const t=!1!==this.config.controls;this.elements.controls&&(this.elements.controls.style.display=t?"":"none")}async loadVideo(){if(this.client&&this.videoElement)try{this.setState({isLoading:!0,error:null});const t=await this.client.videos.getById(this.config.videoId);this.setState({videoData:t}),t.subtitle&&(this.captionCues=this.parseWebVTT(t.subtitle)),this.updateOverlayContent(t),this.emit("loaded",t);const e=t.videoUrl;if(e.includes(".m3u8"))if(sd.isSupported()){this.hls&&this.hls.destroy();const t=new sd({enableWorker:!0,lowLatencyMode:!0});!0===this.config.startMuted&&this.videoElement&&(this.videoElement.muted=!0,this.videoElement.setAttribute("muted","")),t.loadSource(e),t.attachMedia(this.videoElement),!0===this.config.startMuted&&this.videoElement&&(this.videoElement.muted=!0,this.videoElement.setAttribute("muted","")),t.on(sd.Events.MANIFEST_PARSED,()=>{this.setState({isLoading:!1}),this.elements.loading&&(this.elements.loading.style.display="none"),!0===this.config.startMuted&&this.videoElement&&(this.videoElement.muted=!0,this.videoElement.setAttribute("muted",""),this.setState({isMuted:!0}),this.updateVolumeUI()),this.config.autoplay&&(!0===this.config.startMuted&&this.videoElement&&(this.videoElement.muted=!0,this.videoElement.setAttribute("muted",""),this.setState({isMuted:!0}),this.updateVolumeUI()),this.play())}),t.on(sd.Events.ERROR,(t,e)=>{if(e.fatal){const t=`HLS Error: ${e.type} - ${e.details}`;this.showError(t),this.emit("error",new Error(t))}}),this.hls=t}else{if(!this.videoElement.canPlayType("application/vnd.apple.mpegurl"))throw new Error("HLS is not supported in this browser");this.videoElement.src=e,!0===this.config.startMuted&&(this.videoElement.muted=!0,this.videoElement.setAttribute("muted",""),this.setState({isMuted:!0}),this.updateVolumeUI()),this.setState({isLoading:!1}),this.elements.loading&&(this.elements.loading.style.display="none"),this.config.autoplay&&(!0===this.config.startMuted&&this.videoElement&&(this.videoElement.muted=!0,this.videoElement.setAttribute("muted",""),this.setState({isMuted:!0}),this.updateVolumeUI()),this.play())}else this.videoElement.src=e,!0===this.config.startMuted&&(this.videoElement.muted=!0,this.videoElement.setAttribute("muted",""),this.setState({isMuted:!0}),this.updateVolumeUI()),this.setState({isLoading:!1}),this.elements.loading&&(this.elements.loading.style.display="none"),this.config.autoplay&&(!0===this.config.startMuted&&this.videoElement&&(this.videoElement.muted=!0,this.videoElement.setAttribute("muted",""),this.setState({isMuted:!0}),this.updateVolumeUI()),this.play())}catch(t){const e=t instanceof Error?t.message:"Failed to load video";this.showError(e),this.setState({isLoading:!1}),this.emit("error",t instanceof Error?t:new Error(e))}}parseWebVTT(t){const e=[],i=t.split("\n");let s=0;for(;s<i.length;){const t=i[s].trim();if(t.includes("--\x3e")){const[r,n]=t.split("--\x3e").map(t=>t.trim()),a=t=>{const e=t.split(":");if(3===e.length){return 3600*parseFloat(e[0])+60*parseFloat(e[1])+parseFloat(e[2])}if(2===e.length){return 60*parseFloat(e[0])+parseFloat(e[1])}return 0},o=a(r),l=a(n);s++;const h=[];for(;s<i.length&&""!==i[s].trim();)h.push(i[s].trim()),s++;h.length>0&&e.push({start:o,end:l,text:h.join(" ")})}s++}return e}updateOverlayContent(t){const e=!1!==this.config.showLogo,i=!1!==this.config.showTitle,s=!1!==this.config.showAuthor,r=!1!==this.config.showDescription,n=!1!==this.config.showCaptions;if(this.elements.logo&&(this.elements.logo.style.display=e?"block":"none"),this.elements.videoTitle){const e=t.question||"",s=t.creator||"",r=s?`${e} - ${s}`:e;this.elements.videoTitle.textContent=r,this.elements.videoTitle.style.display=i&&e?"block":"none"}if(this.elements.videoAuthor){const e=t.author||t.creator||t.userName||"";this.elements.videoAuthor.textContent=e,this.elements.videoAuthor.style.display=s&&e?"block":"none"}if(this.elements.videoDescription){const e=t.creatorBiography||t.description||"";if(e){const t=150,i=e.length>t?e.substring(0,t)+"...":e;this.elements.videoDescription.innerHTML=`\n <span class="jaaq-description-text">${i}</span>\n ${e.length>t?'<span class="jaaq-read-more"> Read more</span>':""}\n `}this.elements.videoDescription.style.display=r&&e?"block":"none"}this.elements.captionsBtn&&(this.elements.captionsBtn.style.display=n?"flex":"none")}attachEventListeners(){this.videoElement&&(this.videoElement.addEventListener("play",()=>{this.setState({isPlaying:!0}),this.updatePlayPauseButton(),this.elements.centerPlayBtn&&(this.elements.centerPlayBtn.style.display="none"),this.emit("play",void 0)}),this.videoElement.addEventListener("pause",()=>{this.setState({isPlaying:!1}),this.updatePlayPauseButton(),this.elements.centerPlayBtn&&(this.elements.centerPlayBtn.style.display="flex"),this.emit("pause",void 0)}),this.videoElement.addEventListener("timeupdate",()=>{this.setState({currentTime:this.videoElement.currentTime}),this.updateProgress(),this.updateCaptions(),this.emit("timeupdate",this.videoElement.currentTime)}),this.videoElement.addEventListener("durationchange",()=>{this.setState({duration:this.videoElement.duration})}),this.videoElement.addEventListener("volumechange",()=>{this.setState({volume:this.videoElement.volume,isMuted:this.videoElement.muted}),this.updateVolumeUI(),this.emit("volumechange",this.videoElement.volume)}),this.videoElement.addEventListener("ended",()=>{this.emit("ended",void 0)}),this.elements.playPauseBtn?.addEventListener("click",()=>{this.togglePlayPause()}),this.elements.centerPlayBtn?.addEventListener("click",()=>{this.play(),this.elements.centerPlayBtn&&(this.elements.centerPlayBtn.style.display="none")}),this.elements.progressBar?.addEventListener("click",t=>{this.handleSeek(t)}),this.elements.volumeBtn?.addEventListener("click",()=>{this.toggleMute()}),this.elements.captionsBtn?.addEventListener("click",()=>{this.toggleCaptions()}),this.elements.fullscreenBtn?.addEventListener("click",()=>{this.toggleFullscreen()}),document.addEventListener("fullscreenchange",()=>{const t=!!document.fullscreenElement;this.setState({isFullscreen:t}),this.elements.player?.classList.toggle("fullscreen",t),this.emit("fullscreenchange",t)}),this.elements.player?.addEventListener("mousemove",()=>{this.elements.player?.classList.remove("is-paused")}),this.videoElement.addEventListener("pause",()=>{this.elements.player?.classList.add("is-paused")}),this.videoElement.addEventListener("play",()=>{this.elements.player?.classList.remove("is-paused")}))}setState(t){this.state={...this.state,...t}}updatePlayPauseButton(){this.elements.playPauseBtn&&(this.elements.playPauseBtn.textContent=this.state.isPlaying?"⏸":"▶",this.elements.playPauseBtn.setAttribute("aria-label",this.state.isPlaying?"Pause":"Play"))}updateProgress(){if(this.elements.progressFilled&&this.state.duration>0){const t=this.state.currentTime/this.state.duration*100;this.elements.progressFilled.style.width=`${t}%`}}updateVolumeUI(){if(this.elements.volumeBtn){const{isMuted:t,volume:e}=this.state;this.elements.volumeBtn.innerHTML=t||0===e?'\n <svg xmlns="http://www.w3.org/2000/svg" width="22" height="20" viewBox="0 0 22 20" fill="none">\n <path d="M11.2168 19.9287L4.20801 13.7031H0V6.22559H4.20898L11.2168 0V19.9287Z" fill="white"/>\n </svg>\n ':'\n <svg xmlns="http://www.w3.org/2000/svg" width="22" height="20" viewBox="0 0 22 20" fill="none">\n <path d="M11.2168 19.9287L4.20801 13.7031H0V6.22559H4.20898L11.2168 0V19.9287ZM14.0215 0.150391C16.2405 0.150468 18.1409 1.39074 19.4385 3.17676C20.7365 4.9634 21.499 7.36811 21.499 9.96484C21.499 12.5613 20.7363 14.9654 19.4385 16.752C18.1409 18.538 16.2405 19.7792 14.0215 19.7793V17.1025C15.2032 17.1025 16.3824 16.4464 17.3135 15.165C18.2442 13.8839 18.8593 12.0493 18.8594 9.96484C18.8594 7.88034 18.2442 6.04581 17.3135 4.76465C16.3824 3.4832 15.2033 2.82723 14.0215 2.82715V0.150391ZM14.0215 5.75879C15.5701 5.75896 16.8252 7.64189 16.8252 9.96484C16.8251 12.2877 15.57 14.1707 14.0215 14.1709V5.75879Z" fill="white"/>\n </svg>\n '}}updateCaptions(){if(!this.elements.captionDisplay||!this.state.captionsEnabled)return void(this.elements.captionDisplay&&(this.elements.captionDisplay.style.display="none"));const t=this.state.currentTime,e=this.captionCues.find(e=>t>=e.start&&t<=e.end);e?(this.elements.captionDisplay.textContent=e.text,this.elements.captionDisplay.style.display="block"):this.elements.captionDisplay.style.display="none"}handleSeek(t){if(!this.videoElement||!this.state.duration||!this.elements.progressBar)return;const e=this.elements.progressBar.getBoundingClientRect(),i=(t.clientX-e.left)/e.width;this.videoElement.currentTime=this.state.duration*hd(i,0,1)}showError(t){this.setState({error:t,isLoading:!1}),this.elements.error&&(this.elements.error.textContent=t,this.elements.error.style.display="block"),this.elements.loading&&(this.elements.loading.style.display="none")}togglePlayPause(){this.state.isPlaying?this.pause():this.play()}toggleCaptions(){this.setState({captionsEnabled:!this.state.captionsEnabled}),this.updateCaptionsButton(),this.updateCaptions()}updateCaptionsButton(){this.elements.captionsBtn&&(this.state.captionsEnabled?this.elements.captionsBtn.classList.add("active"):this.elements.captionsBtn.classList.remove("active"))}toggleFullscreen(){var t;this.elements.player&&(t=this.elements.player,document.fullscreenElement?document.exitFullscreen():t.requestFullscreen())}play(){this.videoElement&&(!0!==this.config.startMuted||this.videoElement.muted||(this.videoElement.muted=!0,this.videoElement.setAttribute("muted",""),this.setState({isMuted:!0})),this.videoElement.play())}pause(){this.videoElement?.pause()}setVolume(t){this.videoElement&&(this.videoElement.volume=hd(t,0,1),this.videoElement.muted=0===t)}toggleMute(){this.videoElement&&(this.videoElement.muted=!this.videoElement.muted)}seek(t){this.videoElement&&(this.videoElement.currentTime=hd(t,0,this.state.duration))}setFeatures(t){this.config={...this.config,...t},void 0!==t.controls&&this.updateControlsVisibility(),void 0!==t.startMuted&&this.videoElement&&(this.videoElement.muted=!0===t.startMuted,!0===t.startMuted?this.videoElement.setAttribute("muted",""):this.videoElement.removeAttribute("muted"),this.setState({isMuted:!0===t.startMuted}),this.updateVolumeUI()),this.state.videoData?this.updateOverlayContent(this.state.videoData):(void 0!==t.showLogo&&this.elements.logo&&(this.elements.logo.style.display=t.showLogo?"block":"none"),void 0!==t.showCaptions&&this.elements.captionsBtn&&(this.elements.captionsBtn.style.display=t.showCaptions?"flex":"none"))}getState(){return{...this.state}}on(t,e){this.listeners.has(t)||this.listeners.set(t,new Set),this.listeners.get(t).add(e)}off(t,e){const i=this.listeners.get(t);i&&i.delete(e)}emit(t,e){const i=this.listeners.get(t);i&&i.forEach(t=>t(e))}destroy(){this.hls&&(this.hls.destroy(),this.hls=null),this.videoElement&&(this.videoElement.pause(),this.videoElement.src="",this.videoElement=null),this.listeners.clear(),this.container.innerHTML=""}}class ud extends HTMLElement{static get observedAttributes(){return["video-id","api-key","client-id","autoplay","base-url","width","height","controls","show-logo","show-title","show-author","show-description","show-captions","start-muted"]}constructor(){super(),this.player=null,this.container=null,this.clientInstance=null,this.connected=!1,this.attachShadow({mode:"open"})}connectedCallback(){this.connected=!0,this.render(),this.initPlayer()}disconnectedCallback(){this.connected=!1,this.destroyPlayer()}attributeChangedCallback(t,e,i){if(this.connected&&e!==i)if("video-id"===t&&this.player)this.destroyPlayer(),this.initPlayer();else if("width"===t||"height"===t)this.updateContainerStyles();else if(("controls"===t||"show-logo"===t||"show-title"===t||"show-author"===t||"show-description"===t||"show-captions"===t||"start-muted"===t)&&this.player){const e={};"controls"===t?e.controls=!this.hasAttribute("controls")||"false"!==this.getAttribute("controls"):"show-logo"===t?e.showLogo=!this.hasAttribute("show-logo")||"false"!==this.getAttribute("show-logo"):"show-title"===t?e.showTitle=!this.hasAttribute("show-title")||"false"!==this.getAttribute("show-title"):"show-author"===t?e.showAuthor=!this.hasAttribute("show-author")||"false"!==this.getAttribute("show-author"):"show-description"===t?e.showDescription=!this.hasAttribute("show-description")||"false"!==this.getAttribute("show-description"):"show-captions"===t?e.showCaptions=!this.hasAttribute("show-captions")||"false"!==this.getAttribute("show-captions"):"start-muted"===t&&(e.startMuted=this.hasAttribute("start-muted")&&"false"!==this.getAttribute("start-muted")),this.player.setFeatures(e)}}render(){if(!this.shadowRoot)return;const t=document.createElement("style");t.textContent=`\n ${dd}\n .jaaq-vanilla-player {\n user-select: none;\n}\n\n.jaaq-vanilla-player video {\n outline: none;\n}\n\n.jaaq-collection-player {\n width: 100%;\n max-width: 1400px;\n margin: 0 auto;\n font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, sans-serif;\n}\n\n.jaaq-collection-loading {\n display: flex;\n justify-content: center;\n align-items: center;\n min-height: 400px;\n}\n\n.jaaq-collection-spinner {\n width: 50px;\n height: 50px;\n border: 4px solid rgba(0, 123, 255, 0.3);\n border-top-color: #007bff;\n border-radius: 50%;\n animation: jaaq-collection-spin 1s linear infinite;\n}\n\n@keyframes jaaq-collection-spin {\n to {\n transform: rotate(360deg);\n }\n}\n\n.jaaq-collection-error {\n background: rgba(220, 53, 69, 0.9);\n color: white;\n padding: 16px 24px;\n border-radius: 8px;\n text-align: center;\n font-size: 14px;\n margin: 20px;\n}\n\n.jaaq-collection-carousel .splide__track {\n padding: 40px 0;\n}\n\n.jaaq-collection-carousel .splide__slide {\n opacity: 0.7;\n transition: all 0.3s ease;\n display: flex;\n align-items: center;\n justify-content: center;\n}\n\n.jaaq-collection-carousel .splide__slide.is-active {\n opacity: 1;\n}\n\n.jaaq-collection-carousel .splide__slide jaaq-video-player {\n width: 100%;\n max-width: 600px;\n transition: all 0.3s ease;\n}\n\n.jaaq-collection-carousel .splide__slide.is-active jaaq-video-player {\n max-width: 800px;\n}\n\n.jaaq-collection-carousel .splide__arrow {\n background: rgba(0, 0, 0, 0.5);\n border: none;\n width: 48px;\n height: 48px;\n border-radius: 50%;\n color: white;\n cursor: pointer;\n transition: all 0.2s;\n display: flex;\n align-items: center;\n justify-content: center;\n font-size: 20px;\n}\n\n.jaaq-collection-carousel .splide__arrow:hover {\n background: rgba(0, 0, 0, 0.8);\n transform: scale(1.1);\n}\n\n.jaaq-collection-carousel .splide__arrow:disabled {\n opacity: 0.3;\n cursor: not-allowed;\n}\n\n.jaaq-collection-carousel .splide__arrow svg {\n fill: white;\n width: 20px;\n height: 20px;\n}\n\n.jaaq-collection-carousel .splide__pagination {\n bottom: -30px;\n}\n\n.jaaq-collection-carousel .splide__pagination__page {\n background: #ccc;\n border: none;\n width: 10px;\n height: 10px;\n margin: 0 4px;\n border-radius: 50%;\n transition: all 0.2s;\n cursor: pointer;\n}\n\n.jaaq-collection-carousel .splide__pagination__page.is-active {\n background: #007bff;\n transform: scale(1.3);\n}\n\n@media (max-width: 1024px) {\n .jaaq-collection-carousel .splide__slide jaaq-video-player {\n max-width: 500px;\n }\n\n .jaaq-collection-carousel .splide__slide.is-active jaaq-video-player {\n max-width: 650px;\n }\n}\n\n@media (max-width: 768px) {\n .jaaq-collection-carousel .splide__track {\n padding: 20px 0;\n }\n\n .jaaq-collection-carousel .splide__slide jaaq-video-player {\n max-width: 400px;\n }\n\n .jaaq-collection-carousel .splide__slide.is-active jaaq-video-player {\n max-width: 500px;\n }\n\n .jaaq-collection-carousel .splide__arrow {\n width: 40px;\n height: 40px;\n }\n}\n\n@media (max-width: 480px) {\n .jaaq-collection-carousel .splide__slide jaaq-video-player {\n max-width: 100%;\n }\n\n .jaaq-collection-carousel .splide__slide.is-active jaaq-video-player {\n max-width: 100%;\n }\n}\n\n \n:host {\n display: block;\n width: 100%;\n}\n\n:host([hidden]) {\n display: none;\n}\n\n `,this.container=document.createElement("div"),this.container.className="jaaq-webcomponent-container",this.shadowRoot.appendChild(t),this.shadowRoot.appendChild(this.container),this.updateContainerStyles()}updateContainerStyles(){if(!this.container)return;const t=this.getAttribute("width")||"100%",e=this.getAttribute("height")||"auto";this.container.style.width=t,this.container.style.height=e}async initPlayer(){if(!this.container||this.player)return;const t=this.getAttribute("video-id");if(!t)return void this.emitError(new Error("video-id attribute is required"));const e=this.getAttribute("api-key"),i=this.getAttribute("client-id"),s=this.getAttribute("base-url")||void 0,r=this.getAttribute("api-version")||void 0,n=this.hasAttribute("autoplay")&&"false"!==this.getAttribute("autoplay"),a=!this.hasAttribute("controls")||"false"!==this.getAttribute("controls"),o=!this.hasAttribute("show-logo")||"false"!==this.getAttribute("show-logo"),l=!this.hasAttribute("show-title")||"false"!==this.getAttribute("show-title"),h=!this.hasAttribute("show-author")||"false"!==this.getAttribute("show-author"),d=!this.hasAttribute("show-description")||"false"!==this.getAttribute("show-description"),c=!this.hasAttribute("show-captions")||"false"!==this.getAttribute("show-captions"),u=this.hasAttribute("start-muted")&&"false"!==this.getAttribute("start-muted");if(this.clientInstance||e||i)try{this.player=new cd(this.container,{videoId:t??void 0,apiKey:e??void 0,clientId:i??void 0,client:this.clientInstance||void 0,baseUrl:s,apiVersion:r,autoplay:n,controls:a,showLogo:o,showTitle:l,showAuthor:h,showDescription:d,showCaptions:c,startMuted:u}),this.attachPlayerEvents()}catch(t){this.emitError(t instanceof Error?t:new Error("Failed to initialize player"))}else this.emitError(new Error("Either client property or api-key and client-id attributes are required"))}attachPlayerEvents(){this.player&&(this.player.on("loaded",t=>{this.dispatchEvent(new CustomEvent("jaaq:loaded",{detail:t,bubbles:!0,composed:!0}))}),this.player.on("play",()=>{this.dispatchEvent(new CustomEvent("jaaq:play",{bubbles:!0,composed:!0}))}),this.player.on("pause",()=>{this.dispatchEvent(new CustomEvent("jaaq:pause",{bubbles:!0,composed:!0}))}),this.player.on("timeupdate",t=>{this.dispatchEvent(new CustomEvent("jaaq:timeupdate",{detail:t,bubbles:!0,composed:!0}))}),this.player.on("volumechange",t=>{this.dispatchEvent(new CustomEvent("jaaq:volumechange",{detail:t,bubbles:!0,composed:!0}))}),this.player.on("ended",()=>{this.dispatchEvent(new CustomEvent("jaaq:ended",{bubbles:!0,composed:!0}))}),this.player.on("error",t=>{this.emitError(t)}),this.player.on("fullscreenchange",t=>{this.dispatchEvent(new CustomEvent("jaaq:fullscreenchange",{detail:t,bubbles:!0,composed:!0}))}))}emitError(t){this.dispatchEvent(new CustomEvent("jaaq:error",{detail:t,bubbles:!0,composed:!0}))}destroyPlayer(){this.player&&(this.player.destroy(),this.player=null)}get client(){return this.clientInstance}set client(t){this.clientInstance=t,this.connected&&(this.destroyPlayer(),this.initPlayer())}get videoId(){return this.getAttribute("video-id")}set videoId(t){t?this.setAttribute("video-id",t):this.removeAttribute("video-id")}play(){this.player?.play()}pause(){this.player?.pause()}setVolume(t){this.player?.setVolume(t)}toggleMute(){this.player?.toggleMute()}seek(t){this.player?.seek(t)}getState(){return this.player?.getState()||null}destroy(){this.destroyPlayer()}}function fd(t,e,i){return e&&function(t,e){for(var i=0;i<e.length;i++){var s=e[i];s.enumerable=s.enumerable||!1,s.configurable=!0,"value"in s&&(s.writable=!0),Object.defineProperty(t,s.key,s)}}(t.prototype,e),Object.defineProperty(t,"prototype",{writable:!1}),t}
2
2
  /*!
3
3
  * Splide.js
4
4
  * Version : 4.1.4
5
5
  * License : MIT
6
6
  * Copyright: 2022 Naotoshi Fujita
7
- */var ud="(prefers-reduced-motion: reduce)",fd={CREATED:1,MOUNTED:2,IDLE:3,MOVING:4,SCROLLING:5,DRAGGING:6,DESTROYED:7};function gd(t){t.length=0}function md(t,e,i){return Array.prototype.slice.call(t,e,i)}function pd(t){return t.bind.apply(t,[null].concat(md(arguments,1)))}var vd=setTimeout,yd=function(){};function Ed(t){return requestAnimationFrame(t)}function Td(t,e){return typeof e===t}function Sd(t){return!Rd(t)&&Td("object",t)}var bd=Array.isArray,Ad=pd(Td,"function"),Ld=pd(Td,"string"),Id=pd(Td,"undefined");function Rd(t){return null===t}function kd(t){try{return t instanceof(t.ownerDocument.defaultView||window).HTMLElement}catch(t){return!1}}function _d(t){return bd(t)?t:[t]}function Dd(t,e){_d(t).forEach(e)}function wd(t,e){return t.indexOf(e)>-1}function Pd(t,e){return t.push.apply(t,_d(e)),t}function Cd(t,e,i){t&&Dd(e,function(e){e&&t.classList[i?"add":"remove"](e)})}function xd(t,e){Cd(t,Ld(e)?e.split(" "):e,!0)}function Md(t,e){Dd(e,t.appendChild.bind(t))}function Od(t,e){Dd(t,function(t){var i=(e||t).parentNode;i&&i.insertBefore(t,e)})}function Fd(t,e){return kd(t)&&(t.msMatchesSelector||t.matches).call(t,e)}function Nd(t,e){var i=t?md(t.children):[];return e?i.filter(function(t){return Fd(t,e)}):i}function $d(t,e){return e?Nd(t,e)[0]:t.firstElementChild}var Bd=Object.keys;function Ud(t,e,i){return t&&(i?Bd(t).reverse():Bd(t)).forEach(function(i){"__proto__"!==i&&e(t[i],i)}),t}function Gd(t){return md(arguments,1).forEach(function(e){Ud(e,function(i,s){t[s]=e[s]})}),t}function Kd(t){return md(arguments,1).forEach(function(e){Ud(e,function(e,i){bd(e)?t[i]=e.slice():Sd(e)?t[i]=Kd({},Sd(t[i])?t[i]:{},e):t[i]=e})}),t}function Vd(t,e){Dd(e||Bd(t),function(e){delete t[e]})}function jd(t,e){Dd(t,function(t){Dd(e,function(e){t&&t.removeAttribute(e)})})}function Hd(t,e,i){Sd(e)?Ud(e,function(e,i){Hd(t,i,e)}):Dd(t,function(t){Rd(i)||""===i?jd(t,e):t.setAttribute(e,String(i))})}function qd(t,e,i){var s=document.createElement(t);return e&&(Ld(e)?xd(s,e):Hd(s,e)),i&&Md(i,s),s}function Yd(t,e,i){if(Id(i))return getComputedStyle(t)[e];Rd(i)||(t.style[e]=""+i)}function Wd(t,e){Yd(t,"display",e)}function zd(t){t.setActive&&t.setActive()||t.focus({preventScroll:!0})}function Xd(t,e){return t.getAttribute(e)}function Qd(t,e){return t&&t.classList.contains(e)}function Zd(t){return t.getBoundingClientRect()}function Jd(t){Dd(t,function(t){t&&t.parentNode&&t.parentNode.removeChild(t)})}function tc(t){return $d((new DOMParser).parseFromString(t,"text/html").body)}function ec(t,e){t.preventDefault(),e&&(t.stopPropagation(),t.stopImmediatePropagation())}function ic(t,e){return t&&t.querySelector(e)}function sc(t,e){return e?md(t.querySelectorAll(e)):[]}function rc(t,e){Cd(t,e,!1)}function nc(t){return t.timeStamp}function ac(t){return Ld(t)?t:t?t+"px":""}var oc="splide",lc="data-"+oc;function hc(t,e){if(!t)throw new Error("["+oc+"] "+(e||""))}var dc=Math.min,cc=Math.max,uc=Math.floor,fc=Math.ceil,gc=Math.abs;function mc(t,e,i){return gc(t-e)<i}function pc(t,e,i,s){var r=dc(e,i),n=cc(e,i);return s?r<t&&t<n:r<=t&&t<=n}function vc(t,e,i){var s=dc(e,i),r=cc(e,i);return dc(cc(s,t),r)}function yc(t){return+(t>0)-+(t<0)}function Ec(t,e){return Dd(e,function(e){t=t.replace("%s",""+e)}),t}function Tc(t){return t<10?"0"+t:""+t}var Sc={};function bc(){var t=[];function e(t,e,i){Dd(t,function(t){t&&Dd(e,function(e){e.split(" ").forEach(function(e){var s=e.split(".");i(t,s[0],s[1])})})})}return{bind:function(i,s,r,n){e(i,s,function(e,i,s){var a="addEventListener"in e,o=a?e.removeEventListener.bind(e,i,r,n):e.removeListener.bind(e,r);a?e.addEventListener(i,r,n):e.addListener(r),t.push([e,i,s,r,o])})},unbind:function(i,s,r){e(i,s,function(e,i,s){t=t.filter(function(t){return!!(t[0]!==e||t[1]!==i||t[2]!==s||r&&t[3]!==r)||(t[4](),!1)})})},dispatch:function(t,e,i){var s,r=!0;return"function"==typeof CustomEvent?s=new CustomEvent(e,{bubbles:r,detail:i}):(s=document.createEvent("CustomEvent")).initCustomEvent(e,r,!1,i),t.dispatchEvent(s),s},destroy:function(){t.forEach(function(t){t[4]()}),gd(t)}}}var Ac="mounted",Lc="ready",Ic="move",Rc="moved",kc="click",_c="active",Dc="inactive",wc="visible",Pc="hidden",Cc="refresh",xc="updated",Mc="resize",Oc="resized",Fc="scroll",Nc="scrolled",$c="destroy",Bc="arrows:mounted",Uc="navigation:mounted",Gc="autoplay:play",Kc="autoplay:pause",Vc="lazyload:loaded",jc="sk",Hc="sh",qc="ei";function Yc(t){var e=t?t.event.bus:document.createDocumentFragment(),i=bc();return t&&t.event.on($c,i.destroy),Gd(i,{bus:e,on:function(t,s){i.bind(e,_d(t).join(" "),function(t){s.apply(s,bd(t.detail)?t.detail:[])})},off:pd(i.unbind,e),emit:function(t){i.dispatch(e,t,md(arguments,1))}})}function Wc(t,e,i,s){var r,n,a=Date.now,o=0,l=!0,h=0;function d(){if(!l){if(o=t?dc((a()-r)/t,1):1,i&&i(o),o>=1&&(e(),r=a(),s&&++h>=s))return c();n=Ed(d)}}function c(){l=!0}function u(){n&&cancelAnimationFrame(n),o=0,n=0,l=!0}return{start:function(e){e||u(),r=a()-(e?o*t:0),l=!1,n=Ed(d)},rewind:function(){r=a(),o=0,i&&i(o)},pause:c,cancel:u,set:function(e){t=e},isPaused:function(){return l}}}var zc="Arrow",Xc=zc+"Left",Qc=zc+"Right",Zc=zc+"Up",Jc=zc+"Down",tu="ttb",eu={width:["height"],left:["top","right"],right:["bottom","left"],x:["y"],X:["Y"],Y:["X"],ArrowLeft:[Zc,Qc],ArrowRight:[Jc,Xc]};var iu="role",su="tabindex",ru="aria-",nu=ru+"controls",au=ru+"current",ou=ru+"selected",lu=ru+"label",hu=ru+"labelledby",du=ru+"hidden",cu=ru+"orientation",uu=ru+"roledescription",fu=ru+"live",gu=ru+"busy",mu=ru+"atomic",pu=[iu,su,"disabled",nu,au,lu,hu,du,cu,uu],vu=oc+"__",yu="is-",Eu=oc,Tu=vu+"track",Su=vu+"list",bu=vu+"slide",Au=bu+"--clone",Lu=bu+"__container",Iu=vu+"arrows",Ru=vu+"arrow",ku=Ru+"--prev",_u=Ru+"--next",Du=vu+"pagination",wu=Du+"__page",Pu=vu+"progress"+"__bar",Cu=vu+"toggle",xu=vu+"sr",Mu=yu+"initialized",Ou=yu+"active",Fu=yu+"prev",Nu=yu+"next",$u=yu+"visible",Bu=yu+"loading",Uu=yu+"focus-in",Gu=yu+"overflow",Ku=[Ou,$u,Fu,Nu,Bu,Uu,Gu],Vu={slide:bu,clone:Au,arrows:Iu,arrow:Ru,prev:ku,next:_u,pagination:Du,page:wu,spinner:vu+"spinner"};var ju="touchstart mousedown",Hu="touchmove mousemove",qu="touchend touchcancel mouseup click";var Yu="slide",Wu="loop",zu="fade";function Xu(t,e,i,s){var r,n=Yc(t),a=n.on,o=n.emit,l=n.bind,h=t.Components,d=t.root,c=t.options,u=c.isNavigation,f=c.updateOnMove,g=c.i18n,m=c.pagination,p=c.slideFocus,v=h.Direction.resolve,y=Xd(s,"style"),E=Xd(s,lu),T=i>-1,S=$d(s,"."+Lu);function b(){var r=t.splides.map(function(t){var i=t.splide.Components.Slides.getAt(e);return i?i.slide.id:""}).join(" ");Hd(s,lu,Ec(g.slideX,(T?i:e)+1)),Hd(s,nu,r),Hd(s,iu,p?"button":""),p&&jd(s,uu)}function A(){r||L()}function L(){if(!r){var i=t.index;(n=I())!==Qd(s,Ou)&&(Cd(s,Ou,n),Hd(s,au,u&&n||""),o(n?_c:Dc,R)),function(){var e=function(){if(t.is(zu))return I();var e=Zd(h.Elements.track),i=Zd(s),r=v("left",!0),n=v("right",!0);return uc(e[r])<=fc(i[r])&&uc(i[n])<=fc(e[n])}(),i=!e&&(!I()||T);t.state.is([4,5])||Hd(s,du,i||"");Hd(sc(s,c.focusableNodes||""),su,i?-1:""),p&&Hd(s,su,i?-1:0);e!==Qd(s,$u)&&(Cd(s,$u,e),o(e?wc:Pc,R));if(!e&&document.activeElement===s){var r=h.Slides.getAt(t.index);r&&zd(r.slide)}}(),Cd(s,Fu,e===i-1),Cd(s,Nu,e===i+1)}var n}function I(){var s=t.index;return s===e||c.cloneStatus&&s===i}var R={index:e,slideIndex:i,slide:s,container:S,isClone:T,mount:function(){T||(s.id=d.id+"-slide"+Tc(e+1),Hd(s,iu,m?"tabpanel":"group"),Hd(s,uu,g.slide),Hd(s,lu,E||Ec(g.slideLabel,[e+1,t.length]))),l(s,"click",pd(o,kc,R)),l(s,"keydown",pd(o,jc,R)),a([Rc,Hc,Nc],L),a(Uc,b),f&&a(Ic,A)},destroy:function(){r=!0,n.destroy(),rc(s,Ku),jd(s,pu),Hd(s,"style",y),Hd(s,lu,E||"")},update:L,style:function(t,e,i){Yd(i&&S||s,t,e)},isWithin:function(i,s){var r=gc(i-e);return T||!c.rewind&&!t.is(Wu)||(r=dc(r,t.length-r)),r<=s}};return R}var Qu=lc+"-interval";var Zu={passive:!1,capture:!0};var Ju={Spacebar:" ",Right:Qc,Left:Xc,Up:Zc,Down:Jc};function tf(t){return t=Ld(t)?t:t.key,Ju[t]||t}var ef="keydown";var sf=lc+"-lazy",rf=sf+"-srcset",nf="["+sf+"], ["+rf+"]";var af=[" ","Enter"];var of=Object.freeze({__proto__:null,Media:function(t,e,i){var s=t.state,r=i.breakpoints||{},n=i.reducedMotion||{},a=bc(),o=[];function l(t){t&&a.destroy()}function h(t,e){var i=matchMedia(e);a.bind(i,"change",d),o.push([t,i])}function d(){var e=s.is(7),r=i.direction,n=o.reduce(function(t,e){return Kd(t,e[1].matches?e[0]:{})},{});Vd(i),c(n),i.destroy?t.destroy("completely"===i.destroy):e?(l(!0),t.mount()):r!==i.direction&&t.refresh()}function c(e,r,n){Kd(i,e),r&&Kd(Object.getPrototypeOf(i),e),!n&&s.is(1)||t.emit(xc,i)}return{setup:function(){var t="min"===i.mediaQuery;Bd(r).sort(function(e,i){return t?+e-+i:+i-+e}).forEach(function(e){h(r[e],"("+(t?"min":"max")+"-width:"+e+"px)")}),h(n,ud),d()},destroy:l,reduce:function(t){matchMedia(ud).matches&&(t?Kd(i,n):Vd(i,Bd(n)))},set:c}},Direction:function(t,e,i){return{resolve:function(t,e,s){var r="rtl"!==(s=s||i.direction)||e?s===tu?0:-1:1;return eu[t]&&eu[t][r]||t.replace(/width|left|right/i,function(t,e){var i=eu[t.toLowerCase()][r]||t;return e>0?i.charAt(0).toUpperCase()+i.slice(1):i})},orient:function(t){return t*("rtl"===i.direction?1:-1)}}},Elements:function(t,e,i){var s,r,n,a=Yc(t),o=a.on,l=a.bind,h=t.root,d=i.i18n,c={},u=[],f=[],g=[];function m(){s=y("."+Tu),r=$d(s,"."+Su),hc(s&&r,"A track/list element is missing."),Pd(u,Nd(r,"."+bu+":not(."+Au+")")),Ud({arrows:Iu,pagination:Du,prev:ku,next:_u,bar:Pu,toggle:Cu},function(t,e){c[e]=y("."+t)}),Gd(c,{root:h,track:s,list:r,slides:u}),function(){var t=h.id||(n=oc,""+n+Tc(Sc[n]=(Sc[n]||0)+1)),e=i.role;var n;h.id=t,s.id=s.id||t+"-track",r.id=r.id||t+"-list",!Xd(h,iu)&&"SECTION"!==h.tagName&&e&&Hd(h,iu,e);Hd(h,uu,d.carousel),Hd(r,iu,"presentation")}(),v()}function p(t){var e=pu.concat("style");gd(u),rc(h,f),rc(s,g),jd([s,r],e),jd(h,t?e:["style",uu])}function v(){rc(h,f),rc(s,g),f=E(Eu),g=E(Tu),xd(h,f),xd(s,g),Hd(h,lu,i.label),Hd(h,hu,i.labelledby)}function y(t){var e=ic(h,t);return e&&function(t,e){if(Ad(t.closest))return t.closest(e);for(var i=t;i&&1===i.nodeType&&!Fd(i,e);)i=i.parentElement;return i}(e,"."+Eu)===h?e:void 0}function E(t){return[t+"--"+i.type,t+"--"+i.direction,i.drag&&t+"--draggable",i.isNavigation&&t+"--nav",t===Eu&&Ou]}return Gd(c,{setup:m,mount:function(){o(Cc,p),o(Cc,m),o(xc,v),l(document,ju+" keydown",function(t){n="keydown"===t.type},{capture:!0}),l(h,"focusin",function(){Cd(h,Uu,!!n)})},destroy:p})},Slides:function(t,e,i){var s=Yc(t),r=s.on,n=s.emit,a=s.bind,o=e.Elements,l=o.slides,h=o.list,d=[];function c(){l.forEach(function(t,e){f(t,e,-1)})}function u(){m(function(t){t.destroy()}),gd(d)}function f(e,i,s){var r=Xu(t,i,s,e);r.mount(),d.push(r),d.sort(function(t,e){return t.index-e.index})}function g(t){return t?p(function(t){return!t.isClone}):d}function m(t,e){g(e).forEach(t)}function p(t){return d.filter(Ad(t)?t:function(e){return Ld(t)?Fd(e.slide,t):wd(_d(t),e.index)})}return{mount:function(){c(),r(Cc,u),r(Cc,c)},destroy:u,update:function(){m(function(t){t.update()})},register:f,get:g,getIn:function(t){var s=e.Controller,r=s.toIndex(t),n=s.hasFocus()?1:i.perPage;return p(function(t){return pc(t.index,r,r+n-1)})},getAt:function(t){return p(t)[0]},add:function(t,e){Dd(t,function(t){if(Ld(t)&&(t=tc(t)),kd(t)){var s=l[e];s?Od(t,s):Md(h,t),xd(t,i.classes.slide),r=t,o=pd(n,Mc),d=sc(r,"img"),(c=d.length)?d.forEach(function(t){a(t,"load error",function(){--c||o()})}):o()}var r,o,d,c}),n(Cc)},remove:function(t){Jd(p(t).map(function(t){return t.slide})),n(Cc)},forEach:m,filter:p,style:function(t,e,i){m(function(s){s.style(t,e,i)})},getLength:function(t){return t?l.length:d.length},isEnough:function(){return d.length>i.perPage}}},Layout:function(t,e,i){var s,r,n,a=Yc(t),o=a.on,l=a.bind,h=a.emit,d=e.Slides,c=e.Direction.resolve,u=e.Elements,f=u.root,g=u.track,m=u.list,p=d.getAt,v=d.style;function y(){s=i.direction===tu,Yd(f,"maxWidth",ac(i.width)),Yd(g,c("paddingLeft"),T(!1)),Yd(g,c("paddingRight"),T(!0)),E(!0)}function E(t){var e=Zd(f);(t||r.width!==e.width||r.height!==e.height)&&(Yd(g,"height",function(){var t="";s&&(hc(t=S(),"height or heightRatio is missing."),t="calc("+t+" - "+T(!1)+" - "+T(!0)+")");return t}()),v(c("marginRight"),ac(i.gap)),v("width",i.autoWidth?null:ac(i.fixedWidth)||(s?"":b())),v("height",ac(i.fixedHeight)||(s?i.autoHeight?null:b():S()),!0),r=e,h(Oc),n!==(n=_())&&(Cd(f,Gu,n),h("overflow",n)))}function T(t){var e=i.padding,s=c(t?"right":"left");return e&&ac(e[s]||(Sd(e)?0:e))||"0px"}function S(){return ac(i.height||Zd(m).width*i.heightRatio)}function b(){var t=ac(i.gap);return"calc((100%"+(t&&" + "+t)+")/"+(i.perPage||1)+(t&&" - "+t)+")"}function A(){return Zd(m)[c("width")]}function L(t,e){var i=p(t||0);return i?Zd(i.slide)[c("width")]+(e?0:k()):0}function I(t,e){var i=p(t);if(i){var s=Zd(i.slide)[c("right")],r=Zd(m)[c("left")];return gc(s-r)+(e?0:k())}return 0}function R(e){return I(t.length-1)-I(0)+L(0,e)}function k(){var t=p(0);return t&&parseFloat(Yd(t.slide,c("marginRight")))||0}function _(){return t.is(zu)||R(!0)>A()}return{mount:function(){var t,e;y(),l(window,"resize load",(t=pd(h,Mc),e=Wc(0,t,null,1),function(){e.isPaused()&&e.start()})),o([xc,Cc],y),o(Mc,E)},resize:E,listSize:A,slideSize:L,sliderSize:R,totalSize:I,getPadding:function(t){return parseFloat(Yd(g,c("padding"+(t?"Right":"Left"))))||0},isOverflow:_}},Clones:function(t,e,i){var s,r=Yc(t),n=r.on,a=e.Elements,o=e.Slides,l=e.Direction.resolve,h=[];function d(){n(Cc,c),n([xc,Mc],f),(s=g())&&(!function(e){var s=o.get().slice(),r=s.length;if(r){for(;s.length<e;)Pd(s,s);Pd(s.slice(-e),s.slice(0,e)).forEach(function(n,l){var d=l<e,c=function(e,s){var r=e.cloneNode(!0);return xd(r,i.classes.clone),r.id=t.root.id+"-clone"+Tc(s+1),r}(n.slide,l);d?Od(c,s[0].slide):Md(a.list,c),Pd(h,c),o.register(c,l-e+(d?0:r),n.index)})}}(s),e.Layout.resize(!0))}function c(){u(),d()}function u(){Jd(h),gd(h),r.destroy()}function f(){var t=g();s!==t&&(s<t||!t)&&r.emit(Cc)}function g(){var s=i.clones;if(t.is(Wu)){if(Id(s)){var r=i[l("fixedWidth")]&&e.Layout.slideSize(0);s=r&&fc(Zd(a.track)[l("width")]/r)||i[l("autoWidth")]&&t.length||2*i.perPage}}else s=0;return s}return{mount:d,destroy:u}},Move:function(t,e,i){var s,r=Yc(t),n=r.on,a=r.emit,o=t.state.set,l=e.Layout,h=l.slideSize,d=l.getPadding,c=l.totalSize,u=l.listSize,f=l.sliderSize,g=e.Direction,m=g.resolve,p=g.orient,v=e.Elements,y=v.list,E=v.track;function T(){e.Controller.isBusy()||(e.Scroll.cancel(),S(t.index),e.Slides.update())}function S(t){b(R(t,!0))}function b(i,s){if(!t.is(zu)){var r=s?i:function(i){if(t.is(Wu)){var s=I(i),r=s>e.Controller.getEnd();(s<0||r)&&(i=A(i,r))}return i}(i);Yd(y,"transform","translate"+m("X")+"("+r+"px)"),i!==r&&a(Hc)}}function A(t,e){var i=t-_(e),s=f();return t-=p(s*(fc(gc(i)/s)||1))*(e?1:-1)}function L(){b(k(),!0),s.cancel()}function I(t){for(var i=e.Slides.get(),s=0,r=1/0,n=0;n<i.length;n++){var a=i[n].index,o=gc(R(a,!0)-t);if(!(o<=r))break;r=o,s=a}return s}function R(e,s){var r=p(c(e-1)-function(t){var e=i.focus;return"center"===e?(u()-h(t,!0))/2:+e*h(t)||0}(e));return s?function(e){i.trimSpace&&t.is(Yu)&&(e=vc(e,0,p(f(!0)-u())));return e}(r):r}function k(){var t=m("left");return Zd(y)[t]-Zd(E)[t]+p(d(!1))}function _(t){return R(t?e.Controller.getEnd():0,!!i.trimSpace)}return{mount:function(){s=e.Transition,n([Ac,Oc,xc,Cc],T)},move:function(t,e,i,r){var n,l;t!==e&&(n=t>i,l=p(A(k(),n)),n?l>=0:l<=y[m("scrollWidth")]-Zd(E)[m("width")])&&(L(),b(A(k(),t>i),!0)),o(4),a(Ic,e,i,t),s.start(e,function(){o(3),a(Rc,e,i,t),r&&r()})},jump:S,translate:b,shift:A,cancel:L,toIndex:I,toPosition:R,getPosition:k,getLimit:_,exceededLimit:function(t,e){e=Id(e)?k():e;var i=!0!==t&&p(e)<p(_(!1)),s=!1!==t&&p(e)>p(_(!0));return i||s},reposition:T}},Controller:function(t,e,i){var s,r,n,a,o=Yc(t),l=o.on,h=o.emit,d=e.Move,c=d.getPosition,u=d.getLimit,f=d.toPosition,g=e.Slides,m=g.isEnough,p=g.getLength,v=i.omitEnd,y=t.is(Wu),E=t.is(Yu),T=pd(R,!1),S=pd(R,!0),b=i.start||0,A=b;function L(){r=p(!0),n=i.perMove,a=i.perPage,s=D();var t=vc(b,0,v?s:r-1);t!==b&&(b=t,d.reposition())}function I(){s!==D()&&h(qc)}function R(t,e){var i=n||(x()?1:a),r=k(b+i*(t?-1:1),b,!(n||x()));return-1===r&&E&&!mc(c(),u(!t),1)?t?0:s:e?r:_(r)}function k(e,o,l){if(m()||x()){var h=function(e){if(E&&"move"===i.trimSpace&&e!==b)for(var s=c();s===f(e,!0)&&pc(e,0,t.length-1,!i.rewind);)e<b?--e:++e;return e}(e);h!==e&&(o=e,e=h,l=!1),e<0||e>s?e=n||!pc(0,e,o,!0)&&!pc(s,o,e,!0)?y?l?e<0?-(r%a||a):r:e:i.rewind?e<0?s:0:-1:w(P(e)):l&&e!==o&&(e=w(P(o)+(e<o?-1:1)))}else e=-1;return e}function _(t){return y?(t+r)%r||0:t}function D(){for(var t=r-(x()||y&&n?1:a);v&&t-- >0;)if(f(r-1,!0)!==f(t,!0)){t++;break}return vc(t,0,r-1)}function w(t){return vc(x()?t:a*t,0,s)}function P(t){return x()?dc(t,s):uc((t>=s?r-1:t)/a)}function C(t){t!==b&&(A=b,b=t)}function x(){return!Id(i.focus)||i.isNavigation}function M(){return t.state.is([4,5])&&!!i.waitForTransition}return{mount:function(){L(),l([xc,Cc,qc],L),l(Oc,I)},go:function(t,e,i){if(!M()){var r=function(t){var e=b;if(Ld(t)){var i=t.match(/([+\-<>])(\d+)?/)||[],r=i[1],n=i[2];"+"===r||"-"===r?e=k(b+ +(""+r+(+n||1)),b):">"===r?e=n?w(+n):T(!0):"<"===r&&(e=S(!0))}else e=y?t:vc(t,0,s);return e}(t),n=_(r);n>-1&&(e||n!==b)&&(C(n),d.move(r,n,A,i))}},scroll:function(t,i,r,n){e.Scroll.scroll(t,i,r,function(){var t=_(d.toIndex(c()));C(v?dc(t,s):t),n&&n()})},getNext:T,getPrev:S,getAdjacent:R,getEnd:D,setIndex:C,getIndex:function(t){return t?A:b},toIndex:w,toPage:P,toDest:function(t){var e=d.toIndex(t);return E?vc(e,0,s):e},hasFocus:x,isBusy:M}},Arrows:function(t,e,i){var s,r,n=Yc(t),a=n.on,o=n.bind,l=n.emit,h=i.classes,d=i.i18n,c=e.Elements,u=e.Controller,f=c.arrows,g=c.track,m=f,p=c.prev,v=c.next,y={};function E(){!function(){var t=i.arrows;!t||p&&v||(m=f||qd("div",h.arrows),p=A(!0),v=A(!1),s=!0,Md(m,[p,v]),!f&&Od(m,g));p&&v&&(Gd(y,{prev:p,next:v}),Wd(m,t?"":"none"),xd(m,r=Iu+"--"+i.direction),t&&(a([Ac,Rc,Cc,Nc,qc],L),o(v,"click",pd(b,">")),o(p,"click",pd(b,"<")),L(),Hd([p,v],nu,g.id),l(Bc,p,v)))}(),a(xc,T)}function T(){S(),E()}function S(){n.destroy(),rc(m,r),s?(Jd(f?[p,v]:m),p=v=null):jd([p,v],pu)}function b(t){u.go(t,!0)}function A(t){return tc('<button class="'+h.arrow+" "+(t?h.prev:h.next)+'" type="button"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 40 40" width="40" height="40" focusable="false"><path d="'+(i.arrowPath||"m15.5 0.932-4.3 4.38 14.5 14.6-14.5 14.5 4.3 4.4 14.6-14.6 4.4-4.3-4.4-4.4-14.6-14.6z")+'" />')}function L(){if(p&&v){var e=t.index,i=u.getPrev(),s=u.getNext(),r=i>-1&&e<i?d.last:d.prev,n=s>-1&&e>s?d.first:d.next;p.disabled=i<0,v.disabled=s<0,Hd(p,lu,r),Hd(v,lu,n),l("arrows:updated",p,v,i,s)}}return{arrows:y,mount:E,destroy:S,update:L}},Autoplay:function(t,e,i){var s,r,n=Yc(t),a=n.on,o=n.bind,l=n.emit,h=Wc(i.interval,t.go.bind(t,">"),function(t){var e=c.bar;e&&Yd(e,"width",100*t+"%"),l("autoplay:playing",t)}),d=h.isPaused,c=e.Elements,u=e.Elements,f=u.root,g=u.toggle,m=i.autoplay,p="pause"===m;function v(){d()&&e.Slides.isEnough()&&(h.start(!i.resetProgress),r=s=p=!1,T(),l(Gc))}function y(t){void 0===t&&(t=!0),p=!!t,T(),d()||(h.pause(),l(Kc))}function E(){p||(s||r?y(!1):v())}function T(){g&&(Cd(g,Ou,!p),Hd(g,lu,i.i18n[p?"play":"pause"]))}function S(t){var s=e.Slides.getAt(t);h.set(s&&+Xd(s.slide,Qu)||i.interval)}return{mount:function(){m&&(!function(){i.pauseOnHover&&o(f,"mouseenter mouseleave",function(t){s="mouseenter"===t.type,E()});i.pauseOnFocus&&o(f,"focusin focusout",function(t){r="focusin"===t.type,E()});g&&o(g,"click",function(){p?v():y(!0)});a([Ic,Fc,Cc],h.rewind),a(Ic,S)}(),g&&Hd(g,nu,c.track.id),p||v(),T())},destroy:h.cancel,play:v,pause:y,isPaused:d}},Cover:function(t,e,i){var s=Yc(t).on;function r(t){e.Slides.forEach(function(e){var i=$d(e.container||e.slide,"img");i&&i.src&&n(t,i,e)})}function n(t,e,i){i.style("background",t?'center/cover no-repeat url("'+e.src+'")':"",!0),Wd(e,t?"none":"")}return{mount:function(){i.cover&&(s(Vc,pd(n,!0)),s([Ac,xc,Cc],pd(r,!0)))},destroy:pd(r,!1)}},Scroll:function(t,e,i){var s,r,n=Yc(t),a=n.on,o=n.emit,l=t.state.set,h=e.Move,d=h.getPosition,c=h.getLimit,u=h.exceededLimit,f=h.translate,g=t.is(Yu),m=1;function p(t,i,n,a,c){var f=d();if(E(),n&&(!g||!u())){var p=e.Layout.sliderSize(),T=yc(t)*p*uc(gc(t)/p)||0;t=h.toPosition(e.Controller.toDest(t%p))+T}var S=mc(f,t,1);m=1,i=S?0:i||cc(gc(t-f)/1.5,800),r=a,s=Wc(i,v,pd(y,f,t,c),1),l(5),o(Fc),s.start()}function v(){l(3),r&&r(),o(Nc)}function y(t,e,s,n){var a,o,l=d(),h=(t+(e-t)*(a=n,(o=i.easingFunc)?o(a):1-Math.pow(1-a,4))-l)*m;f(l+h),g&&!s&&u()&&(m*=.6,gc(h)<10&&p(c(u(!0)),600,!1,r,!0))}function E(){s&&s.cancel()}function T(){s&&!s.isPaused()&&(E(),v())}return{mount:function(){a(Ic,E),a([xc,Cc],T)},destroy:E,scroll:p,cancel:T}},Drag:function(t,e,i){var s,r,n,a,o,l,h,d,c=Yc(t),u=c.on,f=c.emit,g=c.bind,m=c.unbind,p=t.state,v=e.Move,y=e.Scroll,E=e.Controller,T=e.Elements.track,S=e.Media.reduce,b=e.Direction,A=b.resolve,L=b.orient,I=v.getPosition,R=v.exceededLimit,k=!1;function _(){var t=i.drag;B(!t),a="free"===t}function D(t){if(l=!1,!h){var e=$(t);s=t.target,r=i.noDrag,Fd(s,"."+wu+", ."+Ru)||r&&Fd(s,r)||!e&&t.button||(E.isBusy()?ec(t,!0):(d=e?T:window,o=p.is([4,5]),n=null,g(d,Hu,w,Zu),g(d,qu,P,Zu),v.cancel(),y.cancel(),x(t)))}var s,r}function w(e){if(p.is(6)||(p.set(6),f("drag")),e.cancelable)if(o){v.translate(s+M(e)/(k&&t.is(Yu)?5:1));var r=O(e)>200,n=k!==(k=R());(r||n)&&x(e),l=!0,f("dragging"),ec(e)}else(function(t){return gc(M(t))>gc(M(t,!0))})(e)&&(o=function(t){var e=i.dragMinThreshold,s=Sd(e),r=s&&e.mouse||0,n=(s?e.touch:+e)||10;return gc(M(t))>($(t)?n:r)}(e),ec(e))}function P(s){p.is(6)&&(p.set(3),f("dragged")),o&&(!function(s){var r=function(e){if(t.is(Wu)||!k){var i=O(e);if(i&&i<200)return M(e)/i}return 0}(s),n=function(t){return I()+yc(t)*dc(gc(t)*(i.flickPower||600),a?1/0:e.Layout.listSize()*(i.flickMaxPages||1))}(r),o=i.rewind&&i.rewindByDrag;S(!1),a?E.scroll(n,0,i.snap):t.is(zu)?E.go(L(yc(r))<0?o?"<":"-":o?">":"+"):t.is(Yu)&&k&&o?E.go(R(!0)?">":"<"):E.go(E.toDest(n),!0);S(!0)}(s),ec(s)),m(d,Hu,w),m(d,qu,P),o=!1}function C(t){!h&&l&&ec(t,!0)}function x(t){n=r,r=t,s=I()}function M(t,e){return N(t,e)-N(F(t),e)}function O(t){return nc(t)-nc(F(t))}function F(t){return r===t&&n||r}function N(t,e){return($(t)?t.changedTouches[0]:t)["page"+A(e?"Y":"X")]}function $(t){return"undefined"!=typeof TouchEvent&&t instanceof TouchEvent}function B(t){h=t}return{mount:function(){g(T,Hu,yd,Zu),g(T,qu,yd,Zu),g(T,ju,D,Zu),g(T,"click",C,{capture:!0}),g(T,"dragstart",ec),u([Ac,xc],_)},disable:B,isDragging:function(){return o}}},Keyboard:function(t,e,i){var s,r,n=Yc(t),a=n.on,o=n.bind,l=n.unbind,h=t.root,d=e.Direction.resolve;function c(){var t=i.keyboard;t&&(s="global"===t?window:h,o(s,ef,g))}function u(){l(s,ef)}function f(){var t=r;r=!0,vd(function(){r=t})}function g(e){if(!r){var i=tf(e);i===d(Xc)?t.go("<"):i===d(Qc)&&t.go(">")}}return{mount:function(){c(),a(xc,u),a(xc,c),a(Ic,f)},destroy:u,disable:function(t){r=t}}},LazyLoad:function(t,e,i){var s=Yc(t),r=s.on,n=s.off,a=s.bind,o=s.emit,l="sequential"===i.lazyLoad,h=[Rc,Nc],d=[];function c(){gd(d),e.Slides.forEach(function(t){sc(t.slide,nf).forEach(function(e){var s=Xd(e,sf),r=Xd(e,rf);if(s!==e.src||r!==e.srcset){var n=i.classes.spinner,a=e.parentElement,o=$d(a,"."+n)||qd("span",n,a);d.push([e,t,o]),e.src||Wd(e,"none")}})}),l?m():(n(h),r(h,u),u())}function u(){(d=d.filter(function(e){var s=i.perPage*((i.preloadPages||1)+1)-1;return!e[1].isWithin(t.index,s)||f(e)})).length||n(h)}function f(t){var e=t[0];xd(t[1].slide,Bu),a(e,"load error",pd(g,t)),Hd(e,"src",Xd(e,sf)),Hd(e,"srcset",Xd(e,rf)),jd(e,sf),jd(e,rf)}function g(t,e){var i=t[0],s=t[1];rc(s.slide,Bu),"error"!==e.type&&(Jd(t[2]),Wd(i,""),o(Vc,i,s),o(Mc)),l&&m()}function m(){d.length&&f(d.shift())}return{mount:function(){i.lazyLoad&&(c(),r(Cc,c))},destroy:pd(gd,d),check:u}},Pagination:function(t,e,i){var s,r,n=Yc(t),a=n.on,o=n.emit,l=n.bind,h=e.Slides,d=e.Elements,c=e.Controller,u=c.hasFocus,f=c.getIndex,g=c.go,m=e.Direction.resolve,p=d.pagination,v=[];function y(){s&&(Jd(p?md(s.children):s),rc(s,r),gd(v),s=null),n.destroy()}function E(t){g(">"+t,!0)}function T(t,e){var i=v.length,s=tf(e),r=S(),n=-1;s===m(Qc,!1,r)?n=++t%i:s===m(Xc,!1,r)?n=(--t+i)%i:"Home"===s?n=0:"End"===s&&(n=i-1);var a=v[n];a&&(zd(a.button),g(">"+n),ec(e,!0))}function S(){return i.paginationDirection||i.direction}function b(t){return v[c.toPage(t)]}function A(){var t=b(f(!0)),e=b(f());if(t){var i=t.button;rc(i,Ou),jd(i,ou),Hd(i,su,-1)}if(e){var r=e.button;xd(r,Ou),Hd(r,ou,!0),Hd(r,su,"")}o("pagination:updated",{list:s,items:v},t,e)}return{items:v,mount:function e(){y(),a([xc,Cc,qc],e);var n=i.pagination;p&&Wd(p,n?"":"none"),n&&(a([Ic,Fc,Nc],A),function(){var e=t.length,n=i.classes,a=i.i18n,o=i.perPage,f=u()?c.getEnd()+1:fc(e/o);xd(s=p||qd("ul",n.pagination,d.track.parentElement),r=Du+"--"+S()),Hd(s,iu,"tablist"),Hd(s,lu,a.select),Hd(s,cu,S()===tu?"vertical":"");for(var g=0;g<f;g++){var m=qd("li",null,s),y=qd("button",{class:n.page,type:"button"},m),b=h.getIn(g).map(function(t){return t.slide.id}),A=!u()&&o>1?a.pageX:a.slideX;l(y,"click",pd(E,g)),i.paginationKeyboard&&l(y,"keydown",pd(T,g)),Hd(m,iu,"presentation"),Hd(y,iu,"tab"),Hd(y,nu,b.join(" ")),Hd(y,lu,Ec(A,g+1)),Hd(y,su,-1),v.push({li:m,button:y,page:g})}}(),A(),o("pagination:mounted",{list:s,items:v},b(t.index)))},destroy:y,getAt:b,update:A}},Sync:function(t,e,i){var s=i.isNavigation,r=i.slideFocus,n=[];function a(){var e,i;t.splides.forEach(function(e){e.isParent||(l(t,e.splide),l(e.splide,t))}),s&&(e=Yc(t),(i=e.on)(kc,d),i(jc,c),i([Ac,xc],h),n.push(e),e.emit(Uc,t.splides))}function o(){n.forEach(function(t){t.destroy()}),gd(n)}function l(t,e){var i=Yc(t);i.on(Ic,function(t,i,s){e.go(e.is(Wu)?s:t)}),n.push(i)}function h(){Hd(e.Elements.list,cu,i.direction===tu?"vertical":"")}function d(e){t.go(e.index)}function c(t,e){wd(af,tf(e))&&(d(t),ec(e))}return{setup:pd(e.Media.set,{slideFocus:Id(r)?s:r},!0),mount:a,destroy:o,remount:function(){o(),a()}}},Wheel:function(t,e,i){var s=Yc(t).bind,r=0;function n(s){if(s.cancelable){var n=s.deltaY,a=n<0,o=nc(s),l=i.wheelMinThreshold||0,h=i.wheelSleep||0;gc(n)>l&&o-r>h&&(t.go(a?"<":">"),r=o),function(s){return!i.releaseWheel||t.state.is(4)||-1!==e.Controller.getAdjacent(s)}(a)&&ec(s)}}return{mount:function(){i.wheel&&s(e.Elements.track,"wheel",n,Zu)}}},Live:function(t,e,i){var s=Yc(t).on,r=e.Elements.track,n=i.live&&!i.isNavigation,a=qd("span",xu),o=Wc(90,pd(l,!1));function l(t){Hd(r,gu,t),t?(Md(r,a),o.start()):(Jd(a),o.cancel())}function h(t){n&&Hd(r,fu,t?"off":"polite")}return{mount:function(){n&&(h(!e.Autoplay.isPaused()),Hd(r,mu,!0),a.textContent="…",s(Gc,pd(h,!0)),s(Kc,pd(h,!1)),s([Rc,Nc],pd(l,!0)))},disable:h,destroy:function(){jd(r,[fu,mu,gu]),Jd(a)}}}}),lf={type:"slide",role:"region",speed:400,perPage:1,cloneStatus:!0,arrows:!0,pagination:!0,paginationKeyboard:!0,interval:5e3,pauseOnHover:!0,pauseOnFocus:!0,resetProgress:!0,easing:"cubic-bezier(0.25, 1, 0.5, 1)",drag:!0,direction:"ltr",trimSpace:!0,focusableNodes:"a, button, textarea, input, select, iframe",live:!0,classes:Vu,i18n:{prev:"Previous slide",next:"Next slide",first:"Go to first slide",last:"Go to last slide",slideX:"Go to slide %s",pageX:"Go to page %s",play:"Start autoplay",pause:"Pause autoplay",carousel:"carousel",slide:"slide",select:"Select a slide to show",slideLabel:"%s of %s"},reducedMotion:{speed:0,rewindSpeed:0,autoplay:"pause"}};function hf(t,e,i){var s=e.Slides;function r(){s.forEach(function(t){t.style("transform","translateX(-"+100*t.index+"%)")})}return{mount:function(){Yc(t).on([Ac,Cc],r)},start:function(t,e){s.style("transition","opacity "+i.speed+"ms "+i.easing),vd(e)},cancel:yd}}function df(t,e,i){var s,r=e.Move,n=e.Controller,a=e.Scroll,o=e.Elements.list,l=pd(Yd,o,"transition");function h(){l(""),a.cancel()}return{mount:function(){Yc(t).bind(o,"transitionend",function(t){t.target===o&&s&&(h(),s())})},start:function(e,o){var h=r.toPosition(e,!0),d=r.getPosition(),c=function(e){var s=i.rewindSpeed;if(t.is(Yu)&&s){var r=n.getIndex(!0),a=n.getEnd();if(0===r&&e>=a||r>=a&&0===e)return s}return i.speed}(e);gc(h-d)>=1&&c>=1?i.useScroll?a.scroll(h,c,!1,o):(l("transform "+c+"ms "+i.easing),r.translate(h,!0),s=o):(r.jump(e),o())},cancel:h}}var cf=function(){function t(e,i){var s;this.event=Yc(),this.Components={},this.state=(s=1,{set:function(t){s=t},is:function(t){return wd(_d(t),s)}}),this.splides=[],this._o={},this._E={};var r=Ld(e)?ic(document,e):e;hc(r,r+" is invalid."),this.root=r,i=Kd({label:Xd(r,lu)||"",labelledby:Xd(r,hu)||""},lf,t.defaults,i||{});try{Kd(i,JSON.parse(Xd(r,lc)))}catch(t){hc(!1,"Invalid JSON")}this._o=Object.create(Kd({},i))}var e=t.prototype;return e.mount=function(t,e){var i=this,s=this.state,r=this.Components;return hc(s.is([1,7]),"Already mounted!"),s.set(1),this._C=r,this._T=e||this._T||(this.is(zu)?hf:df),this._E=t||this._E,Ud(Gd({},of,this._E,{Transition:this._T}),function(t,e){var s=t(i,r,i._o);r[e]=s,s.setup&&s.setup()}),Ud(r,function(t){t.mount&&t.mount()}),this.emit(Ac),xd(this.root,Mu),s.set(3),this.emit(Lc),this},e.sync=function(t){return this.splides.push({splide:t}),t.splides.push({splide:this,isParent:!0}),this.state.is(3)&&(this._C.Sync.remount(),t.Components.Sync.remount()),this},e.go=function(t){return this._C.Controller.go(t),this},e.on=function(t,e){return this.event.on(t,e),this},e.off=function(t){return this.event.off(t),this},e.emit=function(t){var e;return(e=this.event).emit.apply(e,[t].concat(md(arguments,1))),this},e.add=function(t,e){return this._C.Slides.add(t,e),this},e.remove=function(t){return this._C.Slides.remove(t),this},e.is=function(t){return this._o.type===t},e.refresh=function(){return this.emit(Cc),this},e.destroy=function(t){void 0===t&&(t=!0);var e=this.event,i=this.state;return i.is(1)?Yc(this).on(Lc,this.destroy.bind(this,t)):(Ud(this._C,function(e){e.destroy&&e.destroy(t)},!0),e.emit($c),e.destroy(),t&&gd(this.splides),i.set(7)),this},cd(t,[{key:"options",get:function(){return this._o},set:function(t){this._C.Media.set(t,!0,!0)}},{key:"length",get:function(){return this._C.Slides.getLength(!0)}},{key:"index",get:function(){return this._C.Controller.getIndex()}}]),t}(),uf=cf;uf.defaults={},uf.STATES=fd;class ff extends HTMLElement{static get observedAttributes(){return["collection-id","api-key","client-id","subscription-id","base-url","autoplay","show-arrows","show-dots","video-settings"]}constructor(){super(),this.splide=null,this.container=null,this.carouselElement=null,this.clientInstance=null,this.connected=!1,this.collectionData=null,this.autoplayTimeoutId=null,this.attachShadow({mode:"open"})}connectedCallback(){this.connected=!0,this.render(),this.initCarousel()}disconnectedCallback(){this.connected=!1,this.destroyCarousel()}attributeChangedCallback(t,e,i){this.connected&&e!==i&&("collection-id"!==t&&"video-settings"!==t||(this.destroyCarousel(),this.initCarousel()),"show-arrows"!==t&&"show-dots"!==t||(this.destroyCarousel(),this.initCarousel()))}getBooleanAttr(t,e){const i=this.getAttribute(t);return null===i?e:"false"!==i}getVideosFromCollection(t){if(t.videos&&t.videos.length>0)return t.videos;if(t.videoGroups&&t.videoGroups.length>0){const e=[];return t.videoGroups.forEach(t=>{t.videos&&t.videos.length>0&&e.push(...t.videos)}),e}return[]}render(){if(!this.shadowRoot)return;const t=document.createElement("style");t.textContent=`\n ${ld}\n .jaaq-collection-player {\n width: 100%;\n max-width: 1400px;\n margin: 0 auto;\n font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, sans-serif;\n}\n\n.jaaq-collection-loading {\n display: flex;\n justify-content: center;\n align-items: center;\n min-height: 400px;\n}\n\n.jaaq-collection-spinner {\n width: 50px;\n height: 50px;\n border: 4px solid rgba(0, 123, 255, 0.3);\n border-top-color: #007bff;\n border-radius: 50%;\n animation: jaaq-collection-spin 1s linear infinite;\n}\n\n@keyframes jaaq-collection-spin {\n to {\n transform: rotate(360deg);\n }\n}\n\n.jaaq-collection-error {\n background: rgba(220, 53, 69, 0.9);\n color: white;\n padding: 16px 24px;\n border-radius: 8px;\n text-align: center;\n font-size: 14px;\n margin: 20px;\n}\n\n.jaaq-collection-carousel .splide__track {\n padding: 40px 0;\n}\n\n.jaaq-collection-carousel .splide__slide {\n opacity: 0.7;\n transition: all 0.3s ease;\n display: flex;\n align-items: center;\n justify-content: center;\n}\n\n.jaaq-collection-carousel .splide__slide.is-active {\n opacity: 1;\n}\n\n.jaaq-collection-carousel .splide__slide jaaq-video-player {\n width: 100%;\n max-width: 600px;\n transition: all 0.3s ease;\n}\n\n.jaaq-collection-carousel .splide__slide.is-active jaaq-video-player {\n max-width: 800px;\n}\n\n.jaaq-collection-carousel .splide__arrow {\n background: rgba(0, 0, 0, 0.5);\n border: none;\n width: 48px;\n height: 48px;\n border-radius: 50%;\n color: white;\n cursor: pointer;\n transition: all 0.2s;\n display: flex;\n align-items: center;\n justify-content: center;\n font-size: 20px;\n}\n\n.jaaq-collection-carousel .splide__arrow:hover {\n background: rgba(0, 0, 0, 0.8);\n transform: scale(1.1);\n}\n\n.jaaq-collection-carousel .splide__arrow:disabled {\n opacity: 0.3;\n cursor: not-allowed;\n}\n\n.jaaq-collection-carousel .splide__arrow svg {\n fill: white;\n width: 20px;\n height: 20px;\n}\n\n.jaaq-collection-carousel .splide__pagination {\n bottom: -30px;\n}\n\n.jaaq-collection-carousel .splide__pagination__page {\n background: #ccc;\n border: none;\n width: 10px;\n height: 10px;\n margin: 0 4px;\n border-radius: 50%;\n transition: all 0.2s;\n cursor: pointer;\n}\n\n.jaaq-collection-carousel .splide__pagination__page.is-active {\n background: white;\n transform: scale(1.3);\n}\n\n@media (max-width: 1024px) {\n .jaaq-collection-carousel .splide__slide jaaq-video-player {\n max-width: 500px;\n }\n\n .jaaq-collection-carousel .splide__slide.is-active jaaq-video-player {\n max-width: 650px;\n }\n}\n\n@media (max-width: 768px) {\n .jaaq-collection-carousel .splide__track {\n padding: 20px 0;\n }\n\n .jaaq-collection-carousel .splide__slide jaaq-video-player {\n max-width: 400px;\n }\n\n .jaaq-collection-carousel .splide__slide.is-active jaaq-video-player {\n max-width: 500px;\n }\n\n .jaaq-collection-carousel .splide__arrow {\n width: 40px;\n height: 40px;\n }\n}\n\n@media (max-width: 480px) {\n .jaaq-collection-carousel .splide__slide jaaq-video-player {\n max-width: 100%;\n }\n\n .jaaq-collection-carousel .splide__slide.is-active jaaq-video-player {\n max-width: 100%;\n }\n}\n\n .splide__container{box-sizing:border-box;position:relative}.splide__list{backface-visibility:hidden;display:-ms-flexbox;display:flex;height:100%;margin:0!important;padding:0!important}.splide.is-initialized:not(.is-active) .splide__list{display:block}.splide__pagination{-ms-flex-align:center;align-items:center;display:-ms-flexbox;display:flex;-ms-flex-wrap:wrap;flex-wrap:wrap;-ms-flex-pack:center;justify-content:center;margin:0;pointer-events:none}.splide__pagination li{display:inline-block;line-height:1;list-style-type:none;margin:0;pointer-events:auto}.splide:not(.is-overflow) .splide__pagination{display:none}.splide__progress__bar{width:0}.splide{position:relative;visibility:hidden}.splide.is-initialized,.splide.is-rendered{visibility:visible}.splide__slide{backface-visibility:hidden;box-sizing:border-box;-ms-flex-negative:0;flex-shrink:0;list-style-type:none!important;margin:0;position:relative}.splide__slide img{vertical-align:bottom}.splide__spinner{animation:splide-loading 1s linear infinite;border:2px solid #999;border-left-color:transparent;border-radius:50%;bottom:0;contain:strict;display:inline-block;height:20px;left:0;margin:auto;position:absolute;right:0;top:0;width:20px}.splide__sr{clip:rect(0 0 0 0);border:0;height:1px;margin:-1px;overflow:hidden;padding:0;position:absolute;width:1px}.splide__toggle.is-active .splide__toggle__play,.splide__toggle__pause{display:none}.splide__toggle.is-active .splide__toggle__pause{display:inline}.splide__track{overflow:hidden;position:relative;z-index:0}@keyframes splide-loading{0%{transform:rotate(0)}to{transform:rotate(1turn)}}.splide__track--draggable{-webkit-touch-callout:none;-webkit-user-select:none;-ms-user-select:none;user-select:none}.splide__track--fade>.splide__list>.splide__slide{margin:0!important;opacity:0;z-index:0}.splide__track--fade>.splide__list>.splide__slide.is-active{opacity:1;z-index:1}.splide--rtl{direction:rtl}.splide__track--ttb>.splide__list{display:block}.splide__arrow{-ms-flex-align:center;align-items:center;background:#ccc;border:0;border-radius:50%;cursor:pointer;display:-ms-flexbox;display:flex;height:2em;-ms-flex-pack:center;justify-content:center;opacity:.7;padding:0;position:absolute;top:50%;transform:translateY(-50%);width:2em;z-index:1}.splide__arrow svg{fill:#000;height:1.2em;width:1.2em}.splide__arrow:hover:not(:disabled){opacity:.9}.splide__arrow:disabled{opacity:.3}.splide__arrow:focus-visible{outline:3px solid #0bf;outline-offset:3px}.splide__arrow--prev{left:1em}.splide__arrow--prev svg{transform:scaleX(-1)}.splide__arrow--next{right:1em}.splide.is-focus-in .splide__arrow:focus{outline:3px solid #0bf;outline-offset:3px}.splide__pagination{bottom:.5em;left:0;padding:0 1em;position:absolute;right:0;z-index:1}.splide__pagination__page{background:#ccc;border:0;border-radius:50%;display:inline-block;height:8px;margin:3px;opacity:.7;padding:0;position:relative;transition:transform .2s linear;width:8px}.splide__pagination__page.is-active{background:#fff;transform:scale(1.4);z-index:1}.splide__pagination__page:hover{cursor:pointer;opacity:.9}.splide__pagination__page:focus-visible{outline:3px solid #0bf;outline-offset:3px}.splide.is-focus-in .splide__pagination__page:focus{outline:3px solid #0bf;outline-offset:3px}.splide__progress__bar{background:#ccc;height:3px}.splide__slide{-webkit-tap-highlight-color:rgba(0,0,0,0)}.splide__slide:focus{outline:0}@supports(outline-offset:-3px){.splide__slide:focus-visible{outline:3px solid #0bf;outline-offset:-3px}}@media screen and (-ms-high-contrast:none){.splide__slide:focus-visible{border:3px solid #0bf}}@supports(outline-offset:-3px){.splide.is-focus-in .splide__slide:focus{outline:3px solid #0bf;outline-offset:-3px}}@media screen and (-ms-high-contrast:none){.splide.is-focus-in .splide__slide:focus{border:3px solid #0bf}.splide.is-focus-in .splide__track>.splide__list>.splide__slide:focus{border-color:#0bf}}.splide__toggle{cursor:pointer}.splide__toggle:focus-visible{outline:3px solid #0bf;outline-offset:3px}.splide.is-focus-in .splide__toggle:focus{outline:3px solid #0bf;outline-offset:3px}.splide__track--nav>.splide__list>.splide__slide{border:3px solid transparent;cursor:pointer}.splide__track--nav>.splide__list>.splide__slide.is-active{border:3px solid #000}.splide__arrows--rtl .splide__arrow--prev{left:auto;right:1em}.splide__arrows--rtl .splide__arrow--prev svg{transform:scaleX(1)}.splide__arrows--rtl .splide__arrow--next{left:1em;right:auto}.splide__arrows--rtl .splide__arrow--next svg{transform:scaleX(-1)}.splide__arrows--ttb .splide__arrow{left:50%;transform:translate(-50%)}.splide__arrows--ttb .splide__arrow--prev{top:1em}.splide__arrows--ttb .splide__arrow--prev svg{transform:rotate(-90deg)}.splide__arrows--ttb .splide__arrow--next{bottom:1em;top:auto}.splide__arrows--ttb .splide__arrow--next svg{transform:rotate(90deg)}.splide__pagination--ttb{bottom:0;display:-ms-flexbox;display:flex;-ms-flex-direction:column;flex-direction:column;left:auto;padding:1em 0;right:.5em;top:0}\n \n:host {\n display: block;\n width: 100%;\n}\n\n:host([hidden]) {\n display: none;\n}\n\n `,this.container=document.createElement("div"),this.container.className="jaaq-collection-player",this.shadowRoot.appendChild(t),this.shadowRoot.appendChild(this.container)}async initCarousel(){if(!this.container)return;const t=this.getAttribute("collection-id");if(!t)return void this.emitError(new Error("collection-id attribute is required"));const e=this.getAttribute("api-key"),i=this.getAttribute("client-id"),s=this.getAttribute("base-url")||void 0,r=this.getAttribute("api-version")||void 0;if(this.clientInstance||e||i){this.showLoading();try{const n=this.clientInstance||nd.init({apiKey:e,clientId:i,baseUrl:s||rd,apiVersion:r});this.collectionData=await n.collections.getById(t);if(0===this.getVideosFromCollection(this.collectionData).length)return void this.emitError(new Error("No videos found in collection"));this.renderCarousel(),this.initSplide(),this.dispatchEvent(new CustomEvent("jaaq:collection:loaded",{detail:this.collectionData,bubbles:!0,composed:!0}))}catch(t){this.emitError(t instanceof Error?t:new Error("Failed to load collection"))}}else this.emitError(new Error("Either client property or api-key and client-id attributes are required"))}showLoading(){this.container&&(this.container.innerHTML='\n <div class="jaaq-collection-loading">\n <div class="jaaq-collection-spinner"></div>\n </div>\n ')}renderCarousel(){if(!this.container||!this.collectionData)return;this.container.innerHTML="",this.carouselElement=document.createElement("div"),this.carouselElement.className="splide jaaq-collection-carousel";const t=document.createElement("div");t.className="splide__track";const e=document.createElement("ul");e.className="splide__list";const i=this.getAttribute("api-key"),s=this.getAttribute("client-id"),r=this.getAttribute("base-url"),n=this.getAttribute("video-settings");let a=null;if(n)try{a=JSON.parse(n)}catch(t){console.warn("[CollectionPlayer] Failed to parse video-settings attribute",t)}this.getVideosFromCollection(this.collectionData).forEach(t=>{const n=document.createElement("li");n.className="splide__slide";const o=document.createElement("jaaq-video-player");o.setAttribute("video-id",t.videoId),i&&o.setAttribute("api-key",i),s&&o.setAttribute("client-id",s),r&&o.setAttribute("base-url",r),o.setAttribute("autoplay","false"),o.setAttribute("width","100%"),a&&(void 0!==a.controls&&o.setAttribute("controls",String(a.controls)),void 0!==a.showLogo&&o.setAttribute("show-logo",String(a.showLogo)),void 0!==a.showTitle&&o.setAttribute("show-title",String(a.showTitle)),void 0!==a.showAuthor&&o.setAttribute("show-author",String(a.showAuthor)),void 0!==a.showDescription&&o.setAttribute("show-description",String(a.showDescription)),void 0!==a.showCaptions&&o.setAttribute("show-captions",String(a.showCaptions)),void 0!==a.startMuted&&o.setAttribute("start-muted",String(a.startMuted)),void 0!==a.width&&o.setAttribute("width",String(a.width)),void 0!==a.height&&o.setAttribute("height",String(a.height))),n.appendChild(o),e.appendChild(n)}),t.appendChild(e),this.carouselElement.appendChild(t),this.container.appendChild(this.carouselElement)}initSplide(){if(!this.carouselElement)return;const t=this.getBooleanAttr("show-arrows",!0),e=this.getBooleanAttr("show-dots",!0);this.splide=new uf(this.carouselElement,{type:"loop",perPage:3,focus:"center",gap:"0.5rem",perMove:1,autoHeight:!0,updateOnMove:!0,padding:"5 rem",breakpoints:{768:{perPage:1},1024:{perPage:2}},arrows:t,pagination:e,autoplay:!1}),this.splide.on("moved",t=>{console.log("[CollectionPlayer] Splide moved event",{newIndex:t,splideIndex:this.splide?.index,Components:this.splide?.Components}),this.handleSlideChange(t);const e=this.collectionData?this.getVideosFromCollection(this.collectionData):[];this.dispatchEvent(new CustomEvent("jaaq:collection:slidechange",{detail:{index:t,video:e[t]},bubbles:!0,composed:!0}))}),this.splide.mount(),console.log("[CollectionPlayer] After mount",{splideIndex:this.splide.index,length:this.splide.length}),setTimeout(()=>{this.splide&&(console.log("[CollectionPlayer] Initial handleSlideChange after DOM update"),this.handleSlideChange(this.splide.index))},100)}handleSlideChange(t){if(!this.carouselElement)return;const e=this.hasAttribute("autoplay")&&"false"!==this.getAttribute("autoplay");console.log("[CollectionPlayer] handleSlideChange called",{activeIndex:t,isAutoplayEnabled:e}),null!==this.autoplayTimeoutId&&(console.log("[CollectionPlayer] Clearing existing autoplay timeout",{timeoutId:this.autoplayTimeoutId}),clearTimeout(this.autoplayTimeoutId),this.autoplayTimeoutId=null);const i=this.carouselElement.querySelector(".splide__slide.is-active:not(.splide__slide--clone)"),s=i?.querySelector("jaaq-video-player"),r=s?.getAttribute("video-id");console.log("[CollectionPlayer] Active slide from DOM:",{activeIndex:t,activeVideoId:r,foundActiveSlide:!!i});const n=this.carouselElement.querySelectorAll(".splide__slide:not(.splide__slide--clone)");Array.from(n).map((t,e)=>{const i=t.querySelector("jaaq-video-player");return{index:e,videoId:i?.getAttribute("video-id")||"unknown",isActive:t.classList.contains("is-active")}}),n.forEach((t,i)=>{const s=t.querySelector("jaaq-video-player");if(!s)return;const r=s.getAttribute("video-id");t.classList.contains("is-active")?e&&(this.autoplayTimeoutId=window.setTimeout(()=>{console.log("[CollectionPlayer] 1s delay complete, playing video",{index:i,videoId:r}),s.play?.()},1e3)):s.pause?.()})}destroyCarousel(){null!==this.autoplayTimeoutId&&(clearTimeout(this.autoplayTimeoutId),this.autoplayTimeoutId=null),this.splide&&(this.splide.destroy(),this.splide=null),this.container&&(this.container.innerHTML=""),this.collectionData=null}emitError(t){this.container&&(this.container.innerHTML=`\n <div class="jaaq-collection-error">\n ${t.message}\n </div>\n `),this.dispatchEvent(new CustomEvent("jaaq:collection:error",{detail:t,bubbles:!0,composed:!0}))}get client(){return this.clientInstance}set client(t){this.clientInstance=t,this.connected&&(this.destroyCarousel(),this.initCarousel())}get collectionId(){return this.getAttribute("collection-id")}set collectionId(t){t?this.setAttribute("collection-id",t):this.removeAttribute("collection-id")}refresh(){this.destroyCarousel(),this.initCarousel()}next(){this.splide?.go("+1")}prev(){this.splide?.go("-1")}go(t){this.splide?.go(t)}destroy(){this.destroyCarousel()}getCollection(){return this.collectionData}}const gf="jaaq-video-player",mf="jaaq-collection-player";function pf(){"undefined"!=typeof window&&"undefined"!=typeof customElements?(customElements.get(gf)||customElements.define(gf,dd),customElements.get(mf)||customElements.define(mf,ff)):console.warn("Custom Elements API is not available. Web components cannot be registered.")}"undefined"!=typeof window&&"undefined"!=typeof document&&("loading"===document.readyState?document.addEventListener("DOMContentLoaded",()=>{pf()}):pf()),t.JaaqCollectionPlayerElement=ff,t.JaaqVideoPlayerElement=dd,t.isRegistered=function(){return"undefined"!=typeof window&&"undefined"!=typeof customElements&&(!!customElements.get(gf)&&!!customElements.get(mf))},t.registerJaaqComponents=pf});
7
+ */var gd="(prefers-reduced-motion: reduce)",md={CREATED:1,MOUNTED:2,IDLE:3,MOVING:4,SCROLLING:5,DRAGGING:6,DESTROYED:7};function pd(t){t.length=0}function vd(t,e,i){return Array.prototype.slice.call(t,e,i)}function yd(t){return t.bind.apply(t,[null].concat(vd(arguments,1)))}var Ed=setTimeout,Td=function(){};function Sd(t){return requestAnimationFrame(t)}function bd(t,e){return typeof e===t}function Ad(t){return!_d(t)&&bd("object",t)}var Ld=Array.isArray,Id=yd(bd,"function"),Rd=yd(bd,"string"),kd=yd(bd,"undefined");function _d(t){return null===t}function Dd(t){try{return t instanceof(t.ownerDocument.defaultView||window).HTMLElement}catch(t){return!1}}function wd(t){return Ld(t)?t:[t]}function Pd(t,e){wd(t).forEach(e)}function Cd(t,e){return t.indexOf(e)>-1}function xd(t,e){return t.push.apply(t,wd(e)),t}function Md(t,e,i){t&&Pd(e,function(e){e&&t.classList[i?"add":"remove"](e)})}function Od(t,e){Md(t,Rd(e)?e.split(" "):e,!0)}function Fd(t,e){Pd(e,t.appendChild.bind(t))}function Nd(t,e){Pd(t,function(t){var i=(e||t).parentNode;i&&i.insertBefore(t,e)})}function $d(t,e){return Dd(t)&&(t.msMatchesSelector||t.matches).call(t,e)}function Bd(t,e){var i=t?vd(t.children):[];return e?i.filter(function(t){return $d(t,e)}):i}function Ud(t,e){return e?Bd(t,e)[0]:t.firstElementChild}var Gd=Object.keys;function Kd(t,e,i){return t&&(i?Gd(t).reverse():Gd(t)).forEach(function(i){"__proto__"!==i&&e(t[i],i)}),t}function Vd(t){return vd(arguments,1).forEach(function(e){Kd(e,function(i,s){t[s]=e[s]})}),t}function jd(t){return vd(arguments,1).forEach(function(e){Kd(e,function(e,i){Ld(e)?t[i]=e.slice():Ad(e)?t[i]=jd({},Ad(t[i])?t[i]:{},e):t[i]=e})}),t}function Hd(t,e){Pd(e||Gd(t),function(e){delete t[e]})}function qd(t,e){Pd(t,function(t){Pd(e,function(e){t&&t.removeAttribute(e)})})}function Yd(t,e,i){Ad(e)?Kd(e,function(e,i){Yd(t,i,e)}):Pd(t,function(t){_d(i)||""===i?qd(t,e):t.setAttribute(e,String(i))})}function Wd(t,e,i){var s=document.createElement(t);return e&&(Rd(e)?Od(s,e):Yd(s,e)),i&&Fd(i,s),s}function zd(t,e,i){if(kd(i))return getComputedStyle(t)[e];_d(i)||(t.style[e]=""+i)}function Xd(t,e){zd(t,"display",e)}function Qd(t){t.setActive&&t.setActive()||t.focus({preventScroll:!0})}function Zd(t,e){return t.getAttribute(e)}function Jd(t,e){return t&&t.classList.contains(e)}function tc(t){return t.getBoundingClientRect()}function ec(t){Pd(t,function(t){t&&t.parentNode&&t.parentNode.removeChild(t)})}function ic(t){return Ud((new DOMParser).parseFromString(t,"text/html").body)}function sc(t,e){t.preventDefault(),e&&(t.stopPropagation(),t.stopImmediatePropagation())}function rc(t,e){return t&&t.querySelector(e)}function nc(t,e){return e?vd(t.querySelectorAll(e)):[]}function ac(t,e){Md(t,e,!1)}function oc(t){return t.timeStamp}function lc(t){return Rd(t)?t:t?t+"px":""}var hc="splide",dc="data-"+hc;function cc(t,e){if(!t)throw new Error("["+hc+"] "+(e||""))}var uc=Math.min,fc=Math.max,gc=Math.floor,mc=Math.ceil,pc=Math.abs;function vc(t,e,i){return pc(t-e)<i}function yc(t,e,i,s){var r=uc(e,i),n=fc(e,i);return s?r<t&&t<n:r<=t&&t<=n}function Ec(t,e,i){var s=uc(e,i),r=fc(e,i);return uc(fc(s,t),r)}function Tc(t){return+(t>0)-+(t<0)}function Sc(t,e){return Pd(e,function(e){t=t.replace("%s",""+e)}),t}function bc(t){return t<10?"0"+t:""+t}var Ac={};function Lc(){var t=[];function e(t,e,i){Pd(t,function(t){t&&Pd(e,function(e){e.split(" ").forEach(function(e){var s=e.split(".");i(t,s[0],s[1])})})})}return{bind:function(i,s,r,n){e(i,s,function(e,i,s){var a="addEventListener"in e,o=a?e.removeEventListener.bind(e,i,r,n):e.removeListener.bind(e,r);a?e.addEventListener(i,r,n):e.addListener(r),t.push([e,i,s,r,o])})},unbind:function(i,s,r){e(i,s,function(e,i,s){t=t.filter(function(t){return!!(t[0]!==e||t[1]!==i||t[2]!==s||r&&t[3]!==r)||(t[4](),!1)})})},dispatch:function(t,e,i){var s,r=!0;return"function"==typeof CustomEvent?s=new CustomEvent(e,{bubbles:r,detail:i}):(s=document.createEvent("CustomEvent")).initCustomEvent(e,r,!1,i),t.dispatchEvent(s),s},destroy:function(){t.forEach(function(t){t[4]()}),pd(t)}}}var Ic="mounted",Rc="ready",kc="move",_c="moved",Dc="click",wc="active",Pc="inactive",Cc="visible",xc="hidden",Mc="refresh",Oc="updated",Fc="resize",Nc="resized",$c="scroll",Bc="scrolled",Uc="destroy",Gc="arrows:mounted",Kc="navigation:mounted",Vc="autoplay:play",jc="autoplay:pause",Hc="lazyload:loaded",qc="sk",Yc="sh",Wc="ei";function zc(t){var e=t?t.event.bus:document.createDocumentFragment(),i=Lc();return t&&t.event.on(Uc,i.destroy),Vd(i,{bus:e,on:function(t,s){i.bind(e,wd(t).join(" "),function(t){s.apply(s,Ld(t.detail)?t.detail:[])})},off:yd(i.unbind,e),emit:function(t){i.dispatch(e,t,vd(arguments,1))}})}function Xc(t,e,i,s){var r,n,a=Date.now,o=0,l=!0,h=0;function d(){if(!l){if(o=t?uc((a()-r)/t,1):1,i&&i(o),o>=1&&(e(),r=a(),s&&++h>=s))return c();n=Sd(d)}}function c(){l=!0}function u(){n&&cancelAnimationFrame(n),o=0,n=0,l=!0}return{start:function(e){e||u(),r=a()-(e?o*t:0),l=!1,n=Sd(d)},rewind:function(){r=a(),o=0,i&&i(o)},pause:c,cancel:u,set:function(e){t=e},isPaused:function(){return l}}}var Qc="Arrow",Zc=Qc+"Left",Jc=Qc+"Right",tu=Qc+"Up",eu=Qc+"Down",iu="ttb",su={width:["height"],left:["top","right"],right:["bottom","left"],x:["y"],X:["Y"],Y:["X"],ArrowLeft:[tu,Jc],ArrowRight:[eu,Zc]};var ru="role",nu="tabindex",au="aria-",ou=au+"controls",lu=au+"current",hu=au+"selected",du=au+"label",cu=au+"labelledby",uu=au+"hidden",fu=au+"orientation",gu=au+"roledescription",mu=au+"live",pu=au+"busy",vu=au+"atomic",yu=[ru,nu,"disabled",ou,lu,du,cu,uu,fu,gu],Eu=hc+"__",Tu="is-",Su=hc,bu=Eu+"track",Au=Eu+"list",Lu=Eu+"slide",Iu=Lu+"--clone",Ru=Lu+"__container",ku=Eu+"arrows",_u=Eu+"arrow",Du=_u+"--prev",wu=_u+"--next",Pu=Eu+"pagination",Cu=Pu+"__page",xu=Eu+"progress"+"__bar",Mu=Eu+"toggle",Ou=Eu+"sr",Fu=Tu+"initialized",Nu=Tu+"active",$u=Tu+"prev",Bu=Tu+"next",Uu=Tu+"visible",Gu=Tu+"loading",Ku=Tu+"focus-in",Vu=Tu+"overflow",ju=[Nu,Uu,$u,Bu,Gu,Ku,Vu],Hu={slide:Lu,clone:Iu,arrows:ku,arrow:_u,prev:Du,next:wu,pagination:Pu,page:Cu,spinner:Eu+"spinner"};var qu="touchstart mousedown",Yu="touchmove mousemove",Wu="touchend touchcancel mouseup click";var zu="slide",Xu="loop",Qu="fade";function Zu(t,e,i,s){var r,n=zc(t),a=n.on,o=n.emit,l=n.bind,h=t.Components,d=t.root,c=t.options,u=c.isNavigation,f=c.updateOnMove,g=c.i18n,m=c.pagination,p=c.slideFocus,v=h.Direction.resolve,y=Zd(s,"style"),E=Zd(s,du),T=i>-1,S=Ud(s,"."+Ru);function b(){var r=t.splides.map(function(t){var i=t.splide.Components.Slides.getAt(e);return i?i.slide.id:""}).join(" ");Yd(s,du,Sc(g.slideX,(T?i:e)+1)),Yd(s,ou,r),Yd(s,ru,p?"button":""),p&&qd(s,gu)}function A(){r||L()}function L(){if(!r){var i=t.index;(n=I())!==Jd(s,Nu)&&(Md(s,Nu,n),Yd(s,lu,u&&n||""),o(n?wc:Pc,R)),function(){var e=function(){if(t.is(Qu))return I();var e=tc(h.Elements.track),i=tc(s),r=v("left",!0),n=v("right",!0);return gc(e[r])<=mc(i[r])&&gc(i[n])<=mc(e[n])}(),i=!e&&(!I()||T);t.state.is([4,5])||Yd(s,uu,i||"");Yd(nc(s,c.focusableNodes||""),nu,i?-1:""),p&&Yd(s,nu,i?-1:0);e!==Jd(s,Uu)&&(Md(s,Uu,e),o(e?Cc:xc,R));if(!e&&document.activeElement===s){var r=h.Slides.getAt(t.index);r&&Qd(r.slide)}}(),Md(s,$u,e===i-1),Md(s,Bu,e===i+1)}var n}function I(){var s=t.index;return s===e||c.cloneStatus&&s===i}var R={index:e,slideIndex:i,slide:s,container:S,isClone:T,mount:function(){T||(s.id=d.id+"-slide"+bc(e+1),Yd(s,ru,m?"tabpanel":"group"),Yd(s,gu,g.slide),Yd(s,du,E||Sc(g.slideLabel,[e+1,t.length]))),l(s,"click",yd(o,Dc,R)),l(s,"keydown",yd(o,qc,R)),a([_c,Yc,Bc],L),a(Kc,b),f&&a(kc,A)},destroy:function(){r=!0,n.destroy(),ac(s,ju),qd(s,yu),Yd(s,"style",y),Yd(s,du,E||"")},update:L,style:function(t,e,i){zd(i&&S||s,t,e)},isWithin:function(i,s){var r=pc(i-e);return T||!c.rewind&&!t.is(Xu)||(r=uc(r,t.length-r)),r<=s}};return R}var Ju=dc+"-interval";var tf={passive:!1,capture:!0};var ef={Spacebar:" ",Right:Jc,Left:Zc,Up:tu,Down:eu};function sf(t){return t=Rd(t)?t:t.key,ef[t]||t}var rf="keydown";var nf=dc+"-lazy",af=nf+"-srcset",of="["+nf+"], ["+af+"]";var lf=[" ","Enter"];var hf=Object.freeze({__proto__:null,Media:function(t,e,i){var s=t.state,r=i.breakpoints||{},n=i.reducedMotion||{},a=Lc(),o=[];function l(t){t&&a.destroy()}function h(t,e){var i=matchMedia(e);a.bind(i,"change",d),o.push([t,i])}function d(){var e=s.is(7),r=i.direction,n=o.reduce(function(t,e){return jd(t,e[1].matches?e[0]:{})},{});Hd(i),c(n),i.destroy?t.destroy("completely"===i.destroy):e?(l(!0),t.mount()):r!==i.direction&&t.refresh()}function c(e,r,n){jd(i,e),r&&jd(Object.getPrototypeOf(i),e),!n&&s.is(1)||t.emit(Oc,i)}return{setup:function(){var t="min"===i.mediaQuery;Gd(r).sort(function(e,i){return t?+e-+i:+i-+e}).forEach(function(e){h(r[e],"("+(t?"min":"max")+"-width:"+e+"px)")}),h(n,gd),d()},destroy:l,reduce:function(t){matchMedia(gd).matches&&(t?jd(i,n):Hd(i,Gd(n)))},set:c}},Direction:function(t,e,i){return{resolve:function(t,e,s){var r="rtl"!==(s=s||i.direction)||e?s===iu?0:-1:1;return su[t]&&su[t][r]||t.replace(/width|left|right/i,function(t,e){var i=su[t.toLowerCase()][r]||t;return e>0?i.charAt(0).toUpperCase()+i.slice(1):i})},orient:function(t){return t*("rtl"===i.direction?1:-1)}}},Elements:function(t,e,i){var s,r,n,a=zc(t),o=a.on,l=a.bind,h=t.root,d=i.i18n,c={},u=[],f=[],g=[];function m(){s=y("."+bu),r=Ud(s,"."+Au),cc(s&&r,"A track/list element is missing."),xd(u,Bd(r,"."+Lu+":not(."+Iu+")")),Kd({arrows:ku,pagination:Pu,prev:Du,next:wu,bar:xu,toggle:Mu},function(t,e){c[e]=y("."+t)}),Vd(c,{root:h,track:s,list:r,slides:u}),function(){var t=h.id||(n=hc,""+n+bc(Ac[n]=(Ac[n]||0)+1)),e=i.role;var n;h.id=t,s.id=s.id||t+"-track",r.id=r.id||t+"-list",!Zd(h,ru)&&"SECTION"!==h.tagName&&e&&Yd(h,ru,e);Yd(h,gu,d.carousel),Yd(r,ru,"presentation")}(),v()}function p(t){var e=yu.concat("style");pd(u),ac(h,f),ac(s,g),qd([s,r],e),qd(h,t?e:["style",gu])}function v(){ac(h,f),ac(s,g),f=E(Su),g=E(bu),Od(h,f),Od(s,g),Yd(h,du,i.label),Yd(h,cu,i.labelledby)}function y(t){var e=rc(h,t);return e&&function(t,e){if(Id(t.closest))return t.closest(e);for(var i=t;i&&1===i.nodeType&&!$d(i,e);)i=i.parentElement;return i}(e,"."+Su)===h?e:void 0}function E(t){return[t+"--"+i.type,t+"--"+i.direction,i.drag&&t+"--draggable",i.isNavigation&&t+"--nav",t===Su&&Nu]}return Vd(c,{setup:m,mount:function(){o(Mc,p),o(Mc,m),o(Oc,v),l(document,qu+" keydown",function(t){n="keydown"===t.type},{capture:!0}),l(h,"focusin",function(){Md(h,Ku,!!n)})},destroy:p})},Slides:function(t,e,i){var s=zc(t),r=s.on,n=s.emit,a=s.bind,o=e.Elements,l=o.slides,h=o.list,d=[];function c(){l.forEach(function(t,e){f(t,e,-1)})}function u(){m(function(t){t.destroy()}),pd(d)}function f(e,i,s){var r=Zu(t,i,s,e);r.mount(),d.push(r),d.sort(function(t,e){return t.index-e.index})}function g(t){return t?p(function(t){return!t.isClone}):d}function m(t,e){g(e).forEach(t)}function p(t){return d.filter(Id(t)?t:function(e){return Rd(t)?$d(e.slide,t):Cd(wd(t),e.index)})}return{mount:function(){c(),r(Mc,u),r(Mc,c)},destroy:u,update:function(){m(function(t){t.update()})},register:f,get:g,getIn:function(t){var s=e.Controller,r=s.toIndex(t),n=s.hasFocus()?1:i.perPage;return p(function(t){return yc(t.index,r,r+n-1)})},getAt:function(t){return p(t)[0]},add:function(t,e){Pd(t,function(t){if(Rd(t)&&(t=ic(t)),Dd(t)){var s=l[e];s?Nd(t,s):Fd(h,t),Od(t,i.classes.slide),r=t,o=yd(n,Fc),d=nc(r,"img"),(c=d.length)?d.forEach(function(t){a(t,"load error",function(){--c||o()})}):o()}var r,o,d,c}),n(Mc)},remove:function(t){ec(p(t).map(function(t){return t.slide})),n(Mc)},forEach:m,filter:p,style:function(t,e,i){m(function(s){s.style(t,e,i)})},getLength:function(t){return t?l.length:d.length},isEnough:function(){return d.length>i.perPage}}},Layout:function(t,e,i){var s,r,n,a=zc(t),o=a.on,l=a.bind,h=a.emit,d=e.Slides,c=e.Direction.resolve,u=e.Elements,f=u.root,g=u.track,m=u.list,p=d.getAt,v=d.style;function y(){s=i.direction===iu,zd(f,"maxWidth",lc(i.width)),zd(g,c("paddingLeft"),T(!1)),zd(g,c("paddingRight"),T(!0)),E(!0)}function E(t){var e=tc(f);(t||r.width!==e.width||r.height!==e.height)&&(zd(g,"height",function(){var t="";s&&(cc(t=S(),"height or heightRatio is missing."),t="calc("+t+" - "+T(!1)+" - "+T(!0)+")");return t}()),v(c("marginRight"),lc(i.gap)),v("width",i.autoWidth?null:lc(i.fixedWidth)||(s?"":b())),v("height",lc(i.fixedHeight)||(s?i.autoHeight?null:b():S()),!0),r=e,h(Nc),n!==(n=_())&&(Md(f,Vu,n),h("overflow",n)))}function T(t){var e=i.padding,s=c(t?"right":"left");return e&&lc(e[s]||(Ad(e)?0:e))||"0px"}function S(){return lc(i.height||tc(m).width*i.heightRatio)}function b(){var t=lc(i.gap);return"calc((100%"+(t&&" + "+t)+")/"+(i.perPage||1)+(t&&" - "+t)+")"}function A(){return tc(m)[c("width")]}function L(t,e){var i=p(t||0);return i?tc(i.slide)[c("width")]+(e?0:k()):0}function I(t,e){var i=p(t);if(i){var s=tc(i.slide)[c("right")],r=tc(m)[c("left")];return pc(s-r)+(e?0:k())}return 0}function R(e){return I(t.length-1)-I(0)+L(0,e)}function k(){var t=p(0);return t&&parseFloat(zd(t.slide,c("marginRight")))||0}function _(){return t.is(Qu)||R(!0)>A()}return{mount:function(){var t,e;y(),l(window,"resize load",(t=yd(h,Fc),e=Xc(0,t,null,1),function(){e.isPaused()&&e.start()})),o([Oc,Mc],y),o(Fc,E)},resize:E,listSize:A,slideSize:L,sliderSize:R,totalSize:I,getPadding:function(t){return parseFloat(zd(g,c("padding"+(t?"Right":"Left"))))||0},isOverflow:_}},Clones:function(t,e,i){var s,r=zc(t),n=r.on,a=e.Elements,o=e.Slides,l=e.Direction.resolve,h=[];function d(){n(Mc,c),n([Oc,Fc],f),(s=g())&&(!function(e){var s=o.get().slice(),r=s.length;if(r){for(;s.length<e;)xd(s,s);xd(s.slice(-e),s.slice(0,e)).forEach(function(n,l){var d=l<e,c=function(e,s){var r=e.cloneNode(!0);return Od(r,i.classes.clone),r.id=t.root.id+"-clone"+bc(s+1),r}(n.slide,l);d?Nd(c,s[0].slide):Fd(a.list,c),xd(h,c),o.register(c,l-e+(d?0:r),n.index)})}}(s),e.Layout.resize(!0))}function c(){u(),d()}function u(){ec(h),pd(h),r.destroy()}function f(){var t=g();s!==t&&(s<t||!t)&&r.emit(Mc)}function g(){var s=i.clones;if(t.is(Xu)){if(kd(s)){var r=i[l("fixedWidth")]&&e.Layout.slideSize(0);s=r&&mc(tc(a.track)[l("width")]/r)||i[l("autoWidth")]&&t.length||2*i.perPage}}else s=0;return s}return{mount:d,destroy:u}},Move:function(t,e,i){var s,r=zc(t),n=r.on,a=r.emit,o=t.state.set,l=e.Layout,h=l.slideSize,d=l.getPadding,c=l.totalSize,u=l.listSize,f=l.sliderSize,g=e.Direction,m=g.resolve,p=g.orient,v=e.Elements,y=v.list,E=v.track;function T(){e.Controller.isBusy()||(e.Scroll.cancel(),S(t.index),e.Slides.update())}function S(t){b(R(t,!0))}function b(i,s){if(!t.is(Qu)){var r=s?i:function(i){if(t.is(Xu)){var s=I(i),r=s>e.Controller.getEnd();(s<0||r)&&(i=A(i,r))}return i}(i);zd(y,"transform","translate"+m("X")+"("+r+"px)"),i!==r&&a(Yc)}}function A(t,e){var i=t-_(e),s=f();return t-=p(s*(mc(pc(i)/s)||1))*(e?1:-1)}function L(){b(k(),!0),s.cancel()}function I(t){for(var i=e.Slides.get(),s=0,r=1/0,n=0;n<i.length;n++){var a=i[n].index,o=pc(R(a,!0)-t);if(!(o<=r))break;r=o,s=a}return s}function R(e,s){var r=p(c(e-1)-function(t){var e=i.focus;return"center"===e?(u()-h(t,!0))/2:+e*h(t)||0}(e));return s?function(e){i.trimSpace&&t.is(zu)&&(e=Ec(e,0,p(f(!0)-u())));return e}(r):r}function k(){var t=m("left");return tc(y)[t]-tc(E)[t]+p(d(!1))}function _(t){return R(t?e.Controller.getEnd():0,!!i.trimSpace)}return{mount:function(){s=e.Transition,n([Ic,Nc,Oc,Mc],T)},move:function(t,e,i,r){var n,l;t!==e&&(n=t>i,l=p(A(k(),n)),n?l>=0:l<=y[m("scrollWidth")]-tc(E)[m("width")])&&(L(),b(A(k(),t>i),!0)),o(4),a(kc,e,i,t),s.start(e,function(){o(3),a(_c,e,i,t),r&&r()})},jump:S,translate:b,shift:A,cancel:L,toIndex:I,toPosition:R,getPosition:k,getLimit:_,exceededLimit:function(t,e){e=kd(e)?k():e;var i=!0!==t&&p(e)<p(_(!1)),s=!1!==t&&p(e)>p(_(!0));return i||s},reposition:T}},Controller:function(t,e,i){var s,r,n,a,o=zc(t),l=o.on,h=o.emit,d=e.Move,c=d.getPosition,u=d.getLimit,f=d.toPosition,g=e.Slides,m=g.isEnough,p=g.getLength,v=i.omitEnd,y=t.is(Xu),E=t.is(zu),T=yd(R,!1),S=yd(R,!0),b=i.start||0,A=b;function L(){r=p(!0),n=i.perMove,a=i.perPage,s=D();var t=Ec(b,0,v?s:r-1);t!==b&&(b=t,d.reposition())}function I(){s!==D()&&h(Wc)}function R(t,e){var i=n||(x()?1:a),r=k(b+i*(t?-1:1),b,!(n||x()));return-1===r&&E&&!vc(c(),u(!t),1)?t?0:s:e?r:_(r)}function k(e,o,l){if(m()||x()){var h=function(e){if(E&&"move"===i.trimSpace&&e!==b)for(var s=c();s===f(e,!0)&&yc(e,0,t.length-1,!i.rewind);)e<b?--e:++e;return e}(e);h!==e&&(o=e,e=h,l=!1),e<0||e>s?e=n||!yc(0,e,o,!0)&&!yc(s,o,e,!0)?y?l?e<0?-(r%a||a):r:e:i.rewind?e<0?s:0:-1:w(P(e)):l&&e!==o&&(e=w(P(o)+(e<o?-1:1)))}else e=-1;return e}function _(t){return y?(t+r)%r||0:t}function D(){for(var t=r-(x()||y&&n?1:a);v&&t-- >0;)if(f(r-1,!0)!==f(t,!0)){t++;break}return Ec(t,0,r-1)}function w(t){return Ec(x()?t:a*t,0,s)}function P(t){return x()?uc(t,s):gc((t>=s?r-1:t)/a)}function C(t){t!==b&&(A=b,b=t)}function x(){return!kd(i.focus)||i.isNavigation}function M(){return t.state.is([4,5])&&!!i.waitForTransition}return{mount:function(){L(),l([Oc,Mc,Wc],L),l(Nc,I)},go:function(t,e,i){if(!M()){var r=function(t){var e=b;if(Rd(t)){var i=t.match(/([+\-<>])(\d+)?/)||[],r=i[1],n=i[2];"+"===r||"-"===r?e=k(b+ +(""+r+(+n||1)),b):">"===r?e=n?w(+n):T(!0):"<"===r&&(e=S(!0))}else e=y?t:Ec(t,0,s);return e}(t),n=_(r);n>-1&&(e||n!==b)&&(C(n),d.move(r,n,A,i))}},scroll:function(t,i,r,n){e.Scroll.scroll(t,i,r,function(){var t=_(d.toIndex(c()));C(v?uc(t,s):t),n&&n()})},getNext:T,getPrev:S,getAdjacent:R,getEnd:D,setIndex:C,getIndex:function(t){return t?A:b},toIndex:w,toPage:P,toDest:function(t){var e=d.toIndex(t);return E?Ec(e,0,s):e},hasFocus:x,isBusy:M}},Arrows:function(t,e,i){var s,r,n=zc(t),a=n.on,o=n.bind,l=n.emit,h=i.classes,d=i.i18n,c=e.Elements,u=e.Controller,f=c.arrows,g=c.track,m=f,p=c.prev,v=c.next,y={};function E(){!function(){var t=i.arrows;!t||p&&v||(m=f||Wd("div",h.arrows),p=A(!0),v=A(!1),s=!0,Fd(m,[p,v]),!f&&Nd(m,g));p&&v&&(Vd(y,{prev:p,next:v}),Xd(m,t?"":"none"),Od(m,r=ku+"--"+i.direction),t&&(a([Ic,_c,Mc,Bc,Wc],L),o(v,"click",yd(b,">")),o(p,"click",yd(b,"<")),L(),Yd([p,v],ou,g.id),l(Gc,p,v)))}(),a(Oc,T)}function T(){S(),E()}function S(){n.destroy(),ac(m,r),s?(ec(f?[p,v]:m),p=v=null):qd([p,v],yu)}function b(t){u.go(t,!0)}function A(t){return ic('<button class="'+h.arrow+" "+(t?h.prev:h.next)+'" type="button"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 40 40" width="40" height="40" focusable="false"><path d="'+(i.arrowPath||"m15.5 0.932-4.3 4.38 14.5 14.6-14.5 14.5 4.3 4.4 14.6-14.6 4.4-4.3-4.4-4.4-14.6-14.6z")+'" />')}function L(){if(p&&v){var e=t.index,i=u.getPrev(),s=u.getNext(),r=i>-1&&e<i?d.last:d.prev,n=s>-1&&e>s?d.first:d.next;p.disabled=i<0,v.disabled=s<0,Yd(p,du,r),Yd(v,du,n),l("arrows:updated",p,v,i,s)}}return{arrows:y,mount:E,destroy:S,update:L}},Autoplay:function(t,e,i){var s,r,n=zc(t),a=n.on,o=n.bind,l=n.emit,h=Xc(i.interval,t.go.bind(t,">"),function(t){var e=c.bar;e&&zd(e,"width",100*t+"%"),l("autoplay:playing",t)}),d=h.isPaused,c=e.Elements,u=e.Elements,f=u.root,g=u.toggle,m=i.autoplay,p="pause"===m;function v(){d()&&e.Slides.isEnough()&&(h.start(!i.resetProgress),r=s=p=!1,T(),l(Vc))}function y(t){void 0===t&&(t=!0),p=!!t,T(),d()||(h.pause(),l(jc))}function E(){p||(s||r?y(!1):v())}function T(){g&&(Md(g,Nu,!p),Yd(g,du,i.i18n[p?"play":"pause"]))}function S(t){var s=e.Slides.getAt(t);h.set(s&&+Zd(s.slide,Ju)||i.interval)}return{mount:function(){m&&(!function(){i.pauseOnHover&&o(f,"mouseenter mouseleave",function(t){s="mouseenter"===t.type,E()});i.pauseOnFocus&&o(f,"focusin focusout",function(t){r="focusin"===t.type,E()});g&&o(g,"click",function(){p?v():y(!0)});a([kc,$c,Mc],h.rewind),a(kc,S)}(),g&&Yd(g,ou,c.track.id),p||v(),T())},destroy:h.cancel,play:v,pause:y,isPaused:d}},Cover:function(t,e,i){var s=zc(t).on;function r(t){e.Slides.forEach(function(e){var i=Ud(e.container||e.slide,"img");i&&i.src&&n(t,i,e)})}function n(t,e,i){i.style("background",t?'center/cover no-repeat url("'+e.src+'")':"",!0),Xd(e,t?"none":"")}return{mount:function(){i.cover&&(s(Hc,yd(n,!0)),s([Ic,Oc,Mc],yd(r,!0)))},destroy:yd(r,!1)}},Scroll:function(t,e,i){var s,r,n=zc(t),a=n.on,o=n.emit,l=t.state.set,h=e.Move,d=h.getPosition,c=h.getLimit,u=h.exceededLimit,f=h.translate,g=t.is(zu),m=1;function p(t,i,n,a,c){var f=d();if(E(),n&&(!g||!u())){var p=e.Layout.sliderSize(),T=Tc(t)*p*gc(pc(t)/p)||0;t=h.toPosition(e.Controller.toDest(t%p))+T}var S=vc(f,t,1);m=1,i=S?0:i||fc(pc(t-f)/1.5,800),r=a,s=Xc(i,v,yd(y,f,t,c),1),l(5),o($c),s.start()}function v(){l(3),r&&r(),o(Bc)}function y(t,e,s,n){var a,o,l=d(),h=(t+(e-t)*(a=n,(o=i.easingFunc)?o(a):1-Math.pow(1-a,4))-l)*m;f(l+h),g&&!s&&u()&&(m*=.6,pc(h)<10&&p(c(u(!0)),600,!1,r,!0))}function E(){s&&s.cancel()}function T(){s&&!s.isPaused()&&(E(),v())}return{mount:function(){a(kc,E),a([Oc,Mc],T)},destroy:E,scroll:p,cancel:T}},Drag:function(t,e,i){var s,r,n,a,o,l,h,d,c=zc(t),u=c.on,f=c.emit,g=c.bind,m=c.unbind,p=t.state,v=e.Move,y=e.Scroll,E=e.Controller,T=e.Elements.track,S=e.Media.reduce,b=e.Direction,A=b.resolve,L=b.orient,I=v.getPosition,R=v.exceededLimit,k=!1;function _(){var t=i.drag;B(!t),a="free"===t}function D(t){if(l=!1,!h){var e=$(t);s=t.target,r=i.noDrag,$d(s,"."+Cu+", ."+_u)||r&&$d(s,r)||!e&&t.button||(E.isBusy()?sc(t,!0):(d=e?T:window,o=p.is([4,5]),n=null,g(d,Yu,w,tf),g(d,Wu,P,tf),v.cancel(),y.cancel(),x(t)))}var s,r}function w(e){if(p.is(6)||(p.set(6),f("drag")),e.cancelable)if(o){v.translate(s+M(e)/(k&&t.is(zu)?5:1));var r=O(e)>200,n=k!==(k=R());(r||n)&&x(e),l=!0,f("dragging"),sc(e)}else(function(t){return pc(M(t))>pc(M(t,!0))})(e)&&(o=function(t){var e=i.dragMinThreshold,s=Ad(e),r=s&&e.mouse||0,n=(s?e.touch:+e)||10;return pc(M(t))>($(t)?n:r)}(e),sc(e))}function P(s){p.is(6)&&(p.set(3),f("dragged")),o&&(!function(s){var r=function(e){if(t.is(Xu)||!k){var i=O(e);if(i&&i<200)return M(e)/i}return 0}(s),n=function(t){return I()+Tc(t)*uc(pc(t)*(i.flickPower||600),a?1/0:e.Layout.listSize()*(i.flickMaxPages||1))}(r),o=i.rewind&&i.rewindByDrag;S(!1),a?E.scroll(n,0,i.snap):t.is(Qu)?E.go(L(Tc(r))<0?o?"<":"-":o?">":"+"):t.is(zu)&&k&&o?E.go(R(!0)?">":"<"):E.go(E.toDest(n),!0);S(!0)}(s),sc(s)),m(d,Yu,w),m(d,Wu,P),o=!1}function C(t){!h&&l&&sc(t,!0)}function x(t){n=r,r=t,s=I()}function M(t,e){return N(t,e)-N(F(t),e)}function O(t){return oc(t)-oc(F(t))}function F(t){return r===t&&n||r}function N(t,e){return($(t)?t.changedTouches[0]:t)["page"+A(e?"Y":"X")]}function $(t){return"undefined"!=typeof TouchEvent&&t instanceof TouchEvent}function B(t){h=t}return{mount:function(){g(T,Yu,Td,tf),g(T,Wu,Td,tf),g(T,qu,D,tf),g(T,"click",C,{capture:!0}),g(T,"dragstart",sc),u([Ic,Oc],_)},disable:B,isDragging:function(){return o}}},Keyboard:function(t,e,i){var s,r,n=zc(t),a=n.on,o=n.bind,l=n.unbind,h=t.root,d=e.Direction.resolve;function c(){var t=i.keyboard;t&&(s="global"===t?window:h,o(s,rf,g))}function u(){l(s,rf)}function f(){var t=r;r=!0,Ed(function(){r=t})}function g(e){if(!r){var i=sf(e);i===d(Zc)?t.go("<"):i===d(Jc)&&t.go(">")}}return{mount:function(){c(),a(Oc,u),a(Oc,c),a(kc,f)},destroy:u,disable:function(t){r=t}}},LazyLoad:function(t,e,i){var s=zc(t),r=s.on,n=s.off,a=s.bind,o=s.emit,l="sequential"===i.lazyLoad,h=[_c,Bc],d=[];function c(){pd(d),e.Slides.forEach(function(t){nc(t.slide,of).forEach(function(e){var s=Zd(e,nf),r=Zd(e,af);if(s!==e.src||r!==e.srcset){var n=i.classes.spinner,a=e.parentElement,o=Ud(a,"."+n)||Wd("span",n,a);d.push([e,t,o]),e.src||Xd(e,"none")}})}),l?m():(n(h),r(h,u),u())}function u(){(d=d.filter(function(e){var s=i.perPage*((i.preloadPages||1)+1)-1;return!e[1].isWithin(t.index,s)||f(e)})).length||n(h)}function f(t){var e=t[0];Od(t[1].slide,Gu),a(e,"load error",yd(g,t)),Yd(e,"src",Zd(e,nf)),Yd(e,"srcset",Zd(e,af)),qd(e,nf),qd(e,af)}function g(t,e){var i=t[0],s=t[1];ac(s.slide,Gu),"error"!==e.type&&(ec(t[2]),Xd(i,""),o(Hc,i,s),o(Fc)),l&&m()}function m(){d.length&&f(d.shift())}return{mount:function(){i.lazyLoad&&(c(),r(Mc,c))},destroy:yd(pd,d),check:u}},Pagination:function(t,e,i){var s,r,n=zc(t),a=n.on,o=n.emit,l=n.bind,h=e.Slides,d=e.Elements,c=e.Controller,u=c.hasFocus,f=c.getIndex,g=c.go,m=e.Direction.resolve,p=d.pagination,v=[];function y(){s&&(ec(p?vd(s.children):s),ac(s,r),pd(v),s=null),n.destroy()}function E(t){g(">"+t,!0)}function T(t,e){var i=v.length,s=sf(e),r=S(),n=-1;s===m(Jc,!1,r)?n=++t%i:s===m(Zc,!1,r)?n=(--t+i)%i:"Home"===s?n=0:"End"===s&&(n=i-1);var a=v[n];a&&(Qd(a.button),g(">"+n),sc(e,!0))}function S(){return i.paginationDirection||i.direction}function b(t){return v[c.toPage(t)]}function A(){var t=b(f(!0)),e=b(f());if(t){var i=t.button;ac(i,Nu),qd(i,hu),Yd(i,nu,-1)}if(e){var r=e.button;Od(r,Nu),Yd(r,hu,!0),Yd(r,nu,"")}o("pagination:updated",{list:s,items:v},t,e)}return{items:v,mount:function e(){y(),a([Oc,Mc,Wc],e);var n=i.pagination;p&&Xd(p,n?"":"none"),n&&(a([kc,$c,Bc],A),function(){var e=t.length,n=i.classes,a=i.i18n,o=i.perPage,f=u()?c.getEnd()+1:mc(e/o);Od(s=p||Wd("ul",n.pagination,d.track.parentElement),r=Pu+"--"+S()),Yd(s,ru,"tablist"),Yd(s,du,a.select),Yd(s,fu,S()===iu?"vertical":"");for(var g=0;g<f;g++){var m=Wd("li",null,s),y=Wd("button",{class:n.page,type:"button"},m),b=h.getIn(g).map(function(t){return t.slide.id}),A=!u()&&o>1?a.pageX:a.slideX;l(y,"click",yd(E,g)),i.paginationKeyboard&&l(y,"keydown",yd(T,g)),Yd(m,ru,"presentation"),Yd(y,ru,"tab"),Yd(y,ou,b.join(" ")),Yd(y,du,Sc(A,g+1)),Yd(y,nu,-1),v.push({li:m,button:y,page:g})}}(),A(),o("pagination:mounted",{list:s,items:v},b(t.index)))},destroy:y,getAt:b,update:A}},Sync:function(t,e,i){var s=i.isNavigation,r=i.slideFocus,n=[];function a(){var e,i;t.splides.forEach(function(e){e.isParent||(l(t,e.splide),l(e.splide,t))}),s&&(e=zc(t),(i=e.on)(Dc,d),i(qc,c),i([Ic,Oc],h),n.push(e),e.emit(Kc,t.splides))}function o(){n.forEach(function(t){t.destroy()}),pd(n)}function l(t,e){var i=zc(t);i.on(kc,function(t,i,s){e.go(e.is(Xu)?s:t)}),n.push(i)}function h(){Yd(e.Elements.list,fu,i.direction===iu?"vertical":"")}function d(e){t.go(e.index)}function c(t,e){Cd(lf,sf(e))&&(d(t),sc(e))}return{setup:yd(e.Media.set,{slideFocus:kd(r)?s:r},!0),mount:a,destroy:o,remount:function(){o(),a()}}},Wheel:function(t,e,i){var s=zc(t).bind,r=0;function n(s){if(s.cancelable){var n=s.deltaY,a=n<0,o=oc(s),l=i.wheelMinThreshold||0,h=i.wheelSleep||0;pc(n)>l&&o-r>h&&(t.go(a?"<":">"),r=o),function(s){return!i.releaseWheel||t.state.is(4)||-1!==e.Controller.getAdjacent(s)}(a)&&sc(s)}}return{mount:function(){i.wheel&&s(e.Elements.track,"wheel",n,tf)}}},Live:function(t,e,i){var s=zc(t).on,r=e.Elements.track,n=i.live&&!i.isNavigation,a=Wd("span",Ou),o=Xc(90,yd(l,!1));function l(t){Yd(r,pu,t),t?(Fd(r,a),o.start()):(ec(a),o.cancel())}function h(t){n&&Yd(r,mu,t?"off":"polite")}return{mount:function(){n&&(h(!e.Autoplay.isPaused()),Yd(r,vu,!0),a.textContent="…",s(Vc,yd(h,!0)),s(jc,yd(h,!1)),s([_c,Bc],yd(l,!0)))},disable:h,destroy:function(){qd(r,[mu,vu,pu]),ec(a)}}}}),df={type:"slide",role:"region",speed:400,perPage:1,cloneStatus:!0,arrows:!0,pagination:!0,paginationKeyboard:!0,interval:5e3,pauseOnHover:!0,pauseOnFocus:!0,resetProgress:!0,easing:"cubic-bezier(0.25, 1, 0.5, 1)",drag:!0,direction:"ltr",trimSpace:!0,focusableNodes:"a, button, textarea, input, select, iframe",live:!0,classes:Hu,i18n:{prev:"Previous slide",next:"Next slide",first:"Go to first slide",last:"Go to last slide",slideX:"Go to slide %s",pageX:"Go to page %s",play:"Start autoplay",pause:"Pause autoplay",carousel:"carousel",slide:"slide",select:"Select a slide to show",slideLabel:"%s of %s"},reducedMotion:{speed:0,rewindSpeed:0,autoplay:"pause"}};function cf(t,e,i){var s=e.Slides;function r(){s.forEach(function(t){t.style("transform","translateX(-"+100*t.index+"%)")})}return{mount:function(){zc(t).on([Ic,Mc],r)},start:function(t,e){s.style("transition","opacity "+i.speed+"ms "+i.easing),Ed(e)},cancel:Td}}function uf(t,e,i){var s,r=e.Move,n=e.Controller,a=e.Scroll,o=e.Elements.list,l=yd(zd,o,"transition");function h(){l(""),a.cancel()}return{mount:function(){zc(t).bind(o,"transitionend",function(t){t.target===o&&s&&(h(),s())})},start:function(e,o){var h=r.toPosition(e,!0),d=r.getPosition(),c=function(e){var s=i.rewindSpeed;if(t.is(zu)&&s){var r=n.getIndex(!0),a=n.getEnd();if(0===r&&e>=a||r>=a&&0===e)return s}return i.speed}(e);pc(h-d)>=1&&c>=1?i.useScroll?a.scroll(h,c,!1,o):(l("transform "+c+"ms "+i.easing),r.translate(h,!0),s=o):(r.jump(e),o())},cancel:h}}var ff=function(){function t(e,i){var s;this.event=zc(),this.Components={},this.state=(s=1,{set:function(t){s=t},is:function(t){return Cd(wd(t),s)}}),this.splides=[],this._o={},this._E={};var r=Rd(e)?rc(document,e):e;cc(r,r+" is invalid."),this.root=r,i=jd({label:Zd(r,du)||"",labelledby:Zd(r,cu)||""},df,t.defaults,i||{});try{jd(i,JSON.parse(Zd(r,dc)))}catch(t){cc(!1,"Invalid JSON")}this._o=Object.create(jd({},i))}var e=t.prototype;return e.mount=function(t,e){var i=this,s=this.state,r=this.Components;return cc(s.is([1,7]),"Already mounted!"),s.set(1),this._C=r,this._T=e||this._T||(this.is(Qu)?cf:uf),this._E=t||this._E,Kd(Vd({},hf,this._E,{Transition:this._T}),function(t,e){var s=t(i,r,i._o);r[e]=s,s.setup&&s.setup()}),Kd(r,function(t){t.mount&&t.mount()}),this.emit(Ic),Od(this.root,Fu),s.set(3),this.emit(Rc),this},e.sync=function(t){return this.splides.push({splide:t}),t.splides.push({splide:this,isParent:!0}),this.state.is(3)&&(this._C.Sync.remount(),t.Components.Sync.remount()),this},e.go=function(t){return this._C.Controller.go(t),this},e.on=function(t,e){return this.event.on(t,e),this},e.off=function(t){return this.event.off(t),this},e.emit=function(t){var e;return(e=this.event).emit.apply(e,[t].concat(vd(arguments,1))),this},e.add=function(t,e){return this._C.Slides.add(t,e),this},e.remove=function(t){return this._C.Slides.remove(t),this},e.is=function(t){return this._o.type===t},e.refresh=function(){return this.emit(Mc),this},e.destroy=function(t){void 0===t&&(t=!0);var e=this.event,i=this.state;return i.is(1)?zc(this).on(Rc,this.destroy.bind(this,t)):(Kd(this._C,function(e){e.destroy&&e.destroy(t)},!0),e.emit(Uc),e.destroy(),t&&pd(this.splides),i.set(7)),this},fd(t,[{key:"options",get:function(){return this._o},set:function(t){this._C.Media.set(t,!0,!0)}},{key:"length",get:function(){return this._C.Slides.getLength(!0)}},{key:"index",get:function(){return this._C.Controller.getIndex()}}]),t}(),gf=ff;gf.defaults={},gf.STATES=md;class mf extends HTMLElement{static get observedAttributes(){return["collection-id","api-key","client-id","subscription-id","base-url","autoplay","show-arrows","show-dots","video-settings"]}constructor(){super(),this.splide=null,this.container=null,this.carouselElement=null,this.clientInstance=null,this.connected=!1,this.collectionData=null,this.autoplayTimeoutId=null,this.attachShadow({mode:"open"})}connectedCallback(){this.connected=!0,this.render(),this.initCarousel()}disconnectedCallback(){this.connected=!1,this.destroyCarousel()}attributeChangedCallback(t,e,i){this.connected&&e!==i&&("collection-id"!==t&&"video-settings"!==t||(this.destroyCarousel(),this.initCarousel()),"show-arrows"!==t&&"show-dots"!==t||(this.destroyCarousel(),this.initCarousel()))}getBooleanAttr(t,e){const i=this.getAttribute(t);return null===i?e:"false"!==i}getVideosFromCollection(t){if(t.videos&&t.videos.length>0)return t.videos;if(t.videoGroups&&t.videoGroups.length>0){const e=[];return t.videoGroups.forEach(t=>{t.videos&&t.videos.length>0&&e.push(...t.videos)}),e}return[]}render(){if(!this.shadowRoot)return;const t=document.createElement("style");t.textContent=`\n ${dd}\n .jaaq-collection-player {\n width: 100%;\n max-width: 1400px;\n margin: 0 auto;\n font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, sans-serif;\n}\n\n.jaaq-collection-loading {\n display: flex;\n justify-content: center;\n align-items: center;\n min-height: 400px;\n}\n\n.jaaq-collection-spinner {\n width: 50px;\n height: 50px;\n border: 4px solid rgba(0, 123, 255, 0.3);\n border-top-color: #007bff;\n border-radius: 50%;\n animation: jaaq-collection-spin 1s linear infinite;\n}\n\n@keyframes jaaq-collection-spin {\n to {\n transform: rotate(360deg);\n }\n}\n\n.jaaq-collection-error {\n background: rgba(220, 53, 69, 0.9);\n color: white;\n padding: 16px 24px;\n border-radius: 8px;\n text-align: center;\n font-size: 14px;\n margin: 20px;\n}\n\n.jaaq-collection-carousel .splide__track {\n padding: 40px 0;\n}\n\n.jaaq-collection-carousel .splide__slide {\n opacity: 0.7;\n transition: all 0.3s ease;\n display: flex;\n align-items: center;\n justify-content: center;\n}\n\n.jaaq-collection-carousel .splide__slide.is-active {\n opacity: 1;\n}\n\n.jaaq-collection-carousel .splide__slide jaaq-video-player {\n width: 100%;\n max-width: 600px;\n transition: all 0.3s ease;\n}\n\n.jaaq-collection-carousel .splide__slide.is-active jaaq-video-player {\n max-width: 800px;\n}\n\n.jaaq-collection-carousel .splide__arrow {\n background: rgba(0, 0, 0, 0.5);\n border: none;\n width: 48px;\n height: 48px;\n border-radius: 50%;\n color: white;\n cursor: pointer;\n transition: all 0.2s;\n display: flex;\n align-items: center;\n justify-content: center;\n font-size: 20px;\n}\n\n.jaaq-collection-carousel .splide__arrow:hover {\n background: rgba(0, 0, 0, 0.8);\n transform: scale(1.1);\n}\n\n.jaaq-collection-carousel .splide__arrow:disabled {\n opacity: 0.3;\n cursor: not-allowed;\n}\n\n.jaaq-collection-carousel .splide__arrow svg {\n fill: white;\n width: 20px;\n height: 20px;\n}\n\n.jaaq-collection-carousel .splide__pagination {\n bottom: -30px;\n}\n\n.jaaq-collection-carousel .splide__pagination__page {\n background: #ccc;\n border: none;\n width: 10px;\n height: 10px;\n margin: 0 4px;\n border-radius: 50%;\n transition: all 0.2s;\n cursor: pointer;\n}\n\n.jaaq-collection-carousel .splide__pagination__page.is-active {\n background: white;\n transform: scale(1.3);\n}\n\n@media (max-width: 1024px) {\n .jaaq-collection-carousel .splide__slide jaaq-video-player {\n max-width: 500px;\n }\n\n .jaaq-collection-carousel .splide__slide.is-active jaaq-video-player {\n max-width: 650px;\n }\n}\n\n@media (max-width: 768px) {\n .jaaq-collection-carousel .splide__track {\n padding: 20px 0;\n }\n\n .jaaq-collection-carousel .splide__slide jaaq-video-player {\n max-width: 400px;\n }\n\n .jaaq-collection-carousel .splide__slide.is-active jaaq-video-player {\n max-width: 500px;\n }\n\n .jaaq-collection-carousel .splide__arrow {\n width: 40px;\n height: 40px;\n }\n}\n\n@media (max-width: 480px) {\n .jaaq-collection-carousel .splide__slide jaaq-video-player {\n max-width: 100%;\n }\n\n .jaaq-collection-carousel .splide__slide.is-active jaaq-video-player {\n max-width: 100%;\n }\n}\n\n .splide__container{box-sizing:border-box;position:relative}.splide__list{backface-visibility:hidden;display:-ms-flexbox;display:flex;height:100%;margin:0!important;padding:0!important}.splide.is-initialized:not(.is-active) .splide__list{display:block}.splide__pagination{-ms-flex-align:center;align-items:center;display:-ms-flexbox;display:flex;-ms-flex-wrap:wrap;flex-wrap:wrap;-ms-flex-pack:center;justify-content:center;margin:0;pointer-events:none}.splide__pagination li{display:inline-block;line-height:1;list-style-type:none;margin:0;pointer-events:auto}.splide:not(.is-overflow) .splide__pagination{display:none}.splide__progress__bar{width:0}.splide{position:relative;visibility:hidden}.splide.is-initialized,.splide.is-rendered{visibility:visible}.splide__slide{backface-visibility:hidden;box-sizing:border-box;-ms-flex-negative:0;flex-shrink:0;list-style-type:none!important;margin:0;position:relative}.splide__slide img{vertical-align:bottom}.splide__spinner{animation:splide-loading 1s linear infinite;border:2px solid #999;border-left-color:transparent;border-radius:50%;bottom:0;contain:strict;display:inline-block;height:20px;left:0;margin:auto;position:absolute;right:0;top:0;width:20px}.splide__sr{clip:rect(0 0 0 0);border:0;height:1px;margin:-1px;overflow:hidden;padding:0;position:absolute;width:1px}.splide__toggle.is-active .splide__toggle__play,.splide__toggle__pause{display:none}.splide__toggle.is-active .splide__toggle__pause{display:inline}.splide__track{overflow:hidden;position:relative;z-index:0}@keyframes splide-loading{0%{transform:rotate(0)}to{transform:rotate(1turn)}}.splide__track--draggable{-webkit-touch-callout:none;-webkit-user-select:none;-ms-user-select:none;user-select:none}.splide__track--fade>.splide__list>.splide__slide{margin:0!important;opacity:0;z-index:0}.splide__track--fade>.splide__list>.splide__slide.is-active{opacity:1;z-index:1}.splide--rtl{direction:rtl}.splide__track--ttb>.splide__list{display:block}.splide__arrow{-ms-flex-align:center;align-items:center;background:#ccc;border:0;border-radius:50%;cursor:pointer;display:-ms-flexbox;display:flex;height:2em;-ms-flex-pack:center;justify-content:center;opacity:.7;padding:0;position:absolute;top:50%;transform:translateY(-50%);width:2em;z-index:1}.splide__arrow svg{fill:#000;height:1.2em;width:1.2em}.splide__arrow:hover:not(:disabled){opacity:.9}.splide__arrow:disabled{opacity:.3}.splide__arrow:focus-visible{outline:3px solid #0bf;outline-offset:3px}.splide__arrow--prev{left:1em}.splide__arrow--prev svg{transform:scaleX(-1)}.splide__arrow--next{right:1em}.splide.is-focus-in .splide__arrow:focus{outline:3px solid #0bf;outline-offset:3px}.splide__pagination{bottom:.5em;left:0;padding:0 1em;position:absolute;right:0;z-index:1}.splide__pagination__page{background:#ccc;border:0;border-radius:50%;display:inline-block;height:8px;margin:3px;opacity:.7;padding:0;position:relative;transition:transform .2s linear;width:8px}.splide__pagination__page.is-active{background:#fff;transform:scale(1.4);z-index:1}.splide__pagination__page:hover{cursor:pointer;opacity:.9}.splide__pagination__page:focus-visible{outline:3px solid #0bf;outline-offset:3px}.splide.is-focus-in .splide__pagination__page:focus{outline:3px solid #0bf;outline-offset:3px}.splide__progress__bar{background:#ccc;height:3px}.splide__slide{-webkit-tap-highlight-color:rgba(0,0,0,0)}.splide__slide:focus{outline:0}@supports(outline-offset:-3px){.splide__slide:focus-visible{outline:3px solid #0bf;outline-offset:-3px}}@media screen and (-ms-high-contrast:none){.splide__slide:focus-visible{border:3px solid #0bf}}@supports(outline-offset:-3px){.splide.is-focus-in .splide__slide:focus{outline:3px solid #0bf;outline-offset:-3px}}@media screen and (-ms-high-contrast:none){.splide.is-focus-in .splide__slide:focus{border:3px solid #0bf}.splide.is-focus-in .splide__track>.splide__list>.splide__slide:focus{border-color:#0bf}}.splide__toggle{cursor:pointer}.splide__toggle:focus-visible{outline:3px solid #0bf;outline-offset:3px}.splide.is-focus-in .splide__toggle:focus{outline:3px solid #0bf;outline-offset:3px}.splide__track--nav>.splide__list>.splide__slide{border:3px solid transparent;cursor:pointer}.splide__track--nav>.splide__list>.splide__slide.is-active{border:3px solid #000}.splide__arrows--rtl .splide__arrow--prev{left:auto;right:1em}.splide__arrows--rtl .splide__arrow--prev svg{transform:scaleX(1)}.splide__arrows--rtl .splide__arrow--next{left:1em;right:auto}.splide__arrows--rtl .splide__arrow--next svg{transform:scaleX(-1)}.splide__arrows--ttb .splide__arrow{left:50%;transform:translate(-50%)}.splide__arrows--ttb .splide__arrow--prev{top:1em}.splide__arrows--ttb .splide__arrow--prev svg{transform:rotate(-90deg)}.splide__arrows--ttb .splide__arrow--next{bottom:1em;top:auto}.splide__arrows--ttb .splide__arrow--next svg{transform:rotate(90deg)}.splide__pagination--ttb{bottom:0;display:-ms-flexbox;display:flex;-ms-flex-direction:column;flex-direction:column;left:auto;padding:1em 0;right:.5em;top:0}\n \n:host {\n display: block;\n width: 100%;\n}\n\n:host([hidden]) {\n display: none;\n}\n\n `,this.container=document.createElement("div"),this.container.className="jaaq-collection-player",this.shadowRoot.appendChild(t),this.shadowRoot.appendChild(this.container)}async initCarousel(){if(!this.container)return;const t=this.getAttribute("collection-id");if(!t)return void this.emitError(new Error("collection-id attribute is required"));const e=this.getAttribute("api-key"),i=this.getAttribute("client-id"),s=this.getAttribute("base-url")||void 0,r=this.getAttribute("api-version")||void 0;if(this.clientInstance||e||i){this.showLoading();try{const n=this.clientInstance||od.init({apiKey:e,clientId:i,baseUrl:s||ad,apiVersion:r});this.collectionData=await n.collections.getById(t);if(0===this.getVideosFromCollection(this.collectionData).length)return void this.emitError(new Error("No videos found in collection"));this.renderCarousel(),this.initSplide(),this.dispatchEvent(new CustomEvent("jaaq:collection:loaded",{detail:this.collectionData,bubbles:!0,composed:!0}))}catch(t){this.emitError(t instanceof Error?t:new Error("Failed to load collection"))}}else this.emitError(new Error("Either client property or api-key and client-id attributes are required"))}showLoading(){this.container&&(this.container.innerHTML='\n <div class="jaaq-collection-loading">\n <div class="jaaq-collection-spinner"></div>\n </div>\n ')}renderCarousel(){if(!this.container||!this.collectionData)return;this.container.innerHTML="",this.carouselElement=document.createElement("div"),this.carouselElement.className="splide jaaq-collection-carousel";const t=document.createElement("div");t.className="splide__track";const e=document.createElement("ul");e.className="splide__list";const i=this.getAttribute("api-key"),s=this.getAttribute("client-id"),r=this.getAttribute("base-url"),n=this.getAttribute("video-settings");let a=null;if(n)try{a=JSON.parse(n)}catch(t){console.warn("[CollectionPlayer] Failed to parse video-settings attribute",t)}this.getVideosFromCollection(this.collectionData).forEach(t=>{const n=document.createElement("li");n.className="splide__slide";const o=document.createElement("jaaq-video-player");o.setAttribute("video-id",t.videoId),i&&o.setAttribute("api-key",i),s&&o.setAttribute("client-id",s),r&&o.setAttribute("base-url",r),o.setAttribute("autoplay","false"),o.setAttribute("width","100%"),a&&(void 0!==a.controls&&o.setAttribute("controls",String(a.controls)),void 0!==a.showLogo&&o.setAttribute("show-logo",String(a.showLogo)),void 0!==a.showTitle&&o.setAttribute("show-title",String(a.showTitle)),void 0!==a.showAuthor&&o.setAttribute("show-author",String(a.showAuthor)),void 0!==a.showDescription&&o.setAttribute("show-description",String(a.showDescription)),void 0!==a.showCaptions&&o.setAttribute("show-captions",String(a.showCaptions)),void 0!==a.startMuted&&o.setAttribute("start-muted",String(a.startMuted)),void 0!==a.width&&o.setAttribute("width",String(a.width)),void 0!==a.height&&o.setAttribute("height",String(a.height))),n.appendChild(o),e.appendChild(n)}),t.appendChild(e),this.carouselElement.appendChild(t),this.container.appendChild(this.carouselElement)}initSplide(){if(!this.carouselElement)return;const t=this.getBooleanAttr("show-arrows",!0),e=this.getBooleanAttr("show-dots",!0);this.splide=new gf(this.carouselElement,{type:"loop",perPage:3,focus:"center",gap:"0.5rem",perMove:1,autoHeight:!0,updateOnMove:!0,padding:"5 rem",breakpoints:{768:{perPage:1},1024:{perPage:2}},arrows:t,pagination:e,autoplay:!1}),this.splide.on("moved",t=>{console.log("[CollectionPlayer] Splide moved event",{newIndex:t,splideIndex:this.splide?.index,Components:this.splide?.Components}),this.handleSlideChange(t);const e=this.collectionData?this.getVideosFromCollection(this.collectionData):[];this.dispatchEvent(new CustomEvent("jaaq:collection:slidechange",{detail:{index:t,video:e[t]},bubbles:!0,composed:!0}))}),this.splide.mount(),console.log("[CollectionPlayer] After mount",{splideIndex:this.splide.index,length:this.splide.length}),setTimeout(()=>{this.splide&&(console.log("[CollectionPlayer] Initial handleSlideChange after DOM update"),this.handleSlideChange(this.splide.index))},100)}handleSlideChange(t){if(!this.carouselElement)return;const e=this.hasAttribute("autoplay")&&"false"!==this.getAttribute("autoplay");console.log("[CollectionPlayer] handleSlideChange called",{activeIndex:t,isAutoplayEnabled:e}),null!==this.autoplayTimeoutId&&(console.log("[CollectionPlayer] Clearing existing autoplay timeout",{timeoutId:this.autoplayTimeoutId}),clearTimeout(this.autoplayTimeoutId),this.autoplayTimeoutId=null);const i=this.carouselElement.querySelector(".splide__slide.is-active:not(.splide__slide--clone)"),s=i?.querySelector("jaaq-video-player"),r=s?.getAttribute("video-id");console.log("[CollectionPlayer] Active slide from DOM:",{activeIndex:t,activeVideoId:r,foundActiveSlide:!!i});const n=this.carouselElement.querySelectorAll(".splide__slide:not(.splide__slide--clone)");Array.from(n).map((t,e)=>{const i=t.querySelector("jaaq-video-player");return{index:e,videoId:i?.getAttribute("video-id")||"unknown",isActive:t.classList.contains("is-active")}}),n.forEach((t,i)=>{const s=t.querySelector("jaaq-video-player");if(!s)return;const r=s.getAttribute("video-id");t.classList.contains("is-active")?e&&(this.autoplayTimeoutId=window.setTimeout(()=>{console.log("[CollectionPlayer] 1s delay complete, playing video",{index:i,videoId:r}),s.play?.()},1e3)):s.pause?.()})}destroyCarousel(){null!==this.autoplayTimeoutId&&(clearTimeout(this.autoplayTimeoutId),this.autoplayTimeoutId=null),this.splide&&(this.splide.destroy(),this.splide=null),this.container&&(this.container.innerHTML=""),this.collectionData=null}emitError(t){this.container&&(this.container.innerHTML=`\n <div class="jaaq-collection-error">\n ${t.message}\n </div>\n `),this.dispatchEvent(new CustomEvent("jaaq:collection:error",{detail:t,bubbles:!0,composed:!0}))}get client(){return this.clientInstance}set client(t){this.clientInstance=t,this.connected&&(this.destroyCarousel(),this.initCarousel())}get collectionId(){return this.getAttribute("collection-id")}set collectionId(t){t?this.setAttribute("collection-id",t):this.removeAttribute("collection-id")}refresh(){this.destroyCarousel(),this.initCarousel()}next(){this.splide?.go("+1")}prev(){this.splide?.go("-1")}go(t){this.splide?.go(t)}destroy(){this.destroyCarousel()}getCollection(){return this.collectionData}}const pf="jaaq-video-player",vf="jaaq-collection-player";function yf(){"undefined"!=typeof window&&"undefined"!=typeof customElements?(customElements.get(pf)||customElements.define(pf,ud),customElements.get(vf)||customElements.define(vf,mf)):console.warn("Custom Elements API is not available. Web components cannot be registered.")}"undefined"!=typeof window&&"undefined"!=typeof document&&("loading"===document.readyState?document.addEventListener("DOMContentLoaded",()=>{yf()}):yf()),t.JaaqCollectionPlayerElement=mf,t.JaaqVideoPlayerElement=ud,t.isRegistered=function(){return"undefined"!=typeof window&&"undefined"!=typeof customElements&&(!!customElements.get(pf)&&!!customElements.get(vf))},t.registerJaaqComponents=yf});
8
8
  //# sourceMappingURL=jaaq-webcomponents-bundled.min.js.map