@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).JaaqVanilla={})}(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 n=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}({}),r=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,d={exports:{}};var h=(l||(l=1,function(t){var e,i,s,n,r;e=/^(?=((?:[a-zA-Z0-9+\-.]+:)?))\1(?=((?:\/\/[^\/?#]*)?))\2(?=((?:(?:[^?#\/]*\/)*[^;?#\/]*)?))\3((?:;[^?#]*)?)(\?[^#]*)?(#[^]*)?$/,i=/^(?=([^\/?#]*))\1([^]*)$/,s=/(?:\/|^)\.(?=\/)/g,n=/(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g,r={buildAbsoluteURL:function(t,e,s){if(s=s||{},t=t.trim(),!(e=e.trim())){if(!s.alwaysNormalize)return t;var n=r.parseURL(t);if(!n)throw new Error("Error trying to parse base URL.");return n.path=r.normalizePath(n.path),r.buildURLFromParts(n)}var a=r.parseURL(e);if(!a)throw new Error("Error trying to parse relative URL.");if(a.scheme)return s.alwaysNormalize?(a.path=r.normalizePath(a.path),r.buildURLFromParts(a)):e;var o=r.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 d={scheme:o.scheme,netLoc:a.netLoc,path:null,params:a.params,query:a.query,fragment:a.fragment};if(!a.netLoc&&(d.netLoc=o.netLoc,"/"!==a.path[0]))if(a.path){var h=o.path,c=h.substring(0,h.lastIndexOf("/")+1)+a.path;d.path=r.normalizePath(c)}else d.path=o.path,a.params||(d.params=o.params,a.query||(d.query=o.query));return null===d.path&&(d.path=s.alwaysNormalize?r.normalizePath(a.path):a.path),r.buildURLFromParts(d)},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(n,"")).length;);return t.split("").reverse().join("")},buildURLFromParts:function(t){return t.scheme+t.netLoc+t.path+t.params+t.query+t.fragment}},t.exports=r}(d)),d.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",p="video",m="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,[p]:null,[m]: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=h.buildAbsoluteURL(this.baseurl,this.relurl,{alwaysNormalize:!0})),this._url||""}set url(t){this._url=t}clearElementaryStreamInfo(){const{elementaryStreams:t}=this;t[g]=null,t[p]=null,t[m]=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,n,r=!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,n)):a[t]={startPTS:e,endPTS:i,startDTS:s,endDTS:n,partial:r}}}class b extends v{constructor(t,e,i,s,n){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 r=t.enumeratedString("BYTERANGE");r&&this.setByteRange(r,n),n&&(this.fragOffset=n.fragOffset+n.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 _(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 k(t,e){if(null==t)return{};var i,s,n=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 r=Object.getOwnPropertySymbols(t);for(s=0;s<r.length;s++)i=r[s],-1===e.indexOf(i)&&{}.propertyIsEnumerable.call(t,i)&&(n[i]=t[i])}return n}function w(t){switch(t.details){case r.FRAG_LOAD_TIMEOUT:case r.KEY_LOAD_TIMEOUT:case r.LEVEL_LOAD_TIMEOUT:case r.MANIFEST_LOAD_TIMEOUT:case r.AUDIO_TRACK_LOAD_TIMEOUT:case r.SUBTITLE_TRACK_LOAD_TIMEOUT:case r.ASSET_LIST_LOAD_TIMEOUT:return!0}return!1}function D(t){return t.details.startsWith("key")}function x(t){return D(t)&&!!t.frag&&!t.frag.decryptdata}function P(t,e){const i=w(e);return t.default[(i?"timeout":"error")+"Retry"]}function C(t,e){const i="linear"===t.backoff?1:Math.pow(2,e);return Math.min(i*t.retryDelayMs,t.maxRetryDelayMs)}function M(t){return _(_({},t),{errorRetry:null,timeoutRetry:null})}function O(t,e,i,s){if(!t)return!1;const n=null==s?void 0:s.code,r=e<t.maxNumRetry&&(function(t){return F(t)||!!t&&(t<400||t>499)}(n)||!!i);return t.shouldRetry?t.shouldRetry(t,e,i,s,r):r}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 B{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 ${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 B(t),this.fast_=new B(e),this.defaultTTFB_=s,this.ttfb_=new B(t)}update(t,e){const{slow_:i,fast_:s,ttfb_:n}=this;i.halfLife!==t&&(this.slow_=new B(t,i.getEstimate(),i.getTotalWeight())),s.halfLife!==e&&(this.fast_=new B(e,s.getEstimate(),s.getTotalWeight())),n.halfLife!==t&&(this.ttfb_=new B(t,n.getEstimate(),n.getTotalWeight()))}sample(t,e){if(e<=0)return;const i=Math.min(this.minDelayMs_,e/1e5),s=8*e,n=Math.max(t,i)/1e3,r=s/n;this.fast_.sample(n,r),this.slow_.sample(n,r)}sampleTTFB(t){const e=t/1e3,i=Math.sqrt(2)*Math.exp(-Math.pow(e,2)/2);this.ttfb_.sample(i,Math.max(t,5))}canEstimate(){return this.fast_.getTotalWeight()>=this.minWeight_}getEstimate(){return this.canEstimate()?Math.min(this.fast_.getEstimate(),this.slow_.getEstimate()):this.defaultEstimate_}getEstimateTTFB(){return this.ttfb_.getTotalWeight()>=this.minWeight_?this.ttfb_.getEstimate():this.defaultTTFB_}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(){},j={trace:G,debug:G,log:G,warn:G,info:G,error:G};function q(){return I({},j)}function K(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 V=q();const H=V;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),n=i.length,r=s.length;return!n||!r||n===r&&!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 nt(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 rt(t,e){const i=e;let s=0;for(;et(t,e);){s+=10;s+=it(t,e+6),nt(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 n=(r=t,z(r)?r:r.buffer);var r;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,d=(o+e)/a,h=Math.floor(Math.max(0,Math.min(d,l)));var c;return new s(n,h,Math.floor(Math.min(h+Math.max(i,0),l))-h)}(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:n}=e;if(!n){const t=i.getUint8(0),e=i.getUint8(1);239==t&&187==e&&191==i.getUint8(2)?(n=Z,s=3):254==t&&255==e?(n=X,s=2):255==t&&254==e?(n=Q,s=2):n=Z}if("undefined"!=typeof TextDecoder)return new TextDecoder(n).decode(i);const{byteLength:r}=i,a=n!==X;let o,l="";for(;s<r;){switch(n){case Z:if(o=i.getUint8(s),o<128)s++;else if(o>=194&&o<=223)if(s+1<r){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<=r-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<=r-1){const t=i.getUint8(s+1),e=i.getUint8(s+2),n=i.getUint8(s+3);t>=128&&t<=191&&e>=128&&e<=191&&n>=128&&n<=191?(o=(7&o)<<18|(63&t)<<12|(63&e)<<6|63&n,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)),n=t.data[2+i],r=t.data.subarray(3+i).indexOf(0);if(-1===r)return;const a=ot(at(t.data,3+i,r));let o;var l;return"--\x3e"===s?o=ot(at(t.data,4+i+r)):o=z(l=t.data.subarray(4+i+r))?l:0==l.byteOffset&&l.byteLength==l.buffer.byteLength?l.buffer:new Uint8Array(l).buffer,e.mimeType=s,e.pictureType=n,e.description=a,e.data=o,e}function dt(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 n=ot(i.subarray(e));return{key:t.type,info:s,data:n}}const e=ot(t.data.subarray(1));return{key:t.type,info:"",data:e}}(t)}function ht(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 n=e+s;for(;e+10<n;){const s=ht(t.subarray(e)),n=dt(s);n&&i.push(n),e+=s.size+10}nt(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 pt(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 mt(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 _t(t,e,i){t[e]=i>>24,t[e+1]=i>>16&255,t[e+2]=i>>8&255,t[e+3]=255&i}function kt(t,e,i){const s=e.byteOffset-t.byteOffset-8,n=8+i,r=e.byteLength+8-n;r<8||(_t(t,s,n),_t(t,s+n,r),_t(t,s+n+4,Tt.free))}function wt(t,e){return[t.byteOffset-e-8,t.byteOffset-e+t.byteLength]}function Dt(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 n=0,r=0;for(let i=0;i<e.length;i++){const[a,o]=e[i];s.set(t.subarray(n,a),r),r+=a-n,n=o}s.set(t.subarray(n),r);return{result:s,dropped:i,droppedBefore:t=>e.reduce((e,[i,s])=>s<=t?e+s-i:e,0)}}function xt(t,e){const i=[];return e.length?(Pt(t,e,0,0,t.byteLength,i),i):i}function Pt(t,e,i,s,n,r){const a=e[i];if(4!==(null==a?void 0:a.length))return;const o=a.charCodeAt(0),l=a.charCodeAt(1),d=a.charCodeAt(2),h=a.charCodeAt(3),c=e.length-1;for(let a=s;a<n;){const s=a+8<=n,u=a+4<=n?16777216*t[a]+(t[a+1]<<16|t[a+2]<<8|t[a+3]):At(t,a),f=u>1?a+u:n;if(s&&t[a+4]===o&&t[a+5]===l&&t[a+6]===d&&t[a+7]===h){const s=Math.min(f,n);i===c?r.push(t.subarray(a+8,s)):Pt(t,e,i+1,a+8,s,r)}a=f}}function Ct(t){const e=[],i=t[0];let s=8;const n=At(t,s);s+=4;let r=0,a=0;0===i?(r=At(t,s),a=At(t,s+4),s+=8):(r=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 r=At(t,i);i+=4;const a=2147483647&r;if(1===(2147483648&r)>>>31)return H.warn("SIDX has hierarchical references (not supported)"),null;const l=At(t,i);i+=4,e.push({referenceSize:a,subsegmentDuration:l,info:{duration:l/n,start:o,end:o+a-1}}),o+=a,i+=4,s=i}return{earliestPresentationTime:r,timescale:n,version:i,referencesCount:l,references:e}}function Mt(t){const e=[],i=xt(t,["moov","trak"]);for(let t=0;t<i.length;t++){const s=i[t],n=xt(s,["tkhd"])[0];if(n){let t=n[0];const i=At(n,0===t?12:20),r=xt(s,["mdia","mdhd"])[0];if(r){t=r[0];const n=At(r,0===t?12:20),a=xt(s,["mdia","hdlr"])[0];if(a){const t=yt(a.subarray(8,12)),r={soun:g,vide:p}[t],o=Ot(xt(s,["mdia","minf","stbl","stsd"])[0]);r?(e[i]={timescale:n,type:r,stsd:o},e[r]=_({timescale:n,id:i},o)):e[i]={timescale:n,type:t,stsd:o}}}}}return xt(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 n,r=s;const a="enca"===s||"encv"===s;if(a){const t=xt(e,[s])[0];xt(t.subarray("enca"===s?28:78),["sinf"]).forEach(t=>{const e=xt(t,["schm"])[0];if(e){const i=yt(e.subarray(4,8));if("cbcs"===i||"cenc"===i){const e=xt(t,["frma"])[0];e&&(r=yt(e))}}})}const o=r;switch(r){case"avc1":case"avc2":case"avc3":case"avc4":{const t=xt(i,["avcC"])[0];t&&t.length>3&&(r+="."+Bt(t[1])+Bt(t[2])+Bt(t[3]),n=Ft("avc1"===o?"dva1":"dvav",i));break}case"mp4a":{const t=xt(e,[s])[0],i=xt(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(r+="."+Bt(s),t+=12,5!==i[t++])break;t=Nt(i,t);const n=i[t++];let a=(248&n)>>3;31===a&&(a+=1+((7&n)<<3)+((224&i[t])>>5)),r+="."+a}break}case"hvc1":case"hev1":{const t=xt(i,["hvcC"])[0];if(t&&t.length>12){const e=t[1],i=["","A","B","C"][e>>6],s=31&e,n=At(t,2),a=(32&e)>>5?"H":"L",o=t[12],l=t.subarray(6,12);r+="."+i+s,r+="."+function(t){let e=0;for(let i=0;i<32;i++)e|=(t>>i&1)<<31-i;return e>>>0}(n).toString(16).toUpperCase(),r+="."+a+o;let d="";for(let t=l.length;t--;){const e=l[t];if(e||d){d="."+e.toString(16).toUpperCase()+d}}r+=d}n=Ft("hev1"==o?"dvhe":"dvh1",i);break}case"dvh1":case"dvhe":case"dvav":case"dva1":case"dav1":r=Ft(r,i)||r;break;case"vp09":{const t=xt(i,["vpcC"])[0];if(t&&t.length>6){const e=t[4],i=t[5],s=t[6]>>4&15;r+="."+$t(e)+"."+$t(i)+"."+$t(s)}break}case"av01":{const t=xt(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,d=2===e&&o?l?12:10:o?10:8,h=(16&t[2])>>4,c=(8&t[2])>>3,u=(4&t[2])>>2,f=3&t[2],g=1,p=1,m=1,v=0;r+="."+e+"."+$t(s)+a+"."+$t(d)+"."+h+"."+c+u+f+"."+$t(g)+"."+$t(p)+"."+$t(m)+"."+v,n=Ft("dav1",i)}break}}return{codec:r,encrypted:a,supplemental:n}}function Ft(t,e){const i=xt(e,["dvvC"]),s=i.length?i[0]:xt(e,["dvcC"])[0];if(s){const e=s[2]>>1&127,i=s[2]<<5&32|s[3]>>3&31;return t+"."+$t(e)+"."+$t(i)}}function Nt(t,e){const i=e+5;for(;128&t[e++]&&e<i;);return e}function Bt(t){return("0"+t.toString(16).toUpperCase()).slice(-2)}function $t(t){return(t<10?"0":"")+t}function Ut(t,e){xt(t,["moov","trak"]).forEach(t=>{const i=xt(t,["mdia","minf","stbl","stsd"])[0];if(!i)return;const s=i.subarray(8);let n=xt(s,["enca"]);const r=n.length>0;r||(n=xt(s,["encv"])),n.forEach(t=>{xt(r?t.subarray(28):t.subarray(78),["sinf"]).forEach(t=>{const i=Gt(t);i&&e(i,r)})})})}function Gt(t){const e=xt(t,["schm"])[0];if(e){const i=yt(e.subarray(4,8));if("cbcs"===i||"cenc"===i){const e=xt(t,["schi","tenc"])[0];if(e)return e}}}let jt;function qt(t){if("undefined"==typeof TextDecoder)return ot(t);return(jt||(jt=new TextDecoder("utf-8"))).decode(t).replace(/\0/g,"")}function Kt(t,i,s,n,r){const a={};let o=!1;const l=function(t){const e=t.byteLength,i=[];for(let s=0;s<e;){const n=s+8<=e,r=s+4<=e?16777216*t[s]+(t[s+1]<<16|t[s+2]<<8|t[s+3]):At(t,s),a=r>1?s+r:e;if(n&&109===t[s+4]&&111===t[s+5]&&111===t[s+6]&&102===t[s+7]){const n=Math.min(a,e);for(let e=s+8;e<n;){const r=e+8<=n,a=e+4<=n?16777216*t[e]+(t[e+1]<<16|t[e+2]<<8|t[e+3]):At(t,e),o=a>1?e+a:n;if(r&&116===t[e+4]&&114===t[e+5]&&97===t[e+6]&&102===t[e+7]){const r=Math.min(o,n);let a,l;const d=[];for(let i=e+8;i<r;){const e=i+8<=r,s=i+4<=r?16777216*t[i]+(t[i+1]<<16|t[i+2]<<8|t[i+3]):At(t,i),n=s>1?i+s:r;if(e&&116===t[i+4]){const e=Math.min(n,r);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]&&d.push(t.subarray(i+8,e))}i=n}i.push({moofOffset:t.byteOffset+s,tfdt:a,tfhd:l,truns:d})}e=o}}s=a}return i}(t),d=t.byteLength;for(let u=0;u<l.length;u++){const{moofOffset:f,tfdt:g,tfhd:m,truns:v}=l[u],y=At(m,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),r&&e(S)&&(r.timeOffset=S/r.timescale)}const b=(null==r?void 0:r.trackId)===y&&E.type===p,A=E.default,L=16777215&At(m,0);let I,R=(null==A?void 0:A.duration)||0,_=(null==A?void 0:A.sampleSize)||0,k=8;1&L&&(k+=8),2&L&&(k+=4),8&L&&(R=At(m,k),I=m.byteOffset-t.byteOffset+k,k+=4),16&L&&(_=At(m,k));let w=0;const D=!!(1&L),x=!D&&!!(131072&L);D?(w=At(m,8),w*=Math.pow(2,32),w+=At(m,12)):x&&(w=f);let P=S||0,C=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],p=2&s[2],m=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,k=w+u;if(!n&&0===s[1]&&6===s[2]&&1===s[3]){var h,c;const i=P,n=k,o=E;let l=-1,u=0,f=0,g=null!=(h=null==r?void 0:r.timeOffset)?h:0;const p=R/(null!=(c=null==r?void 0:r.timescale)?c:1),m=!0===(null==r?void 0:r.isHEVCFlavor),v=m?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),n=-1===l&&void 0===T.keyFrameIndex&&!(1&s[E+5]);E+=8;const a=k+i;if(b){if(i>0){let e=k;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],n=m?s>>1&63:31&s;(m?39===n||40===n:6===n)&&Wt(t.subarray(e,e+i),v,g,r.samples),e+=i}while(e<a)}g+=p}k=a,n&&(l=e,u=k)}if(k<=d)f=a;else{let t=n,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>d)break;f=i+1,e+=8}}if(b&&(r.timeOffset=g),-1!==l&&u<=d&&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;P=i+y,C+=y;continue}n&&(S=[],A={sampleOffset:k,samples:S,defaultSampleDurationOffset:I},k<=d&&T.trun.push(A));for(let i=0;i<a;i++){let a,o,l;g?(n&&(a=s.byteOffset-t.byteOffset+E),M=At(s,E),E+=4):M=R,p?(L=At(s,E),E+=4):L=_,m&&(l=1&s[E+1]?1:0,n&&(o={isNonSync:l,dependsOn:1==(3&s[E])?1:2}),E+=4);let h=0;if(y){h=0===s[0]?At(s,E):Rt(s,E),E+=4}if(b){let e=k,i=0;for(;i<L;){const s=At(t,e);e+=4,Yt(r.isHEVCFlavor,t[e])&&Wt(t.subarray(e,e+s),r.isHEVCFlavor?2:1,r.timeOffset+h/r.timescale,r.samples),e+=s,i+=s+4}r.timeOffset+=M/r.timescale}if(k+=L,k<=d){A&&void 0!==a&&(A.lastSampleDurationOffset=a),0===l&&void 0===T.keyFrameIndex&&(T.keyFrameIndex=i,T.keyFrameStart=P);const t=P+h;(!e(T.ptsMin)||t<T.ptsMin)&&(T.ptsMin=t),(!e(T.ptsMax)||t+M>T.ptsMax)&&(T.ptsMax=t+M),S&&(S[i]={cts:h,duration:M,flags:o,size:L})}P+=M,C+=M}!C&&R&&(C+=R*a)}T.duration+=C,T.duration&&(o=!0)}if(!o){let i=1/0,s=0;const n=xt(t,["sidx"]);for(let t=0;t<n.length;t++){const e=Ct(n[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 Vt(t,e){const i=new Uint8Array(t.length+e.length);return i.set(t),i.set(e,t.length),i}function Ht(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 n=zt(t);let r=0;r+=e;let a=0,o=0,l=0;for(;r<n.length;){a=0;do{if(r>=n.length)break;l=n[r++],a+=l}while(255===l);o=0;do{if(r>=n.length)break;l=n[r++],o+=l}while(255===l);const t=n.length-r;let e=r;if(o<t)r+=o;else if(o>t){H.error(`Malformed SEI payload. ${o} is too small, only ${t} bytes left to parse.`);break}if(4===a){if(181===n[e++]){const t=bt(n,e);if(e+=2,49===t){const t=At(n,e);if(e+=4,1195456820===t){const t=n[e++];if(3===t){const r=n[e++],o=64&r,l=o?2+3*(31&r):0,d=new Uint8Array(l);if(o){d[0]=r;for(let t=1;t<l;t++)d[t]=n[e++]}s.push({type:t,payloadType:a,pts:i,bytes:d})}}}}}else if(5===a&&o>16){const t=[];for(let i=0;i<16;i++){const s=n[e++].toString(16);t.push(1==s.length?"0"+s:s),3!==i&&5!==i&&7!==i&&9!==i||t.push("-")}const r=o-16,l=new Uint8Array(r);for(let t=0;t<r;t++)l[t]=n[e++];s.push({payloadType:a,pts:i,uuid:t.join(""),userData:qt(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 n=e-i.length,r=new Uint8Array(n);let a=0,o=0;for(let e=0;e<n;o++,e++)o===i[a]&&(o++,a++),r[e]=t[o];return r}function Xt(t,e,i){if(16!==t.byteLength)throw new RangeError("Invalid system id");let s,n,r;s=0,n=new Uint8Array,r=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,n=i;for(;n--;)s+=e[n].byteLength;const r=new Uint8Array(s);for(r[0]=s>>24&255,r[1]=s>>16&255,r[2]=s>>8&255,r[3]=255&s,r.set(t,4),n=0,s=8;n<i;n++)r.set(e[n],s),s+=e[n].byteLength;return r}([112,115,115,104],new Uint8Array([0,0,0,0]),t,r,n,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 n=t.getUint32(8)>>>24;if(0!==n&&1!==n)return{offset:i,size:e};const r=t.buffer,a=pt(new Uint8Array(r,i+12,16));let o=null,l=null,d=0;if(0===n)d=28;else{const n=t.getUint32(28);if(!n||s<32+16*n)return{offset:i,size:e};o=[];for(let t=0;t<n;t++)o.push(new Uint8Array(r,i+32+16*t,16));d=32+16*n}if(!d)return{offset:i,size:e};const h=t.getUint32(d);return e-32<h?{offset:i,size:e}:(l=new Uint8Array(r,i+d+4,h),0===n&&(o=function(t){const e=[];for(let i=0;i<t.length;){const s=t[i++],n=7&s;if(0===n){for(;128&t[i++];);continue}if(2!==n){i+=1===n?8:4;continue}let r=0;for(let e=0,s=128;128&s;e+=7)r|=(127&(s=t[i++]))<<e;if(s>>3==2)if(32===r){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===r&&e.push(t.subarray(i,i+16));i+=r}return e}(l)),{version:n,systemId:a,kids:o,data:l,offset:i,size:e})}const Jt=ne("userAgent"),te=ne("vendor");let ee,ie,se;function ne(t){try{return navigator[t]||""}catch(t){}return""}function re(){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 de(t,e,i=!0){return!t.split(",").some(t=>!he(t,e,i))}function he(t,e,i=!0){var s;const n=Y(i);return null!=(s=null==n?void 0:n.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&&Ht(i)?9:oe.video[i];return s?(2*s+t)/(t?3:2):(oe.audio[i]+t)/(t?2:1)},0)}const ge={};const pe=/flac|opus|mp4a\.40\.34/i;function me(t,e=!0){return t.replace(pe,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 n=0;n<i.length;n++){var s;if(he(i[n],"audio",e))return ge[t]=i[n],i[n];if("mp3"===i[n]&&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)&&he(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,n,r,a){const o=t.videoCodec,l=t.audioCodec?t.audioGroups:null,d=null==a?void 0:a.audioCodec,h=null==a?void 0:a.channels,c=h?parseInt(h):d?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=>Ht(t))||t.width>1920&&t.height>1088||t.height>1920&&t.width>1088||t.frameRate>Math.max(n,30)||"SDR"!==t.videoRange&&t.videoRange!==s||t.bitrate>Math.max(r,8e6))||!!u&&e(c)&&Object.keys(u).some(t=>parseInt(t)>c)}function Re(t,e,i,s={}){const n=t.videoCodec;if(!n&&!t.audioCodec||!i)return Promise.resolve(Ae);const r=[],a=function(t){var e;const i=null==(e=t.videoCodec)?void 0:e.split(","),s=ke(t),n=t.width||640,r=t.height||480,a=t.frameRate||30,o=t.videoRange.toLowerCase();return i?i.map(t=>{const e={contentType:ce(Ee(t),"video"),width:n,height:r,bitrate:s,framerate:a};return"sdr"!==o&&(e.transferFunction=o),e}):[]}(t),o=a.length,l=function(t,e,i){var s;const n=null==(s=t.audioCodec)?void 0:s.split(","),r=ke(t);if(n&&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||"");n.forEach(e=>{const n={contentType:ce(e,"audio"),bitrate:i?_e(e,r):r};s&&(n.channels=""+s),t.push(n)})}return t},t):t},[]);return[]}(t,e,o>0),d=l.length;for(let t=o||1*d||1;t--;){const e={type:"media-source"};if(o&&(e.video=a[t%o]),d){e.audio=l[t%d];const i=e.audio.bitrate;e.video&&i&&(e.video.bitrate-=i)}r.push(e)}if(n){const t=navigator.userAgent;if(n.split(",").some(t=>Ht(t))&&ae())return Promise.resolve(Le(new Error(`Overriding Windows Firefox HEVC MediaCapabilities result based on user-agent string: (${t})`),r))}return Promise.all(r.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:r,decodingInfoResults:t})).catch(t=>({supported:!1,configurations:r,decodingInfoResults:[],error:t}))}function _e(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 ke(t){return 1e3*Math.ceil(Math.max(.9*t.bitrate,t.averageBitrate)/1e3)||1}function we(t,e,i){const s=encodeURIComponent(e),n=`${s}=${encodeURIComponent(i)}`;let r=!1;const a=[];t.search.substring(1).split("&").forEach(t=>{t===s||t.startsWith(s+"=")?r||(a.push(n),r=!0):t&&a.push(t)}),r||a.push(n),t.search=a.join("&")}const De=["NONE","TYPE-0","TYPE-1",null];const xe=["SDR","PQ","HLG"];var Pe="",Ce="YES",Me="v2";function Oe(t){const{canSkipUntil:e,canSkipDateRanges:i,age:s}=t;return e&&s<e/2?i?Me:Ce:Pe}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&&we(e,"_HLS_msn",this.msn.toString()),void 0!==this.part&&we(e,"_HLS_part",this.part.toString()),this.skip&&we(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 Be(this._audioGroups,t)}hasSubtitleGroup(t){return Be(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 Be(t,e){return!(!e||!t)&&-1!==t.indexOf(e)}function $e(t,e){let i=!1,s=[];if(t&&(i="SDR"!==t,s=[t]),e){s=e.allowedVideoRanges||xe.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){H.log(`[abr] start candidates with "${t}" ignored because ${e}`)}function je(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 qe(t){if(!t)return t;const{lang:e,assocLang:i,characteristics:s,channels:n,audioCodec:r}=t;return{lang:e,assocLang:i,characteristics:s,channels:n,audioCodec:r}}function Ke(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(Ve(t,e[s],i))return s}return-1}function Ve(t,e,i){const{groupId:s,name:n,lang:r,assocLang:a,default:o}=t,l=t.forced;return(void 0===s||e.groupId===s)&&(void 0===n||e.name===n)&&(void 0===r||function(t,e="--"){if(t.length===e.length)return t===e;return t.startsWith(e)||e.startsWith(t)}(r,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 He(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,n=null,r=null;for(;i<=s;){n=(i+s)/2|0,r=t[n];const a=e(r);if(a>0)i=n+1;else{if(!(a<0))return r;s=n-1}}return null};function Ze(t,e,i=0,s=0,n=.005){let r=null;if(t){r=e[1+t.sn-e[0].sn]||null;const s=t.endDTS-i;s>0&&s<15e-7&&(i+=15e-7),r&&t.level!==r.level&&r.end<=t.end&&(r=e[2+t.sn-e[0].sn]||null)}else 0===i&&0===e[0].start&&(r=e[0]);if(r&&((!t||t.level===r.level)&&0===Je(i,s,r)||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}(r,t,Math.min(n,s))))return r;const a=Qe(e,Je.bind(null,i,s));return!a||a===t&&r?r: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:n}=t;let r;return n&&(s=s.concat(n)),Qe(s,t=>t.cc<e?1:t.cc>e?-1:(r=t,t.end<=i?1:t.start>i?-1:0)),r||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,ni=2,ri=3,ai=5,oi=0,li=1,di=2,hi=4,ci=8,ui=16;function fi(t){const e=t.details;return e===r.BUFFER_ADD_CODEC_ERROR||e===r.MEDIA_SOURCE_REQUIRES_RESET||e===r.BUFFER_APPEND_ERROR&&!gi(t)}function gi(t){return t.details===r.BUFFER_APPEND_ERROR&&("QuotaExceededError"===t.error.name||"InvalidStateError"===t.error.name)}function pi(t){const e={action:si,flags:oi};return t&&(e.resolved=!0),e}var mi="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,n=Object.keys(s);for(let r=n.length;r--;){const a=s[n[r]];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,n,r){this.timeRanges&&(this.timeRanges[t]=e);const o=(null==n?void 0:n.fragment.sn)||-1;Object.keys(this.fragments).forEach(n=>{const l=this.fragments[n];if(!l||!this.hls)return;const d=l.body;if(o>=d.sn)return;if(!l.buffered&&(!l.loaded||r))return void(d.type===i&&this.removeFragment(d));const h=l.range[t];if(h)if(0!==h.time.length){if(h.time.some(t=>{const i=!this.isTimeBuffered(t.startPTS,t.endPTS,e);return i&&this.removeFragment(d),i}),s&&s!==d&&re()){const t=s.endPTS,e=d.startPTS;if(t&&e&&l.range.video){const i=e-t;i<0&&i>-.1&&(this.removeFragment(d),this.hls.trigger(a.BUFFER_FLUSHING,{startOffset:t+.004,endOffset:1/0,type:"video"}))}}}else this.removeFragment(d)})}detectPartialFragments(t){const e=this.timeRanges,{frag:i,part:s,id:n}=t;if(!e||!y(i))return;const r=bi(i),a=this.fragments[r];if(!a||a.buffered&&i.gap)return;const o=!i.relurl;Object.keys(e).forEach(t=>{const r=i.elementaryStreams[t];if(!r)return;const l=e[t],d=o||!0===r.partial;a.range[t]=this.getBufferedTimes(i,s,d,l),this.detectEvictedFragments(t,l,n,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 n=null==(s=a.range[e])?void 0:s.time,r=0===n.length||1===n.length&&n[0].endPTS-n[0].startPTS<t;return r&&this.addAsGap(i),r})}}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 n={time:[],partial:i},r=t.start,a=t.end,o=t.minEndPTS||a,l=t.maxStartPTS||r;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){n.time.push({startPTS:Math.max(r,s.start(t)),endPTS:Math.min(a,s.end(t))});break}if(r<i&&a>e){const e=Math.max(r,s.start(t)),i=Math.min(a,s.end(t));i>e&&(n.partial=!0,n.time.push({startPTS:e,endPTS:i}))}else if(a<=e)break}return n}getPartialFragment(t){let e,i,s,n=null,r=0;const{bufferPadding:a,fragments:o}=this;return Object.keys(o).forEach(l=>{const d=o[l];d&&Si(d)&&(i=d.body.start-a,s=d.body.end+a,t>=i&&t<=s&&(e=Math.min(t-i,s-t),r<=e&&(n=d.body,r=e)))}),n}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:mi}isTimeBuffered(t,e,i){let s,n;for(let r=0;r<i.length;r++){if(s=i.start(r)-this.bufferPadding,n=i.end(r)+this.bufferPadding,t>=s&&e<=n)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,n=bi(i);this.fragments[n]={body:i,appendedPTS:null,loaded:s,buffered:!1,range:Object.create(null)}}onBufferAppended(t,e){const{frag:i,part:s,timeRanges:n}=e;if(!y(i))return;const r=i.type;if(s){let t=this.activePartLists[r];t||(this.activePartLists[r]=t=[]),t.push(s)}this.timeRanges=n}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 n=e[i[s]];if((null==n?void 0:n.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 n=0,r=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 d=l.body;if(d.gap)return 0;const h=d.hasStats&&d.stats.loaded||d.byteLength||d.bitrate&&8*d.bitrate*d.duration;if(d.end<=t&&h&&(n+=h,r=Math.max(r,d.end),n>=i))return r}return r>0?r:0}removeFragmentsInRange(t,e,i,s,n){s&&!this.hasGaps||Object.keys(this.fragments).forEach(r=>{const a=this.fragments[r];if(!a)return;const o=a.body;o.type!==i||s&&!o.gap||o.start<e&&o.end>t&&(a.buffered||n)&&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,n;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!=(n=t.range.subs)&&n.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 _i{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],n=i[1],r=i[2],a=i[3],o=this.invSubMix,l=o[0],d=o[1],h=o[2],c=o[3],u=new Uint32Array(256);let f=0,g=0,p=0;for(p=0;p<256;p++)u[p]=p<128?p<<1:p<<1^283;for(p=0;p<256;p++){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],p=u[o],m=u[p];let v=257*u[i]^16843008*i;s[f]=v<<24|v>>>8,n[f]=v<<16|v>>>16,r[f]=v<<8|v>>>24,a[f]=v,v=16843009*m^65537*p^257*o^16843008*f,l[i]=v<<24|v>>>8,d[i]=v<<16|v>>>16,h[i]=v<<8|v>>>24,c[i]=v,f?(f=o^u[u[u[m^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 n=this.keySize=e.length;if(4!==n&&6!==n&&8!==n)throw new Error("Invalid aes key size="+n);const r=this.ksRows=4*(n+6+1);let a,o;const l=this.keySchedule=new Uint32Array(r),d=this.invKeySchedule=new Uint32Array(r),h=this.sBox,c=this.rcon,u=this.invSubMix,f=u[0],g=u[1],p=u[2],m=u[3];let v,y;for(a=0;a<r;a++)a<n?v=l[a]=e[a]:(y=v,a%n===0?(y=y<<8|y>>>24,y=h[y>>>24]<<24|h[y>>>16&255]<<16|h[y>>>8&255]<<8|h[255&y],y^=c[a/n|0]<<24):n>6&&a%n===4&&(y=h[y>>>24]<<24|h[y>>>16&255]<<16|h[y>>>8&255]<<8|h[255&y]),l[a]=v=(l[a-n]^y)>>>0);for(o=0;o<r;o++)a=r-o,y=3&o?l[a]:l[a-4],d[o]=o<4||a<=4?y:f[h[y>>>24]]^g[h[y>>>16&255]]^p[h[y>>>8&255]]^m[h[255&y]],d[o]=d[o]>>>0}networkToHostOrderSwap(t){return t<<24|(65280&t)<<8|(16711680&t)>>8|t>>>24}decrypt(t,e,i){const s=this.keySize+6,n=this.invKeySchedule,r=this.invSBox,a=this.invSubMix,o=a[0],l=a[1],d=a[2],h=a[3],c=this.uint8ArrayToUint32Array_(i);let u=c[0],f=c[1],g=c[2],p=c[3];const m=new Int32Array(t),v=new Int32Array(m.length);let y,E,T,S,b,A,L,I,R,_,k,w,D,x;const P=this.networkToHostOrderSwap;for(;e<m.length;){for(R=P(m[e]),_=P(m[e+1]),k=P(m[e+2]),w=P(m[e+3]),b=R^n[0],A=w^n[1],L=k^n[2],I=_^n[3],D=4,x=1;x<s;x++)y=o[b>>>24]^l[A>>16&255]^d[L>>8&255]^h[255&I]^n[D],E=o[A>>>24]^l[L>>16&255]^d[I>>8&255]^h[255&b]^n[D+1],T=o[L>>>24]^l[I>>16&255]^d[b>>8&255]^h[255&A]^n[D+2],S=o[I>>>24]^l[b>>16&255]^d[A>>8&255]^h[255&L]^n[D+3],b=y,A=E,L=T,I=S,D+=4;y=r[b>>>24]<<24^r[A>>16&255]<<16^r[L>>8&255]<<8^r[255&I]^n[D],E=r[A>>>24]<<24^r[L>>16&255]<<16^r[I>>8&255]<<8^r[255&b]^n[D+1],T=r[L>>>24]<<24^r[I>>16&255]<<16^r[b>>8&255]<<8^r[255&A]^n[D+2],S=r[I>>>24]<<24^r[b>>16&255]<<16^r[A>>8&255]<<8^r[255&L]^n[D+3],v[e]=P(y^u),v[e+1]=P(S^f),v[e+2]=P(T^g),v[e+3]=P(E^p),u=R,f=_,g=k,p=w,e+=4}return v.buffer}}class ki{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 wi{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,n){return this.decryptRange=n,this.useSoftware||n?new Promise((n,r)=>{const a=ArrayBuffer.isView(t)?t:new Uint8Array(t);this.softwareDecrypt(a,e,i,s);const o=this.flush();o?n(o.buffer):r(new Error("[softwareDecrypt] Failed to decrypt data"))}):this.webCryptoDecrypt(new Uint8Array(t),e,i,s)}softwareDecrypt(t,e,i,s){const{currentIV:n,currentResult:r,remainderData:a}=this;if(s!==Li||16!==e.byteLength)return H.warn("SoftwareDecrypt: can only handle AES-128-CBC"),null;this.logOnce("JS AES decrypt"),a&&(t=Vt(a,t),this.remainderData=null);const o=this.getValidChunk(t);if(!o.length)return null;n&&(i=n);let l=this.softwareDecrypter;l||(l=this.softwareDecrypter=new _i),l.expandKey(e);const d=r;return this.currentResult=l.decrypt(o.buffer,0,i),this.currentIV=o.slice(-16).buffer,d||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 ki(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(n=>(H.warn(`[decrypter]: WebCrypto Error, disable WebCrypto API, ${n.name}: ${n.message}`),this.onWebCryptoError(t,e,i,s)))}onWebCryptoError(t,e,i,s){const n=this.enableSoftwareAES;if(n){this.useSoftware=!0,this.logEnabled=!0,this.softwareDecrypt(t,e,i,s);const n=this.flush();if(n)return n.buffer}throw new Error("WebCrypto"+(n?" 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&&(H.log(`[decrypter]: ${t}`),this.logEnabled=!1)}}const Di=Math.pow(2,17);class xi{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:n.NETWORK_ERROR,details:r.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,d=o.loader;return new Promise((h,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 d(o),f=Pi(t,null,e);t.loader=u;const g=M(o.fragLoadPolicy.default),p={loadPolicy:g,timeout:g.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:"initSegment"===t.sn?1/0:Di};u.stats.retry=t.stats.retry,t.stats=u.stats;const m={onSuccess:(e,i,s,n)=>{this.resetLoader(t,u);let r=e.data;s.resetIV&&t.decryptdata&&(t.decryptdata.iv=new Uint8Array(r.slice(0,16)),r=r.slice(16)),h({frag:t,part:null,payload:r,networkDetails:n})},onError:(e,i,s,o)=>{this.resetLoader(t,u),c(new Oi({type:n.NETWORK_ERROR,details:r.FRAG_LOAD_ERROR,fatal:!1,frag:t,response:_({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:n.NETWORK_ERROR,details:r.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:n.NETWORK_ERROR,details:r.FRAG_LOAD_TIMEOUT,fatal:!1,frag:t,error:new Error(`Timeout after ${p.timeout}ms`),networkDetails:s,stats:e}))}};if(i){const e=this.gateProgress(i,s);m.onProgress=(i,s,n,r)=>e({frag:t,part:null,payload:n,networkDetails:r})}u.load(f,p,m)})}gateProgress(t,e){let i=t;if(e){const s=[];let n=!1;e.then(()=>{n=!0,s.forEach(e=>t(e)),s.length=0}).catch(()=>{}),i=e=>{n?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,d)=>{if(this.loader&&this.loader.destroy(),t.gap||e.gap)return void d(Mi(t,e));const h=this.loader=a?new a(s):new o(s),c=Pi(t,e);t.loader=h;const u=M(s.fragLoadPolicy.default),f={loadPolicy:u,timeout:u.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:Di};e.stats=h.stats,h.load(c,f,{onSuccess:(s,n,r,a)=>{this.resetLoader(t,h),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,h),d(new Oi({type:n.NETWORK_ERROR,details:r.FRAG_LOAD_ERROR,fatal:!1,frag:t,part:e,response:_({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,h),d(new Oi({type:n.NETWORK_ERROR,details:r.INTERNAL_ABORTED,fatal:!1,frag:t,part:e,error:new Error("Aborted"),networkDetails:a,stats:i}))},onTimeout:(i,s,a)=>{this.resetLoader(t,h),d(new Oi({type:n.NETWORK_ERROR,details:r.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,n=s.total;if(i.loaded+=s.loaded,n){const s=Math.round(t.duration/e.duration),r=Math.min(Math.round(i.loaded/n),s),a=(s-r)*Math.round(i.loaded/r);i.total=i.loaded+a}else i.total=Math.max(i.loaded,i.total);const r=i.loading,a=s.loading;r.start?r.first+=a.first-a.start:(r.start=a.start,r.first=a.first),r.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 Pi(t,e=null,i){const s=e||t,n={type:u.MEDIA_FRAGMENT,frag:t,part:e,responseType:"arraybuffer",url:s.url,headers:{},rangeStart:0,rangeEnd:0},r=Ci(t,e,i);return r.resetIV&&(n.resetIV=!0),r.byteRange&&(n.rangeStart=r.byteRange.start,n.rangeEnd=r.byteRange.end),n}function Ci(t,i=null,s){const n={},r=i||t,a=r.byteRangeStartOffset,o=r.byteRangeEndOffset;var l,d;if(e(a)&&e(o))if("initSegment"!==t.sn&&!s||"AES-128"!==(d=null==(l=t.decryptdata)?void 0:l.method)&&"AES-256"!==d)n.byteRange={start:a,end:o};else{let t=16*Math.floor(a/16);const e=16*Math.ceil(o/16);n.decryptRange={start:a-t,end:o-t},t>=16&&(n.resetIV=!0,t-=16),n.byteRange={start:t,end:e}}return n}function Mi(t,e){const i=new Error(`GAP ${t.gap?"tag":"attribute"} found`),s={type:n.MEDIA_ERROR,details:r.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,n=-1,r=!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=n,this.partial=r,this.duration=a||0,this.decryptRange=l,this.iframe=o||!1}}const Bi={length:0,start:()=>0,end:()=>0};class $i{static isBuffered(t,e){if(t){const i=$i.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=$i.getBuffered(t);return $i.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=$i.bufferedRanges(t);if(s.length)return $i.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,n=[];if(i)for(let r=0;r<t.length;r++){e>=t[r].start&&e<=t[r].end&&(s=r);const a=n.length;if(a){const e=n[a-1].end;t[r].start-e<i?t[r].end>e&&(n[a-1].end=t[r].end):n.push(t[r])}else n.push(t[r])}else n=t;let r,a=0,o=e,l=e;for(let t=0;t<n.length;t++){const d=n[t].start,h=n[t].end;if(-1===s&&e>=d&&e<=h&&(s=t),e+i>=d&&e<h)o=d,l=h,a=l-e;else if(e+i<d){r=d;break}}return{len:a,start:o||0,end:l||0,nextStart:r,buffered:t,bufferedIndex:s}}static getBuffered(t){try{return t.buffered||Bi}catch(t){return H.log("failed to get media.buffered",t),Bi}}}const Ui=/\{\$([a-zA-Z0-9-_]+)\}/g;function Gi(t){return Ui.lastIndex=0,Ui.test(t)}function ji(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),n=null==i?void 0:i[s];return void 0===n?(t.playlistParsingError||(t.playlistParsingError=new Error(`Missing preceding EXT-X-DEFINE tag for Variable Reference: "${s}"`)),e):n})}return e}function qi(t,e,i){let s,n,r=t.variableList;if(r||(t.variableList=r={}),"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}"`);n=t.get(s)}catch(e){t.playlistParsingError||(t.playlistParsingError=new Error(`EXT-X-DEFINE QUERYPARAM: ${e.message}`))}}else s=e.NAME,n=e.VALUE;s in r?t.playlistParsingError||(t.playlistParsingError=new Error(`EXT-X-DEFINE duplicate Variable Name declarations: "${s}"`)):r[s]=n||""}function Ki(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 Vi=/^(\d+)x(\d+)$/,Hi=/(.+?)=(".*?"|.*?)(?:,|$)/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=Vi.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(Hi.lastIndex=0;null!==(i=Hi.exec(t));){const n=i[1].trim();let r=i[2];const a=0===r.indexOf('"')&&r.lastIndexOf('"')===r.length-1;let o=!1;if(a)r=r.slice(1,-1);else switch(n){case"IV":case"SCTE35-CMD":case"SCTE35-IN":case"SCTE35-OUT":o=!0}if(e&&(a||o))r=ji(e,r);else if(!o&&!a)switch(n){case"CLOSED-CAPTIONS":if("NONE"===r)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":H.warn(`${t}: attribute ${n} is missing quotes`)}s[n]=r}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 n;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!=(n=null==i?void 0:i.tagOrder)?n:s,i){const e=i.attr;for(const i in e)if(Object.prototype.hasOwnProperty.call(t,i)&&t[i]!==e[i]){H.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?(H.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 ns(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],n=s[1];e?(t.splice(-1,1),i=vt(n)):i=function(t){const e=is(t).subarray(0,16),i=new Uint8Array(16);return i.set(e,16-e.length),i}(n)}}return i}const rs="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",ds="com.microsoft.playready",hs="urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed";function cs(t){switch(t){case ls:return as.FAIRPLAY;case ds:return as.PLAYREADY;case hs: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 ds;case as.WIDEVINE:return hs;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 ps=null!=rs&&null!=(ms=rs.navigator)&&ms.requestMediaKeySystemAccess?self.navigator.requestMediaKeySystemAccess.bind(self.navigator):null;var ms;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],n=null,r){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=n,this.encrypted=!!t&&"NONE"!==t,this.isCommonEncryption=this.encrypted&&!ts(t),null!=r&&r.startsWith("0x")&&(this.keyId=new Uint8Array(mt(r)))}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 hs:case ds: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&&(H.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=ns(this.uri);if(s)switch(this.keyFormat){case hs:if(this.pssh=s,!this.keyId){const t=Qt(s.buffer).filter(t=>t.systemId===us);if(t.length){var n;const e=t[0];this.keyId=null!=(n=e.kids)&&n.length?e.kids[0]:null}}this.keyId||(this.keyId=Ts(e));break;case ds:{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[hs];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[ds];if(e){const t=ns(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 h.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 n;for(;null!=(n=Ss.exec(t));)if(n[1]){const t=_s(new Yi(n[1],i),n[2],e,i,s);t&&i.levels.push(t)}else if(n[3]){const t=n[3],r=n[4];switch(t){case"I-FRAME-STREAM-INF":{const t=new Yi(r,i),n=_s(t,t.URI,e,i,s,!0);n&&i.iframeVariants.push(n)}break;case"SESSION-DATA":{const t=new Yi(r,i),e=t["DATA-ID"];e&&(null===i.sessionData&&(i.sessionData={}),i.sessionData[e]=t);break}case"SESSION-KEY":{const t=Ds(r,e,i);t.encrypted&&t.isSupported()?(null===i.sessionKeys&&(i.sessionKeys=[]),i.sessionKeys.push(t)):H.warn(`[Keys] Ignoring invalid EXT-X-SESSION-KEY tag: "${r}"`);break}case"DEFINE":qi(i,new Yi(r,i),e);break;case"CONTENT-STEERING":{const t=new Yi(r,i);i.contentSteering={uri:Rs.resolve(t["SERVER-URI"],e),pathwayId:t["PATHWAY-ID"]||"."};break}case"START":i.startTimeOffset=xs(r)}}const r=s.length>0&&s.length<i.levels.length;return i.levels=r?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 n={},r=i.levels,a={AUDIO:r.map(t=>({id:t.attrs.AUDIO,audioCodec:t.audioCodec})),SUBTITLES:r.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),r=t.TYPE;if(r){const i=a[r],s=n[r]||[];n[r]=s;const l=t.LANGUAGE,d=t["ASSOC-LANGUAGE"],h=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:r,default:t.bool("DEFAULT"),autoselect:t.bool("AUTOSELECT"),forced:t.bool("FORCED"),lang:l,url:t.URI?Rs.resolve(t.URI,e):""};if(d&&(f.assocLang=d),h&&(f.channels=h),c&&(f.characteristics=c),u&&(f.instreamId=u),null!=i&&i.length){const t=Rs.findGroup(i,f.groupId)||i[0];Cs(f,t,"audioCodec"),Cs(f,t,"textCodec")}s.push(f)}}return n}static parseLevelPlaylist(t,i,s,n,r,a){var o;const l={url:i},d=new Qi(i),h=d.fragments,c=[];let u,f,g,p,m=null,v=0,y=0,E=0,T=0,A=0,L=null,R=new S(n,l),_=-1,k=!1,w=null;if(Ls.lastIndex=0,d.m3u8=t,d.hasVariableRefs=Gi(t),"#EXTM3U"!==(null==(o=Ls.exec(t))?void 0:o[0]))return d.playlistParsingError=new Error("Missing format identifier #EXTM3U"),d;for(;null!==(u=Ls.exec(t));){k&&(k=!1,R=new S(n,l),R.playlistOffset=E,R.setStart(E),R.sn=v,R.cc=T,A&&(R.bitrate=A),R.level=s,m&&(R.initSegment=m,m.rawProgramDateTime&&(R.rawProgramDateTime=m.rawProgramDateTime,m.rawProgramDateTime=null),w&&(R.setByteRange(w),w=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 D;R.playlistOffset=E,R.setStart(E),g&&Fs(R,g,d),R.sn=v,R.level=s,R.cc=T;const t=(" "+u[3]).slice(1);R.relurl=ji(d,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),d.iframesOnly&&e[0]&&(null==(D=m)?void 0:D.cc)!==T){const t=new S(n,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))),m=t,R.initSegment=m}h.push(R),k=!0}}else{if(u=u[0].match(Is),!u){H.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),r=(" "+u[f+1]).slice(1),o=u[f+2]?(" "+u[f+2]).slice(1):null;switch(t){case"BYTERANGE":L?R.setByteRange(r,L):R.setByteRange(r);break;case"PROGRAM-DATE-TIME":R.rawProgramDateTime=r,R.tagList.push(["PROGRAM-DATE-TIME",r]),-1===_&&(_=h.length);break;case"PLAYLIST-TYPE":d.type&&Ns(d,t,u),d.type=r.toUpperCase();break;case"MEDIA-SEQUENCE":0!==d.startSN?Ns(d,t,u):null!==L&&Bs(d,t,u),d.startSN=parseInt(r),v=d.startSN+d.skippedSegments;break;case"SKIP":{d.skippedSegments&&Ns(d,t,u);const i=new Yi(r,d),s=i.decimalInteger("SKIPPED-SEGMENTS");if(e(s)){d.skippedSegments+=s;for(let t=s;t--;)h.push(null);v+=s}const n=i.enumeratedString("RECENTLY-REMOVED-DATERANGES");n&&(d.recentlyRemovedDateranges=(d.recentlyRemovedDateranges||[]).concat(n.split("\t")));break}case"TARGETDURATION":0!==d.targetduration&&Ns(d,t,u),d.targetduration=Math.max(parseInt(r),1);break;case"VERSION":null!==d.version&&Ns(d,t,u),d.version=parseInt(r);break;case"INDEPENDENT-SEGMENTS":break;case"I-FRAMES-ONLY":d.iframesOnly=!0;break;case"ENDLIST":d.live||Ns(d,t,u),d.live=!1;break;case"#":(r||o)&&R.tagList.push(o?[r,o]:[r]);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,r]),A=1e3*parseInt(r),e(A)?R.bitrate=A:A=0;break;case"DATERANGE":{const t=new Yi(r,d),e=new Xi(t,d.dateRanges[t.ID],d.dateRangeTagCount);d.dateRangeTagCount++,e.isValid||d.skippedSegments?d.dateRanges[e.id]=e:H.log(`Ignoring invalid DATERANGE tag: ${e.invalidReason}: ${r}`),R.tagList.push(["EXT-X-DATERANGE",r]);break}case"DEFINE":{const t=new Yi(r,d);"IMPORT"in t?Ki(d,t,a):qi(d,t,i)}break;case"DISCONTINUITY-SEQUENCE":0!==d.startCC&&Ns(d,t,u),d.startCC=T=parseInt(r),h.forEach(t=>t&&(t.cc=T));break;case"KEY":{const t=Ds(r,i,d);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 H.warn(`[Keys] Ignoring unsupported EXT-X-KEY tag: "${r}"`);break}case"START":d.startTimeOffset=xs(r);break;case"MAP":{const t=new Yi(r,d);if(R.duration){const e=new S(n,l);Os(e,t,s,g),m=e,R.initSegment=m,m.rawProgramDateTime&&!R.rawProgramDateTime&&(R.rawProgramDateTime=m.rawProgramDateTime)}else{const e=R.byteRangeEndOffset;if(e){const t=R.byteRangeStartOffset;w=`${e-t}@${t}`}else w=null;Os(R,t,s,g),m=R,k=!0}m.cc=T;break}case"SERVER-CONTROL":p&&Ns(d,t,u),p=new Yi(r),d.canBlockReload=p.bool("CAN-BLOCK-RELOAD"),d.canSkipUntil=p.optionalFloat("CAN-SKIP-UNTIL",0),d.canSkipDateRanges=d.canSkipUntil>0&&p.bool("CAN-SKIP-DATERANGES"),d.partHoldBack=p.optionalFloat("PART-HOLD-BACK",0),d.holdBack=p.optionalFloat("HOLD-BACK",0);break;case"PART-INF":{d.partTarget&&Ns(d,t,u);const e=new Yi(r);d.partTarget=e.decimalFloatingPoint("PART-TARGET");break}case"PART":{let t=d.partList;t||(t=d.partList=[]);const e=y>0?t[t.length-1]:void 0,i=y++,s=new Yi(r,d),n=new b(s,R,l,i,e);t.push(n),R.duration+=n.duration;break}case"PRELOAD-HINT":{const t=new Yi(r,d);d.preloadHint=t;break}case"RENDITION-REPORT":{const t=new Yi(r,d);d.renditionReports=d.renditionReports||[],d.renditionReports.push(t);break}default:H.warn(`line parsed but not handled: ${u}`)}}}L&&!L.relurl?(h.pop(),E-=L.duration,d.partList&&(d.fragmentHint=L)):d.partList&&(Ms(R,L,c),R.cc=T,d.fragmentHint=R,g&&Fs(R,g,d)),d.targetduration||(d.playlistParsingError=new Error("Missing Target Duration"));const x=h.length,P=h[0],C=h[x-1];if(E+=d.skippedSegments*d.targetduration,E>0&&x&&C){d.averagetargetduration=E/x;const t=C.sn;d.endSN="initSegment"!==t?t:0,d.live||(C.endList=!0),_>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}}(h,_,_>x-1?R:null),P&&c.unshift(P))}return d.fragmentHint&&(E+=d.fragmentHint.duration),d.totalduration=E,c.length&&d.dateRangeTagCount&&P&&ks(c,d),d.endCC=T,d}}function _s(t,e,i,s,n,r){var a;if(void 0===e)return null;const o=ji(s,e),l={attrs:t,bitrate:t.decimalInteger("BANDWIDTH")||t.decimalInteger("AVERAGE-BANDWIDTH"),name:t.NAME,url:Rs.resolve(o,i)},d=t.decimalResolution("RESOLUTION");d&&(l.width=d.width,l.height=d.height),Ps(t.CODECS,l);const h=t["SUPPLEMENTAL-CODECS"];return h&&(l.supplemental={},Ps(h,l.supplemental)),null!=(a=l.unknownCodecs)&&a.length||n.push(l),r&&(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],n=e.live?1/0:e.totalduration,r=Object.keys(e.dateRanges);for(let o=r.length;o--;){const l=e.dateRanges[r[o]],d=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=ws(e,d,t,s,n);if(i){l.tagAnchor=i.ref;break}}}}function ws(t,e,i,s,n){const r=i[s];if(r){const o=r.programDateTime;if(e>=o||0===s){var a;if(e<=o+1e3*(((null==(a=i[s+1])?void 0:a.start)||n)-r.start)){const n=r.sn-t.startSN,a=t.fragments;if(n>=0&&n<a.length){if(a.length>i.length){const r=i[s+1]||a[a.length-1];for(let i=Math.min(r.sn-t.startSN,a.length-1);i>n;i--){const t=a[i].programDateTime;if(e>=t&&e<t+1e3*a[i].duration)return a[i]}}return a[n]}}}}return null}function Ds(t,e,i){var s,n;const r=new Yi(t,i),a=null!=(s=r.METHOD)?s:"",o=r.URI,l=r.hexadecimalInteger("IV"),d=r.KEYFORMATVERSIONS,h=null!=(n=r.KEYFORMAT)?n:"identity";o&&r.IV&&!l&&H.error(`Invalid IV: ${r.IV}`);const c=o?Rs.resolve(o,e):"",u=(d||"1").split("/").map(Number).filter(Number.isFinite);return new Es(a,c,h,u,l,r.KEYID)}function xs(t){const i=new Yi(t).decimalFloatingPoint("TIME-OFFSET");return e(i)?i:null}function Ps(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 Cs(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 Bs(t,e,i){t.playlistParsingError=new Error(`#EXT-X-${e} must appear before the first Media Segment (${i[0]})`)}function $s(t,i){const s=i.startPTS;if(e(s)){let e,n=0;i.sn>t.sn?(n=s-t.start,e=t):(n=t.start-s,e=i),e.duration!==n&&e.setDuration(n)}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,n,r,a,o,l){n-s<=0&&(l.warn("Fragment should have a positive duration",i),n=s+i.duration,a=r+i.duration);let d=s,h=n;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,d=Math.max(s,c),s=Math.min(s,c),r=void 0!==i.startDTS?Math.min(r,i.startDTS):r,h=Math.min(n,u),n=Math.max(n,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(n-i.start),i.startPTS=s,i.maxStartPTS=d,i.startDTS=r,i.endPTS=n,i.minEndPTS=h,i.endDTS=a;const g=i.sn;if(!t||g<t.startSN||g>t.endSN)return 0;let p;const m=g-t.startSN,v=t.fragments;for(v[m]=i,p=m;p>0;p--)$s(v[p],v[p-1]);for(p=m;p<v.length-1;p++)$s(v[p],v[p+1]);return t.fragmentHint&&$s(v[v.length-1],t.fragmentHint),t.PTSKnown=t.alignedSliding=!0,f}function Gs(t,i,s){if(t===i)return;let n=null;const r=t.fragments;for(let t=r.length-1;t>=0;t--){const e=r[t].initSegment;if(e){n=e;break}}let a;t.fragmentHint&&delete t.fragmentHint.endPTS,function(t,e,i){var s;const n=e.skippedSegments,r=Math.max(t.startSN,e.startSN)-e.startSN,a=(t.fragmentHint?1:0)+(n?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,d=null!=(s=t.fragmentHint)&&s.duration?t.fragments.concat(t.fragmentHint):t.fragments;for(let s=r;s<=a;s++){const r=d[o+s];let a=l[s];if(n&&!a&&r&&(a=e.fragments[s]=r),r&&a){i(r,a,s,l);const n=r.relurl,o=a.relurl;if(n&&zs(n,o))return void(e.playlistParsingError=js(`media sequence mismatch ${a.sn}:`,t,e,r,a));if(r.cc!==a.cc)return void(e.playlistParsingError=js(`discontinuity sequence mismatch (${r.cc}!=${a.cc})`,t,e,r,a))}}}(t,i,(t,s,r,o)=>{if((!i.startCC||i.skippedSegments)&&s.cc!==t.cc){const e=t.cc-s.cc;for(let t=r;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,n=t.initSegment)});const o=i.fragments,l=i.fragmentHint?o.concat(i.fragmentHint):o;if(n&&l.forEach(t=>{var e;!t||t.initSegment&&t.initSegment.relurl!==(null==(e=n)?void 0:e.relurl)||(t.initSegment=n)}),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:n}=e,r=I({},t);n&&n.forEach(t=>{delete r[t]});const a=Object.keys(r).length;if(!a)return s;return Object.keys(s).forEach(t=>{const e=r[t],n=new Xi(s[t].attr,e);n.isValid?(r[t]=n,e||(n.tagOrder+=a)):i.warn(`Ignoring invalid Playlist Delta Update DATERANGE tag: "${Ue(s[t].attr)}"`)}),r}(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);ks(e,i)}i.endCC=o[o.length-1].cc}if(!i.startCC){var d;const e=Vs(t,i.startSN-1);i.startCC=null!=(d=null==e?void 0:e.cc)?d:o[0].cc}if(function(t,e,i){if(t&&e){let s=0;for(let n=0,r=t.length;n<r;n++){const r=t[n],a=e[n+s];r&&a&&r.index===a.index&&r.fragment.sn===a.fragment.sn?i(r,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 qs(t,i);o.length&&(i.totalduration=i.edge-o[0].start),i.driftStartTime=t.driftStartTime,i.driftStart=t.driftStart;const h=i.advancedDateTime;if(i.advanced&&h){const t=i.edge;i.driftStart||(i.driftStartTime=h,i.driftStart=t),i.driftEndTime=h,i.driftEnd=t}else i.driftEndTime=t.driftEndTime,i.driftEnd=t.driftEnd,i.advancedDateTime=t.advancedDateTime;-1===i.requestScheduled&&(i.requestScheduled=t.requestScheduled)}function js(t,e,i,s,n){return new Error(`${t} ${n.url}\nPlaylist starting @${e.startSN}\n${e.m3u8}\n\nPlaylist starting @${i.startSN}\n${i.m3u8}`)}function qs(t,e,i=!0,s){const n=e.startSN+e.skippedSegments-t.startSN,r=t.fragments,a=n>=0;let o=0;if(a&&n<r.length)o=r[n].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+n*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 Ks(t,e=1/0){let i=1e3*t.targetduration;if(t.updated){const s=t.fragments,n=4;if(s.length&&i*n>e){const t=1e3*s[s.length-1].duration;t>0&&t<i&&(i=t)}}else i/=2;return Math.round(i)}function Vs(t,e,i){var s;if(!t)return null;let n=t.fragments[e-t.startSN];return n||(n=t.fragmentHint,(null==(s=n)?void 0:s.sn)===e?n:i&&e<t.startSN&&i.sn===e?i:null)}function Hs(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 n=t[s];if(n.index===i&&n.fragment.sn===e)return n}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,n=t.length;s<n;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 tn(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),n=Qs(e.fragments,s),r=Qs(t.fragments,s);if(!n||!r)return;const a=n.start-r.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,n=e.fragments;if(!s.length||!n.length)return;let r,a;const o=Math.min(e.endCC,t.endCC);e.startCC<o&&t.startCC<o&&(r=Qs(n,o),a=Qs(s,o));r&&a||(r=n[Math.floor(n.length/2)]||n.filter(t=>!!t)[0],a=Qs(s,r.cc)||s[Math.floor(s.length/2)]);const l=r.programDateTime,d=a.programDateTime;if(!l||!d)return;const h=(d-l)/1e3;if(Math.abs(h)>Math.max(60,t.totalduration))return void i.log(`Cannot align playlists using PDT without overlap (${Math.abs(h)} > ${t.totalduration})`);const c=h-(a.start-r.start);i.log(`Aligning playlists using PDT (diff: ${c})`),Js(c,t)}(e,t,i),e.alignedSliding||e.skippedSegments||qs(t,e,!1,i))}function en(t,e,i){sn(t,e,i),t.addEventListener(e,i)}function sn(t,e,i){t.removeEventListener(e,i)}function nn(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 rn="STOPPED",an="IDLE",on="KEY_LOADING",ln="FRAG_LOADING",dn="FRAG_LOADING_WAITING_RETRY",hn="WAITING_TRACK",cn="PARSING",un="PARSED",fn="ENDED",gn="ERROR",pn="WAITING_INIT_PTS",mn="WAITING_LEVEL";class vn extends Fi{constructor(t,e,i,s,n){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=rn,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:n}=this,r=i?i.currentTime:0,a=$i.bufferInfo(s||i,r,t.maxBufferHole),o=a.len;if(this.log(`Media seeking to ${r}, state: ${n}, ${o?"in":"out of"} buffer`),this.state===fn)this.resetLoadingState();else if(e){const i=t.maxFragLookUpTolerance,s=e.start-i,n=e.start+e.duration+i;if(!o||n<a.start||s>a.end){const t=r<s,i=r>n;(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(r,1/0,this.playlistType,!0);if(r>this.lastCurrentTime&&(this.lastCurrentTime=r),!this.loadingParts){const t=Math.max(a.end,r),e=this.shouldLoadParts(this.getLevelDetails(),t);e&&(this.log(`LL-Part loading ON after seeking to ${r} with buffer @${t}`),this.loadingParts=e)}}const l=!$i.isBuffered(i,r);this.hls.hasEnoughToStart&&!l||(this.log(`Setting ${l?"startPosition":"nextLoadPosition"} to ${r} for seek without enough to start`),this.nextLoadPosition=r,l&&(this.startPosition=r)),o<1&&this.state===an&&this.tickImmediate()},this.onMediaEnded=()=>{this.log("setting startPosition to 0 because media ended"),this.startPosition=this.lastCurrentTime=0},this.playlistType=n,this.hls=t,this.fragmentLoader=new xi(t.config),this.initFragmentLoader=new xi(t.config),this.keyLoader=i,this.fragmentTracker=e,this.config=t.config,this.decrypter=new wi(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===rn)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=rn}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 n=t.buffered;this.config.maxBufferHole&&n&&n.length>1&&(t=$i.bufferedInfo(n,t.start,0));const r=t.nextStart;if(r&&r>s&&r<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 $i.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;en(i,"seeking",this.onMediaSeeking),en(i,"ended",this.onMediaEnded);const s=this.config;this.levels&&s.autoStartLoad&&this.state===rn&&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),sn(s,"seeking",this.onMediaSeeking),sn(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=rn,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===ln||!this.fragCurrent&&e===cn)&&(this.fragmentTracker.removeFragment(i),this.state=an):("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!==rn&&this.state!==gn&&(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),n=Math.max(t.duration,s?s.len:this.config.maxBufferLength),r=this.backtrackFragment;(1===(r?t.sn-r.sn:0)||this.reduceMaxBufferLength(n,t.duration))&&i.removeFragment(t)}else 0===(null==(e=this.mediaBuffer)?void 0:e.buffered.length)?i.removeAllFragments():i.hasParts(t.type)&&(i.detectPartialFragments({frag:t,part:null,stats:t.stats,id:t.type}),i.getState(t)===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:n.NETWORK_ERROR,details:r.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:d}=Ci(i,null,this.iframesOnly);return this.decrypter.decrypt(new Uint8Array(s),o.key.buffer,o.iv.buffer,es(o.method),d).catch(t=>{throw e.trigger(a.ERROR,{type:n.MEDIA_ERROR,details:r.FRAG_DECRYPT_ERROR,fatal:!1,error:t,reason:t.message,frag:i}),this.fragmentLoader.abort(),t}).then(s=>{const n=self.performance.now();return e.trigger(a.FRAG_DECRYPTED,{frag:i,part:null,payload:s,stats:{tstart:l,tdecrypt:n}}),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===rn||this.state===gn)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:n.KEY_SYSTEM_ERROR,details:r.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?nn($i.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=an)}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=an}_handleFragmentLoadComplete(t){const{transmuxer:e}=this;if(!e)return;const i=t.frag,{part:s,partsLoaded:n}=t,r=!n||0===n.length||n.some(t=>!t),{decryptRange:a}=Ci(i,s),o=new Ni(i.level,i.sn,i.stats.chunkCount+1,0,s?s.index:-1,!r,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 n=null;return!t.encrypted||null!=(s=t.decryptdata)&&s.key?t.encrypted||(n=this.keyLoader.loadClear(t,e.encryptedFragments,this.startFragRequested),n&&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=on,n=this.keyLoader.load(t,i).then(t=>{if(!this.fragContextChanged(t.frag))return this.hls.trigger(a.KEY_LOADED,t),this.state===on&&(this.state=an),t}),this.hls.trigger(a.KEY_LOADING,{frag:t})),n}_doFragLoad(t,i,s=null,n){this.fragCurrent=t;const r=i.details;if(!this.levels||!r)throw new Error(`frag load aborted, missing level${r?"":" 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=r.partList;if(e&&n){s>r.fragmentEnd&&r.fragmentHint&&(t=r.fragmentHint);const l=this.getNextPart(e,t,s);if(l>-1){const d=e[l];if(!E(t=this.fragCurrent=d.fragment,o)&&!this.shouldLoadParts(i.details,t.end))return this.log(`LL-Part loading OFF @${this.playhead} next part: ${this.fragInfo(t,!1,d)}`),this.loadingParts=!1,Promise.resolve(null);if(!this.filterReplacedPrimary(d,i.details))return Promise.resolve(null);const h=this.loadKeyFor(t,r);if(this.fragContextChanged(t))return Promise.resolve(null);let c;this.log(`Loading ${t.type} sn: ${t.sn} part: ${d.index} (${l}/${e.length-1}) of ${this.fragInfo(t,!1,d)} cc: ${t.cc} [${r.startSN}-${r.endSN}], target: ${s}${d.byteRange.length?` range:${d.byteRange.join("-")}`:""}`),this.nextLoadPosition=d.start+d.duration,this.state=ln;const u=this.loadInitSegmentIfNeeded(t);if(h||u){const e=!!h;c=Promise.all([h,u]).then(([s])=>!e||s&&!this.fragContextChanged(s.frag)?this.doFragPartsLoad(t,d,i,n):null).catch(t=>this.handleFragLoadError(t))}else c=this.doFragPartsLoad(t,d,i,n).catch(t=>this.handleFragLoadError(t));return this.hls.trigger(a.FRAG_LOADING,{frag:t,part:d,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=r.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 d=this.loadInitSegmentIfNeeded(t),h=this.loadKeyFor(t,r,d);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==d||d.catch(()=>null),null==h||h.catch(()=>null),Promise.resolve(null);this.log(`Loading ${t.type} sn: ${t.sn} of ${this.fragInfo(t,!1)} cc: ${t.cc} ${"["+r.startSN+"-"+r.endSN+"]"}, target: ${s}${t.byteRange.length?` range:${t.byteRange.join("-")}`:""}`),e(t.sn)&&!this.bitrateTest&&(this.nextLoadPosition=t.start+t.duration),this.state=ln;const u=this.config.progressive&&t.type!==f.SUBTITLE;let g;return g=u&&h?h.then(e=>!e||this.fragContextChanged(e.frag)?null:this.fragmentLoader.load(t,this.iframesOnly,n,d)).catch(t=>this.handleFragLoadError(t)):Promise.all([this.fragmentLoader.load(t,this.iframesOnly,u?n:void 0,u?d:void 0),h,d]).then(([t])=>(!u&&n&&n(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,d]).then(([t])=>t)}doFragPartsLoad(t,e,i,s){return new Promise((n,r)=>{var o;const l=[],d=null==(o=i.details)?void 0:o.partList,h=e=>{this.fragmentLoader.loadPart(t,e,s).then(s=>{l[e.index]=s;const r=s.part;this.hls.trigger(a.FRAG_LOADED,s);const o=Hs(i.details,t.sn,e.index+1)||Ys(d,t.sn,e.index+1);if(!o)return n({frag:t,part:r,partsLoaded:l});h(o)}).catch(r)};h(e)})}handleFragLoadError(t){if("data"in t){const e=t.data;e.frag&&e.details===r.INTERNAL_ABORTED?this.handleFragLoadAborted(e.frag,e.part):e.frag&&e.type===n.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:n.OTHER_ERROR,details:r.INTERNAL_EXCEPTION,err:t,error:t,fatal:!0});return null}_handleTransmuxerFlush(t){const e=this.getCurrentContext(t);if(!e||this.state!==cn)return void(this.fragCurrent||this.state===rn||this.state===gn||(this.state=an));const{frag:i,part:s,level:n}=e,r=self.performance.now();i.stats.parsing.end=r,s&&(s.stats.parsing.end=r);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,n,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:n,part:r}=t;if(null==e||!e[s])return this.warn(`Levels object was unset while buffering fragment ${n} of ${this.playlistLabel()} ${s}. The current chunk will not be buffered.`),null;const a=e[s],o=a.details,l=r>-1?Hs(o,n,r):null,d=l?l.fragment:Vs(o,n,i);return d?(i&&i!==d&&(d.stats=i.stats),{frag:d,part:l,level:a}):null}bufferFragmentData(t,e,i,s,n){if(this.state!==cn)return;y(e)&&!this.fragContextChanged(e)&&(this.fragPrevious=e);const{data1:r,data2:o}=t;let l=r;if(o&&(l=Vt(r,o)),!l.length)return;const d=this.initPTS[e.cc],h=d?-d.baseTime/d.timescale:void 0,c={type:t.type,frag:e,part:i,chunkMeta:s,offset:h,parent:e.type,data:l};if(this.hls.trigger(a.BUFFER_APPENDING,c),t.dropped&&t.independent&&!i){if(n)return;this.flushBufferGap(e)}}flushBufferGap(t){const e=this.media;if(!e)return;if(!$i.isBuffered(e,e.currentTime))return void this.flushMainBuffer(0,t.start);const i=e.currentTime,s=$i.bufferInfo(e,i,0),n=t.duration,r=Math.min(2*this.config.maxFragLookUpTolerance,.25*n),a=Math.max(Math.min(t.start-r,s.end-r),i+r);t.start-a>r&&this.flushMainBuffer(a,t.start)}getFwdBufferInfo(t,e){var i;const s=this.playhead,n=this.lastCurrentTime>s||null!=(i=this.media)&&i.paused?0:this.config.maxBufferHole;return this.getFwdBufferInfoAtPos(t,s,e,n)}getFwdBufferInfoAtPos(t,e,i,s){const n=$i.bufferInfo(t,e,s);if(0===n.len&&void 0!==n.nextStart){const r=this.fragmentTracker.getBufferedFrag(e,i);if(r&&(n.nextStart<=r.end||r.gap)){const i=Math.max(Math.min(n.nextStart,r.end)-e,s);return $i.bufferInfo(t,e,i)}}return n}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 n=t.len;const r=t.bufferedIndex;for(let t=s.length-1;t>r;t--)s[t].start<i.start&&(n+=s[t].end-s[t].start);return n>=e}}return!1}reduceMaxBufferLength(t,e){const i=this.config,s=Math.max(Math.min(t-e,i.maxBufferLength),e/2),n=Math.max(t-3*e,i.maxMaxBufferLength/2,s);return n>=s&&(i.maxMaxBufferLength=n,this.warn(`Reduce max buffer length to ${n}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:n}=this,r=e.fragmentStart,a=n.lowLatencyMode&&!!e.partList;let o=null;if(e.live){const i=n.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<r){var l;o=this.getInitialLiveFragment(e);const i=this.config.startPosition,s=this.hls.startPosition,n=this.hls.liveSyncPosition,a=(null==(l=o)?void 0:l.start)||0;let d,h;if(-1!==s&&s>=r?(d=s,h=s===i?"config":"next load start"):n?(d=n,h="live edge"):(d=t,h="buffer pos"),d<a&&(d=a,h="live frag start"),d<r&&(d=r,h="playlist start"),this.startPosition!=d||this.nextLoadPosition!=d){const l=e.live&&!this.filterReplacedPrimary(o,e)?-1:d;this.log(`Setting startPosition to ${l} next load ${d} ${-1===s?"":`(from ${i}) `}based on ${h}. live edge: ${n} live frag start: ${a} playlist start: ${r} buffer pos: ${t}`),this.startPosition=l,this.nextLoadPosition=d}}}else t<=r&&(o=i[0]);if(!o){const i=this.loadingParts?e.partEnd:e.fragmentEnd;o=this.getFragmentAtPosition(t,i,e)}let d=this.filterReplacedPrimary(o,e);return!d&&o&&(d=ii(e,o.sn),d&&(this.nextLoadPosition=d.start)),d}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,n){let r=null;if(t.gap&&(r=this.getNextFragment(this.nextLoadPosition,e),r&&!r.gap&&i.nextStart)){const t=this.getFwdBufferInfoAtPos(this.mediaBuffer?this.mediaBuffer:this.media,i.nextStart,s,0);if(null!==t&&i.len+t.len>=n){const t=r.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,r}get primaryPrefetch(){if(En(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(En(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(yn(t,null==i?void 0:i.playerQueue,this.playhead))return null}return t}getNextPart(t,e,i){let s=-1,n=!1,r=!0;for(let a=0,o=t.length;a<o;a++){const o=t[a];if(r=r&&!o.independent,s>-1&&i<o.start)break;const l=o.loaded||o.gap;l?s=-1:(n||(o.independent||r)&&o.fragment===e)&&(s=a),n=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 n=null;if(s){if(t.hasProgramDateTime&&(n=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 n=t[e];if(ti(i,s,n))return n}return null}(i,s.endProgramDateTime,this.config.maxFragLookUpTolerance),n&&this.log(`Live playlist, switching playlist, load frag with same PDT: ${s.programDateTime}`)),!n){const e=s.sn+1;if(e>=t.startSN&&e<=t.endSN){const r=i[e-t.startSN];s.cc===r.cc&&(n=r,this.log(`Live playlist, switching playlist, load frag with next SN: ${n.sn}`))}n||(n=ei(t,s.cc,s.end),n&&this.log(`Live playlist, switching playlist, load frag with same CC: ${n.sn}`))}}else{const e=this.hls.liveSyncPosition;null!==e&&(n=this.getFragmentAtPosition(e,this.bitrateTest?t.fragmentEnd:t.edge,t))}return n}getFragmentAtPosition(t,e,i){const{config:s}=this;let{fragPrevious:n}=this,{fragments:r,endSN:a}=i;const{fragmentHint:o}=i,{maxFragLookUpTolerance:l}=s,d=i.partList,h=!!(this.loadingParts&&null!=d&&d.length&&o);let c;if(h&&!this.bitrateTest&&d[d.length-1].fragment.sn===o.sn&&(r=r.concat(o),a=o.sn),n&&this.fragmentTracker.getState(n)===mi&&(n=null),t<e){var u;c=Ze(n,r,t,t<this.lastCurrentTime||t>e-l||null!=(u=this.media)&&u.paused||!this.startFragRequested?0:l)}else c=r[r.length-1];if(c){const t=c.sn-i.startSN,e=this.fragmentTracker.getState(c);if((e===Ei||e===yi&&c.gap)&&(n=c),E(c,n)&&(!h||d[0].fragment.sn>c.sn||!i.live)){const e=r[t+1];c=c.sn<a&&this.fragmentTracker.getState(e)!==Ei?e:null}}return c}alignPlaylists(t,i,s){const n=t.fragments.length;if(!n)return this.warn("No fragments in live playlist"),0;const r=t.fragmentStart,a=!i,o=t.alignedSliding&&e(r);if(a||!o&&!r){tn(s,t,this);const e=t.fragmentStart;return this.log(`Live playlist sliding: ${e} start-sn: ${i?i.startSN:"na"}->${t.startSN} fragments: ${n}`),e}return r}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 n=this.timelineOffset;if(-1===s){const r=null!==this.startTimeOffset,a=r?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 ${r?"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+n}this.nextLoadPosition=s+n}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===dn)||(this.state=an)}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 n;if(this.fragContextChanged(i))return void this.warn(`Frag load error must match current frag to retry ${i.relurl} > ${null==(n=this.fragCurrent)?void 0:n.relurl}`);const a=e.details===r.FRAG_GAP;a&&this.fragmentTracker.addAsGap(i);const o=e.errorAction;if(!o)return void(this.state=gn);const{action:l,flags:d,retryCount:h=0,retryConfig:c}=o,u=!!c,f=u&&l===ai,g=u&&!o.resolved&&d&li,p=this.hls.latestLevelDetails,m=null==p?void 0:p.live;if(!f&&g&&y(i)&&m&&i.sn<p.endSN&&!x(e))this.resetFragmentErrors(t),s?s.gap=!0:this.treatAsGap(i),o.resolved=!0;else if((f||g)&&h<c.maxNumRetry){var v;const s=F(null==(v=e.response)?void 0:v.code),n=C(c,h);if(this.resetStartWhenNotLoaded(),this.retryDate=self.performance.now()+n,this.state=dn,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 ${h+1}/${c.maxNumRetry} in ${n}ms`)}else if(c){if(this.resetFragmentErrors(t),!(h<c.maxNumRetry))return void this.warn(`${e.details} reached or exceeded max retry (${h})`);a||l===ri||(o.resolved=!0)}else this.state=l===ni?mn:gn;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=an)}reduceLengthAndFlushBuffer(t){if(this.state===cn||this.state===un){const e=t.frag,i=t.parent,s=this.getFwdBufferInfo(this.mediaBuffer,i),n=s&&s.len>.5;n&&this.reduceMaxBufferLength(s.len,(null==e?void 0:e.duration)||10);const r=!n;return r?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(),r}return!1}resetFragmentErrors(t){t===f.AUDIO&&(this.fragCurrent=null),this.hls.hasEnoughToStart||(this.startFragRequested=!1),this.state!==rn&&(this.state=an)}afterBufferFlushed(t,e){if(!t)return;const i=$i.getBuffered(t);this.fragmentTracker.detectEvictedFragments(e,i,this.playlistType),this.state===fn&&this.resetLoadingState()}resetLoadingState(){this.log("Reset loading state"),this.fragCurrent=null,this.fragPrevious=null,this.state!==rn&&(this.state=an)}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,n)=>{const r=t.elementaryStreams[n];if(r){const l=r.endPTS-r.startPTS;if(l<=0)return this.warn(`Could not parse fragment ${t.sn} ${n} duration reliably (${l})`),e||!1;const d=s.partial?0:Us(o,t,r.startPTS,r.endPTS,r.startDTS,r.endDTS,this.iframesOnly,this);return this.hls.trigger(a.LEVEL_PTS_UPDATED,{details:o,level:i,drift:d,type:n,frag:t,start:r.startPTS,end:r.endPTS}),!0}return e},!1)){var l,d,h,c;const s=null===(null==(l=this.transmuxer)?void 0:l.error),o=null!=(null==(d=this.transmuxer)?void 0:d.error),u=(null!=(h=null==(c=this.levels)?void 0:c.length)?h: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:n.MEDIA_ERROR,details:r.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=un,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,n;return`${this.playlistLabel()} ${t.level} (${i?"part":"frag"}:[${null!=(s=e&&!i?t.startPTS:(i||t).start)?s:NaN}-${null!=(n=e&&!i?t.endPTS:(i||t).end)?n: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,n=(i.total-i.loaded)/(this.hls.bandwidthEstimate||this.hls.config.abrEwmaDefaultEstimate);return s&&n<=.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:n,config:r,levels:a,playlistType:o}=this,l=this.getLevelDetails();if(n&&!n.paused&&a){var d;const e=o===f.AUDIO?_e(t.audioCodec,128e3):t.maxBitrate,n=1+s.ttfbEstimate/1e3,a=s.bandwidthEstimate*r.abrBandWidthUpFactor;i=n+e*(l&&(this.loadingParts?l.partTarget:l.averagetargetduration)||(null==(d=this.fragCurrent)?void 0:d.duration)||6)/a,t.details||(i+=n)}const h=this.playhead;return{fetchdelay:i,okToFlushForwardBuffer:!(null!=l&&l.live)||e.end-h>1.5*i}}scheduleTrackSwitch(t,e,i){const{media:s,playlistType:n}=this;if(!s||!t)return;const r=i?this.getBufferedFrag(this.playhead+e):null;if(r){const t=this.followingBufferedFrag(r);if(t){var a;this.abortCurrentFrag();const e=t.maxStartPTS?t.maxStartPTS:t.start,i=t.duration,s=Math.max(r.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=n===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 on:case ln:case dn:case cn:case un:this.state=an}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($i.isBuffered(t,i)?e=this.getAppendedFrag(i):$i.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:n}=this;if(null!=e&&e.readyState&&t&&i&&s){const e=this.getBufferOutput(),s=this.getFwdBufferInfo(e,n);if(!s)return;const r=t[n===f.AUDIO?i.nextAudioTrack:i.nextLoadLevel],{fetchdelay:a,okToFlushForwardBuffer:o}=this.calculateOptimalSwitchPoint(r,s);this.scheduleTrackSwitch(s,a,o)}this.tickImmediate()}}function yn(t,e,i){if(e)for(let s=e.length;s--;){const n=e[s].interstitial,r=n.startTime,a=Math.min(r+n.duration,n.resumeTime);if(n.appendInPlace){if(t.start>=r&&t.end<=a)return!0;if(i>t.start&&t.end>r&&t.start<a)return!0}}return!1}function En(t){return!!t.interstitialsController&&!1!==t.enableInterstitialPlayback}class Tn{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 n=t[e];i.set(n,s),s+=n.length}return i}(t,e),this.reset(),i):new Uint8Array(0)}reset(){this.chunks.length=0,this.dataLength=0}}var Sn,bn={exports:{}};var An=(Sn||(Sn=1,function(t){var e=Object.prototype.hasOwnProperty,i="~";function s(){}function n(t,e,i){this.fn=t,this.context=e,this.once=i||!1}function r(t,e,s,r,a){if("function"!=typeof s)throw new TypeError("The listener must be a function");var o=new n(s,r||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,n=[];if(0===this._eventsCount)return n;for(s in t=this._events)e.call(t,s)&&n.push(i?s.slice(1):s);return Object.getOwnPropertySymbols?n.concat(Object.getOwnPropertySymbols(t)):n},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 n=0,r=s.length,a=new Array(r);n<r;n++)a[n]=s[n].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,n,r,a){var o=i?i+t:t;if(!this._events[o])return!1;var l,d,h=this._events[o],c=arguments.length;if(h.fn){switch(h.once&&this.removeListener(t,h.fn,void 0,!0),c){case 1:return h.fn.call(h.context),!0;case 2:return h.fn.call(h.context,e),!0;case 3:return h.fn.call(h.context,e,s),!0;case 4:return h.fn.call(h.context,e,s,n),!0;case 5:return h.fn.call(h.context,e,s,n,r),!0;case 6:return h.fn.call(h.context,e,s,n,r,a),!0}for(d=1,l=new Array(c-1);d<c;d++)l[d-1]=arguments[d];h.fn.apply(h.context,l)}else{var u,f=h.length;for(d=0;d<f;d++)switch(h[d].once&&this.removeListener(t,h[d].fn,void 0,!0),c){case 1:h[d].fn.call(h[d].context);break;case 2:h[d].fn.call(h[d].context,e);break;case 3:h[d].fn.call(h[d].context,e,s);break;case 4:h[d].fn.call(h[d].context,e,s,n);break;default:if(!l)for(u=1,l=new Array(c-1);u<c;u++)l[u-1]=arguments[u];h[d].fn.apply(h[d].context,l)}}return!0},o.prototype.on=function(t,e,i){return r(this,t,e,i,!1)},o.prototype.once=function(t,e,i){return r(this,t,e,i,!0)},o.prototype.removeListener=function(t,e,s,n){var r=i?i+t:t;if(!this._events[r])return this;if(!e)return a(this,r),this;var o=this._events[r];if(o.fn)o.fn!==e||n&&!o.once||s&&o.context!==s||a(this,r);else{for(var l=0,d=[],h=o.length;l<h;l++)(o[l].fn!==e||n&&!o[l].once||s&&o[l].context!==s)&&d.push(o[l]);d.length?this._events[r]=1===d.length?d[0]:d:a(this,r)}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}(bn)),bn.exports),Ln=o(An);const In="1.7.3",Rn={};function _n(t,e){return 255===t[e]&&240==(246&t[e+1])}function kn(t,e){return 1&t[e+1]?7:9}function wn(t,e){return(3&t[e+3])<<11|t[e+4]<<3|(224&t[e+5])>>>5}function Dn(t,e){return e+1<t.length&&_n(t,e)}function xn(t,e){if(Dn(t,e)){const i=kn(t,e);if(e+i>=t.length)return!1;const s=wn(t,e);if(s<=i)return!1;const n=e+s;return n===t.length||Dn(t,n)}return!1}function Pn(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:n.MEDIA_ERROR,details:r.FRAG_PARSING_ERROR,fatal:!0,error:e,reason:e.message})}const d=1+(o>>6&3),h=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!==d&&29!==d||(f-=3);const g=(14&f)>>1,p=(1&f)<<7|h<<3;let m=0;if(1===d&&l>=6){m=5;const t=l-3;u=[m<<3|g,p|(14&t)>>1,(1&t)<<7|8,0]}else u=[d<<3|g,p];const v="mp4a.40."+(m||d);return H.log(`manifest codec:${s}, parsed codec:${v}, channels:${h}, rate:${c} (ADTS object type:${d} sampling index:${l} esds config:[${u.join(",")}])`),{config:u,samplerate:c,channelCount:h,codec:v,parsedCodec:v,manifestCodec:s}}(e,i,s,o);if(!l)return;I(t,l)}}function Cn(t){return 9216e4/t}function Mn(t,e,i,s,n){const r=s+n*Cn(t.samplerate),a=function(t,e){const i=kn(t,e);if(e+i<=t.length){const s=wn(t,e)-i;if(s>0)return{headerLength:i,frameLength:s}}}(e,i);let o;if(a){const{frameLength:s,headerLength:n}=a,l=n+s,d=Math.max(0,i+l-e.length);d?(o=new Uint8Array(l-n),o.set(e.subarray(i+n,e.length),0)):o=e.subarray(i+n,i+l);const h={unit:o,pts:r};return d||t.samples.push(h),{sample:h,length:l,missing:d}}const l=e.length-i;o=new Uint8Array(l),o.set(e.subarray(i,e.length),0);return{sample:{unit:o,pts:r},length:l,missing:-1}}let On=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 Fn(t="",e=9e4){return{type:t,id:-1,pid:-1,inputTimeScale:e,sequenceNumber:-1,samples:[],dropped:0}}class Nn{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=Vt(this.cachedData,t),this.cachedData=null);let s,n=rt(t,0),r=n?n.length:0;const a=this._audioTrack,o=this._id3Track,l=n?gt(n):void 0,d=t.length;for((null===this.basePTS||0===this.frameIndex&&e(l))&&(this.basePTS=Bn(l,i,this.initPTS),this.lastPTS=this.basePTS),null===this.lastPTS&&(this.lastPTS=this.basePTS),n&&n.length>0&&o.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:n,type:On.audioId3,duration:Number.POSITIVE_INFINITY});r<d;){if(this.canParse(t,r)){const e=this.appendFrame(a,t,r);e?(this.frameIndex++,this.lastPTS=e.sample.pts,r+=e.length,s=r):r=d}else st(t,r)?(n=rt(t,r),o.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:n,type:On.audioId3,duration:Number.POSITIVE_INFINITY}),r+=n.length,s=r):r++;if(r===d&&s!==d){const e=t.slice(s);this.cachedData?this.cachedData=Vt(this.cachedData,e):this.cachedData=e}}return{audioTrack:a,videoTrack:Fn(),id3Track:o,textTrack:Fn()}}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:Fn(),id3Track:this._id3Track,textTrack:Fn()}}destroy(){this.cachedData=null,this._audioTrack=this._id3Track=void 0}}const Bn=(t,i,s)=>{if(e(t))return 90*t;return 9e4*i+(s?9e4*s.baseTime/s.timescale:0)},$n=[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],Un=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],Gn=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],jn=[0,1,1,4];function qn(t,e,i,s,n){if(i+24>e.length)return;const r=Kn(e,i);if(r&&i+r.frameLength<=e.length){const a=s+n*(9e4*r.samplesPerFrame/r.sampleRate),o={unit:e.subarray(i,i+r.frameLength),pts:a,dts:a};return t.config=[],t.channelCount=r.channelCount,t.samplerate=r.sampleRate,t.samples.push(o),{sample:o,length:r.frameLength,missing:0}}}function Kn(t,e){const i=t[e+1]>>3&3,s=t[e+1]>>1&3,n=t[e+2]>>4&15,r=t[e+2]>>2&3;if(1!==i&&0!==n&&15!==n&&3!==r){const a=t[e+2]>>1&1,o=t[e+3]>>6,l=1e3*$n[14*(3===i?3-s:3===s?3:4)+n-1],d=Un[3*(3===i?0:2===i?1:2)+r],h=3===o?1:2,c=Gn[i][s],u=jn[s],f=8*c*u,g=Math.floor(c*l/d+a)*u,p=re();return!!p&&p<=87&&2===s&&l>=224e3&&0===o&&(t[e+3]=128|t[e+3]),{sampleRate:d,channelCount:h,frameLength:g,samplesPerFrame:f}}}function Vn(t,e){return!(255!==t[e]||224&~t[e+1]||!(6&t[e+1]))}function Hn(t,e){return e+1<t.length&&Vn(t,e)}function Yn(t,e){if(e+1<t.length&&Vn(t,e)){const i=4,s=Kn(t,e);let n=i;null!=s&&s.frameLength&&(n=s.frameLength);const r=e+n;return r===t.length||Hn(t,r)}return!1}class Wn{constructor(t,e,i){this.keyData=void 0,this.decrypter=void 0,this.keyData=i,this.decrypter=new wi(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 n=s.subarray(16,s.length-s.length%16),r=n.buffer.slice(n.byteOffset,n.byteOffset+n.length);this.decryptBuffer(r).then(n=>{const r=new Uint8Array(n);s.set(r,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,n){const r=zt(n.data),a=this.getAvcEncryptedData(r);this.decryptBuffer(a.buffer).then(a=>{n.data=this.getAvcDecryptedUnit(r,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 n=t[e].units;for(;!(i>=n.length);i++){const r=n[i];if(!(r.data.length<=48||1!==r.type&&5!==r.type||(this.decryptAvcSample(t,e,i,s,r),this.decrypter.isSync())))return}}}}const zn=(t,e)=>{let i=0,s=5;e+=s;const n=new Uint32Array(1),r=new Uint32Array(1),a=new Uint8Array(1);for(;s>0;){a[0]=t[e];const o=Math.min(s,8),l=8-o;r[0]=4278190080>>>24+l<<l,n[0]=(a[0]&r[0])>>l,i=i?i<<o|n[0]:n[0],e+=1,s-=o}return i};class Xn extends Nn{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=Qn(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=rt(t,0);if(!e)return!1;const i=e.length;if(11===t[i]&&119===t[i+1]&&void 0!==gt(e)){if(zn(t,i)<16)return!0;throw new Error("Containerless ec-3 is not supported")}return!1}}function Qn(t,e,i,s,n){if(i+8>e.length)return-1;if(11!==e[i]||119!==e[i+1])return-1;const r=e[i+4]>>6;if(r>=3)return-1;const a=[48e3,44100,32e3][r],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+r];if(i+l>e.length)return-1;const d=e[i+6]>>5;let h=0;2===d?h+=2:(1&d&&1!==d&&(h+=2),4&d&&(h+=2));const c=(e[i+6]<<8|e[i+7])>>12-h&1,u=[2,1,2,3,3,4,4,5][d]+c,f=e[i+5]>>3,g=7&e[i+5],p=new Uint8Array([r<<6|f<<1|g>>2,(3&g)<<6|d<<3|c<<2|o>>4,o<<4&224]),m=s+n*(1536/a*9e4),v=e.subarray(i,i+l);return t.config=p,t.channelCount=u,t.samplerate=a,t.samples.push({unit:v,pts:m}),l}const Zn=/\/emsg[-/]ID3/i;function Jn(t,i){return e(t.presentationTime)?t.presentationTime/t.timeScale:i+t.presentationTimeDelta/t.timeScale}class tr{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 n=t.naluState||0,r=-1===n?0:n,a=[];let o=0,l=0,d=-1,h=0;for(-1===n&&(d=0,h=this.getNALuType(e,0),l=1);l<s;){const i=e.indexOf(1,l);if(-1===i)break;l=i+1;let n=i;for(;n>0&&0===e[n-1];)n--;if(!(i-n+(0===n?r:0)<2)){if(d>=0)a.push({data:e.subarray(d,n),type:h});else{const i=this.getLastNalUnit(t.samples);i&&(n>0?i.data=Vt(i.data,e.subarray(0,n)):r>0&&(i.data=i.data.subarray(0,i.data.byteLength-r)),i.state=0)}if(!(l<s)){o=-1,d=-1;break}d=l,h=this.getNALuType(e,l)}}if(-1!==o){let t=s;for(;t>0&&0===e[t-1];)t--;o=s-t+(0===t?r:0)}if(d>=0)a.push({data:e.subarray(d),type:h,state:o});else if(0===a.length&&-1!==o){const i=this.getLastNalUnit(t.samples);i&&(i.data=Vt(i.data,e),i.state=o)}return t.naluState=o,a}}class er{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),n=Math.min(4,e);if(0===n)throw new Error("no bytes available");s.set(t.subarray(i,i+n)),this.word=new DataView(s.buffer).getUint32(0),this.bitsAvailable=8*n,this.bytesAvailable-=n}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&&H.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 ir extends tr{parsePES(t,e,i,s,n){const r=n.iframe,a=this.parseNALu(t,i.data,s);let o,l=this.VideoSample,d=!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 n,a;switch(s.type){case 1:{if(r)break;let e=!1;o=!0;const n=s.data;if(d&&n.length>4){const t=this.readSliceType(n);2!==t&&4!==t&&7!==t&&9!==t||(e=!0)}var h;if(e)null!=(h=l)&&h.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!=(n=l)&&n.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(r)break;o=!0,Wt(s.data,1,i.pts,e.samples);break;case 7:{var c,u;o=!0,d=!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 n="avc1.";for(let t=0;t<3;t++){let e=s[t].toString(16);e.length<2&&(e="0"+e),n+=e}t.codec=n}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 er(t);return e.readUByte(),e.readUEG(),e.readUEG()}skipScalingList(t,e){let i,s=8,n=8;for(let r=0;r<t;r++)0!==n&&(i=e.readEG(),n=(s+i+256)%256),s=0===n?s:n}readSPS(t){const e=new er(t);let i,s,n,r=0,a=0,o=0,l=0;const d=e.readUByte.bind(e),h=e.readBits.bind(e),c=e.readUEG.bind(e),u=e.readBoolean.bind(e),f=e.skipBits.bind(e),g=e.skipEG.bind(e),p=e.skipUEG.bind(e),m=this.skipScalingList.bind(this);d();const v=d();if(h(5),f(3),d(),p(),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),p(),p(),f(1),u())for(s=3!==t?8:12,n=0;n<s;n++)u()&&m(n<6?16:64,e)}p();const y=c();if(0===y)c();else if(1===y)for(f(1),g(),g(),i=c(),n=0;n<i;n++)g();p(),f(1);const E=c(),T=c(),S=h(1);0===S&&f(1),f(1),u()&&(r=c(),a=c(),o=c(),l=c());let b=[1,1];if(u()&&u()){switch(d()){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=[d()<<8|d(),d()<<8|d()]}}return{width:Math.ceil(16*(E+1)-2*r-2*a),height:(2-S)*(T+1)*16-(S?2:4)*(o+l),pixelRatio:b}}}class sr extends tr{constructor(...t){super(...t),this.initVPS=null}parsePES(t,e,i,s){const n=this.parseNALu(t,i.data,s);let r,a=this.VideoSample,o=!1;i.data=null;const l=t=>(a=this.VideoSample=this.createVideoSample(t,i.pts,i.dts),a);n.forEach((s,n)=>{var d,h;if(this.startsNewAccessUnit(a,t,s,n)){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,r=!0;break;case 16:case 17:case 18:case 21:case 22:case 23:var c;if(r=!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:r=!0,null!=(d=a)&&d.frame&&!a.key&&(this.pushAccessUnit(a,t),a=this.VideoSample=null),a||(a=l(!0)),a.key=!0,a.frame=!0;break;case 39:r=!0,Wt(s.data,2,i.pts,e.samples);break;case 32:r=!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(r=!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(r=!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:r=!0,t.audFound=!0,null!=(h=a)&&h.frame&&(this.pushAccessUnit(a,t),a=null),a||(a=l(!1));break;default:r=!1}if(a&&r){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:n,data:r}=i;return!!(n>=32&&n<=35||39===n||n>=41&&n<=44||n>=48&&n<=55)||n<=31&&r.length>2&&!!(128&r[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 er(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 er(this.ebsp2rbsp(t));e.readUByte(),e.readUByte(),e.readBits(4);const i=e.readBits(3);e.readBoolean();const s=e.readBits(2),n=e.readBoolean(),r=e.readBits(5),a=e.readUByte(),o=e.readUByte(),l=e.readUByte(),d=e.readUByte(),h=e.readUByte(),c=e.readUByte(),u=e.readUByte(),f=e.readUByte(),g=e.readUByte(),p=e.readUByte(),m=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 _=e.readUEG(),k=e.readUEG(),w=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 D=e.readUEG();let x=0;for(let t=0;t<D;t++){let i=!1;if(0!==t&&(i=e.readBoolean()),i){t===D&&e.readUEG(),e.readBoolean(),e.readUEG();let i=0;for(let t=0;t<=x;t++){const t=e.readBoolean();let s=!1;t||(s=e.readBoolean()),(t||s)&&i++}x=i}else{const t=e.readUEG(),i=e.readUEG();x=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<w+4;t++)e.readBits(1);e.readBits(1)}}let P=0,C=1,M=1,O=!0,F=1,N=0;e.readBoolean(),e.readBoolean();let B=!1;if(e.readBoolean()){if(e.readBoolean()){const t=e.readUByte();t>0&&t<16?(C=[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&&(C=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(),B=e.readBoolean(),B&&(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 n=!1;(t||s)&&(n=e.readBoolean(),n&&(e.readUByte(),e.readBits(5),e.readBoolean(),e.readBits(5)),e.readBits(4),e.readBits(4),n&&e.readBits(4),e.readBits(5),e.readBits(5),e.readBits(5));for(let r=0;r<=i;r++){O=e.readBoolean();let i=!1;O||e.readBoolean()?e.readEG():i=e.readBoolean();const r=i?1:e.readUEG()+1;if(t)for(let t=0;t<r;t++)e.readUEG(),e.readUEG(),n&&(e.readUEG(),e.readUEG()),e.skipBits(1);if(s)for(let t=0;t<r;t++)e.readUEG(),e.readUEG(),n&&(e.readUEG(),e.readUEG()),e.skipBits(1)}}}e.readBoolean()&&(e.readBoolean(),e.readBoolean(),e.readBoolean(),P=e.readUEG())}let $=T,U=S;if(b){let t=1,e=1;1===E?t=e=2:2==E&&(t=2),$=T-t*L-t*A,U=S-e*R-e*I}const G=s?["A","B","C"][s]:"",j=a<<24|o<<16|l<<8|d;let q=0;for(let t=0;t<32;t++)q=(q|(j>>t&1)<<31-t)>>>0;let K=q.toString(16);1===r&&"2"===K&&(K="6");return{codecString:`hvc1.${G}${r}.${K}.${n?"H":"L"}${m}.B0`,params:{general_tier_flag:n,general_profile_idc:r,general_profile_space:s,general_profile_compatibility_flags:[a,o,l,d],general_constraint_indicator_flags:[h,c,u,f,g,p],general_level_idc:m,bit_depth:_+8,bit_depth_luma_minus8:_,bit_depth_chroma_minus8:k,min_spatial_segmentation_idc:P,chroma_format_idc:E,frame_rate:{fixed:O,fps:N/F}},width:$,height:U,pixelRatio:[C,M]}}readPPS(t){const e=new er(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 n=1;return s&&i?n=0:s?n=3:i&&(n=2),{parallelismType:n}}matchSPS(t,e){return yt(t).substring(3)===yt(e).substring(3)}}const nr=188;class rr{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=rr.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-nr)+1,s=0;for(;s<i;){let n=!1,r=-1,a=0;for(let o=s;o<e;o+=nr){if(71!==t[o]||e-o!==nr&&71!==t[o+nr]){if(a)return-1;break}if(a++,-1===r&&(r=o,0!==r&&(i=Math.min(r+18612,t.length-nr)+1)),n||(n=0===ar(t,o)),n&&a>1&&(0===r&&a>2||o+nr>i))return r}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,n,r){this.pmtParsed=!1,this._pmtId=-1,this._videoTrack=rr.createTrack("video"),this._videoTrack.duration=s,this.videoIntegrityChecker="skip"===this.config.handleMpegTsVideoIntegrityErrors?new ur(this.logger):null,this._audioTrack=rr.createTrack("audio",s),this._id3Track=rr.createTrack("id3"),this._txtTrack=rr.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,r,"SAMPLE-AES"===(null==n?void 0:n.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,n=!1){let r;s||(this.sampleAes=null);const a=this._videoTrack,o=this.videoIntegrityChecker,l=this._audioTrack,d=this._id3Track,h=this._txtTrack,c=i.iframe;let u=a.pid,f=a.pesData,g=l.pid,p=d.pid,m=this._klvPid,v=l.pesData,y=d.pesData,E=null,T=null,S=this.pmtParsed,b=this._pmtId,A=t.length;if(this.remainderData&&(A=(t=Vt(this.remainderData,t)).length,this.remainderData=null),A<nr&&!n)return this.remainderData=t,{audioTrack:l,videoTrack:a,id3Track:d,textTrack:h};const L=Math.max(0,rr.syncOffset(t));A-=(A-L)%nr,A<t.byteLength&&!n&&(this.remainderData=new Uint8Array(t.buffer,A,t.buffer.byteLength-A));let I=0;for(let e=L;e<A;e+=nr)if(71===t[e]){const n=!!(64&t[e+1]),A=ar(t,e);let I;if((48&t[e+3])>>4>1){if(I=e+5+t[e+4],I===e+nr)continue}else I=e+4;switch(A){case u:n&&(!f||null!=o&&o.isCorrupted||!(r=cr(f,this.logger))||(this.readyVideoParser(a.segmentCodec),null!==this.videoParser&&this.videoParser.parsePES(a,h,r,!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+nr)),f.size+=e+nr-I);break;case g:if(c)break;if(n){if(v&&(r=cr(v,this.logger)))switch(l.segmentCodec){case"aac":this.parseAACPES(l,r,i);break;case"mp3":this.parseMPEGPES(l,r);break;case"ac3":this.parseAC3PES(l,r)}v={data:[],size:0}}v&&(v.data.push(t.subarray(I,e+nr)),v.size+=e+nr-I);break;case p:if(c)break;n&&(y&&(r=cr(y,this.logger))&&this.parseID3PES(d,r),y={data:[],size:0}),y&&(y.data.push(t.subarray(I,e+nr)),y.size+=e+nr-I);break;case m:if(c)break;n&&(E&&(r=cr(E,this.logger))&&this.parseKlvPES(d,r),E={data:[],size:0}),E&&(E.data.push(t.subarray(I,e+nr)),E.size+=e+nr-I);break;case 0:n&&(I+=t[I]+1),b=this._pmtId=or(t,I);break;case b:{n&&(I+=t[I]+1);const r=lr(t,I,this.typeSupported,s,this.observer,this.logger,this.config,i);u=r.videoPid,u>0&&(a.pid=u,a.segmentCodec=r.segmentVideoCodec),g=r.audioPid,g>0&&(l.pid=g,l.segmentCodec=r.segmentAudioCodec),p=r.id3Pid,p>0&&(d.pid=p),m=r.klvPid,m>0&&(this._klvPid=m),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&&dr(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,d.pesData=y;const R={audioTrack:l,videoTrack:a,id3Track:d,textTrack:h};return n&&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:n,textTrack:r}=t,a=s.pesData,o=i.pesData,l=n.pesData,d=this.videoIntegrityChecker;let h;if(!a||null!=d&&d.isCorrupted||!(h=cr(a,this.logger))?s.pesData=a:(this.readyVideoParser(s.segmentCodec),null!==this.videoParser&&(this.videoParser.parsePES(s,r,h,!0,e),s.pesData=null)),o&&(h=cr(o,this.logger))){switch(i.segmentCodec){case"aac":this.parseAACPES(i,h,e);break;case"mp3":this.parseMPEGPES(i,h);break;case"ac3":this.parseAC3PES(i,h)}i.pesData=null}else null!=o&&o.size&&this.logger.log("last AAC PES packet truncated,might overlap between fragments"),i.pesData=o;l&&(h=cr(l,this.logger))?(this.parseID3PES(n,h),n.pesData=null):n.pesData=l}demuxSampleAes(t,e,i,s){const n=this.demux(t,i,s,!0,!this.config.progressive),r=this.sampleAes=new Wn(this.observer,this.config,e);return this.decrypt(n,r)}readyVideoParser(t){null===this.videoParser&&("avc"===t?this.videoParser=new ir:"hevc"===t&&(this.videoParser=new sr))}decrypt(t,e){return new Promise(i=>{const{audioTrack:s,videoTrack:n}=t;s.samples&&"aac"===s.segmentCodec?e.decryptAacSamples(s.samples,0,()=>{n.samples?e.decryptAvcSamples(n.samples,0,0,()=>{i(t)}):i(t)}):n.samples&&e.decryptAvcSamples(n.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 n=this.aacOverFlow;let r,a,o,l=e.data;if(n){this.aacOverFlow=null;const e=n.missing,i=n.sample.unit.byteLength;if(-1===e)l=Vt(n.sample.unit,l);else{const r=i-e;n.sample.unit.set(l.subarray(0,e),r),t.samples.push(n.sample),s=n.missing}}for(r=s,a=l.length;r<a-1&&!Dn(l,r);r++);if(r!==s){let t;const e=r<a-1;if(t=e?`AAC PES did not start with ADTS header,offset:${r}`:"No ADTS header found in AAC PES",dr(this.observer,new Error(t),i,e,this.logger),!e)return}if(Pn(t,this.observer,l,r,this.audioCodec),void 0!==e.pts)o=e.pts;else{if(!n)return void this.logger.warn("[tsdemuxer]: AAC PES unknown PTS");{const e=Cn(t.samplerate);o=n.sample.pts+e}}let d,h=0;for(;r<a;){if(d=Mn(t,l,r,o,h),r+=d.length,d.missing){this.aacOverFlow=d;break}for(h++;r<a-1&&!Dn(l,r);r++);}}parseMPEGPES(t,e){const i=e.data,s=i.length;let n=0,r=0;const a=e.pts;if(void 0!==a)for(;r<s;)if(Hn(i,r)){const e=qn(t,i,r,a,n);if(!e)break;r+=e.length,n++}else r++;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 n=i.length;let r,a=0,o=0;for(;o<n&&(r=Qn(t,i,o,s,a++))>0;)o+=r}}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?On.emsg:On.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 n=e.data;if(n.length<16)return void this.logger.warn("[tsdemuxer]: KLV PES payload too short");let r=0;for(;r<n.length;){var a;if(r+16>n.length)break;const i=r;if(r+=16,r>=n.length)break;const o=n[r];r+=1;let l=0;if(128&o){const t=127&o;if(0===t||t>4||r+t>n.length){this.logger.warn("[tsdemuxer]: Invalid KLV length encoding");break}for(let e=0;e<t;e++)l=l<<8|n[r+e];r+=t}else l=o;if(r+l>n.length){this.logger.warn("[tsdemuxer]: KLV value extends beyond PES payload");break}const d=r+l,h=n.subarray(i,d),c={data:h,len:h.byteLength,pts:s,dts:null!=(a=e.dts)?a:s,type:On.misbklv,duration:Number.POSITIVE_INFINITY};t.samples.push(c),r=d}}}function ar(t,e){return((31&t[e+1])<<8)+t[e+2]}function or(t,e){return(31&t[e+10])<<8|t[e+11]}function lr(t,e,i,s,n,r,a,o){const l={audioPid:-1,videoPid:-1,id3Pid:-1,klvPid:-1,segmentVideoCodec:"avc",segmentAudioCodec:"aac"},d=e+3+((15&t[e+1])<<8|t[e+2])-4;for(e+=12+((15&t[e+10])<<8|t[e+11]);e<d;){const d=ar(t,e),h=(15&t[e+3])<<8|t[e+4];switch(t[e]){case 207:if(!s){hr("ADTS AAC",r);break}case 15:-1===l.audioPid&&(l.audioPid=d);break;case 21:-1===l.id3Pid&&(l.id3Pid=d);break;case 219:if(!s){hr("H.264",r);break}case 27:-1===l.videoPid&&(l.videoPid=d);break;case 3:case 4:i.mpeg||i.mp3?-1===l.audioPid&&(l.audioPid=d,l.segmentAudioCodec="mp3"):r.log("MPEG audio found, not supported in this browser");break;case 193:if(!s){hr("AC-3",r);break}case 129:i.ac3?-1===l.audioPid&&(l.audioPid=d,l.segmentAudioCodec="ac3"):r.log("AC-3 audio found, not supported in this browser");break;case 6:if(h>0){let s=e+5,n=h;for(;n>2;){switch(t[s]){case 106:-1===l.audioPid&&(!0!==i.ac3?r.log("AC-3 audio found, not supported in this browser for now"):(l.audioPid=d,l.segmentAudioCodec="ac3"));break;case 5:-1===l.klvPid&&a.enableEmsgKLVMetadata&&(l.klvPid=d,r.log(`KLV metadata PID found: ${d}`))}const e=t[s+1]+2;s+=e,n-=e}}break;case 194:case 135:return dr(n,new Error("Unsupported EC-3 in M2TS found"),o,void 0,r),l;case 36:-1===l.videoPid&&(l.videoPid=d,l.segmentVideoCodec="hevc",r.log("HEVC in M2TS found"))}e+=h+5}return l}function dr(t,e,i,s,o){o.warn(`parsing error: ${e.message}`),t.emit(a.ERROR,a.ERROR,{type:n.MEDIA_ERROR,details:r.FRAG_PARSING_ERROR,fatal:!1,levelRetry:s,chunkMeta:i,error:e,reason:e.message})}function hr(t,e){e.log(`${t} with AES-128-CBC encryption found in unencrypted stream`)}function cr(t,e){let i,s,n,r,a,o=0;const l=t.data;if(!t||0===t.size)return null;for(;l[0].length<19&&l.length>1;)l[0]=Vt(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 d=i[7];192&d&&(r=536870912*(14&i[9])+4194304*(255&i[10])+16384*(254&i[11])+128*(255&i[12])+(254&i[13])/2,64&d?(a=536870912*(14&i[14])+4194304*(255&i[15])+16384*(254&i[16])+128*(255&i[17])+(254&i[18])/2,r-a>54e5&&(e.warn(`${Math.round((r-a)/9e4)}s delta between PTS and DTS, align them`),r=a)):a=r),n=i[8];let h=n+9;if(t.size<=h)return null;t.size-=h;const c=new Uint8Array(t.size);for(let t=0,e=l.length;t<e;t++){i=l[t];let e=i.byteLength;if(h){if(h>e){h-=e;continue}i=i.subarray(h),e-=h,h=0}c.set(i,o),o+=e}return s&&(s-=n+3),{data:c,pts:r,dts:a,len:s}}return null}class ur{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=ar(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],n=this.lastContinuityCounter;this.lastContinuityCounter=s;const r=!!(1&i);if(!!(2&i)&&0!=t[4]&&!!(128&t[5]))return;if(n<0)return;const a=r?n+1&15:n;return s!==a?(this.logger.warn(`MPEG-TS Continuity Counter check failed for PID='${e}', CC=${s}, Expected-CC=${a} Last-CC=${n}`),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 fr{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 gr;const pr={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])},mr=new Uint8Array([0,0,0,0,0,0,0,0]),vr=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),yr=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0]),Er=new Uint8Array([0,0,0,0,0,0,0,0]),Tr=new Uint8Array([0,0,0,0,0,0,0,1]),Sr=new Uint8Array([105,115,111,109]),br=new Uint8Array([97,118,99,49]),Ar=new Uint8Array([0,0,0,1]);class Lr{static box(t,...e){let i=8,s=e.length;const n=s;for(;s--;)i+=e[s].byteLength;const r=new Uint8Array(i);for(_t(r,0,i),_t(r,4,t),s=0,i=8;s<n;s++)r.set(e[s],i),i+=e[s].byteLength;return r}static hdlr(t){return Lr.box(Tt.hdlr,pr[t])}static mdat(t){return Lr.box(Tt.mdat,t)}static mdhd(t,e){e*=t;const i=Math.floor(e/(Et+1)),s=Math.floor(e%(Et+1));return Lr.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 Lr.box(Tt.mdia,Lr.mdhd(t.timescale||0,t.duration||0),Lr.hdlr(t.type),Lr.minf(t))}static mfhd(t){return Lr.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?Lr.box(Tt.minf,Lr.box(Tt.smhd,Er),Lr.DINF,Lr.stbl(t)):Lr.box(Tt.minf,Lr.box(Tt.vmhd,yr),Lr.DINF,Lr.stbl(t))}static moof(t,e,i){return Lr.box(Tt.moof,Lr.mfhd(t),Lr.traf(i,e))}static moov(t){let e=t.length;const i=[];for(;e--;)i[e]=Lr.trak(t[e]);return Lr.box.apply(null,[Tt.moov,Lr.mvhd(t[0].timescale||0,t[0].duration||0)].concat(i).concat(Lr.mvex(t)))}static mvex(t){let e=t.length;const i=[];for(;e--;)i[e]=Lr.trex(t[e]);return Lr.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)),n=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 Lr.box(Tt.mvhd,n)}static sdtp(t){const e=t.samples||[],i=new Uint8Array(4+e.length);let s,n;for(s=0;s<e.length;s++)n=e[s].flags,i[s+4]=n.dependsOn<<4|n.isDependedOn<<2|n.hasRedundancy;return Lr.box(Tt.sdtp,i)}static stbl(t){return Lr.box(Tt.stbl,Lr.stsd(t),Lr.box(Tt.stts,mr),Lr.box(Tt.stsc,mr),Lr.box(Tt.stsz,vr),Lr.box(Tt.stco,mr))}static avc1(t){let e,i,s,n=[],r=[];for(e=0;e<t.sps.length;e++)i=t.sps[e],s=i.byteLength,n.push(s>>>8&255),n.push(255&s),n=n.concat(Array.prototype.slice.call(i));for(e=0;e<t.pps.length;e++)i=t.pps[e],s=i.byteLength,r.push(s>>>8&255),r.push(255&s),r=r.concat(Array.prototype.slice.call(i));const a=Lr.box(Tt.avcC,new Uint8Array([1,n[3],n[4],n[5],255,224|t.sps.length].concat(n).concat([t.pps.length]).concat(r))),o=t.width,l=t.height,d=t.pixelRatio[0],h=t.pixelRatio[1];return Lr.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,Lr.box(Tt.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),Lr.box(Tt.pasp,new Uint8Array([d>>24,d>>16&255,d>>8&255,255&d,h>>24,h>>16&255,h>>8&255,255&h])))}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 Lr.box(Tt.mp4a,Lr.audioStsd(t),Lr.box(Tt.esds,Lr.esds(t)))}static mp3(t){return Lr.box(Tt[".mp3"],Lr.audioStsd(t))}static ac3(t){return Lr.box(Tt["ac-3"],Lr.audioStsd(t),Lr.box(Tt.dac3,t.config))}static stsd(t){const{segmentCodec:e}=t;if("audio"===t.type){if("aac"===e)return Lr.box(Tt.stsd,Tr,Lr.mp4a(t));if("ac3"===e&&t.config)return Lr.box(Tt.stsd,Tr,Lr.ac3(t));if("mp3"===e&&"mp3"===t.codec)return Lr.box(Tt.stsd,Tr,Lr.mp3(t))}else{if(!t.pps||!t.sps)throw new Error("video track missing pps or sps");if("avc"===e)return Lr.box(Tt.stsd,Tr,Lr.avc1(t));if("hevc"===e&&t.vps)return Lr.box(Tt.stsd,Tr,Lr.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,n=t.height||0,r=Math.floor(i/(Et+1)),a=Math.floor(i%(Et+1));return Lr.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,r>>24,r>>16&255,r>>8&255,255&r,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,n>>8&255,255&n,0,0]))}static traf(t,e){const i=Lr.sdtp(t),s=t.id,n=Math.floor(e/(Et+1)),r=Math.floor(e%(Et+1));return Lr.box(Tt.traf,Lr.box(Tt.tfhd,new Uint8Array([0,0,0,0,s>>24,s>>16&255,s>>8&255,255&s])),Lr.box(Tt.tfdt,new Uint8Array([1,0,0,0,n>>24,n>>16&255,n>>8&255,255&n,r>>24,r>>16&255,r>>8&255,255&r])),Lr.trun(t,i.length+16+20+8+16+8+8),i)}static trak(t){return t.duration=t.duration||4294967295,Lr.box(Tt.trak,Lr.tkhd(t),Lr.mdia(t))}static trex(t){const e=t.id;return Lr.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,n=12+16*s,r=new Uint8Array(n);let a,o,l,d,h,c;for(e+=8+n,r.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,d=o.size,h=o.flags,c=o.cts,r.set([l>>>24&255,l>>>16&255,l>>>8&255,255&l,d>>>24&255,d>>>16&255,d>>>8&255,255&d,h.isLeading<<2|h.dependsOn,h.isDependedOn<<6|h.hasRedundancy<<4|h.paddingValue<<1|h.isNonSync,61440&h.degradPrio,15&h.degradPrio,c>>>24&255,c>>>16&255,c>>>8&255,255&c],12+16*a);return Lr.box(Tt.trun,r)}static initSegment(t){const e=Lr.moov(t);return Vt(Lr.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 n=s.length;for(let t=0;t<i.length;t+=1){n+=3;for(let e=0;e<i[t].length;e+=1)n+=2+i[t][e].length}const r=new Uint8Array(n);r.set(s,0),n=s.length;const a=i.length-1;for(let t=0;t<i.length;t+=1){r.set(new Uint8Array([32+t|(t===a?128:0),0,i[t].length]),n),n+=3;for(let e=0;e<i[t].length;e+=1)r.set(new Uint8Array([i[t][e].length>>8,255&i[t][e].length]),n),n+=2,r.set(i[t][e],n),n+=i[t][e].length}const o=Lr.box(Tt.hvcC,r),l=t.width,d=t.height,h=t.pixelRatio[0],c=t.pixelRatio[1];return Lr.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,d>>8&255,255&d,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,Lr.box(Tt.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),Lr.box(Tt.pasp,new Uint8Array([h>>24,h>>16&255,h>>8&255,255&h,c>>24,c>>16&255,c>>8&255,255&c])))}}gr=Lr,Lr.FTYP=gr.box(Tt.ftyp,Sr,Ar,Sr,br),Lr.DINF=gr.box(Tt.dinf,gr.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 Ir(t,e,i=1,s=!1){const n=t*e*i;return s?Math.round(n):n}function Rr(t,e=!1){return Ir(t,1e3,1/9e4,e)}function _r(t){const{baseTime:e,timescale:i,trackId:s}=t;return`${e/i} (${e}/${i}) trackId: ${s}`}const kr=8589934592;function wr(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 Dr 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?_r(e):e} > ${t?_r(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 n=s.pts,r=n-t;return r<-4294967296&&(e=!0,n=xr(n,i),r=n-t),r>0?t:n},i);return e&&this.debug("PTS rollover detected"),s}remux(t,e,i,s,n,r,a,o,l){let d,h,c,u,g,p,m=n,v=n;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,n,r));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(p=!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`),p=!1);if(this.ISGenerated){if(S&&b&&n){const i=this.getVideoStartPts(e.samples),s=(xr(t.samples[0].pts,i)-i)/e.inputTimeScale;m+=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,n,r)),h=this.remuxAudio(t,m,this.isAudioContiguous,r,E||b||o===f.AUDIO?v:void 0,l),b){const s=h?h.endPTS-h.startPTS:0;e.inputTimeScale||(this.warn("regenerate InitSegment as video detected"),c=this.generateIS(t,e,n,r)),d=this.remuxVideo(e,v,i,s,l)}}else b&&(d=this.remuxVideo(e,v,i,0,l));d&&(d.firstKeyFrame=a,d.independent=-1!==a,d.firstKeyFramePTS=s)}}return this.ISGenerated&&this._initPTS&&this._initDTS&&(i.samples.length&&(g=Pr(i,n,this._initPTS,this._initDTS)),s.samples.length&&(u=Cr(s,n,this._initPTS))),{audio:h,video:d,initSegment:c,independent:p,text:u,id3:g}}computeInitPts(t,e,i,s){const n=Math.round(i*e);let r=xr(t,n);if(r<n)for(this.log(`Adjusting PTS for rollover in timeline near ${(n-r)/e} ${s}`);r<n;)r+=kr;return r-n}generateIS(t,i,s,n){const r=t.samples,a=i.samples,o=this.typeSupported,l={},d=this._initPTS,h=!d||n;let c,u,f,g="audio/mp4",p=-1;if(h&&(c=u=1/0),t.config&&r.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):Lr.initSegment([t]),metadata:{channelCount:t.channelCount}},h){p=t.id,f=t.inputTimeScale;const e=this.computeInitPts(r[0].pts,f,s,"audio");(!d||f!==d.timescale||0===s&&e<d.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:Lr.initSegment([i]),metadata:{width:i.width,height:i.height}},h){p=i.id,f=i.inputTimeScale;const t=this.getVideoStartPts(a),n=xr(a[0].dts,t),r=this.computeInitPts(n,f,s,"video"),o=this.computeInitPts(t,f,s,"video");(!d||f!==d.timescale||e(c)||0===s&&o<d.baseTime)&&(u=Math.min(u,r),c=Math.min(c,r))}this.videoTrackConfig={width:i.width,height:i.height,pixelRatio:i.pixelRatio}}if(Object.keys(l).length)return this.ISGenerated=!0,h&&e(c)?(d&&this.warn(`Timestamps at playlist time: ${n?"":"~"}${s} ${c/f} != initPTS: ${d.baseTime/d.timescale} (${d.baseTime}/${d.timescale}) trackId: ${d.trackId}`),this.log(`Found initPTS at playlist time: ${s} offset: ${c/f} (${c}/${f}) trackId: ${p}`),this._initPTS={baseTime:c,timescale:f,trackId:p},this._initDTS={baseTime:u,timescale:f,trackId:p}):c=f=void 0,{tracks:l,initPTS:c,timescale:f,trackId:p}}remuxVideo(t,e,i,s,o){const l=t.inputTimeScale,d=t.samples,h=[],c=d.length,u=this._initPTS,f=u.baseTime*l/u.timescale;let g,p,m=this.nextVideoTs,v=8,y=this.videoSampleDuration,E=Number.POSITIVE_INFINITY,T=Number.NEGATIVE_INFINITY,S=!1;if(!i||null===m){const t=f+e*l,s=d[0].pts-xr(d[0].dts,d[0].pts);re()&&null!==m&&Math.abs(t-s-(m+f))<15e3?i=!0:m=t-s-f}const b=m+f;for(let t=0;t<c;t++){const e=d[t];e.pts=xr(e.pts,b),e.dts=xr(e.dts,b),e.dts<d[t>0?t-1:t].dts&&(S=!0)}S&&d.sort(function(t,e){const i=t.dts-e.dts,s=t.pts-e.pts;return i||s}),g=d[0].dts,p=d[d.length-1].dts;const A=p-g,L=A?Math.round(A/(c-1)):y||t.inputTimeScale/30;if(i){const i=g-b,s=i>L,n=i<-1;if((s||n)&&(s?this.warn(`${(t.segmentCodec||"").toUpperCase()}: ${Rr(i,!0)} ms (${i}dts) hole between fragments detected at ${e.toFixed(3)}`):this.warn(`${(t.segmentCodec||"").toUpperCase()}: ${Rr(-i,!0)} ms (${i}dts) overlapping between fragments detected at ${e.toFixed(3)}`),!n||b>=d[0].pts||re())){g=b;const t=d[0].pts-i;if(s)d[0].dts=g,d[0].pts=t;else{let e=!0;for(let s=0;s<d.length&&!(d[s].dts>t&&e);s++){const t=d[s].pts;if(d[s].dts-=i,d[s].pts-=i,s<d.length-1){const i=d[s+1].pts;e=i<=d[s].pts==i<=t}}}this.log(`Video: Initial PTS/DTS adjusted: ${Rr(t,!0)}/${Rr(g,!0)}, delta: ${Rr(i,!0)} ms`)}}g=Math.max(0,g);let R=0,_=0,k=g;for(let t=0;t<c;t++){const e=d[t],i=e.units,s=i.length;let n=0;for(let t=0;t<s;t++)n+=i[t].data.length;_+=n,R+=s,e.length=n,e.dts<k?(e.dts=k,k+=L/4|0||1):k=e.dts,E=Math.min(e.pts,E),T=Math.max(e.pts,T)}p=d[c-1].dts;const w=_+4*R+8;let D;try{D=new Uint8Array(w)}catch(t){return void this.observer.emit(a.ERROR,a.ERROR,{type:n.MUX_ERROR,details:r.REMUX_ALLOC_ERROR,fatal:!1,chunkMeta:o,error:t,bytes:w,reason:`fail allocating video mdat ${w}`})}_t(D,0,w),_t(D,4,Tt.mdat);let x=!1,P=Number.POSITIVE_INFINITY,C=Number.POSITIVE_INFINITY,M=Number.NEGATIVE_INFINITY,O=Number.NEGATIVE_INFINITY;for(let t=0;t<c;t++){const e=d[t],n=e.units;let r,a=0;for(let t=0,e=n.length;t<e;t++){const e=n[t],i=e.data,s=e.data.byteLength;_t(D,v,s),v+=4,D.set(i,v),v+=s,a+=4+s}if(t<c-1)y=d[t+1].dts-e.dts,r=d[t+1].pts-e.pts;else{const i=this.config,n=t>0?e.dts-d[t-1].dts:L;if(r=t>0?e.pts-d[t-1].pts:L,i.stretchShortVideoTrack&&null!==this.nextAudioTs){const t=Math.floor(i.maxBufferHole*l),r=(s?E+s*l:this.nextAudioTs+f)-e.pts;r>t?(y=r-n,y<0?y=n:x=!0,this.log(`It is approximately ${r/90} ms to the next segment; using duration ${y/90} ms for the last video frame.`)):y=n}else y=n}let u=Math.round(e.pts-e.dts);if(P=Math.min(P,y),M=Math.max(M,y),C=Math.min(C,r),O=Math.max(O,r),!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)}h.push(wr(e.key,y,a,u))}if(h.length){const t=re();if(t){if(t<70){const t=h[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-C<M-P&&L/M<.025&&0===h[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=h.length;e<i;e++){const s=t+h[e].duration,n=t+h[e].cts;if(e<i-1){const t=s+h[e+1].cts;h[e].duration=t-n}else h[e].duration=e?h[e-1].duration:L;h[e].cts=0,t=s}}}y=x||!y?L:y;const F=p+y;this.nextVideoTs=m=F-f,this.videoSampleDuration=y,this.isVideoContiguous=!0,o.iframe&&(1===h.length?(h[0].duration=y=o.duration*l,this.nextVideoTs=m=g+y-f):this.warn(`Not adjusting IFrame duration (sample count ${h.length})`));const N={data1:Lr.moof(o.sn,g,I(t,{samples:h})),data2:D,startPTS:(E-f)/l,endPTS:(T+y-f)/l,startDTS:(g-f)/l,endDTS:m/l,type:"video",hasAudio:!1,hasVideo:!0,nb:h.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 d=t.inputTimeScale,h=d/(t.samplerate?t.samplerate:d),c=this.getSamplesPerFrame(t),u=c*h,f=this._initPTS,g="mp3"===t.segmentCodec&&this.typeSupported.mpeg,p=[],m=void 0!==o;let v=t.samples,y=g?0:8,E=this.nextAudioTs||-1;const T=f.baseTime*d/f.timescale,S=T+e*d;if(this.isAudioContiguous=i=i||v.length&&E>0&&(s&&Math.abs(S-(E+T))<9e3||Math.abs(xr(v[0].pts,S)-(E+T))<20*u),v.forEach(function(t){t.pts=xr(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} / ${d})`),!v.length)return;E=0===o?0:s&&!m?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 n=v[i],r=n.pts,a=r-s,o=Math.abs(1e3*a/d);if(a<=-e*u&&m)0===i&&(this.warn(`Audio frame @ ${(r/d).toFixed(3)}s overlaps marker by ${Math.round(1e3*a/d)} ms.`),this.nextAudioTs=E=r-T,s=r);else if(a>=e*u&&o<1e4&&m){let e=Math.round(a/u);for(s=r-e*u;s<0&&e&&u;)e--,s+=u;0===i&&(this.nextAudioTs=E=s-T),this.warn(`Injecting ${e} audio frames @ ${((s-T)/d).toFixed(3)}s due to ${Math.round(1e3*a/d)} ms gap.`);for(let r=0;r<e;r++){let e=fr.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=n.unit.subarray()),v.splice(i,0,{unit:e,pts:s}),s+=u,i++}}n.pts=s,s+=u}}let b,A=null,L=null,R=0,_=v.length;for(;_--;)R+=v[_].unit.byteLength;for(let e=0,s=v.length;e<s;e++){const s=v[e],o=s.unit;let d=s.pts;if(null!==L){p[e-1].duration=Math.round((d-L)/h)}else{if(i&&"aac"===t.segmentCodec&&(d=E+T),A=d,!(R>0))return;R+=y;try{b=new Uint8Array(R)}catch(t){return void this.observer.emit(a.ERROR,a.ERROR,{type:n.MUX_ERROR,details:r.REMUX_ALLOC_ERROR,fatal:!1,chunkMeta:l,error:t,bytes:R,reason:`fail allocating audio mdat ${R}`})}g||(_t(b,0,R),_t(b,4,Tt.mdat))}b&&b.set(o,y);const u=o.byteLength;y+=u,p.push(wr(!0,c,u,0)),L=d}const k=p.length;if(!k)return;const w=p[p.length-1];E=L-T,this.nextAudioTs=E+h*w.duration;const D=g?new Uint8Array(0):Lr.moof(t.sequenceNumber++,A/h,I({},t,{samples:p}));t.samples=[];const x=(A-T)/d,P=this.nextAudioTs/d,C={data1:D,data2:b,startPTS:x,endPTS:P,startDTS:x,endDTS:P,type:"audio",hasAudio:!0,hasVideo:!1,nb:k};return this.isAudioContiguous=!0,C}}function xr(t,e){let i;if(null===e)return t;for(i=e<t?-8589934592:kr;Math.abs(t-e)>4294967296;)t+=i;return t}function Pr(t,e,i,s){const n=t.samples.length;if(!n)return;const r=t.inputTimeScale;for(let a=0;a<n;a++){const n=t.samples[a];n.pts=xr(n.pts-i.baseTime*r/i.timescale,e*r)/r,n.dts=xr(n.dts-s.baseTime*r/s.timescale,e*r)/r}const a=t.samples;return t.samples=[],{samples:a}}function Cr(t,e,i){const s=t.samples.length;if(!s)return;const n=t.inputTimeScale;for(let r=0;r<s;r++){const s=t.samples[r];s.pts=xr(s.pts-i.baseTime*n/i.timescale,e*n)/n}t.samples.sort((t,e)=>t.pts-e.pts);const r=t.samples;return t.samples=[],{samples:r}}function Mr(t,e,i=!1){return void 0!==(null==t?void 0:t.start)?(t.start+(i?t.duration:0))/t.timescale:e}function Or(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 me(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 Fr;try{Fr=self.performance.now.bind(self.performance)}catch(t){Fr=Date.now}const Nr=[{demux:class{constructor(t,e,i,s=H){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 n=this.videoTrack=Fn("video",1),r=this.audioTrack=Fn("audio",1),a=this.txtTrack=Fn("text",1);if(this.id3Track=Fn("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;n.id=t,n.timescale=a.timescale=e,n.codec=i,n.supplemental=s}if(o.audio){const{id:t,timescale:e,codec:i}=o.audio;r.id=t,r.timescale=e,r.codec=i}a.id=St.text,n.sampleDuration=0,n.duration=r.duration=s}resetContiguity(){this.remainderData=null}static probe(t){return function(t,e){const i=t.byteLength;for(let s=0;s<i;){const n=At(t,s);if(n>8&&At(t,s+4)===Tt[e])return!0;s=n>1?s+n:i}return!1}(t,"moof")}demux(t,e,i){this.timeOffset=e;let s=t;const n=this.videoTrack,r=this.txtTrack;if(this.config.progressive){this.remainderData&&(s=Vt(this.remainderData,t));const e=function(t){const e={valid:null,remainder:null},i=xt(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,n.samples=e.valid||new Uint8Array}else n.samples=s;const a=this.extractID3Track(n,e),o=this.parseFragment(n,r,e,i);return{videoTrack:n,audioTrack:this.audioTrack,id3Track:a,textTrack:this.txtTrack,initData:this.initData,sampleData:o}}flush(t,e){const i=this.timeOffset,s=this.videoTrack,n=this.txtTrack;s.samples=this.remainderData||new Uint8Array,this.remainderData=null;const r=this.extractID3Track(s,this.timeOffset),a=this.parseFragment(s,n,i,e);return{videoTrack:s,audioTrack:Fn(),id3Track:r,textTrack:Fn(),initData:this.initData,sampleData:a}}parseFragment(t,e,i,s){const n=this.initData;if(n&&s){const{samples:r,sampleData:a}=function(t,e,i,s,n=!1){const r=[];return{samples:r,sampleData:{includeSampleDetails:n,tracks:Kt(e.samples,i,s,n,{isHEVCFlavor:Ht(e.codec),samples:r,timeOffset:t,timescale:e.timescale,trackId:e.id})}}}(i,t,n,this.logger,s.iframe);return e.samples=r,a}e.samples=function(t,e){const i=[],s=e.samples,n=e.timescale,r=e.id;let a=!1;return xt(s,["moof"]).map(o=>{const l=o.byteOffset-8;xt(o,["traf"]).map(o=>{const d=xt(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/n})[0];return void 0!==d&&(t=d),xt(o,["tfhd"]).map(d=>{const h=At(d,4),c=16777215&At(d,0),u=!!(1&c);let f=0;const g=!!(2&c),m=!!(8&c);let v=0;const y=!!(16&c);let E=0;const T=!!(32&c),S=!u&&!!(131072&c);let b=8;h===r&&(u?(f=At(d,b),b+=4,f*=Math.pow(2,32),f+=At(d,b),b+=4):S&&(f=l),g&&(b+=4),m&&(v=At(d,b),b+=4),y&&(E=At(d,b),b+=4),T&&(b+=4),"video"===e.type&&(a=Ht(e.codec)),xt(o,["trun"]).map(r=>{const o=r[0],l=16777215&At(r,0),d=!!(1&l);let h=0;const c=!!(4&l),u=!!(256&l);let g=0;const m=!!(512&l);let y=0;const T=!!(1024&l),S=!!(2048&l);let b=0;const A=At(r,4);let L=8;d&&(h=At(r,L),L+=4),c&&(L+=4);let I=f+h;for(let l=0;l<A;l++){if(u?(g=At(r,L),L+=4):g=v,m?(y=At(r,L),L+=4):y=E,T&&(L+=4),S&&(b=0===o?At(r,L):Rt(r,L),L+=4),e.type===p){let e=0;for(;e<y;){const r=At(s,I);I+=4,Yt(a,s[I])&&Wt(s.subarray(I,I+r),a?2:1,t+b/n,i),I+=r,e+=r+4}}t+=g/n}}))})})}),i}(i,t)}extractID3Track(t,e){const s=this.id3Track;if(t.samples.length){const n=xt(t.samples,["emsg"]);n&&n.forEach(t=>{const n=function(t){const e=t[0];let s,n="",r="",a=0,o=0,l=0,d=0,h=4;if(0===e){const e=It(t,h),i=null!==e?It(t,h+e.length):null;null!==e&&null!==i?(n=e,r=i,h+=e.length+i.length,a=At(t,h),h+=4,o=At(t,h),h+=4,l=At(t,h),h+=4,d=At(t,h),h+=4):(H.warn(`Unterminated ${null===e?"scheme_id_uri":"value"} in parsing emsg box: version 0 box ends inside a string, dropping all of its fields`),h=t.length)}else if(1===e){a=At(t,h),h+=4;const e=At(t,h);h+=4;const o=At(t,h);h+=4,s=2**32*e+o,i(s)||(s=Number.MAX_SAFE_INTEGER,H.warn("Presentation time exceeds safe integer limit and wrapped to max safe integer in parsing emsg box")),l=At(t,h),h+=4,d=At(t,h),h+=4;const c=It(t,h),u=null!==c?It(t,h+c.length):null;null!==c&&(n=c,h+=c.length),null!==u?(r=u,h+=u.length):(H.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"}`),h=t.length)}return{schemeIdUri:n,value:r,timeScale:a,presentationTime:s,presentationTimeDelta:o,eventDuration:l,id:d,payload:t.subarray(h,t.byteLength)}}(t);if(Zn.test(n.schemeIdUri)){const t=Jn(n,e);let i=4294967295===n.eventDuration?Number.POSITIVE_INFINITY:n.eventDuration/n.timeScale;i<=.001&&(i=Number.POSITIVE_INFINITY);const r=n.payload;s.samples.push({data:r,len:r.byteLength,dts:t,pts:t,type:On.emsg,duration:i})}else if(this.config.enableEmsgKLVMetadata){const t=this.config.emsgKLVSchemaUri||On.misbklv;if(n.schemeIdUri.startsWith(t)){const t=Jn(n,e);s.samples.push({data:n.payload,len:n.payload.byteLength,dts:t,pts:t,type:On.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:n}=this;if(null==t||!t.byteLength)return this.initTracks=void 0,void(this.initData=void 0);const{audio:r,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)||(H.log(`[eme] Patching keyId in 'enc${e?"a":"v"}>sinf>>tenc' box: ${pt(s)} -> ${pt(i)}`),t.set(i,8))})}(t,e);else{const t=r||a;null!=t&&t.encrypted&&this.warn(`Init segment with encrypted track with has no key ("${t.codec}")!`)}r&&(s=Or(r,g,this)),a&&(n=Or(a,p,this));const o={};r&&a?o.audiovideo={container:"video/mp4",codec:s+","+n,supplemental:a.supplemental,encrypted:a.encrypted,initSegment:t,id:"main"}:r?o.audio={container:"audio/mp4",codec:s,encrypted:r.encrypted,initSegment:t,id:"audio"}:a?o.video={container:"video/mp4",codec:n,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,n,r,a,o,l,d,h,c){var u,f;let{initPTS:g,lastEndTime:p}=this;const m={audio:void 0,video:void 0,text:void 0,id3:s,initSegment:void 0};e(p)||(p=this.lastEndTime=r||0);const v=i.samples;if(!v.length)return m;const y=this.pendingInitSegment;y&&(this.pendingInitSegment=void 0,this.generateInitSegment(y,this.decryptdata,h));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."),m;if(d.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=xt(t,["moov"]);if(1!==e.length||xt(t,["moof"]).length)return null;const i=t.byteOffset,s=[],n=[];let r=!1;const a=xt(e[0],["trak"]);for(let t=0;t<a.length;t++){const e=a[t],o=xt(e,["mdia","hdlr"])[0];if("vide"===(o?yt(o.subarray(8,12)):"")){r=!0;continue}const l=xt(e,["tkhd"])[0];if(!l)return null;const d=l[0];n.push(At(l,0===d?12:20)),s.push(wt(e,i))}if(!r||!s.length)return null;const o=xt(e[0],["mvex"])[0];let l=0;if(o){const t=xt(o,["trex"]);for(let e=0;e<t.length;e++){const r=t[e];-1!==n.indexOf(At(r,4))&&(s.push(wt(r,i)),l+=r.byteLength+8)}}const{result:d,dropped:h,droppedBefore:c}=Dt(t,s);if(_t(d,e[0].byteOffset-i-8,e[0].byteLength+8-h),o&&l){const t=o.byteOffset-i-8;_t(d,t-c(t),o.byteLength+8-l)}return d}(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,m.initSegment=E,this.emitInitSegment=!1);const A=d.iframe,L=!c||A&&!c.includeSampleDetails?function(t,e,i,s,n=!0){return Kt(t,e,s,n)}(v,T,0,this,A):c.tracks,I=T.audio?L[T.audio.id]:null,R=T.video?L[T.video.id]:null,_=!!T.audio,k=!!T.video;let w="";_&&(w+="audio"),k&&(w+="video");const D=Mr(R,1/0),x=Mr(I,1/0),P=Mr(R,0,!0),C=Mr(I,0,!0);let M=r,O=0;R&&I&&T.audio&&(x>P||D>C)&&this.warn(`audio and video track sample timestamps do not overlap. v: ${D}-${P} a: ${x}-${C}}`,R,I);const F=!!I&&(!R||!g&&x<D||!!g&&g.trackId===T.audio.id),N=F?I:R;if(!N)return this.log(`No media samples found in ${l} ${d.level} ${-1===d.part?"":`part: ${d.part} of`} sn: ${d.sn} at playlist time: ${r}`),m;let B,$=v;if(R&&R.sampleCount>=1&&T.video&&d.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 n=t[0];let r=n;for(let e=t.length;e--;)if(t[e].samples.length){r=t[e];break}const a=r.lastSampleDurationOffset,{defaultSampleDurationOffset:o}=n,l=Math.abs(d.duration-(P-D))>.05,h=s.length<R.sampleCount;if(l||h||this.videoOnlyRemux||!i){const t=h?r.sampleOffset+r.samples.reduce((t,e)=>t+e.size,0):void 0,i=l?d.duration:P-D,n=function(t,e,i,s){if(void 0!==i){const s=t[t.length-1];let n=e;for(let e=0;e<t.length-1;e++)n-=t[e].duration;return n<=0&&(n=s.duration),s.duration=n,{durationOffset:i,value:n}}if(void 0===s)return;const n=Math.round(e/t.length);for(let e=0;e<t.length;e++)t[e].duration=n;return{durationOffset:s,value:n}}(s,i*T.video.timescale,a,o),c=function(t,e,i,s,n){if(i<1)return null;const r=xt(t,["moof"]);if(1!==r.length)return null;const a=r[0],o=t.byteOffset,l=[],d=[],h=xt(a,["traf"]);let c=!0;for(let t=0;t<h.length;t++){const i=h[t],s=xt(i,["tfhd"])[0];if(!s)return null;At(s,4)===e?(l.push(i),131072&At(s,0)||(c=!1)):d.push(wt(i,o))}if(!l.length)return null;if(d.length&&!c)return null;if(void 0!==s){let e=i;for(let i=0;i<l.length;i++){const s=l[i];let n=0;const r=xt(s,["trun"]);for(let i=0;i<r.length;i++){const s=r[i],a=Math.min(e,At(s,4));if(a){_t(t,s.byteOffset-o+4,a);const e=16777215&At(s,0);kt(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 _t(t,s.byteOffset-o-4,Tt.free);e-=a,n+=a}const a=xt(s,["senc"])[0];a&&_t(t,a.byteOffset-o+4,n);const d=xt(s,["saiz"])[0];if(d){let e=4;1&(d[1]<<16|d[2]<<8|d[3])&&(e+=8);const i=d[e];e+=1,_t(t,d.byteOffset-o+e,n),kt(t,d,e+4+(0===i?n:0))}}const n=xt(t,["mdat"]);if(1===n.length){const e=n[0].byteOffset-o-8;_t(t,e,s-e)}}let u=t,f=0,g=()=>0;if(d.length){({result:u,dropped:f,droppedBefore:g}=Dt(t,d)),_t(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=xt(e,["trun"]);for(let t=0;t<s.length;t++){const e=s[t];1&At(e,0)&&_t(u,e.byteOffset-o-i+8,At(e,8)-f)}if(i){const t=xt(e,["saio"]);for(let e=0;e<t.length;e++){const s=t[e],n=0===s[0]?4:8;let r=1&At(s,0)?12:4,a=At(s,r);for(r+=4;a--;r+=n){const t=r+n-4;_t(u,s.byteOffset-o-i+t,At(s,t)-i)}}}}}if(n){const{durationOffset:t,value:e}=n;_t(u,t-g(t),e)}return void 0!==s?u.subarray(0,s-f):u}(v,T.video.id,s.length,t,n);c?($=c,B=function(t,e){let i=t,s=t;for(let t=0;t<e.length;t++){const{cts:n,duration:r}=e[t];s=Math.max(s,i+(n||0)+r),i+=r}return s}(e,s)):this.warn(`IFrame remux skipped (sn ${d.sn}); using native sample duration`),O=c&&n?i:P-D}else O=P-D}else this.warn(`Could not remux IFrame track fragment (no samples in range, trun count ${t.length})`),O=P-D}else O=F?C-x:P-D;if(this.videoOnlyRemux&&$===v)return this.warn(`Dropping muxed I-Frame fragment that could not be remuxed to video-only (sn: ${d.sn})`),m;const U=N.timescale,G=N.start-r*U,j=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 n=Math.max(s,1),r=e-t.baseTime/t.timescale;return Math.abs(r-i)>=n}(g,M,r,O)||U!==g.timescale)){let t=!1;const e=F?"audio":"video";if(g){const i=0!==r?M/r:1+M/1;t=M>=0&&Math.abs(1-i)<.001,this.log(`${e} timestamps in track ${j} at playlist time: ${a?"":"~"}${r} maps to ${M} with initPTS: ${g.baseTime/g.timescale} (${G/U-g.baseTime/g.timescale}s diff) (${w}) drift estimate: ${i} ${t?"(ignoring drift)":"remapping timestamps (initPTS)"}`)}t||(this.log(`Found initPTS in ${e} track ${j} at playlist time: ${r} offset: ${M-r} (${G}/${U})`),g=null,E.initPTS=G,E.timescale=U,E.trackId=j)}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 q=M-g.baseTime/g.timescale,K=q+O,V=k&&void 0!==(null==N?void 0:N.ptsMin)?N.ptsMin/N.timescale-g.baseTime/g.timescale:q,H=void 0!==B&&R?B/R.timescale-g.baseTime/g.timescale:k&&null!=N&&N.ptsMax?N.ptsMax/N.timescale-g.baseTime/g.timescale:K;O>0?this.lastEndTime=K:(this.warn("Duration parsed from mp4 should be greater than zero"),this.resetNextTimestamp());const Y={data1:$,data2:void 0,startPTS:V,startDTS:q,endPTS:H,endDTS:K,type:w,hasAudio:_,hasVideo:k,nb:1,dropped:0,encrypted:!!T.audio&&T.audio.encrypted||!!T.video&&T.video.encrypted};m.audio=_&&!k?Y:void 0,m.video=k?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||(m.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 m.initSegment=E,m.id3=Pr(s,r,g,g),n.samples.length&&(m.text=Cr(n,r,g)),m}}},{demux:rr,remux:Dr},{demux:class extends Nn{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=rt(t,0);let s=(null==i?void 0:i.length)||0;if(Yn(t,s))return!1;for(let i=t.length;s<i;s++)if(xn(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)&&_n(t,e)&&wn(t,e)<=t.length-e}(t,e)}appendFrame(t,e,i){Pn(t,this.observer,e,i,t.manifestCodec);const s=Mn(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),n=this.sampleAes=new Wn(this.observer,this.config,e);return new Promise(t=>{n.decryptAacSamples(s.audioTrack.samples,0,()=>{t(s)})})}},remux:Dr},{demux:class extends Nn{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=rt(t,0);let i=(null==e?void 0:e.length)||0;if(e&&11===t[i]&&119===t[i+1]&&void 0!==gt(e)&&zn(t,i)<=16)return!1;for(let e=t.length;i<e;i++)if(Yn(t,i))return H.log("MPEG Audio sync word found !"),!0;return!1}canParse(t,e){return function(t,e){return Vn(t,e)&&4<=t.length-e}(t,e)}appendFrame(t,e,i){if(null!==this.basePTS)return qn(t,e,i,this.basePTS,this.frameIndex)}},remux:Dr}];Nr.splice(2,0,{demux:Xn,remux:Dr});class Br{constructor(t,e,i,s,n,r){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=n,this.logger=r}configure(t){this.transmuxConfig=t,this.decrypter&&this.decrypter.reset()}push(t,e,i,s){if(!this.observer)return $r(i);const o=i.transmuxing;o.executeStart=Fr();const l=new Uint8Array(t),{currentTransmuxState:d,transmuxConfig:h}=this;s&&(this.currentTransmuxState=s);const{contiguous:c,discontinuity:u,trackSwitch:f,accurateTimeOffset:g,timeOffset:p,initSegmentChange:m}=s||d,{audioCodec:v,videoCodec:y,defaultInitPts:E,duration:T,initSegmentData:S}=h,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&&rr.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:n.MEDIA_ERROR,details:r.FRAG_PARSING_ERROR,fatal:!1,error:e,reason:e.message}),o.executeEnd=Fr(),$r(i)}(u||f||m||A)&&this.resetInitSegment(S,v,y,T,e,i),(u||m||A)&&this.resetInitialTimestamp(E),c||this.resetContiguity();const L=this.transmux(l,b,p,g,i);this.asyncResult=Ur(L);const I=this.currentTransmuxState;return I.contiguous=!0,I.discontinuity=!1,I.trackSwitch=!1,o.executeEnd=Fr(),L}flush(t){const e=t.transmuxing;e.executeStart=Fr();const{decrypter:i,currentTransmuxState:s,decryptionPromise:n}=this;if(n)return this.asyncResult=!0,n.then(()=>this.flush(t));const r=[],{timeOffset:a}=s;if(i){const e=i.flush();e&&r.push(this.push(e.buffer,null,t))}const{demuxer:o,remuxer:l}=this;if(!o||!l){e.executeEnd=Fr();const i=[$r(t)];return this.asyncResult?Promise.resolve(i):i}const d=o.flush(a,t);return Ur(d)?(this.asyncResult=!0,d.then(e=>(this.flushRemux(r,e,t),r))):(this.flushRemux(r,d,t),this.asyncResult?Promise.resolve(r):r)}flushRemux(t,e,i){if(!this.remuxer)return;const{audioTrack:s,videoTrack:n,id3Track:r,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 d=this.remuxer.remux(s,n,r,a,l,o,!0,this.id,i,e.initData,e.sampleData);t.push({remuxResult:d,chunkMeta:i}),i.transmuxing.executeEnd=Fr()}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,n,r){const{demuxer:a,remuxer:o}=this;a&&o&&(a.resetInitSegment(t,e,i,s,n,r),o.resetInitSegment(t,e,i,n))}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,n){let r;return r="SAMPLE-AES"===(null==e?void 0:e.method)?this.transmuxSampleAes(t,e,i,s,n):this.transmuxUnencrypted(t,i,s,n),r}transmuxUnencrypted(t,e,i,s){const{demuxer:n,remuxer:r}=this;if(!n||!r)return $r(s);const a=n.demux(t,e,s,!1,!this.config.progressive),{audioTrack:o,videoTrack:l,id3Track:d,textTrack:h}=a;return{remuxResult:r.remux(o,l,d,h,e,i,!1,this.id,s,a.initData,a.sampleData),chunkMeta:s}}transmuxSampleAes(t,e,i,s,n){return this.demuxer?this.demuxer.demuxSampleAes(t,e,i,n).then(t=>({remuxResult:this.remuxer.remux(t.audioTrack,t.videoTrack,t.id3Track,t.textTrack,i,s,!1,this.id,n,t.initData,t.sampleData),chunkMeta:n})):Promise.reject(new Error("no demuxer"))}configureTransmuxer(t){const{config:e,observer:i,typeSupported:s}=this;if(!i)return;let n;try{for(let e=0,i=Nr.length;e<i;e++){var r;if(null!=(r=Nr[e].demux)&&r.probe(t,this.logger)){n=Nr[e];break}}}catch(t){return t}if(!n)return new Error("Failed to find demuxer by probing fragment data");const a=this.demuxer,o=this.remuxer,l=n.demux,d=n.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 d||(this.logger.log(`Using ${d.name}`),this.remuxer=new d(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 wi(this.config)),t}}const $r=t=>({remuxResult:{},chunkMeta:t});function Ur(t){return"then"in t&&t.then instanceof Function}class Gr{constructor(t,e,i,s,n){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=n||null}}class jr{constructor(t,e,i,s,n,r){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=n,this.initSegmentChange=r}}let qr=0;class Kr{constructor(t,e,i,s){this.error=null,this.hls=void 0,this.id=void 0,this.instanceNo=qr++,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:n.OTHER_ERROR,details:r.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 Ln,this.observer.on(a.FRAG_DECRYPTED,l),this.observer.on(a.ERROR,l);const d=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=Rn[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 Rn[t]=s,s}(o.workerPath)):(i.log(`injecting Web Worker for "${e}"`),this.workerContext=function(){const t=Rn[In];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 Rn[In]=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:d,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 Br(this.observer,d,o,"",e,t.logger)}return}}this.transmuxer=new Br(this.observer,d,o,"",e,t.logger)}reset(){if(this.frag=null,this.part=null,this.workerContext){const t=this.instanceNo;this.instanceNo=qr++;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=Rn[t||In];if(e&&1===e.clientCount--){const{worker:i,objectURL:s}=e;delete Rn[t||In],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,n,r,a,o,l,d){var h,c;l.transmuxing.start=self.performance.now();const{instanceNo:u,transmuxer:f}=this,g=r?r.start:n.start,p=n.decryptdata,m=this.frag,v=!m||n.cc!==m.cc,y=!m||l.level!==m.level,E=m?l.sn-m.sn:-1,T=this.part?l.part-this.part.index:-1,S=0===E&&l.id>1&&l.id===(null==m?void 0:m.stats.chunkCount),b=!y&&(1===E||0===E&&(1===T||S&&T<=0)),A=self.performance.now();(y||E||0===n.stats.parsing.start)&&(n.stats.parsing.start=A),!r||!T&&b||(r.stats.parsing.start=A);const L=!(m&&(null==(h=n.initSegment)?void 0:h.url)===(null==(c=m.initSegment)?void 0:c.url)),I=new jr(v,b,o,y,g,L);if(!b||v||L){this.hls.logger.log(`[transmuxer-interface]: Starting new transmux session for ${n.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 Gr(i,s,e,a,d);this.configureTransmuxer(t)}if(this.frag=n,this.part=r,this.workerContext)this.workerContext.worker.postMessage({instanceNo:u,cmd:"demux",data:t,decryptdata:p,chunkMeta:l,state:I},t instanceof ArrayBuffer?[t]:[]);else if(f){const e=f.push(t,p,l,I);Ur(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);Ur(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:n.MEDIA_ERROR,details:r.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 Vr 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 n=-1;for(let i=0;i<s.length;i++){const r=s[i];let a;try{a=new self.URL(r.URI,e.url).href}catch(t){this.warn(`Could not construct new URL for Rendition Report: ${t}`),a=r.URI||""}if(a===t){n=i;break}a===t.substring(0,a.length)&&(n=i)}if(-1!==n){const t=s[n],r=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(r,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,d=self.performance.now(),h=o.loading.first?Math.max(0,Math.floor(d-o.loading.first)):0;s.advancedDateTime=Date.now()-h;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:n.NETWORK_ERROR,details:r.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:n.NETWORK_ERROR,details:r.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,p=g?g.end-g.len:0,m=Ks(s,1e3*(s.edge-p));s.requestScheduled+m<d?s.requestScheduled=d:s.requestScheduled<=d&&(s.requestScheduled+=m);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,n=s.lastPartSn,r=s.endSN,a=s.lastPartIndex,o=n===r;-1!==a?o?(E=r+1,T=t?0:a):(E=n,T=t?a+1:s.maxPartIndex):E=r+1;const l=s.age,h=l+s.ageHeader;let u=Math.min(h-s.partTarget,1.5*s.targetduration);if(u>0){if(h>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&&h-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=d,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(m-2*h,m/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 n=self.performance.now(),r=s.requestScheduled;if(n>=r&&!this.loadingSync)return this.loadingSync=!0,this.loadingPlaylist(t,e),void(this.loadingSync=!1);const a=Math.max(r-n,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 n=Oe(t);return null!=e&&e.skip&&t.deltaUpdateFailed&&(i=e.msn,s=e.part,n=Pe),new Fe(i,s,n)}checkRetry(t){const e=t.details,i=w(t),s=t.errorAction,{action:n,retryCount:r=0,retryConfig:a}=s||{},o=!!s&&!!a&&(n===ai||!s.resolved&&n===ni);if(o){var l;if(r>=a.maxNumRetry)return!1;if(i&&null!=(l=t.context)&&l.deliveryDirectives)this.warn(`Retrying playlist loading ${r+1}/${a.maxNumRetry} after "${e}" without delivery-directives`),this.loadPlaylist();else{var d;const i=F(null==(d=t.response)?void 0:d.code);if(this.clearTimer(),i)this.log("Waiting for connection (offline)"),t.reason="offline",this.timer=self.setTimeout(()=>this.checkOfflineStatus(),1e3);else{const t=C(a,r);this.warn(`Retrying playlist loading ${r+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 Hr(t,e){if(t.length!==e.length)return!1;for(let i=0;i<t.length;i++)if(!Yr(t[i].attrs,e[i].attrs))return!1;return!0}function Yr(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 Wr{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 n=null==(i=this.tracks[t])?void 0:i.buffer;null!=n&&n.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 zr=/(avc[1234]|hvc1|hev1|dvh[1e]|vp09|av01)(?:\.[^.,]+)+/,Xr="HlsJsTrackRemovedError";class Qr extends Error{constructor(t){super(t),this.name=Xr}}function Zr(t){const e=t.querySelectorAll("source");[].slice.call(e).forEach(e=>{t.removeChild(e)})}function Jr(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 n=0;for(let e=0;e<t.length;e++){const r=t[e];if(r.start>=s)break;const a=Math.max(i,r.start),o=Math.min(s,r.end);o>a&&(n+=o-a)}return n}function sa(t,e){return e.duration-t<=.05}class na{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),na.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 n=t.length-1;const r=Math.max(e,i);for(let e=0;e<t.length;e+=1){const i=t[e];if((i.width>=r||i.height>=r)&&s(i,t[e+1])){n=e;break}}return n}}var ra=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} "${n=e,Array.isArray(n)?JSON.stringify(n):n instanceof Map?"Map{}":n instanceof Set?"Set{}":"object"==typeof n?JSON.stringify(n):String(n)}" as ${i}`,{cause:s});var n}const oa="Bare Item";const la=/[\x00-\x1f\x7f]+/;var da=class{constructor(t){this.description=t}};function ha(t,e,i){return aa("serialize",t,e,i)}function ca(t){if(!1===ArrayBuffer.isView(t))throw ha(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 ha(t,"Integer");return t.toString()}function fa(t){const e=J(t,3);if(Math.floor(Math.abs(e)).toString().length>12)throw ha(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 ha(e,"Token");return e}function pa(t){switch(typeof t){case"number":if(!e(t))throw ha(t,oa);return Number.isInteger(t)?ua(t):fa(t);case"string":return function(t){if(la.test(t))throw ha(t,"String");return`"${t.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}(t);case"symbol":return ga(t);case"boolean":return function(t){if("boolean"!=typeof t)throw ha(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 da)return ga(t);default:throw ha(t,oa)}}function ma(t){if(!1===/^[a-z*][a-z0-9\-_.*]*$/.test(t))throw ha(t,"Key");return t}function va(t){return null==t?"":Object.entries(t).map(([t,e])=>!0===e?`;${ma(t)}`:`;${ma(t)}=${pa(e)}`).join("")}function ya(t){return t instanceof ra?`${pa(t.value)}${va(t.params)}`:pa(t)}function Ea(t,e={whitespace:!0}){if("object"!=typeof t||null==t)throw ha(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 ra==!1&&(e=new ra(e));let i=ma(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 ra?new ra(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 ra&&"string"==typeof t.value?new ra(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 n=i.pathname.split("/").slice(1),r=s.pathname.split("/").slice(1,-1),a=Math.min(n.length,r.length);for(let t=0;t<a&&n[t]===r[t];t++)n.shift(),r.shift();for(;r.length;)r.shift(),n.unshift("..");return n.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),_a=t=>t instanceof ra?new ra(100*Math.round(t.value/100),t.params):100*Math.round(t/100),ka=t=>Array.isArray(t)?t.map(_a):_a(t),wa={br:Ia,d:Ia,bl:ka,dl:ka,mtp:ka,nor:(t,e)=>{let i=t;return e.version>=2&&(t instanceof ra&&"string"==typeof t.value?i=new ra([t]):"string"==typeof t&&(i=[t])),Ra(i,e)},rtp:ka,tb:Ia},Da=2,xa="rr",Pa="bc",Ca="e",Ma=xa,Oa="ce",Fa=new Map([["ps","sta"],["pr","pr"],["c","cid"],["b","bg"],["bc","br"]]),Na="event",Ba="request",$a=["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 ja(t){return Ga.test(t)}const qa=new Set(Ua);function Ka(t){return qa.has(t)||ja(t)}const Va=["cmsdd","cmsds","rc","smrt","ttfb","ttfbb","ttlb","url"],Ha=new Set(Va);function Ya(t){return Ha.has(t)}const Wa=new Set($a);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)||ja(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 Ka(t)||Ya(t)||Wa.has(t)},[Ba]:Ka};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 ra?t.value:t}function no(t,i={}){const s={};if(null==t||"object"!=typeof t)return s;const n=i.version||t.v||Da,r=i.reportingMode||Ba,a=1===n?function(t){const e={};for(const[s,n]of Object.entries(t))if(null!=n)if("nor"===s){const t=(Array.isArray(n)?n:[n])[0];var i;t instanceof ra?(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(n,t.ot):e[s]=n;else e[s]=n;return e}(t):t,o=1===n?Za:io[r];let l=Object.keys(a).filter(o);a.e&&a.e!==xa&&(l=l.filter(t=>!Ya(t)));const d=i.filter;"function"==typeof d&&(l=l.filter(d));const h=r===Na;if(h){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;n>1&&!l.includes("v")&&l.push("v");const c={version:n,reportingMode:r,baseUrl:i.baseUrl};l.sort();for(const t of l){var u,f;let r=a[t];const o=null!=(u=null==(f=i.formatters)?void 0:f[t])?u:wa[t];if("function"==typeof o&&(r=o(r,c)),"v"===t){if(1===n)continue;r=n}if("pr"===t&&1===r&&(!h||"pr"!==a.e))continue;h&&"ts"===t&&!e(r)&&(r=Date.now());const l=h&&!1===r&&"bg"===t&&"b"===a.e;(eo(r)||l)&&(to(t)&&"string"==typeof r&&(r=new da(r)),s[t]=r)}return s}const ro="CMCD-Object",ao="CMCD-Request",oo="CMCD-Session",lo="CMCD-Status",ho=ao,co={ab:ro,br:ro,d:ro,lab:ro,lb:ro,ot:ro,tab:ro,tb:ro,tpb:ro,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),n=e?(r=e,Object.keys(r).reduce((t,e)=>{var i;return null==(i=r[e])||i.forEach(i=>t[i]=e),t},{})):{};var r;for(const e of s){var a;const s=co[e]||n[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 po=[...Xa,...Ua,...Va,...$a].filter((t,e,i)=>i.indexOf(t)===e),mo="m",vo="a",yo="v",Eo="av",To="i",So="tt",bo="s",Ao="p",Lo="k",Io="r",Ro="a",_o="e",ko="f",wo="d",Do="query",xo="headers";function Po(t,e,i){var s;const n=new Set(null!=(s=e.enabledKeys)?s:[]);return{version:e.version||Da,reportingMode:t,filter:t=>n.has(t),baseUrl:i}}const Co=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],n=e[i];if(s===n)continue;if("number"==typeof s||"number"==typeof n)return!1;if(s.value!==n.value)return!1;const r=s.params,a=n.params,o=r&&Object.keys(r)[0],l=a&&Object.keys(a)[0];if(o!==l)return!1;if(void 0!==o&&void 0!==l&&r&&a&&r[o]!==a[l])return!1}return!0}(t,e),snapshot:t=>t.slice()}:{event:t,field:e,equal:Co,snapshot:Mo}),Fo=new Map(Oo.map(t=>[t.event,t]));function No(t){const{url:e}=t,i=k(t,Sa);return fetch(e,i)}var Bo=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=Da,eventTargets:i=[],sid:s=tt(),transmissionMode:n=Do}=t;return _(_({},k(t,ba)),{},{version:e,transmissionMode:n,sid:s,eventTargets:i.reduce((t,e)=>{var i,s,n;return null!=e&&e.url&&null!=(i=e.events)&&i.length&&t.push({version:e.version||Da,enabledKeys:(null==(s=e.enabledKeys)?void 0:s.slice())||[],url:e.url,events:e.events.slice(),interval:null!=(n=e.interval)?n: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=_(_(_({},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 n=this.data[t];if(void 0===n)return;if(i.equal(n,this.lastEmitted[t]))return;I(this.lastEmitted,{[t]:i.snapshot(n)})}this.eventTargets.forEach((i,s)=>{this.recordTargetEvent(i,s,t,e)}),this.processEventTargets()}recordTargetEvent(t,e,i,s={}){var n;if(!e.events.includes(i))return;const r=_(_(_({},this.data),s),{},{e:i,ts:null!=(n=s.ts)?n:Date.now(),sn:t.sn++});isNaN(this.msd)||t.msdSent||(r.msd=this.msd,t.msdSent=!0),t.queue.push(r)}recordResponseReceived(t,e={}){var i,s,n;const{request:r}=t,a=null!=(i=e.url)?i:null==r?void 0:r.url;if(!a)return;const o=new URL(a);o.searchParams.delete(fo);const l={url:o.toString(),rc:t.status},d=t.resourceTiming;d&&(null!=d.startTime&&(l.ts=Math.round(this.timeOrigin+d.startTime),null!=d.responseStart&&(l.ttfb=Math.round(d.responseStart-d.startTime))),null!=d.duration&&(l.ttlb=Math.round(d.duration)));const h=null!=(s=null==(n=r.customData)?void 0:n.cmcd)?s:{};this.recordEvent(xa,_(_(_({},h),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:n={}}=t,r=_(_({},k(t,Aa)),{},{headers:_({},n),customData:_(_({},s),{},{cmcd:{}})});if(null==(i=this.config.enabledKeys)||!i.length||!r.url)return r;const a=new URL(r.url),o=_(_(_({},this.data),e),{},{sn:this.requestTarget.sn++}),l=Po(Ba,this.config,r.url);isNaN(this.msd)||this.requestTarget.msdSent||(o.msd=this.msd,this.requestTarget.msdSent=!0);const d=r.customData.cmcd=no(o,l);switch(this.config.transmissionMode){case Do:const t=go(d);t&&(a.searchParams.set(fo,t),r.url=a.toString());break;case xo:I(r.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}(d,l.customHeaderMap))}return r}processEventTargets(t=!1){let e=!1;this.eventTargets.forEach((i,s)=>{const{queue:n}=i;if(!n.length)return;if(n.length<s.batchSize&&!t)return;const r=t?n.length:s.batchSize,a=n.splice(0,r);this.sendEventReport(s,a).catch(()=>{i.queue.unshift(...a)}),e||(e=n.length>0)}),e&&this.processEventTargets()}async sendEventReport(t,e){const i=Po(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(no(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 $o="h",Uo="v",Go="l",jo="ll";new Set(Xa),new Set(po);const qo=["includeKeys"];function Ko(t){return Object.keys(t).every(ja)}function Vo(t,e,i,s){t&&Object.keys(e).forEach(n=>{const r=t.filter(t=>t.groupId===n).map(t=>{const r=I({},t);return r.details=void 0,r.attrs=new Yi(r.attrs),r.url=r.attrs.URI=Ho(t.url,t.attrs["STABLE-RENDITION-ID"],"PER-RENDITION-URIS",i),r.groupId=r.attrs["GROUP-ID"]=e[n],r.attrs["PATHWAY-ID"]=s,r});t.push(...r)})}function Ho(t,e,i,s){if(e){const{[i]:t}=s;if(t){const i=t[e];if(i)return i}}const{HOST:n,PARAMS:r}=s,a=new self.URL(t);return n&&(a.hostname=n),r&&Object.keys(r).sort().forEach(t=>{t&&we(a,t,r[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 Ln,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(n=>{let r;const a=cs(n),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");r=new Uint8Array(e.subarray(8,24))}catch(t){return void this.warn(`${s} Failed to parse sinf: ${t}`)}else if(a===as.PLAYREADY)r=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];r=null!=(l=e.kids)&&l.length?e.kids[0]:null}}let d;if(r){const t=pt(r);for(let s=0;s<o.length;s++){const n=o[s];if(n.keyId&&(Zi(r,n.keyId)||-1!==n.uri.replace(/-/g,"").indexOf(t))){n.pssh||(n.scheme=e,n.pssh=new Uint8Array(i),n.keyId=r,Es.setKeyIdForUri(n.uri,r)),d=this.getSessionForKey(n,"encrypted-event-key-match");break}}}if(!d){var h,c;if(o.length)return(h=o[0]).scheme||(h.scheme=e),(c=o[0]).pssh||(c.pssh=new Uint8Array(i)),this.getSessionForKey(o[0],"encrypted-event-no-match");if(r)throw new Error(`Key ID ${pt(r)} not encountered in playlist`);this.log(`Ignoring "${t.type}" event - could not determine keyId`)}return d}).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:n.KEY_SYSTEM_ERROR,details:r.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===ps&&"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 n=function(t,e,i,s){let n;switch(t){case as.FAIRPLAY:n=["cenc","sinf"];break;case as.WIDEVINE:case as.PLAYREADY:n=["cenc"];break;case as.CLEARKEY:n=["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}))}]}(n,e,i,s)}(t,e,i,this.config.drmSystemOptions||{});let r=this.keySystemAccessPromises[t],a=null==(s=r)?void 0:s.keySystemAccess;if(!a){this.log(`Requesting encrypted media "${t}" key-system access with config: ${Ue(n)}`),a=this.requestMediaKeySystemAccess(t,n);const e=r=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 n=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 n.catch(e=>{this.error(`Failed to create media-keys for "${t}"}: ${e}`)}),n})}return a.then(()=>r.mediaKeys)}getMediaKeySessionContext(t,e,i,s){const{mediaKeySessions:n}=this,r=` key-session "${t}" keyId: ${pt(i.keyId||[])} keyUri: ${i.uri} for "${s}"`;for(let t=0;t<n.length;t++){const e=n[t];if(!e.initialized&&e.createdFor.levelKey.uri===i.uri)return this.log(`Reusing${r}`),e}this.log(`Creating${r}`);const a=e.createSession(),o={keySystem:t,mediaKeys:e,mediaKeysSession:a,keyRequests:{},keyStatuses:{},createdFor:{levelKey:i,reason:s},initialized:!1};return n.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 ${pt(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,n=e.length;s<n;s++){const r=e[s];if(t.cc<=r.cc&&(!y(t)||!y(r)||t.sn<r.sn)||!i&&s==n-1)return this.selectKeySystemFormat(r).then(t=>{if(!this.hls)return;r.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} (${pt(e.keyId||[])})`),Promise.reject(s)}const s=t.type,n=this.activeKeys,r=n[s];r&&!e.matches(r.decryptdata)&&(n.previous||(n.previous=[]),n.previous.push(r),delete n[s]),n[s]||(n[s]=t);for(let t=this.mediaKeySessions.length;t--;){const i=this.mediaKeySessions[t];if(e.keyId&&"expired"===i.keyStatuses[pt(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,n=this.sessionSetupByUri[s];let r;r=void 0===n?this.resolveSessionForKey(t,e):n.catch(()=>{}).then(()=>(this.throwIfDestroyed(),this.resolveSessionForKey(t,e))),this.sessionSetupByUri[s]=r;const a=()=>{this.sessionSetupByUri[s]===r&&delete this.sessionSetupByUri[s]};return r.then(a,a),r}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 n=this.getUsableKeyPromise(s,t,e);if(n)return n}return this.attemptSetMediaKeys(i,s).then(()=>(this.throwIfDestroyed(),this.getMediaKeySessionContext(i,s,t,e))).then(i=>{this.throwIfDestroyed();const s=t.scheme||"cenc",n=t.pssh?t.pssh.buffer:null;return this.generateRequestWithPreferredKeySession(i,t,s,n,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 pt(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?` (${pt(i.keyId||[])})`:""}`),this.hls.trigger(a.ERROR,t.data)}else this.error(t.message),this.hls.trigger(a.ERROR,{type:n.KEY_SYSTEM_ERROR,details:r.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:n.KEY_SYSTEM_ERROR,details:r.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,n){var r;const a=null==(r=this.config.drmSystems)||null==(r=r[t.keySystem])?void 0:r.generateRequest;if(a)try{const r=a.call(this.hls,i,s,I({},t,{decryptdata:e,reason:n}),n);if(!r)throw new Error("Invalid response from configured generateRequest filter");e.scheme=r.initDataType?r.initDataType:"cenc";const o=r.initData?r.initData:null;return e.pssh=o?new Uint8Array(o):null,r}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,n){const r=this.getUsableKeyPromise(t,e,n);if(r)return r;const a=this.filterInitData(t,e,i,s,n);if(a&&(s=a.initData?a.initData:null,i=a.initDataType),null===s)return n.startsWith("encrypted-event")?Promise.reject(new Error(`missing initialization data for "${n}"`)):(this.log(`Skipping key-session request for "${n}" (no initData)`),Promise.resolve(t));const o=e.uri,l=new Yo;t.keyRequests[o]=l;const d=i=>{const s=t.mediaKeysSession;if(!s){const t=new Error("invalid state");return void(l.errored=t)}const{messageType:n,message:r}=i;l.status=n,this.log(`"${n}" message event for session "${s.sessionId}" message size: ${r.byteLength}`),"license-request"===n||"license-renewal"===n?this.renewLicense(t,e,r).catch(e=>{l.errored=e,l.hasListeners||this.handleError(e),this.removeSession(t)}):"license-release"===n?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 "${n}"`)};l.onmessage=d,en(t.mediaKeysSession,"message",d);return this.generateRequest(t,e,i,s,n,!1)}generateRequest(t,e,i,s,a,o){if(o){const n=this.filterInitData(t,e,i,s,a);n&&(s=n.initData?n.initData:s,i=n.initDataType)}const l=e.uri,d=t.keyRequests[l],h=pt(e.keyId||[]),c=t=>{let i;t.startsWith("usable")?d.resolve():"internal-error"===t||"output-restricted"===t||"output-downscaled"===t?i=Qo(t,e):"expired"===t?i=new Error(`key expired (keyId: ${h})`):"released"===t?i=new Error("key released"):"status-pending"===t||this.warn(`unhandled key status change "${t}" (keyId: ${h})`),i&&(d.errored=i,d.hasListeners||this.handleError(i))},u=i=>{if(!t.mediaKeysSession){const t=new Error("invalid state");return void(d.errored=t)}const s=t.keyStatuses=this.getKeyStatuses(t);if(!Object.keys(s).some(t=>"status-pending"!==s[t]))return;const n=this.activeLevelKeys();for(let i=0;i<n.length;i++){const a=pt(n[i].keyId||[]);if("expired"===s[a]){var r;this.log(`Expired key ${Ue(s)} in key-session "${null==(r=t.mediaKeysSession)?void 0:r.sessionId}"`),this.renewKeySession(e,t).catch(t=>this.handleError(t));break}}let a=s[h];if(a)c(a);else{var o;const i=1e3;t.keyStatusTimeouts||(t.keyStatusTimeouts={}),(o=t.keyStatusTimeouts)[h]||(o[h]=self.setTimeout(()=>{var s;if(!t.mediaKeysSession)return;const n=this.getKeyStatus(e);var r;if(n&&"status-pending"!==n)return this.log(`No status for keyId ${h} in key-session "${null==(r=t.mediaKeysSession)?void 0:r.sessionId}". Using session key-status ${n} from other session.`),c(n);this.log(`key status for ${h} 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 ${h} (${Ue(s)}).`)}};d.onkeystatuseschange=u,en(t.mediaKeysSession,"keystatuseschange",u);const f=d.useable;return this.log(`Generating key-session request for "${a}" keyId: ${h} URI: ${l} (init data type: ${i} length: ${s.byteLength})`),d.status="started",t.initialized=!0,t.mediaKeysSession.generateRequest(i,s).then(()=>{var e;d.status="generated",this.log(`Request generated for key-session "${null==(e=t.mediaKeysSession)?void 0:e.sessionId}" keyId: ${h} URI: ${l}`)}).catch(t=>{throw this.log(`mediaKeysSession.generateRequest failed: ${t}`),new Wo({type:n.KEY_SYSTEM_ERROR,details:r.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!==r.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED&&s!==r.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,n)=>{if("string"==typeof n&&"object"==typeof s){const t=n;n=s,s=t}const r="buffer"in n?new Uint8Array(n.buffer,n.byteOffset,n.byteLength):new Uint8Array(n);if(t.keySystem===as.PLAYREADY&&16===r.length){const t=pt(r);e[t]=s,ss(r)}const a=pt(r);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},d=e.certLoadPolicy.default,h={loadPolicy:d,timeout:d.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},c={onSuccess:(t,e,i,s)=>{a(t.data)},onError:(e,i,a,d)=>{o(new Wo({type:n.KEY_SYSTEM_ERROR,details:r.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:a,response:_({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:n.KEY_SYSTEM_ERROR,details:r.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,h,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(n=>{this.log(`setServerCertificate ${n?"success":"not supported by CDM"} (${i.byteLength}) on "${e}"`),s(t)}).catch(t=>{a(new Wo({type:n.KEY_SYSTEM_ERROR,details:r.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:n.KEY_SYSTEM_ERROR,details:r.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"),n=s.querySelectorAll("HttpHeader");if(n.length>0){let e;for(let i=0,s=n.length;i<s;i++){var r,a;e=n[i];const s=null==(r=e.querySelector("name"))?void 0:r.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,n){const r=this.config.licenseXhrSetup;return r?Promise.resolve().then(()=>(this.throwIfDestroyed(),r.call(this.hls,t,e,_(_({},i),{},{decryptdata:s}),n))).catch(a=>{if(!i.mediaKeysSession)throw a;return t.open("POST",e,!0),r.call(this.hls,t,e,_(_({},i),{},{decryptdata:s}),n)}).then(i=>{t.readyState||t.open("POST",e,!0);return{xhr:t,licenseChallenge:i||n}}):(t.open("POST",e,!0),Promise.resolve({xhr:t,licenseChallenge:n}))}requestLicense(t,e,i){return new Promise((s,a)=>{const o=function(t,e){const{drmSystems:i,widevineLicenseUrl:s}=e,n=null==i?void 0:i[t];if(n)return n.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 d=this.config.keyLoadPolicy.default,h=new XMLHttpRequest;h.responseType="arraybuffer",h.onreadystatechange=()=>{if(!this.hls||!t.mediaKeysSession)return a(new Error("invalid state"));if(4===h.readyState)if(200===h.status){l.requestErrors=[];let i=h.response;this.log(`License received ${i instanceof ArrayBuffer?i.byteLength:i}`);const n=this.config.licenseResponseCallback;if(n)try{i=n.call(this.hls,h,o,_(_({},t),{},{decryptdata:e}))}catch(t){this.error(t)}s(i)}else{const c=d.errorRetry,u=c?c.maxNumRetry:0;if(l.requestErrors.push({status:h.status,message:h.statusText}),l.requestErrors.length>u||h.status>=400&&h.status<500)a(new Wo({type:n.KEY_SYSTEM_ERROR,details:r.KEY_SYSTEM_LICENSE_REQUEST_FAILED,decryptdata:e,fatal:!0,networkDetails:h,response:{url:o,data:void 0,code:h.status,text:h.statusText}},`License Request XHR failed (${o}). Status: ${h.status} (${h.statusText})`));else{const n=u-l.requestErrors.length;this.warn(`Retrying license request, ${n} attempts left`),this.requestLicense(t,e,i).then(s,a)}}},l.licenseXhr&&l.licenseXhr.readyState!==XMLHttpRequest.DONE&&l.licenseXhr.abort(),l.licenseXhr=h,this.setupLicenseXHR(h,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,en(i,"encrypted",this.onMediaEncrypted),en(i,"waitingforkey",this.onWaitingForKey);const s=this.mediaResolved;s?s():this.mediaKeys=i.mediaKeys}onMediaDetached(){const t=this.media;t&&(sn(t,"encrypted",this.onMediaEncrypted),sn(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:n.OTHER_ERROR,details:r.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:n.OTHER_ERROR,details:r.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:n.OTHER_ERROR,details:r.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:n.OTHER_ERROR,details:r.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[pt(i)]}}function Qo(t,e){const i="output-restricted"===t,s=i?r.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:r.KEY_SYSTEM_STATUS_INTERNAL_ERROR;return new Wo({type:n.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!=rs&&rs.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 n(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 r(e,r,a){const o=this,l={enumerable:!0};o.hasBeenReset=!1;let d="",h=!1,c=e,u=r,f=a,g=null,p="",m=!0,v="auto",y="start",E=50,T="middle",S=50,b="middle";Object.defineProperty(o,"id",n({},l,{get:function(){return d},set:function(t){d=""+t}})),Object.defineProperty(o,"pauseOnExit",n({},l,{get:function(){return h},set:function(t){h=!!t}})),Object.defineProperty(o,"startTime",n({},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",n({},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",n({},l,{get:function(){return f},set:function(t){f=""+t,this.hasBeenReset=!0}})),Object.defineProperty(o,"region",n({},l,{get:function(){return g},set:function(t){g=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"vertical",n({},l,{get:function(){return p},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.");p=s,this.hasBeenReset=!0}})),Object.defineProperty(o,"snapToLines",n({},l,{get:function(){return m},set:function(t){m=!!t,this.hasBeenReset=!0}})),Object.defineProperty(o,"line",n({},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",n({},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",n({},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",n({},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",n({},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",n({},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 r.prototype.getCueAsHTML=function(){return self.WebVTT.convertCueToDOMTree(self,this.text)},r}();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 n=s?t.split(s):[t];for(const t in n){if("string"!=typeof n[t])continue;const s=n[t].split(i);if(2!==s.length)continue;e(s[0],s[1])}}const sl=new Zo(0,0,""),nl="middle"===sl.align?"middle":"center";function rl(t,e,i){const s=t;function n(){const e=tl(t);if(null===e)throw new Error("Malformed timestamp: "+s);return t=t.replace(/^[^\sa-zA-Z-]+/,""),e}function r(){t=t.replace(/^\s+/,"")}if(r(),e.startTime=n(),r(),"--\x3e"!==t.slice(0,3))throw new Error("Malformed time stamp (time stamps must be separated by '--\x3e'): "+s);t=t.slice(3),r(),e.endTime=n(),r(),function(t,e){const s=new el;il(t,function(t,e){let n;switch(t){case"region":for(let n=i.length-1;n>=0;n--)if(i[n].id===e){s.set(t,i[n].region);break}break;case"vertical":s.alt(t,e,["rl","lr"]);break;case"line":n=e.split(","),s.integer(t,n[0]),s.percent(t,n[0])&&s.set("snapToLines",!1),s.alt(t,n[0],["auto"]),2===n.length&&s.alt("lineAlign",n[1],["start",nl,"end"]);break;case"position":n=e.split(","),s.percent(t,n[0]),2===n.length&&s.alt("positionAlign",n[1],["start",nl,"end","line-left","line-right","auto"]);break;case"size":s.percent(t,e);break;case"align":s.alt(t,e,["start",nl,"end","left","right"])}},/:/,/\s/),e.region=s.get("region",null),e.vertical=s.get("vertical","");let n=s.get("line","auto");"auto"===n&&-1===sl.line&&(n=-1),e.line=n,e.lineAlign=s.get("lineAlign","start"),e.snapToLines=s.get("snapToLines",!0),e.size=s.get("size",100),e.align=s.get("align",nl);let r=s.get("position","auto");"auto"===r&&50===sl.position&&(r="start"===e.align||"left"===e.align?0:"end"===e.align||"right"===e.align?100:50),e.position=r}(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 n=!1;for(;e.buffer;){if(!/\r\n|\n/.test(e.buffer))return this;switch(n?n=!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{rl(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&&(n=!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 dl=/\r\n|\n\r|\n|\r/g,hl="Missing initPTS for VTT ";function cl(t,e,i){return ll(t.toString())+ll(e.toString())+ll(i)}function ul(t,i,s,n,r,a,o){const l=new ol,d=ot(new Uint8Array(t)).trim().replace(dl,"\n").split("\n"),h=[],c=i?function(t,e=1){return Ir(t,9e4,1/e)}(i.baseTime,i.timescale):0;let u,f="00:00.000",g=0,p=0,m=!1,v=!0;l.oncue=function(t){const e=s[n];let a=s.ccOffset;const o=(g-c)/9e4;if(m){if(null!=e&&e.new&&(a=s.ccOffset=e.start),o){if(!i)return void(u=new Error(hl+"MPEGTS"));a=o-s.presentationOffset}}else{if(!i)return void(u=new Error(hl+"without X-TIMESTAMP-MAP"));a=-i.baseTime/i.timescale}const l=t.endTime-t.startTime,d=xr(9e4*(t.startTime+a-p),9e4*r)/9e4;t.startTime=Math.max(d,0),t.endTime=Math.max(d+l,0);const f=t.text.trim();t.text=decodeURIComponent(encodeURIComponent(f)),t.id?n&&(t.id=`hlsjscc${n}_${t.id}`):t.id=cl(t.startTime,t.endTime,f),t.endTime>0&&h.push(t)},l.onparsingerror=function(t){u=t},l.onflush=function(){u?o(u):a(h)},d.forEach(t=>{if(v){if(t.startsWith("X-TIMESTAMP-MAP=")){v=!1,m=!0,t.slice(16).split(",").forEach(t=>{t.startsWith("LOCAL:")?f=t.slice(6):t.startsWith("MPEGTS:")&&(g=parseInt(t.slice(7)))});try{p=function(t){let i=parseInt(t.slice(-3));const s=parseInt(t.slice(-6,-4)),n=parseInt(t.slice(-9,-7)),r=t.length>9?parseInt(t.substring(0,t.indexOf(":"))):0;if(!(e(i)&&e(s)&&e(n)&&e(r)))throw Error(`Malformed X-TIMESTAMP-MAP: Local:${t}`);return i+=1e3*s,i+=6e4*n,i+=36e5*r,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+)?$/,pl=/^(\d*(?:\.\d*)?)(h|m|s|ms|f|t)$/,ml={left:"start",center:"center",right:"end",start:"start",end:"end"};function vl(t,e,i,s){const n=xt(new Uint8Array(t),["mdat"]);if(0===n.length)return void s(new Error("Could not parse IMSC1 mdat"));const r=n.map(t=>ot(t)),a=function(t,e,i=1,s=!1){return Ir(t,e,1/i,s)}(e.baseTime,1,e.timescale);try{r.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 n={frameRate:30,subFrameRate:1,frameRateMultiplier:0,tickRate:1},r=Object.keys(n).reduce((t,e)=>(t[e]=s.getAttribute(`ttp:${e}`)||n[e],t),{});!s.getAttribute("ttp:tickRate")&&s.getAttribute("ttp:frameRate")&&(r.tickRate=Number(r.frameRate)*Number(r.subFrameRate));const a="preserve"!==s.getAttribute("xml:space"),o=El(yl(s,"styling","style")),l=El(yl(s,"layout","region")),d=yl(s,"body","[begin]");return[].map.call(d,t=>{const i=Tl(t,a);if(!i||!t.hasAttribute("begin"))return null;const s=Al(t.getAttribute("begin"),r),n=Al(t.getAttribute("dur"),r);let d=Al(t.getAttribute("end"),r);if(null===s)throw bl(t);if(null===d){if(null===n)throw bl(t);d=s+n}const h=new Zo(s-e,d-e,i);h.id=cl(h.startTime,h.endTime,h.text);const c=function(t,e,i){const s="http://www.w3.org/ns/ttml#styling";let n=null;const r=["displayAlign","textAlign","color","backgroundColor","fontSize","fontFamily"],a=null!=t&&t.hasAttribute("style")?t.getAttribute("style"):null;a&&i.hasOwnProperty(a)&&(n=i[a]);return r.reduce((i,r)=>{const a=Sl(e,s,r)||Sl(t,s,r)||Sl(n,s,r);return a&&(i[r]=a),i},{})}(l[t.getAttribute("region")],o[t.getAttribute("style")],o),{textAlign:u}=c;if(u){const t=ml[u];t&&(h.lineAlign=t),h.align=u}return I(h,c),h}).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 n;return"br"===i.nodeName&&s?t+"\n":null!=(n=i.childNodes)&&n.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):pl.test(t)&&(i=function(t,e){const i=pl.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="",n="disabled"){const r=t.ownerDocument.createElement("track");return r.kind=e,r.label=i,s&&(r.srclang=s),r.src="data:,WEBVTT",r.track.mode=n,t.appendChild(r),r}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){H.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){H.debug(`[texttrack-utils]: Legacy TextTrackCue fallback failed: ${t}`)}}"disabled"===i&&(t.mode=i)}function _l(t,e,i,s){const n=t.mode;if("disabled"===n&&(t.mode="hidden"),t.cues&&t.cues.length>0){const n=function(t,e,i){const s=[],n=function(t,e){if(e<=t[0].startTime)return 0;const i=t.length-1;if(e>t[i].endTime)return-1;let s,n=0,r=i;for(;n<=r;)if(s=Math.floor((r+n)/2),e<t[s].startTime)r=s-1;else{if(!(e>t[s].startTime&&n<i))return s;n=s+1}return t[n].startTime-e<e-t[r].startTime?n:r}(t,e);if(n>-1)for(let r=n,a=t.length;r<a;r++){const n=t[r];if(n.startTime>=e&&n.endTime<=i)s.push(n);else if(n.startTime>i)return s}return s}(t.cues,e,i);for(let e=0;e<n.length;e++)s&&!s(n[e])||t.removeCue(n[e])}"disabled"===n&&(t.mode=n)}function kl(t,e){const i=wl(t.main);if(i&&i.start<=e)return i;const s=wl(t.audio);return s&&s.start<=e?s:null}function wl(t){if(!t)return null;switch(t.state){case an:case rn:case fn:case gn:return null}return t.frag}function Dl(t,e){return e.getAppendedFrag(t,f.MAIN)||e.getPartialFragment(t)}function xl(t,e,i,s){const n=s.latestLevelDetails,r=Dl(e,i);if(En(s.config)&&!t.nextStart&&n&&r&&s.interstitialsManager){const i="type"in r?r:r.fragment,a=ii(n,i.sn);(null==a?void 0:a.level)===i.level&&yn(a,s.interstitialsManager.playerQueue,e)&&(t.nextStart=a.start)}}function Pl(){if("undefined"!=typeof self)return self.VTTCue||self.TextTrackCue}function Cl(t,e,i,s,n){let r=new t(e,i,"");try{r.value=s,n&&(r.type=n)}catch(a){r=new t(e,i,Ue(n?_({type:n},s):s))}return r}const Ml=(()=>{const t=Pl();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,Bl=1,$l=2;class Ul extends vn{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=an,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=rn}stopLoad(){this._forceStartLoad=!1,super.stopLoad()}doTick(){switch(this.state){case mn:{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=an;break}if(this.hls.nextLoadLevel!==this.level){this.state=an;break}break}case dn:this.checkRetryDate()}this.state===an&&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 n=this.buffering?t.nextLoadLevel:t.loadLevel;if(null==i||!i[n])return;const r=i[n],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=fn)}if(!this.buffering)return;t.loadLevel!==n&&-1===t.manualLevel&&this.log(`Adapting to level ${n} from level ${this.level}`),this.level=t.nextLoadLevel=n;const d=r.details;if(!d||this.state===mn||this.waitForLive(r))return this.level=n,this.state=mn,void(this.startFragRequested=!1);const h=o.len,c=this.getMaxBufferLength(r.maxBitrate);if(h>=c)return;this.backtrackFragment&&this.backtrackFragment.start>o.end&&(this.backtrackFragment=void 0);const u=this.backtrackFragment?this.backtrackFragment.start:o.end;let m=this.getNextFragment(u,d);if(this.couldBacktrack&&!this.fragPrevious&&m&&y(m)&&this.fragmentTracker.getState(m)!==Ei){var v;const t=(null!=(v=this.backtrackFragment)?v:m).sn-d.startSN,e=d.fragments[t-1];e&&m.cc===e.cc&&(m=e,this.fragmentTracker.removeFragment(e))}else this.backtrackFragment&&o.len&&(this.backtrackFragment=void 0);if(m&&this.isLoopLoading(m,u)){if(!m.gap){const t=this.audioOnly&&!this.altAudio?g:p,e=(t===p?this.videoBuffer:this.mediaBuffer)||this.media;e&&this.afterBufferFlushed(e,t)}m=this.getNextFragmentLoopLoading(m,d,o,f.MAIN,c)}m&&(this.exceedsMaxBuffer(o,c,m)||this.loadFragment(m,r,u))}loadFragment(t,e,i){const s=this.fragmentTracker.getState(t);s===mi||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===$l?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!==$l||this.audioOnly?null:"video"}onMediaAttached(t,e){super.onMediaAttached(t,e);const i=e.media;en(i,"playing",this.onMediaPlaying),en(i,"seeked",this.onMediaSeeked)}onMediaDetaching(t,e){const{media:i}=this;i&&(sn(i,"playing",this.onMediaPlaying),sn(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 n=e.levels[t].audioCodec;n&&(i=i||-1!==n.indexOf("mp4a.40.2"),s=s||-1!==n.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!==an)return;const s=e.levelInfo;(!s.details||s.details.live&&(this.levelLastLoaded!==s||s.details.expired)||this.waitForCdnTuneIn(s.details))&&(this.state=mn)}onLevelLoaded(t,e){var i;const{levels:s,startFragRequested:n}=this,r=e.level,o=e.details,l=o.totalduration;if(!s)return void this.warn(`Levels were reset while loading level ${r}`);this.log(`Level ${r} loaded [${o.startSN},${o.endSN}]${o.lastPartSn?`[part-${o.lastPartSn}-${o.lastPartIndex}]`:""}, cc [${o.startCC}, ${o.endCC}] duration:${l}`);const d=e.levelInfo,h=this.fragCurrent;!h||this.state!==ln&&this.state!==dn||h.level!==e.level&&h.loader&&this.abortCurrentFrag();let c=0;if(o.live||null!=(i=d.details)&&i.live){var u;if(this.checkLiveUpdate(o),o.deltaUpdateFailed)return;c=this.alignPlaylists(o,d.details,null==(u=this.levelLastLoaded)?void 0:u.details)}if(d.details=o,this.levelLastLoaded=d,n||this.setStartPosition(o,c),this.hls.trigger(a.LEVEL_UPDATED,{details:o,level:r}),this.state===mn){if(this.waitForCdnTuneIn(o))return;this.state=an}n&&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,n=this.playhead,r=t.fragmentStart,a=t.edge,o=n>=r-e.maxFragLookUpTolerance&&n<=a;if(null!==s&&i.duration>s&&(n<s||!o)){const r=void 0!==e.liveMaxLatencyDuration?e.liveMaxLatencyDuration:e.liveMaxLatencyDurationCount*t.targetduration;if((!o&&i.readyState<4||n<a-r)&&(this._hasEnoughToStart||(this.nextLoadPosition=s),i.readyState))if(this.warn(`Playback: ${n} is located too far from the end of live sliding playlist: ${a}, reset currentTime to : ${s}`),"buffered"===this.config.liveSyncMode){var l;const t=$i.bufferInfo(i,s,0);if(null==(l=t.buffered)||!l.length)return void(i.currentTime=s);if(t.start<=n)return void(i.currentTime=s);const{nextStart:e}=$i.bufferedInfo(t.buffered,n,0);e&&(i.currentTime=e)}else i.currentTime=s}}_handleFragmentLoadProgress(t){var e;const i=t.frag,{part:s,payload:n}=t,{levels:r}=this;if(!r)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=r[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,d=o.PTSKnown||!o.live,h=null==(e=i.initSegment)?void 0:e.data,c=this._getAudioCodec(a),u=this.transmuxer=this.transmuxer||new Kr(this.hls,f.MAIN,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)),g=s?s.index:-1,p=-1!==g,{decryptRange:m,byteRange:v}=Ci(i,s,this.iframesOnly),y=new Ni(i.level,i.sn,i.stats.chunkCount,v?v.end-v.start:n.byteLength,g,p,i.duration,this.iframesOnly,m),E=this.initPTS[i.cc];u.push(n,h,c,l,i,s,o.totalduration,d,y,E)}onAudioTrackSwitching(t,e){const i=this.hls,s=this.altAudio!==Nl;if(We(e.url,i))this.altAudio=Bl;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?$l:Nl,this.tick()}onBufferCreated(t,e){const i=e.tracks;let s,n,r=!1;for(const t in i){const e=i[t];if("main"===e.id){if(n=t,s=e,"video"===t){const e=i[t];e&&(this.videoBuffer=e.buffer)}}else r=!0}r&&s?(this.log(`Alternate track found, use ${n}.buffered to schedule main fragment loading`),this.mediaBuffer=s.buffer):this.mediaBuffer=this.media}onFragBuffered(t,e){const{frag:i,part:s}=e,n=i.type===f.MAIN;if(n){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===un&&(this.state=an));let t=!1;if(y(i)&&(t=!!i.gap&&!i.tagList.some(t=>"GAP"===t[0])),this.fragBufferedComplete(i,s),t){var r;i.stats.retry++;const t=null==(r=this.levels)?void 0:r[i.level];t&&t.fragmentError++}}const a=this.media;a&&(!this._hasEnoughToStart&&$i.getBuffered(a).length&&(this._hasEnoughToStart=!0,this.seekToStartPos()),n&&this.tick())}get hasEnoughToStart(){return this._hasEnoughToStart}onError(t,e){var i;if(e.fatal)this.state=gn;else switch(e.details){case r.FRAG_GAP:case r.FRAG_PARSING_ERROR:case r.FRAG_DECRYPT_ERROR:case r.FRAG_LOAD_ERROR:case r.FRAG_LOAD_TIMEOUT:case r.KEY_LOAD_ERROR:case r.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(f.MAIN,e);break;case r.LEVEL_LOAD_ERROR:case r.LEVEL_LOAD_TIMEOUT:case r.LEVEL_PARSING_ERROR:e.levelRetry||this.state!==mn||(null==(i=e.context)?void 0:i.type)!==u.LEVEL||(this.state=an);break;case r.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 r.BUFFER_ADD_CODEC_ERROR:case r.BUFFER_APPEND_ERROR:if("main"!==e.parent)return;this.reduceLengthAndFlushBuffer(e)&&this.resetLoadingState();break;case r.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 r.INTERNAL_EXCEPTION:this.recoverWorkerError(e)}}onFragLoadEmergencyAborted(){this.state=an,this._hasEnoughToStart||(this.startFragRequested=!1,this.nextLoadPosition=this.lastCurrentTime),this.tickImmediate()}onBufferFlushed(t,{type:e}){if(e!==g||!this.altAudio){const t=(e===p?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 n=this.getLevelDetails(),r=$i.getBuffered(t),a=r.length?r.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==n?void 0:n.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=an,this.startFragRequested=!1,this.bitrateTest=!1;const n=s.stats;n.parsing.start=n.parsing.end=n.buffering.start=n.buffering.end=self.performance.now(),i.trigger(a.FRAG_LOADED,t),s.bitrateTest=!1}).catch(e=>{this.state!==rn&&this.state!==gn&&(this.warn(e),this.resetFragmentLoading(t))})}_handleTransmuxComplete(t){const i=this.playlistType,{hls:s}=this,{remuxResult:n,chunkMeta:r}=t,o=this.getCurrentContext(r);if(!o)return void this.resetWhenMissingContext(r);const{frag:l,part:d,level:h}=o,{video:c,text:u,id3:f,initSegment:p}=n,{details:m}=h,v=this.altAudio?void 0:n.audio;if(this.fragContextChanged(l))this.fragmentTracker.removeFragment(l);else{if(this.state=cn,p){const t=p.tracks;if(t){const e=l.initSegment||l;if(this.unhandledEncryptionError(p,l))return;this._bufferInitSegment(h,t,e,r),s.trigger(a.FRAG_PARSING_INIT_SEGMENT,{frag:e,id:i,tracks:t})}const n=p.initPTS,o=p.timescale,d=this.initPTS[l.cc];if(e(n)&&(!d||d.baseTime!==n||d.timescale!==o)){const t=p.trackId;this.initPTS[l.cc]={baseTime:n,timescale:o,trackId:t};const e=this.initPTS.slice(0);s.trigger(a.INIT_PTS_FOUND,{timestampOffsets:e,frag:l,id:i,initPTS:n,timescale:o,trackId:t})}}if(c&&m){v&&"audiovideo"===c.type&&this.logMuxedErr(l);const t=m.fragments[l.sn-1-m.startSN],e=l.sn===m.startSN,i=!t||l.cc>t.cc;if(!1!==n.independent){const{startPTS:t,endPTS:s,startDTS:n,endDTS:a}=c;if(d)d.elementaryStreams[c.type]={startPTS:t,endPTS:s,startDTS:n,endDTS:a};else if(c.firstKeyFrame&&c.independent&&1===r.id&&!i&&(this.couldBacktrack=!0),c.dropped&&c.independent){const n=this.getMainFwdBufferInfo(),r=(n?n.end:this.getLoadPosition())+this.config.maxBufferHole,o=c.firstKeyFramePTS?c.firstKeyFramePTS:t;if(!e&&r<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-(m.appliedTimelineOffset||0)>2&&(l.gap=!0);l.setElementaryStreamInfo(c.type,t,s,n,a),this.backtrackFragment&&(this.backtrackFragment=l),this.bufferFragmentData(c,l,d,r,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;d&&(d.elementaryStreams[g]={startPTS:t,endPTS:e,startDTS:i,endDTS:s}),l.setElementaryStreamInfo(g,t,e,i,s),this.bufferFragmentData(v,l,d,r)}if(m&&null!=f&&f.samples.length){const t={id:i,frag:l,details:m,samples:f.samples};s.trigger(a.FRAG_PARSING_METADATA,t)}if(m&&u){const t={id:i,frag:l,details:m,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!==cn)return;this.audioOnly=!!e.audio&&!e.video,this.altAudio&&!this.audioOnly&&(delete e.audio,e.audiovideo&&this.logMuxedErr(i));const{audio:n,video:r,audiovideo:o}=e;if(n){const i=t.audioCodec;let s=ve(n.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=n.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"!==n.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}"`),n.levelCodec=s,n.id=f.MAIN,this.log(`Init audio buffer, container:${n.container}, codecs[selected/level/parsed]=[${s||""}/${i||""}/${n.codec}]`),delete e.audiovideo}if(r){r.levelCodec=t.videoCodec,r.id=f.MAIN;const i=r.codec;if(4===(null==i?void 0:i.length))switch(i){case"hvc1":case"hev1":r.codec="hvc1.1.6.L120.90";break;case"av01":r.codec="av01.0.04M.08";break;case"avc1":r.codec="avc1.42e01e"}this.log(`Init video buffer, container:${r.container}, codecs[level/parsed]=[${t.videoCodec||""}/${i}]${r.codec!==i?" parsed-corrected="+r.codec:""}${r.supplemental?" supplemental="+r.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 n=e[t].initSegment;null!=n&&n.byteLength&&this.hls.trigger(a.BUFFER_APPENDING,{type:t,data:n,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=an}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 rn:case fn:case gn:this.state=an}this.state===an?(this.hls.resumeBuffering(),this.tick(),this.currentOp=[s,e]):this.nextOp=[s,e],this.hls.off(a.BUFFERED_TO_END,this.onBufferedToEnd);const n=this.media;if(i&&n){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,n=void 0!==s?s:e.duration;t>=n&&(t=n-.01);if($i.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!==mi&&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=ln;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=rn,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?nn($i.getBuffered(this.media)):"none"}`)),s&&this.loadMediaAt.apply(this,s)}flushPipeline(t,e){if(e){const e=this.media;if(e){const i=$i.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 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 rn:case fn:case gn:this.state=an}if(this.state===an){if(this.hls.resumeBuffering(),this.media||(this.media={}),this.tick(),this.state===an){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 n=this._img;if(n&&s){const r=self.performance.now();(e?e.stats:t.stats).buffering.start=t.stats.buffering.start=r,n.onload=()=>{if(!this.hls)return;const s=this.hls.levels[t.level];null!=s&&s.fragmentError&&(s.fragmentError=0,t.stats.retry=0);const n=self.performance.now(),r=e?e.stats:t.stats;r.buffering.end=t.stats.buffering.end=n,this.hls.trigger(a.FRAG_BUFFERED,{frag:t,part:e,stats:r,id:t.type,chunkMeta:i})},n.onerror=()=>{this.handleError("Image decode error",t,e,i)};const o=n.src;o&&self.URL.revokeObjectURL(o);const l=new Blob([s],{type:"image/jpeg"});n.src=self.URL.createObjectURL(l)}else this.state=rn,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:n.MEDIA_ERROR,details:r.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 n=xt(new Uint8Array(t.data1),["mdat"]);if(0===n.length)return void this.handleError("Could not find I-Frame mdat",e,i,s);const r=e;this.cacheSet(r,n[0]),this.updateImage(r,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 ql="Image I-Frame player does not accept HTMLMediaElements",Kl={seekOnAppend:!0};let Vl,Hl;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&&we(s,"_HLS_primary_id",e),s}function td(t,e){for(;null!=(i=t.assetList[++e])&&i.error;)var i;return e}function ed(t){const e=t.timelineStart,i=t.duration||0;return`["${t.identifier}" ${e.toFixed(2)}-${(e+i).toFixed(2)}]`}class id{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 n=this.hls=new t(e);this.interstitial=i,this.assetItem=s;const r=()=>{this.hasDetails=!0};n.once(a.LEVEL_LOADED,r),n.once(a.AUDIO_TRACK_LOADED,r),n.once(a.SUBTITLE_TRACK_LOADED,r),n.on(a.MEDIA_ATTACHING,(t,{media:e})=>{this.removeMediaListeners(),this.mediaAttached=e;this.interstitial.playoutLimit&&(e.addEventListener("timeupdate",this.checkPlayout),this.appendInPlace&&n.on(a.BUFFER_APPENDED,()=>{const t=this.bufferedEnd;this.reachedPlayout(t)&&(this._bufferedEosTime=t,n.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),n=this.timelineOffset+(e||0),r=$i.bufferInfo(t,n,.02);return this.getAssetTime(r.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=$i.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: ${ed(this.assetItem)} ${null==(t=this.hls)?void 0:t.sessionId} ${this.appendInPlace?"append-in-place":""}`}}const sd=.033;class nd 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!=(n=s[i])&&n.event;){var n;i--}return i}findItemIndexAtTime(t,e){const i=this.items;if(i)for(let s=0;s<i.length;s++){let n=i[s];e&&"primary"!==e&&(n=n[e]);const r=n.start,a=i[s].event,o=null!=a&&a.cue.pre?a.duration:n.end;if(t===r||t>r&&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 n=i[t];if(!n.error){const i=n.timelineStart;if(e===i||e>i&&(e<i+(n.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:n}=s,r=this.events,a=this.parseDateRanges(n,{url:s.url},e),o=Object.keys(n),l=r?r.filter(t=>-1===o.indexOf(t.identifier)):[];a.length&&a.sort((t,e)=>{const i=t.cue.pre,s=t.cue.post,n=e.cue.pre,r=e.cue.post;if(i&&!n)return-1;if(n&&!i)return 1;if(s&&!r)return 1;if(r&&!s)return-1;if(!(i||n||s||r)){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 n=this.events||[];if(n.length||e.length||this.length<2){const r=this.items,a=this.parseSchedule(n,t,i);(s||e.length||(null==r?void 0:r.length)!==a.length||a.some((t,e)=>Math.abs(t.playout.start-r[e].playout.start)>.005||Math.abs(t.playout.end-r[e].playout.end)>.005))&&(this.items=a,this.onScheduleUpdate(e,r))}}parseDateRanges(t,e,i){const s=[],n=Object.keys(t);for(let r=0;r<n.length;r++){const a=n[r],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=[],n=e.main.details,r=n.live?1/0:n.edge;let a=0;if((t=t.filter(t=>!(t.error||t.cue.once&&t.hasPlayed))).length){this.resolveOffsets(t,e);let l=0,d=0;if(t.forEach((e,o)=>{const h=e.cue.pre,c=e.cue.post,u=t[o-1]||null,f=e.appendInPlace,g=c?r:e.startOffset,p=e.duration,m=e.timelineOccupancy===Wl.Range?p:0,v=h&&n.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+p:g+y;if(h||!c&&g<=0){const t=d;d+=m,e.timelineStart=T;const i=a;a+=p,s.push({event:e,start:T,end:S,playout:{start:i,end:a},integrated:{start:t,end:d}})}else{if(!(g<=r))return;{if(!E){const i=g-l;if(i>sd){const n=l,r=d;d+=i;const h=a;a+=i;const c={previousEvent:t[o-1]||null,nextEvent:e,start:n,end:n+i,playout:{start:h,end:a},integrated:{start:r,end:d}};s.push(c)}else i>0&&u&&(u.cumulativeDuration+=i,s[s.length-1].end=g)}c&&(S=T),e.timelineStart=T;const i=d;d+=m;const n=a;a+=p,s.push({event:e,start:T,end:S,playout:{start:n,end:a},integrated:{start:i,end:d}})}}const b=v||e.resumeTime;l=c||b>r?r:!h&&S&&e.appendInPlaceStarted&&b-S>sd?S:b}),l<r){var o;const t=l,e=d,i=r-l;d+=i;const n=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:n,end:a},integrated:{start:e,end:d}})}this.setDurations(r,a,d)}else{const t=0;s.push({previousEvent:null,nextEvent:null,start:t,end:r,playout:{start:t,end:r},integrated:{start:t,end:r}}),this.setDurations(r,r,r)}return s}setDurations(t,e,i){this.durations={primary:t,playout:e,integrated:i}}resolveOffsets(t,i){const s=i.main.details,n=s.live?1/0:s.edge;let r=0,a=-1;t.forEach((o,l)=>{const d=o.cue.pre,h=o.cue.post,c=d?0:h?n:o.startTime;this.updateAssetDurations(o);if(a===c?o.cumulativeDuration=r:(r=0,a=c),!h&&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<sd&&(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;r+=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 n=e[s].details,r=n.edge;if(i>=r)return this.log(`"${t.identifier}" resumption ${i} past ${s} playlist end ${r}`),!1;const a=Ze(null,n.fragments,i);if(!a)return this.log(`"${t.identifier}" resumption ${i} does not align with any fragments in ${s} playlist (${n.fragStart}-${n.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,n=!1;for(let r=0;r<t.assetList.length;r++){const a=t.assetList[r],o=e+i;a.startOffset=i,a.timelineStart=o,s||(s=null===a.duration),n||(n=!!a.error);i+=a.error?0:a.duration||0}t.duration=s&&!n?Math.max(i,t.duration):i}removeEvent(t){t.reset(),delete this.eventMap[t.identifier]}}function rd(t){return`[${t.event?'"'+t.event.identifier+'"':"primary"}: ${t.start.toFixed(2)}-${t.end.toFixed(2)}]`}class ad{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,r.ASSET_LIST_LOAD_ERROR,e,i);return void this.hls.trigger(a.ERROR,s)}e&&"data:"!==s.protocol&&we(s,"_HLS_start_offset",""+e);const n=this.hls.config,o=new(0,n.loader)(n),l={type:u.INTERSTITIAL_ASSET_LIST,responseType:"json",url:s.href},d=n.interstitialAssetListLoadPolicy.default,h={loadPolicy:d,timeout:d.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},c={onSuccess:(e,i,s,n)=>{const o=e.data,l=null==o?void 0:o.ASSETS;if(!Array.isArray(l)){const e=this.assignAssetListError(t,r.ASSET_LIST_PARSING_ERROR,new Error("Invalid interstitial asset list"),s.url,i,n);return void this.hls.trigger(a.ERROR,e)}t.assetListResponse=o,this.hls.trigger(a.ASSET_LIST_LOADED,{event:t,assetListResponse:o,networkDetails:n})},onError:(e,i,s,n)=>{const o=this.assignAssetListError(t,r.ASSET_LIST_LOAD_ERROR,new Error(`Error loading X-ASSET-LIST: HTTP status ${e.code} ${e.text} (${i.url})`),i.url,n,s);this.hls.trigger(a.ERROR,o)},onTimeout:(e,i,s)=>{const n=this.assignAssetListError(t,r.ASSET_LIST_LOAD_TIMEOUT,new Error(`Timeout loading X-ASSET-LIST (${i.url})`),i.url,e,s);this.hls.trigger(a.ERROR,n)}};return o.load(l,h,c),this.hls.trigger(a.ASSET_LIST_LOADING,{event:t}),o}assignAssetListError(t,e,i,s,r,a){return t.error=i,{type:n.NETWORK_ERROR,details:e,fatal:!1,interstitial:t,url:s,error:i,networkDetails:a,stats:r}}}function od(t){var e;null==t||null==(e=t.play())||e.catch(()=>{})}function ld(t,e){return`[${t}] Advancing timeline position to ${e}`}class dd{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 hd={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},cd=t=>String.fromCharCode(hd[t]||t),ud=15,fd=42,gd={17:1,18:3,21:5,22:7,23:9,16:11,19:12,20:14},pd={17:2,18:4,21:6,22:8,23:10,19:13,20:15},md={25:1,26:3,29:5,30:7,31:9,24:11,27:12,28:14},vd={25:2,26:4,29:6,30:8,31:10,27:13,28:15},yd=["white","green","blue","cyan","red","yellow","magenta","black","transparent"];class Ed{constructor(){this.time=null,this.verboseLevel=0}log(t,e){if(this.verboseLevel>=t){const i="function"==typeof e?e():e;H.log(`${this.time} [${t}] ${i}`)}}}const Td=function(t){const e=[];for(let i=0;i<t.length;i++)e.push(t[i].toString(16));return e},Sd=Object.freeze({foreground:"white",underline:!1,italics:!1,background:"black",flash:!1});class bd{constructor(){this.styles=Sd}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=Sd}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 Ad{constructor(){this.uchar=" ",this.penState=new bd}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 Ld{constructor(t){this.chars=[],this.pos=0,this.currPenState=new bd,this.cueStartTime=null,this.logger=void 0;for(let t=0;t<fd;t++)this.chars.push(new Ad);this.logger=t}equals(t){const e=this.chars,i=t.chars;for(let t=0;t<fd;t++){const s=e[t],n=i[t];if(s.uchar!==n.uchar)return!1;const r=s.penState.styles,a=n.penState.styles;if(r!==a&&(r.foreground!==a.foreground||r.underline!==a.underline||r.italics!==a.italics||r.background!==a.background||r.flash!==a.flash))return!1}return!0}copy(t){for(let e=0;e<fd;e++)this.chars[e].copy(t.chars[e])}isEmpty(){const t=this.chars;for(let e=0;e<fd;e++){const i=t[e];if(" "!==i.uchar)return!1;const s=i.penState.styles;if(s!==Sd&&("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>=fd&&(this.logger.log(3,"Too large cursor position "+this.pos),this.pos=41)}moveCursor(t){const e=Math.min(this.pos+t,fd);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=cd(t);this.pos>=fd?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<fd;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<fd;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 Id{constructor(t){this.rows=[],this.currRow=14,this.nrRollUpRows=null,this.lastOutputScreen=null,this.logger=void 0;for(let e=0;e<ud;e++)this.rows.push(new Ld(t));this.logger=t}reset(){for(let t=0;t<ud;t++)this.rows[t].clear();this.currRow=14}equals(t){let e=!0;for(let i=0;i<ud;i++)if(!this.rows[i].equals(t.rows[i])){e=!1;break}return e}copy(t){for(let e=0;e<ud;e++){const i=this.rows[e].chars,s=t.rows[e].chars;for(let t=0;t<fd;t++){const e=i[t],n=s[t];e.uchar=n.uchar,e.penState.styles=n.penState.styles}}}isEmpty(){let t=!0;for(let e=0;e<ud;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<ud;t++)this.rows[t].clear();const t=this.currRow+1-this.nrRollUpRows,i=this.lastOutputScreen;if(i){const s=i.rows[t].cueStartTime,n=this.logger.time;if(null!==s&&null!==n&&s<n)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<ud;i++){const n=this.rows[i].getTextString();n&&(s=i+1,t?e.push("Row "+s+": '"+n+"'"):e.push(n.trim()))}return e.length>0&&(i=t?"["+e.join(" | ")+"]":e.join("\n")),i}getTextAndFormat(){return this.rows}}class Rd{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 Id(i),this.nonDisplayedMemory=new Id(i),this.lastOutputScreen=new Id(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 _d{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 Ed,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 Rd(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 n=!1,r=null;if(0===i&&0===s)continue;this.logger.log(3,()=>"["+Td([e[t],e[t+1]])+"] -> ("+Td([i,s])+")");const a=this.cmdHistory;if(i>=16&&i<=31){if(wd(i,s,a)){kd(null,null,a),this.logger.log(3,()=>"Repeated command ("+Td([i,s])+") is dropped");continue}kd(i,s,this.cmdHistory),n=this.parseCmd(i,s),n||(n=this.parseMidrow(i,s)),n||(n=this.parsePAC(i,s)),n||(n=this.parseBackgroundAttributes(i,s))}else kd(null,null,a);if(!n&&(r=this.parseChars(i,s),r)){const t=this.currentChannel;if(t&&t>0){this.getChannel(t).insertChars(r)}else this.logger.log(2,"No channel found yet. TEXT-MODE?")}n||r||this.logger.log(2,()=>"Couldn't parse cleaned data "+Td([i,s])+" orig: "+Td([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 ("+Td([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?gd[t]:md[t]:1===s?pd[t]:vd[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,n=null;if(t>=25?(i=2,n=t-8):(i=1,n=t),n>=17&&n<=19){let t;t=17===n?e+80:18===n?e+112:e+144,this.logger.log(2,()=>"Special char '"+cd(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 = "+Td(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=yd[i],e%2==1&&(s.background=s.background+"_semi")):45===e?s.background="transparent":(s.foreground="black",47===e&&(s.underline=!0));const n=t<=23?1:2;return this.getChannel(n).setBkgData(s),!0}reset(){for(let t=0;t<Object.keys(this.channels).length;t++){const e=this.channels[t];e&&e.reset()}kd(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 kd(t,e,i){i.a=t,i.b=e}function wd(t,e,i){return i.a===t&&i.b===e}class Dd{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 xd(t,e,i,s){return Math.min(e,s)-Math.max(t,i)}const Pd=/\s/,Cd={newCue(t,e,i,s){const n=[];let r,a,o,l,d;const h=self.VTTCue||self.TextTrackCue;for(let u=0;u<s.rows.length;u++)if(r=s.rows[u],o=!0,l=0,d="",!r.isEmpty()){var c;for(let t=0;t<r.chars.length;t++)Pd.test(r.chars[t].uchar)&&o?l++:(d+=r.chars[t].uchar,o=!1);r.cueStartTime=e,e===i&&(i+=1e-4),l>=16?l--:l++;const s=al(d.trim()),f=cl(e,i,s);null!=t&&null!=(c=t.cues)&&c.getCueById(f)||(a=new h(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)),n.push(a))}return t&&n.length&&(n.sort((t,e)=>"auto"===t.line||"auto"===e.line?0:t.line>8&&e.line>8?e.line-t.line:t.line-e.line),n.forEach(e=>Rl(t,e))),n}};class Md{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;H.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=C(t,i.retry),i.retry++,H.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 Od=/(\d+)-(\d+)\/(\d+)/;class Fd extends Md{constructor(t){super(),this.fetchSetup=void 0,this.request=null,this.response=null,this.controller=null,this.fetchSetup=t.fetchSetup||Nd}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 n=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),r="arraybuffer"===i.responseType,a=r?"byteLength":"length",{maxTimeToFirstByteMs:o,maxLoadTimeMs:l}=t.loadPolicy;this.request=this.fetchSetup(i,n),self.clearTimeout(this.requestTimeout),t.timeout=o&&e(o)?o:l,this.requestTimeout=self.setTimeout(()=>{this.loadtimeout()},t.timeout);(Ur(this.request)?this.request.then(self.fetch):self.fetch(this.request)).then(n=>{var a;this.response=n;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)),!n.ok){const{status:t,statusText:e}=n;throw new Bd(e||"fetch, bad network response",t,n)}s.loading.first=o,s.total=function(t){const i=t.get("Content-Range");if(i){const t=function(t){const e=Od.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)}(n.headers)||s.total;const d=null==(a=this.callbacks)?void 0:a.onProgress;return d&&e(t.highWaterMark)?this.loadProgressively(n,s,i,t.highWaterMark,d):r?n.arrayBuffer():"json"===i.responseType?n.json():n.text()}).then(n=>{var r,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 d=n[a];d&&(s.loaded=s.total=d);const h={url:l.url,data:n,code:l.status},c=null==(r=this.callbacks)?void 0:r.onProgress;c&&!e(t.highWaterMark)&&c(s,i,n,l),null==(o=this.callbacks)||o.onSuccess(h,s,i,l)}).catch(e=>{if(self.clearTimeout(this.requestTimeout),s.aborted)return;const n=e&&e.code||0,r=e?e.message:null,a=t.loadPolicy.errorRetry;var o;O(a,s.retry,!1,{url:i.url,data:void 0,code:n})?this.retry(a):(H.error(`${n} while loading ${i.url}`),null==(o=this.callbacks)||o.onError({code:n,text:r},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,n){const r=new Tn,a=t.body.getReader(),o=()=>a.read().then(a=>{if(a.done)return r.dataLength&&n(e,i,r.flush().buffer,t),Promise.resolve(new ArrayBuffer(0));const l=a.value,d=l.length;return e.loaded+=d,d<s||r.dataLength?(r.push(l),r.dataLength>=s&&n(e,i,r.flush().buffer,t)):n(e,i,l.buffer,t),o()}).catch(()=>Promise.reject());return o()}}function Nd(t,e){return new self.Request(t.url,e)}class Bd extends Error{constructor(t,e,i){super(t),this.code=void 0,this.details=void 0,this.code=e,this.details=i}}const $d=/^age:\s*[\d.]+\s*$/im;class Ud extends Md{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 n=this.xhrSetup;n?Promise.resolve().then(()=>{if(this.loader===i&&!this.stats.aborted)return n.call(this,i,e.url,e)}).catch(t=>{if(this.loader===i&&!this.stats.aborted)return i.open("GET",e.url,!0),n.call(this,i,e.url,e)}).then(()=>{this.loader!==i||this.stats.aborted||this.openAndSendXhr(i,e,t)}).catch(t=>{var n;null==(n=this.callbacks)||n.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 n=i.headers,{maxTimeToFirstByteMs:r,maxLoadTimeMs:a}=s.loadPolicy;if(n)for(const e in n)t.setRequestHeader(e,n[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=r&&e(r)?r: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,n=this.config;if(!i.aborted&&s>=2&&(0===i.loading.first&&(i.loading.first=Math.max(self.performance.now(),i.loading.start),n.timeout!==n.loadPolicy.maxLoadTimeMs&&(self.clearTimeout(this.requestTimeout),n.timeout=n.loadPolicy.maxLoadTimeMs,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),n.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 n=null!=l?l:e.response;if(null!=n){var r,a;i.loading.end=Math.max(self.performance.now(),i.loading.first);const o="arraybuffer"===e.responseType?n.byteLength:n.length;i.loaded=i.total=o,i.bwEstimate=8e3*i.total/(i.loading.end-i.loading.first);const l=null==(r=this.callbacks)?void 0:r.onProgress;l&&l(i,t,n,e);const d={url:e.responseURL,data:n,code:s};return t.rangeEnd&&o!==t.rangeEnd-t.rangeStart&&H.warn(`Payload length ${o} does not match requested Range: bytes=${t.rangeStart}-${t.rangeEnd-1}`),void(null==(a=this.callbacks)||a.onSuccess(d,i,t,e))}}const d=n.loadPolicy.errorRetry;var o;if(O(d,i.retry,!1,{url:t.url,data:void 0,code:s}))this.retry(d);else H.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&&$d.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 Gd=_(_({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:Ud,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:ps,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:n,hls:r}=this;if(!r)return;const{autoLevelEnabled:o,media:l}=r;if(!s||!l)return;const d=performance.now(),h=n?n.stats:s.stats,c=n?n.duration:s.duration,u=d-h.loading.start,f=r.minAutoLevel,g=s.level,p=this._nextAutoLevel;if(h.aborted||h.loaded&&h.loaded===h.total||g<=f)return this.clearTimer(),void(this._nextAutoLevel=-1);if(!o)return;const m=p>-1&&p!==g,v=!!t||m;if(!v&&(l.paused||!l.playbackRate||!l.readyState))return;const y=r.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=h.loading.first?h.loading.first-h.loading.start:-1,A=h.loaded&&b>-1,L=this.getBwEstimate(),I=r.levels,R=I[g],_=Math.max(h.loaded,Math.round(c*(s.bitrate||R.averageBitrate)/8));let k=A?u-b:u;k<1&&A&&(k=Math.min(u,8*h.loaded/L));const w=A?1e3*h.loaded/k:0,D=E/1e3,x=w?(_-h.loaded)/w:8*_/L+D;if(x<=S)return;const P=w?8*w:L,C=!0===(null==(i=(null==t?void 0:t.details)||r.latestLevelDetails)?void 0:i.live),M=r.config.abrBandWidthUpFactor;let O,F=Number.POSITIVE_INFINITY;for(O=g-1;O>f;O--){const t=I[O].maxBitrate,e=!I[O].details||C;if(F=this.getTimeToLoadFrag(D,P,c*t,e),F<Math.min(S,c+D))break}if(F>=x)return;if(F>10*c)return;A?this.bwEstimator.sample(u-Math.min(E,b),h.loaded):this.bwEstimator.sampleTTFB(u);const N=I[O].maxBitrate;this.getBwEstimate()*M>N&&(this.firstAutoFloor=Math.min(O,r.firstLevel),this.resetEstimator(N));const B=this.findBestLevel(N,f,O,0,S,1,1);B>-1&&(O=B),this.warn(`Fragment ${s.sn}${n?" part "+n.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: ${x.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`),r.nextLoadLevel=r.nextAutoLevel=O,this.clearTimer();const $=()=>{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)}}};m||x>2*F?$():this.timer=self.setInterval($,1e3*F),r.trigger(a.FRAG_LOAD_EMERGENCY_ABORTED,{frag:s,part:n,stats:h})},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 $(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 r.BUFFER_ADD_CODEC_ERROR:case r.BUFFER_APPEND_ERROR:this.lastLoadedFragLevel=-1,this.firstSelection=-1;break;case r.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,n=e-i.loading.start,r=i.loading.first?i.loading.first-i.loading.start:-1;if(i.loaded&&r>-1){const t=this.bwEstimator.getEstimateTTFB();this.bwEstimator.sample(n-Math.min(t,r),i.loaded)}else this.bwEstimator.sampleTTFB(n)}break}}}getTimeToLoadFrag(t,e,i,s){return t+i/e+(s?t+this.lastLevelLoadSec:0)}onLevelLoaded(t,i){const s=this.hls.config,{loading:n}=i.stats,r=n.end-n.first;e(r)&&(this.lastLevelLoadSec=r/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:n}=e,r=n?n.stats:s.stats;if(s.type===f.MAIN&&this.bwEstimator.sampleTTFB(r.loading.first-r.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=n?n.duration:s.duration,e=this.hls.levels[s.level],i=(e.loaded?e.loaded.bytes:0)+r.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:r,frag:s,part:n,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,n=null!=s&&s.stats.loaded?s.stats:i.stats;if(n.aborted)return;if(this.ignoreFragment(i))return;const r=((i.bitrate||0)>=1e5?n.parsing.end:n.loading.end)-n.loading.start-Math.min(n.loading.first-n.loading.start,this.bwEstimator.getEstimateTTFB());this.bwEstimator.sample(r,n.loaded),n.bwEstimate=this.getBwEstimate(),i.bitrateTest?this.bitrateTestDelay=r/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(),n=this.getStarvationDelay(),r=t.config.maxStarvationDelay,a=this.findBestLevel(s,i,e,n/2,r,1,1);if(a>-1)return a;const o=t.firstLevel,l=-1===this.firstAutoFloor?1/0:this.firstAutoFloor,d=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 ${d}`),d}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:n,minAutoLevel:r}=i,a=e?e.duration:t?t.duration:0,o=this.getBwEstimate(),l=this.getStarvationDelay();let d=n.abrBandWidthFactor,h=n.abrBandWidthUpFactor;if(l){const t=this.findBestLevel(o,r,s,l,0,d,h);if(t>=0)return this.rebufferNotice=-1,t}let c=a?Math.min(a,n.maxStarvationDelay):n.maxStarvationDelay;if(!l){const t=this.bitrateTestDelay;if(t){c=(a?Math.min(a,n.maxLoadingDelay):n.maxLoadingDelay)-t,this.info(`bitrate test took ${Math.round(1e3*t)}ms, set first fragment max fetchDuration to ${Math.round(1e3*c)} ms`),d=h=1}}const u=this.findBestLevel(o,r,s,l,c,d,h);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[r],g=i.loadLevelObj;return g&&(null==f?void 0:f.bitrate)<g.bitrate?r: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,n,r,a,o){const{hls:l,lastLoadedFragLevel:d,fragCurrent:h,partCurrent:c}=this;if(!l)return-1;const u=n+r,f=-1===d?l.firstLevel:d,{levels:g,allAudioTracks:p,loadLevel:m,latestLevelDetails:v,config:y}=l;if(1===g.length)return 0;const E=g[f],T=!(null==v||!v.live),S=-1===m||-1===d;let b,A="SDR",L=(null==E?void 0:E.frameRate)||0;const{audioPreference:I,videoPreference:R}=y,_=this.audioTracksByGroup||(this.audioTracksByGroup=je(p));let k=-1;if(S){if(-1!==this.firstSelection)return this.firstSelection;const n=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 n=i.audioGroups;let r=t[i.codecSet];r||(t[i.codecSet]=r={minBitrate:1/0,minHeight:1/0,minFramerate:1/0,minIndex:s,maxScore:0,videoRanges:{SDR:0},channels:{2:0},hasDefaultAudio:!n,fragmentError:0}),r.minBitrate=Math.min(r.minBitrate,i.bitrate);const a=Math.min(i.height,i.width);return r.minHeight=Math.min(r.minHeight,a),r.minFramerate=Math.min(r.minFramerate,i.frameRate),r.minIndex=Math.min(r.minIndex,s),r.maxScore=Math.max(r.maxScore,i.score),r.fragmentError+=i.fragmentError,r.videoRanges[i.videoRange]=(r.videoRanges[i.videoRange]||0)+1,n&&n.forEach(t=>{if(!t)return;const i=e.groups[t];i&&(r.hasDefaultAudio=r.hasDefaultAudio||e.hasDefaultAudio?i.hasDefault:i.hasAutoSelect||!e.hasDefaultAudio&&!e.hasAutoSelectAudio,Object.keys(i.channels).forEach(t=>{r.channels[t]=(r.channels[t]||0)+i.channels[t]}))}),t},{})}(g,_,i,s)),r=function(t,i,s,n,r){const a=Object.keys(t),o=null==n?void 0:n.channels,l=null==n?void 0:n.audioCodec,d=null==r?void 0:r.videoCodec,h=o&&2===parseInt(o);let c=!1,u=!1,f=1/0,g=1/0,p=1/0,m=1/0,v=0,y=[];const{preferHDR:E,allowedVideoRanges:T}=$e(i,r);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),p=Math.min(p,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);p=e(p)?p:s,s=Math.max(p,s),u||(i=void 0);const A=a.length>1;return{codecSet:a.reduce((e,i)=>{const n=t[i];if(i===e)return e;if(y=u?T.filter(t=>n.videoRanges[t]>0):[],A){if(n.minBitrate>s)return Ge(i,`min bitrate of ${n.minBitrate} > current estimate of ${s}`),e;if(!n.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&&!h){if(!n.channels[o])return Ge(i,`no renditions with ${o} channel sound found (channels options: ${Object.keys(n.channels)})`),e}else if((!l||h)&&c&&0===n.channels[2])return Ge(i,"no renditions with stereo sound found"),e;if(n.minHeight>S)return Ge(i,`min resolution of ${n.minHeight} > maximum of ${S}`),e;if(n.minFramerate>b)return Ge(i,`min framerate of ${n.minFramerate} > maximum of ${b}`),e;if(!y.some(t=>n.videoRanges[t]>0))return Ge(i,`no variants with VIDEO-RANGE of ${Ue(y)} found`),e;if(d&&i.indexOf(d.substring(0,4))%5!=0)return Ge(i,`video codec preference "${d}" not found`),e;if(n.maxScore<v)return Ge(i,`max score of ${n.maxScore} < selected max of ${v}`),e}return e&&(fe(i)>=fe(e)||n.fragmentError>t[e].fragmentError)?e:(m=n.minIndex,v=n.maxScore,i)},void 0),videoRanges:y,preferHDR:E,minFramerate:g,minBitrate:p,minIndex:m}}(n,A,t,I,R),{codecSet:a,videoRanges:o,minFramerate:l,minBitrate:d,minIndex:h,preferHDR:c}=r;k=h,b=a,A=c?o[o.length-1]:o[0],L=l,t=Math.max(t,d),this.log(`picked start tier ${Ue(r)}`)}else b=null==E?void 0:E.codecSet,A=null==E?void 0:E.videoRange;const w=c?c.duration:h?h.duration:0,D=this.bwEstimator.getEstimateTTFB()/1e3,x=[];for(let l=s;l>=i;l--){var P;const i=g[l],h=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,_,A,L,t,I)?(i.supportedPromise=Re(i,_,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||h&&L>i.frameRate||!h&&L>0&&L<i.frameRate||null!=(P=i.supportedResult)&&null!=(P=P.decodingInfoResults)&&P.some(t=>!1===t.smooth))&&(!S||l!==k)){x.push(l);continue}const p=i.details,v=(c?null==p?void 0:p.partTarget:null==p?void 0:p.averagetargetduration)||w||1;let E;E=h?o*t:a*t;const R=w&&n>=2*w&&0===r?i.averageBitrate:i.maxBitrate,C=this.getTimeToLoadFrag(D,E,R*v,!p||p.live);if(E>=R&&(l===d||0===i.loadError&&0===i.fragmentError||N(i,y.errorPenaltyExpireMs))&&(C<=D||!e(C)||T&&!this.bitrateTestDelay||C<u)){const t=this.forcedAutoLevel;return l===m||-1!==t&&t===m||(x.length&&this.trace(`Skipped level(s) ${x.join(",")} of ${s} max with CODECS and VIDEO-RANGE:"${g[x[0]].codecs}" ${g[x[0]].videoRange}; not compatible with "${b}" ${A}`),this.info(`switch candidate:${f}->${l} adjustedbw(${Math.round(E)})-bitrate=${Math.round(E-R)} ttfb:${D.toFixed(1)} avgDuration:${v.toFixed(1)} maxFetchDuration:${u.toFixed(1)} fetchDuration:${C.toFixed(1)} firstSelection:${S} codecSet:${i.codecSet} videoRange:${i.videoRange} hls.loadLevel:${m}`)),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&&(sn(i,"sourceopen",this._onMediaSourceOpen),sn(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:n.MEDIA_ERROR,details:r.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{const t=this._objectUrl=self.URL.createObjectURL(n);if(this.appendSource)try{i.removeAttribute("src");const e=self.ManagedMediaSource;i.disableRemotePlayback=i.disableRemotePlayback||e&&n instanceof e,Zr(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}en(i,"emptied",this._onMediaEmptied),en(i,"error",this._onMediaError),this.appendSource&&en(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}`),en(t,"sourceopen",this._onMediaSourceOpen),en(t,"sourceended",this._onMediaSourceEnded),en(t,"sourceclose",this._onMediaSourceClose),this.appendSource&&(en(t,"startstreaming",this._onStartStreaming),en(t,"endstreaming",this._onEndStreaming))}attachTransferred(){const t=this.media,e=this.transferData;if(!e||!t)return;const i=this.tracks,s=e.tracks,n=s?Object.keys(s):null,r=n?n.length:0,o=()=>{Promise.resolve().then(()=>{this.media&&this.mediaSourceOpenOrEnded&&this._onMediaSourceOpen()})};if(s&&n&&r){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 n=t.currentTime,r=this.details,o=Math.max(n,(null==r?void 0:r.fragments[0].start)||0);return o-n>1?void this.log(`attachTransferred: waiting for playback to reach new tracks start time ${n} -> ${o}`):(this.warn(`attachTransferred: resetting MediaSource for incompatible tracks ("${Object.keys(s)}"->"${Object.keys(i)}") start time: ${o} currentTime: ${n}`),this.onMediaDetaching(a.MEDIA_DETACHING,{}),this.onMediaAttaching(a.MEDIA_ATTACHING,e),void(t.currentTime=o))}this.transferData=void 0,n.forEach(t=>{const e=t,i=s[e];if(i){const t=i.buffer;if(t){const s=this.fragmentTracker,n=i.id;if(s.hasFragments(n)||s.hasParts(n)){const i=$i.getBuffered(t);s.detectEvictedFragments(e,i,n,null,null,!0)}const r=Jr(e),a=[e,t];this.sourceBuffers[r]=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:n,_objectUrl:r}=this;if(n){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"===n.readyState;try{const e=n.sourceBuffers;for(let i=e.length;i--;)t&&e[i].abort(),n.removeSourceBuffer(e[i]);t&&n.endOfStream()}catch(t){this.warn(`onMediaDetaching: ${t.message} while calling endOfStream`)}}this.sourceBufferCount&&this.onBufferReset()}sn(n,"sourceopen",this._onMediaSourceOpen),sn(n,"sourceended",this._onMediaSourceEnded),sn(n,"sourceclose",this._onMediaSourceClose),this.appendSource&&(sn(n,"startstreaming",this._onStartStreaming),sn(n,"endstreaming",this._onEndStreaming)),this.mediaSource=null,this._objectUrl=null}s&&(sn(s,"emptied",this._onMediaEmptied),sn(s,"error",this._onMediaError),sn(s,"seeking",this._onStartStreaming),i||(r&&self.URL.revokeObjectURL(r),this.mediaSrc===r?(s.removeAttribute("src"),this.appendSource&&Zr(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[Jr(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 Wr(this.tracks)}onBufferCodecs(t,e){var i;const s=this.tracks,n=Object.keys(e);this.log(`BUFFER_CODECS: "${n}" (current SB count ${this.sourceBufferCount})`);const r="audiovideo"in e&&(s.audio||s.video)||s.audiovideo&&("audio"in e||"video"in e),a=!r&&this.sourceBufferCount&&this.media&&n.some(t=>!s[t]);r||a?this.warn(`Unsupported transition between "${Object.keys(s)}" and "${n}" SourceBuffers`):(n.forEach(t=>{var i,n;const r=e[t],{id:a,codec:o,levelCodec:l,container:d,metadata:h,supplemental:c}=r;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,p=(null==g?void 0:g.pendingCodec)||(null==g?void 0:g.codec),m=null==g?void 0:g.levelCodec;u||(u=s[t]={buffer:void 0,listeners:[],codec:o,supplemental:c,container:d,levelCodec:l,metadata:h,id:a});const v=ve(p,m),y=null==v?void 0:v.replace(zr,"$1");let E=ve(o,l);const T=null==(n=E)?void 0:n.replace(zr,"$1");E&&v&&y!==T&&("audio"===t.slice(0,5)&&(E=me(E,this.appendSource)),this.log(`switching codec ${p} to ${E}`),E!==(u.pendingCodec||u.codec)&&(u.pendingCodec=E),u.container=d,this.appendChangeType(t,d,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}`,n={label:`change-type=${s}`,execute:()=>{const n=this.tracks[t];if(n){const r=n.buffer;null!=r&&r.changeType&&(this.log(`changing ${t} sourceBuffer type to ${s}`),r.changeType(s),n.codec=i,n.container=e)}this.shiftAndExecuteNext(t)},onStart:()=>{},onComplete:()=>{},onError:e=>{this.warn(`Failed to change ${t} SourceBuffer type`,e)}};this.append(n,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 n={label:"block-audio",execute:()=>{var t,e;(this.lastVideoAppendEnd>s||$i.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(n,"audio",!0)}unblockAudio(){this.operationQueue&&this.operationQueue.unblockAudio()}onBufferAppending(t,i){const{tracks:s}=this,{data:o,type:l,parent:d,frag:h,part:c,chunkMeta:u,offset:f}=i,g=u.buffering[l],p=y(h)&&!c&&!h.gap&&!u.partial&&!u.iframe;let m=null,v=!1;const{sn:E,cc:T}=h,S=self.performance.now();g.start=S;const b=h.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,_=null==R?void 0:R.buffer;if(_&&"initSegment"!==E&&void 0!==f){const t=null==L?void 0:L.buffer,e=c||h;if("audio"===l&&"main"!==d&&!R.ending&&!R.ended&&t&&$i.getBuffered(t).length){const t=e.start+.05*e.duration,i=$i.getBuffered(_),s=this.currentOp("video");i.length||s?!$i.isBuffered(_,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 k=(c||h).start,w={label:`append-${l}`,execute:()=>{var t;g.executeStart=self.performance.now();const i=null==(t=this.tracks[l])?void 0:t.buffer;i&&(p&&(m=$i.timeRangesToArray($i.getBuffered(i)),v=sa(ia(m,h),h)),I?this.updateTimestampOffset(i,k,.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]=$i.getBuffered(i))}),p){const t=this.getFragmentAppendProgress(h),i=e[l];if(i&&m){const e=ia($i.timeRangesToArray(i),h);t.progressed||(t.progressed=e-ia(m,h)>.001);const s=v&&sa(e,h);t.fullyBuffered[l]=(void 0===t.fullyBuffered[l]||t.fullyBuffered[l])&&s}}this.hls.trigger(a.BUFFER_APPENDED,{type:l,frag:h,part:c,chunkMeta:u,parent:d,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,h.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,w,i],l)}this.warn(`QuotaExceededError on "${l}" sn: ${E} - no back buffer available to evict`)}p&&(this.getFragmentAppendProgress(h).errored=!0);const s={type:n.MEDIA_ERROR,parent:d,details:r.BUFFER_APPEND_ERROR,sourceBufferName:l,frag:h,part:c,chunkMeta:u,error:t,err:t,fatal:!1},f=null==(e=this.media)?void 0:e.error;if(t.name!==Xr||0!==this.sourceBufferCount||this.media&&0!==this.pendingTrackCount){var g;i&&(s.details=r.BUFFER_FULL_ERROR);const e=++this.appendErrors[l],n=this.hls.config.appendErrorMaxRetry;this.warn(`Failed ${e}/${n+1} times to append segment in "${l}" sourceBuffer with error: ${t.message}`),e>=n&&(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=r.MEDIA_SOURCE_REQUIRES_RESET)}else s.errorAction=pi(!0);this.appendError=s,this.hls.trigger(a.ERROR,s),i&&this.hls&&this.trimBuffers(h.start,1)}};this.log(`queuing "${l}" append sn: ${E}${c?" p: "+c.index:""} of ${d} playlist ${h.level} cc: ${T} offset: ${f} bytes: ${o.byteLength}`),this.append(w,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 n=null==(s=this.tracks[t])?void 0:s.buffer;this.log(`Remove request ${e}-${i} from ${t} Source Buffer complete > buffer: ${n?nn($i.getBuffered(n)):"(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:n}=e;i&&"audio"!==i||this.unblockAudio(),i?this.append(this.getFlushOp(i,s,n),i):this.sourceBuffers.forEach(([t])=>{t&&this.append(this.getFlushOp(t,s,n),t)})}onFragParsed(t,e){const{frag:i,part:s,chunkMeta:n}=e,r=[],o=s?s.elementaryStreams:i.elementaryStreams;o[m]?r.push("audiovideo"):(o[g]&&r.push("audio"),o[p]&&r.push("video"));0===r.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,n,r),this.hls&&(this.hls.trigger(a.FRAG_BUFFERED,{frag:i,part:s,stats:e,id:i.type,chunkMeta:n}),!s&&i.gap&&e.retry&&this.log(`Nothing buffered for ${i.type} level: ${i.level} sn: ${i.sn} retries ${e.retry}`))},r).catch(t=>{this.warn(`Fragment buffered callback ${t.message}`),this.stepOperationQueue(this.sourceBufferTypes)})}onFragChanged(t,e){var i,s;const n=null==(i=this.hls)?void 0:i.config;if(!n)return;const{backBufferLength:r,frontBufferFlushThreshold:a}=n;this.trimBuffers(a,r,e.frag,e.previousFrag);const o=e.frag.elementaryStreams,{appendErrors:l}=this,d=null==(s=this.appendError)?void 0:s.sourceBufferName;Object.keys(o).forEach(t=>{o[t]&&(l[t]=0,t===d&&(this.appendError=void 0),"audio"===t||"video"===t?(l.audiovideo=0,"audiovideo"===d&&(this.appendError=void 0)):(l.audio=0,l.video=0,"audiovideo"!==d&&(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===r.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 d=t.stats.buffering;if(d.start&&!d.first)return;const h=(null==l?void 0:l.stats)===t.stats?l:void 0;if(null!=h&&h.errored)return;const c=s.length>0&&s.every(t=>!0===(null==h?void 0:h.fullyBuffered[t]));if(null!=h&&h.progressed||c)return void delete this.appendsWithoutProgress[o];if(!h&&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:n.MEDIA_ERROR,details:r.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,n){const{hls:r,details:a,media:o}=this;if(!o||null===a)return;if(!this.sourceBufferCount)return;const l=r.config,d=o.currentTime,h=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,h);c=Math.floor(d/h)*h-t}if(s){const t=this.getLoopBackBufferFlushEnd(s,null!=n?n:null);t>0&&(c=Math.max(c,t))}if(c>0&&this.flushBackBuffer(d,h,c),e(t)&&t>0){const e=Math.max(l.maxBufferLength,t),i=Math.max(e,h),s=Math.floor(d/h)*h+i;this.flushFrontBuffer(d,h,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:n,audiovideo:r}=t.elementaryStreams;if(null!=n&&n.partial||null!=r&&r.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 n=t.start;return s?n=Math.min(n,s.startDTS):(e&&(n=Math.min(n,e.startDTS)),i&&(n=Math.min(n,i.startDTS))),n}flushBackBuffer(t,e,i){this.sourceBuffers.forEach(([t,e])=>{if(e){const o=$i.getBuffered(e);if(o.length>0&&i>o.start(0)){var s,n,r;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==(n=this.media)||!n.loop||!1===(null==(r=this.hls)?void 0:r.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 n=$i.getBuffered(s),r=n.length;if(r<2)return;const o=n.start(r-1),l=n.end(r-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 n=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,n)}}return{duration:1/0}}const r=null==(t=this.overrides)?void 0:t.duration;if(r)return e(r)?{duration:r}:null;const a=this.media.duration;return n>(e(s.duration)?s.duration:0)&&n>a||!e(a)?{duration:n}:null}updateMediaSource({duration:t,start:i,end:s}){const n=this.mediaSource;n&&this.media&&"open"===n.readyState&&(n.duration!==t&&(e(t)&&this.log(`Updating MediaSource duration to ${t.toFixed(3)}`),n.duration=t),void 0!==i&&void 0!==s&&(this.log(`MediaSource duration is set to ${n.duration}. Setting seekable range to ${i}-${s}.`),n.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:n.MEDIA_ERROR,details:r.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,d=t[l];if(this.isPending(d)){const t=this.getTrackCodec(d,l),o=`${d.container};codecs=${t}`;d.codec=t,this.log(`creating sourceBuffer(${o})${this.currentOp(l)?" Queued":""} ${Ue(d)}`);try{const t=i.addSourceBuffer(o),s=Jr(l),n=[l,t];e[s]=n,d.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:n.MEDIA_ERROR,details:r.BUFFER_ADD_CODEC_ERROR,fatal:!1,error:t,sourceBufferName:l,mimeType:o,parent:d.id})}this.trackSourceBuffer(l,d)}}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)&&de(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 n=ve(s,t.levelCodec);return n?"audio"===e.slice(0,5)?me(n,this.appendSource):n:""}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 ${nn(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:n.MEDIA_ERROR,details:r.BUFFER_APPENDING_ERROR,sourceBufferName:t,error:o,fatal:!1});const l=this.currentOp(t);l&&l.onError(o)}updateTimestampOffset(t,e,i,s,n,r){const a=e-t.timestampOffset;Math.abs(a)>=i&&(this.log(`Updating ${s} SourceBuffer timestampOffset to ${e} (sn: ${n} cc: ${r})`),t.timestampOffset=e)}removeExecutor(t,i,s){const{media:n,mediaSource:r}=this,a=this.tracks[t],o=null==a?void 0:a.buffer;if(!n||!r||!o)throw new Error(`Attempting to remove from the ${t} SourceBuffer, but it does not exist`);const l=e(n.duration)?n.duration:1/0,d=e(r.duration)?r.duration:1/0,h=Math.max(0,i);var c;if(h>=d)return null==(c=this.currentOp(t))||c.onComplete(),void this.shiftAndExecuteNext(t);const u=Math.min(s,l,d);if(!(u>h)||a.ending&&!a.ended)throw new Error(`Cannot remove ${u<=h?`invalid range (${h} >= ${u}) `:""}from the ${t} SourceBuffer${a.ending?" while track ending":""}`);a.ended=!1,this.log(`Removing [${h},${u}] from the ${t} SourceBuffer`),o.remove(h,u)}appendExecutor(t,e){const i=this.tracks[e],s=null==i?void 0:i.buffer;if(!s)throw new Qr(`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=$i.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 n=s.buffer;if(!n)return;const r=i.bind(this,t);s.listeners.push({event:e,listener:r}),en(n,e,r)}removeBufferListeners(t){const e=this.tracks[t];if(!e)return;const i=e.buffer;i&&(e.listeners.forEach(t=>{sn(i,t.event,t.listener)}),e.listeners.length=0)}},capLevelController:na,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 r.FRAG_LOAD_ERROR:case r.FRAG_LOAD_TIMEOUT:case r.KEY_LOAD_ERROR:case r.KEY_LOAD_TIMEOUT:return void(e.errorAction=this.getFragRetryOrSwitchAction(e));case r.FRAG_PARSING_ERROR:if(null!=(i=e.frag)&&i.gap)return void(e.errorAction=pi());case r.FRAG_GAP:case r.FRAG_DECRYPT_ERROR:return e.errorAction=this.getFragRetryOrSwitchAction(e),void(e.errorAction.action=ni);case r.PLAYLIST_UNCHANGED_ERROR:case r.LEVEL_EMPTY_ERROR:case r.LEVEL_PARSING_ERROR:{var o;const t=e.parent===f.MAIN?e.level:s.loadLevel;e.details===r.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 r.LEVEL_LOAD_ERROR:case r.LEVEL_LOAD_TIMEOUT:return void("number"==typeof(null==a?void 0:a.level)&&(e.errorAction=this.getPlaylistRetryOrSwitchAction(e,a.level)));case r.AUDIO_TRACK_LOAD_ERROR:case r.AUDIO_TRACK_LOAD_TIMEOUT:case r.SUBTITLE_LOAD_ERROR:case r.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=li)}return;case r.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:return void(e.errorAction={action:ni,flags:di});case r.KEY_SYSTEM_SESSION_UPDATE_FAILED:case r.KEY_SYSTEM_STATUS_INTERNAL_ERROR:case r.KEY_SYSTEM_NO_SESSION:return void(e.errorAction={action:ni,flags:hi});case r.BUFFER_ADD_CODEC_ERROR:case r.REMUX_ALLOC_ERROR:case r.BUFFER_APPEND_ERROR:return void(e.errorAction||(e.errorAction=this.getLevelSwitchAction(e,e.level)));case r.MEDIA_SOURCE_REQUIRES_RESET:return e.errorAction||(e.errorAction=this.getLevelSwitchAction(e,e.level)),void(e.errorAction.flags|=ui|ci);case r.INTERNAL_EXCEPTION:case r.BUFFER_APPENDING_ERROR:case r.BUFFER_APPEND_NO_PROGRESS:case r.BUFFER_FULL_ERROR:case r.LEVEL_SWITCH_ERROR:case r.BUFFER_STALLED_ERROR:case r.BUFFER_SEEK_OVER_HOLE:case r.BUFFER_NUDGE_ON_STALL:return void(e.errorAction=pi())}e.type===n.KEY_SYSTEM_ERROR&&(e.levelRetry=!1,e.errorAction=pi())}getPlaylistRetryOrSwitchAction(t,e){const i=P(this.hls.config.playlistLoadPolicy,t),s=this.playlistError++;if(O(i,s,w(t),t.response))return{action:ai,flags:oi,retryConfig:i,retryCount:s};const n=this.getLevelSwitchAction(t,e);return i&&(n.retryConfig=i,n.retryCount=s),n}getFragRetryOrSwitchAction(t){const e=this.hls,i=this.getVariantLevelIndex(t.frag),s=e.levels[i],{fragLoadPolicy:n,keyLoadPolicy:a}=e.config,o=P(D(t)?a:n,t),l=e.levels.reduce((t,e)=>t+e.fragmentError,0);if(s&&(t.details!==r.FRAG_GAP&&s.fragmentError++,!x(t))){if(O(o,l,w(t),t.response))return{action:ai,flags:oi,retryConfig:o,retryCount:l}}const d=this.getLevelSwitchAction(t,i);return o&&(d.retryConfig=o,d.retryCount=l),d}getLevelSwitchAction(t,e){const i=this.hls;null==e&&(e=i.loadLevel);const s=this.hls.levels[e];if(s){var n,a;const e=t.details;s.loadError++,s.loadErrorTime=self.performance.now(),e===r.BUFFER_APPEND_ERROR&&s.fragmentError++;let d=-1;const{levels:h,loadLevel:c,minAutoLevel:g,maxAutoLevel:p}=i;i.autoLevelEnabled||i.config.preserveManualLevelOnError||(i.loadLevel=-1);const m=null==(n=t.frag)?void 0:n.type,v=(m===f.AUDIO&&e===r.FRAG_PARSING_ERROR||"audio"===t.sourceBufferName&&fi(t))&&h.some(({audioCodec:t})=>s.audioCodec!==t),y="video"===t.sourceBufferName&&fi(t)&&h.some(({codecSet:t,audioCodec:e})=>s.codecSet!==t&&s.audioCodec===e),{type:E,groupId:T}=null!=(a=t.context)?a:{};for(let n=h.length;n--;){const a=(n+c)%h.length;if(a!==c&&a>=g&&a<=p&&(0===h[a].loadError||N(h[a],i.config.errorPenaltyExpireMs))){var o,l;const i=h[a];if(e===r.FRAG_GAP&&m===f.MAIN&&t.frag){const e=h[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(m===f.AUDIO&&null!=(o=s.audioGroups)&&o.some(t=>i.hasAudioGroup(t))||m===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}d=a;break}}if(d>-1&&i.loadLevel!==d)return t.levelRetry=!0,this.playlistError=0,{action:ni,flags:oi,nextAutoLevel:d}}return{action:ni,flags:li}}onErrorOut(t,e){var i,s;switch(null==(i=e.errorAction)?void 0:i.action){case si:break;case ni:this.sendAlternateToPenaltyBox(e),e.errorAction.resolved||e.details===r.FRAG_GAP||e.details===r.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&di){const s=this.getVariantLevelIndex(t.frag),n=e.levels[s],r=null==n?void 0:n.attrs["HDCP-LEVEL"];i.hdcpLevel=r;const a="NONE"===r;r&&!a?(e.maxHdcpLevel=De[De.indexOf(r)-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|=hi)}if(i.flags&hi){const e=t.decryptdata;if(e){const s=this.hls.levels,a=s.length;for(let i=a;i--;){var n,r;if(this.variantHasKey(s[i],e))this.log(`Banned key found in level ${i} (${s[i].bitrate}bps) or audio group "${null==(n=s[i].audioGroups)?void 0:n.join(",")}" (${null==(r=t.frag)?void 0:r.type} fragment) ${pt(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===r.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,n=i-this.lastDroppedFrames,r=e-this.lastDecodedFrames,o=1e3*n/t,l=this.hls;if(l.trigger(a.FPS_DROP,{currentDropped:n,currentDecoded:r,totalDroppedFrames:i}),o>0&&n>l.config.fpsDroppedMonitoringThreshold*r){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:n}=e;this.id3Track||(this.id3Track=this.createTrack(this.media));const r=Pl();if(r)for(let t=0;t<n.length;t++){const e=n[t].type;if(e===On.emsg&&!i||!s)continue;const a=ct(n[t].data),o=n[t].pts;let l=o+n[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=Cl(r,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 n=s[i];n.type===e&&n.startTime<t&&n.endTime===Ml&&(n.endTime=t)}}onBufferFlushing(t,{startOffset:e,endOffset:i,type:s}){const{id3Track:n,hls:r}=this;if(!r)return;const{config:{enableEmsgMetadataCues:a,enableID3MetadataCues:o}}=r;if(n&&(a||o)){let t;t="audio"===s?t=>t.type===On.audioId3&&o:"video"===s?t=>t.type===On.emsg&&a:t=>t.type===On.audioId3&&o||t.type===On.emsg&&a,_l(n.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:n,enableDateRangeMetadataCues:r,interstitialsController:a}=this.hls.config;if(!r)return;const o=Pl();if(s&&n&&!a){const{fragmentStart:e,fragmentEnd:i}=t;let n=this.assetCue;n?(n.startTime=e,n.endTime=i):o&&(n=this.assetCue=Cl(o,e,i,{assetPlayerId:this.hls.config.assetPlayerId},"hlsjs.interstitial.asset"),n&&(n.id=s,this.id3Track||(this.id3Track=this.createTrack(this.media)),this.id3Track.track.addCue(n),n.addEventListener("enter",this.onEventCueEnter)))}if(!t.hasProgramDateTime)return;const{id3Track:l}=this,{dateRanges:d}=t,h=Object.keys(d);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===h.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!==h.length&&e(null==g?void 0:g.programDateTime)){this.id3Track||(this.id3Track=this.createTrack(this.media));for(let t=0;t<h.length;t++){const e=h[t],i=d[e],s=i.startTime,n=c[e],r=(null==n?void 0:n.cues)||{};let l=(null==n?void 0:n.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=h.reduce((t,e)=>{if(e!==i.id){const s=d[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 p=Object.keys(i.attr);for(let t=0;t<p.length;t++){const d=p[t];if(!Wi(d))continue;const h=r[d];if(h)!l||null!=n&&n.durationKnown?Math.abs(h.startTime-s)>.01&&(h.startTime=s,h.endTime=u):h.endTime=u;else if(o){let t=i.attr[d];zi(d)&&(t=mt(t));const n=Cl(o,s,u,{key:d,data:t},On.dateRange);n&&(n.id=e,this.id3Track.track.addCue(n),r[d]=n,a&&("X-ASSET-LIST"!==d&&"X-ASSET-URL"!==d||n.addEventListener("enter",this.onEventCueEnter)))}}c[e]={cues:r,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;en(i,"playing",this.onMediaPlaying),en(i,"waiting",this.onMediaWaiting),en(i,"ended",this.onMediaEnded)}onMediaDetaching(t,e){this.clearInterval();const{media:i}=this;i&&(sn(i,"playing",this.onMediaPlaying),sn(i,"waiting",this.onMediaWaiting),sn(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 n=null==(i=this.hls)?void 0:i.config;if(!n)return;const r=this.media;if(!r)return;const{seeking:o}=r,l=this.seeking&&!o,d=!this.seeking&&o,h=r.paused&&!o||r.ended||0===r.playbackRate;if(this.seeking=o,t!==e)return e&&(this.ended=0),this.moved=!0,o||(this.skipRetry=this.nudgeRetry=0,n.nudgeOnVideoHole&&!h&&t>e&&this.nudgeOnVideoHole(t,e)),void(0===this.waiting&&this.stallResolved(t));if(d||l)return void(l&&this.stallResolved(t));if(h)return this.skipRetry=this.nudgeRetry=0,this.stallResolved(t),void(!this.ended&&r.ended&&this.hls&&(this.ended=t||1,this.hls.trigger(a.MEDIA_ENDED,{stalled:!1})));if(!$i.getBuffered(r).length)return void(this.skipRetry=this.nudgeRetry=0);const c=$i.bufferInfo(r,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=kl(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=Dl(t,u);if(e>0&&(e<=i||s))return void(r.paused||this._trySkipBufferHole(s))}const p=n.detectStallWithCurrentTimeMs,m=self.performance.now(),v=this.waiting;let y=this.stalled;if(null===y){if(!(v>0&&m-v<p))return void(this.stalled=m);y=this.stalled=v}const E=m-y;if(!o&&(E>=p||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(r.currentTime!==t){const e=t;return t=r.currentTime,this.moved=!0,void this.log(`currentTime changed ${e} > ${t}`)}}const S=$i.bufferInfo(r,t,n.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=$i.bufferedInfo($i.timeRangesToArray(this.buffered.audio),t,0);if(i.len>1&&e>=i.start){const i=$i.timeRangesToArray(s),o=$i.bufferedInfo(i,e,0).bufferedIndex;if(o>-1&&o<i.length-1){const e=$i.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=Dl(t,this.fragmentTracker);o&&"fragment"in o?o=o.fragment:o||(o=void 0);const d=$i.bufferInfo(this.media,t,0);this.hls.trigger(a.ERROR,{type:n.MEDIA_ERROR,details:r.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:i,reason:i.message,frag:o,buffer:d.len,bufferInfo:d})}}}}}_tryFixBufferStall(t,e,i){var s,n;const{fragmentTracker:r,media:a}=this,o=null==(s=this.hls)?void 0:s.config;if(!a||!r||!o)return;const l=null==(n=this.hls)?void 0:n.latestLevelDetails,d=Dl(i,r);if(d||null!=l&&l.live&&i<l.fragmentStart){if(this._trySkipBufferHole(d)||!this.media)return}const h=t.buffered,c=this.adjacentTraversal(t,i);(h&&h.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),n=i.getFragAtPos(s,f.MAIN);if(t&&n)return n.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:n.MEDIA_ERROR,details:r.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,d=$i.bufferInfo(i,l,0);xl(d,l,e,s);const h=l<d.start?d.start:d.nextStart;if(h){const u=d.len<=o.maxBufferHole,g=d.len>0&&d.len<1&&i.readyState<3,p=h-l;if(p>0&&(u||g)){if(p>o.maxBufferHole){let i=!1;if(0===l){const t=e.getAppendedFrag(0,f.MAIN);t&&h<t.end&&(i=!0)}if(!i&&t){var c;if(null==(c=s.loadLevelObj)||!c.details)return 0;if(kl(s.inFlightFragments,h))return 0;let i=!1,n=t.end;for(;n<h;){const t=Dl(n,e),s=t?t.duration:0;if(!(s>0)){i=!0;break}n+=s}if(i)return 0}}const{nudgeMaxRetry:u,skipBufferHolePadding:g}=o,m=++this.skipRetry>u,v=Math.max(h,l)+g;if(m||(this.warn(`skipping hole, adjusting currentTime from ${l} to ${v}`),this.moved=!0,i.currentTime=v),null==t||!t.gap||m){const e=new Error(m?`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:n.MEDIA_ERROR,details:r.BUFFER_SEEK_OVER_HOLE,fatal:m,error:e,reason:e.message,buffer:d.len,bufferInfo:d};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 d=l+(s+1)*o.nudgeOffset,h=new Error(`Nudging 'currentTime' from ${l} to ${d}`);this.warn(h.message),i.currentTime=d,e.trigger(a.ERROR,{type:n.MEDIA_ERROR,details:r.BUFFER_NUDGE_ON_STALL,error:h,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:n.MEDIA_ERROR,details:r.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,n=this.computeLatency();if(null===n)return;this._latency=n;const{lowLatencyMode:r,maxLiveSyncPlaybackRate:a}=s;if(!r||1===a||!i.live)return;const o=this.targetLatency;if(null===o)return;const l=n-o,d=l<Math.min(this.maxLatency,o+i.targetduration),h=En(s)&&!(null==(t=this.hls.interstitialsManager)||null==(t=t.playingItem)||!t.event);if(d&&l>.05&&this.forwardBufferLength>1&&!h){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:n}=t,{liveSyncDuration:r,liveSyncDurationCount:a,lowLatencyMode:o}=e,l=this.hls.userConfig;let d=o&&s||i;(this._targetLatencyUpdated||l.liveSyncDuration||l.liveSyncDurationCount||0===d)&&(d=void 0!==r?r:a*n);const h=n;return d+Math.min(this.stallCount*e.liveSyncOnStallIncrease,h)}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,n=t-e-this.edgeStalled,r=s-i.totalduration,a=s-(this.hls.config.lowLatencyMode&&i.partTarget||i.targetduration);return Math.min(Math.max(r,n),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,n=this.media||e.event.appendInPlace&&(null==s||null==(i=s.interstitialsManager)?void 0:i.playerQueue.reduce((t,e)=>t||e.media,null));s&&n&&n.playbackRate>1&&n.playbackRate<=s.config.maxLiveSyncPlaybackRate&&this.changeMediaPlaybackRate(n,1)}onError(t,e){var i;e.details===r.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:Cd,enableWebVTT:!0,enableIMSC1:!0,enableCEA708Captions:!0,captionsTextTrack1Label:"English",captionsTextTrack1LanguageCode:"en",captionsTextTrack2Label:"Spanish",captionsTextTrack2LanguageCode:"es",captionsTextTrack3Label:"Unknown CC",captionsTextTrack3LanguageCode:"",captionsTextTrack4Label:"Unknown CC",captionsTextTrack4LanguageCode:"",renderTextTracksNatively:!0}),{},{subtitleStreamController:class extends vn{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=an,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:n}=e;if(!n)return;const r=this.tracksBuffered[this.currentTrackId];if(!r)return;let a;const o=(s||i).start;for(let t=0;t<r.length;t++)if(o>=r[t].start&&o<=r[t].end){a=r[t];break}const l=o+(s||i).duration;if(a?a.end=l:(a={start:o,end:l},r.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===r.FRAG_GAP&&this.fragmentTracker.addAsGap(i),this.fragCurrent&&this.fragCurrent.abortRequests(),this.state!==rn&&(this.state=an))}onSubtitleTracksUpdated(t,{subtitleTracks:e}){this.levels&&Hr(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!==rn&&this.setInterval(500)):this.mediaBuffer=null}onSubtitleTrackLoaded(t,e){var i;const{currentTrackId:s,levels:n}=this,{details:r,id:o}=e;if(!n)return void this.warn(`Subtitle tracks were reset while loading level ${o}`);const l=n[o];if(o>=n.length||!l)return;this.log(`Subtitle track ${o} loaded [${r.startSN},${r.endSN}]${r.lastPartSn?`[part-${r.lastPartSn}-${r.lastPartIndex}]`:""},duration:${r.totalduration}`),this.mediaBuffer=this.mediaBufferTimeRanges;const d=this.mainDetails;let h=0;if(r.live||null!=(i=l.details)&&i.live){if(r.deltaUpdateFailed)return;if(!d)return void(this.startFragRequested=!1);var c;if(l.details)h=this.alignPlaylists(r,l.details,null==(c=this.levelLastLoaded)?void 0:c.details);r.alignedSliding||(tn(d,r,this),h=r.fragmentStart)}l.details=r,this.levelLastLoaded=l,d&&!this.startFragRequested&&this.setStartPosition(d,h),o===s&&(this.hls.trigger(a.SUBTITLE_TRACK_UPDATED,{details:r,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:n.MEDIA_ERROR,details:r.FRAG_DECRYPT_ERROR,fatal:!1,error:t,reason:t.message,frag:e,part:i}),i||(this.warn(`${t.name}: ${t.message}`),this.state=an)})}doTick(){if(this.state===an&&this.levels){var t;if(!this.media&&!this.primaryPrefetch&&(this.startFragRequested||!this.config.startFragPrefetch))return;const{currentTrackId:i,levels:s}=this,n=s[i],r=null==n?void 0:n.details;if(!r||this.waitForLive(n)||this.waitForCdnTuneIn(r))return void(this.startFragRequested=!1);const{config:a}=this,o=this.playhead,l=$i.bufferedInfo(this.tracksBuffered[this.currentTrackId]||[],o,a.maxBufferHole),{end:d,len:h}=l;if(h>Math.max(this.hls.maxBufferLength+r.levelTargetDuration,(null==(t=this.hls.mainForwardBufferInfo)?void 0:t.len)||0)||h&&!this.buffering)return;let c=this.getNextFragment(d,r);if(!c)return;if(y(c)){var e;const t=c.sn-r.startSN,i=r.fragments[t-1];c.cc!==(null==i?void 0:i.cc)||null!=(e=r.partList)&&e.length||this.fragmentTracker.getState(i)!==mi||(c=i)}this.loadFragment(c,n,d)}}loadFragment(t,e,i){const s=this.fragmentTracker.getState(t);s!==mi&&s!==yi||super.loadFragment(t,e,i)}get mediaBufferTimeRanges(){return new dd(this.tracksBuffered[this.currentTrackId]||[])}},subtitleTrackController:class extends Vr{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 n;t>-1&&(this._subtitleDisplay="showing"===(null==(n=this.tracksInGroup[t].trackNode)?void 0:n.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:n}=e,r=this.tracksInGroup[i];if(!r||r.groupId!==s)return void this.warn(`Subtitle track with id:${i} and group:${s} not found in active group ${null==r?void 0:r.groupId}`);const a=r.details;r.details=e.details,this.log(`Subtitle track ${i} "${r.name}" lang:${r.lang} group:${s} loaded [${n.startSN}-${n.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 n=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(!n&&e){this.selectDefaultTrack=!1;const i=Ke(e,t);if(i>-1)n=t[i];else{const t=Ke(e,this.tracks);n=this.tracks[t]}}let s=this.findTrackId(n);-1===s&&n&&(s=this.findTrackId(null));const r={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,r),this.setSubtitleTrack(s),this.createTracksInGroup()}}findTrackId(t){const e=this.tracksInGroup,i=this.selectDefaultTrack;for(let s=0;s<e.length;s++){const n=e[s];if((!i||n.default)&&(i||t)&&(!t||Ve(n,t)))return s}if(t){for(let i=0;i<e.length;i++){const s=e[i];if(Yr(t.attrs,s.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return i}for(let i=0;i<e.length;i++){const s=e[i];if(Yr(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&&Ve(t,i))return i;const s=Ke(t,this.tracksInGroup);if(s>-1){const t=this.tracksInGroup[s];return this.setSubtitleTrack(s,!0),t}if(i)return null;{const i=Ke(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,n=this.getUrlWithDirectives(t.url,e),r=t.details,o=null==r?void 0:r.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&&r.live?" age "+o.toFixed(1)+(r.type&&" "+r.type||""):""} ${n}`),this.hls.trigger(a.SUBTITLE_TRACK_LOADING,{url:n,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 n=this.currentTrack,r=s[t]||null;if(this.trackId=t,this.currentTrack=r,i&&this.toggleTrackModes(),!r)return void(n&&this.hls.trigger(a.SUBTITLE_TRACK_SWITCH,{id:t}));const o=!!r.details&&!r.details.live;if(r===n&&o)return;this.log(`Switching to subtitle-track ${t}`+(r?` "${r.name}" lang:${r.lang} group:${r.groupId}`:""));const{id:l,groupId:d="",name:h,type:c,url:u}=r;this.hls.trigger(a.SUBTITLE_TRACK_SWITCH,{id:l,groupId:d,name:h,type:c,url:u});const f=this.switchParams(r.url,null==n?void 0:n.details,r.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 Dd(this,"textTrack1"),e=new Dd(this,"textTrack2"),i=new Dd(this,"textTrack3"),s=new Dd(this,"textTrack4");this.cea608Parser1=new _d(1,t,e),this.cea608Parser2=new _d(3,i,s)}addCues(t,e,i,s,n){let r=!1;for(let t=n.length;t--;){const s=n[t],a=xd(s[0],s[1],e,i);if(a>=0&&(s[0]=Math.min(s[0],e),s[1]=Math.max(s[1],i),r=!0,a/(i-e)>.5))return}if(r||n.push([e,i]),this.config.renderTextTracksNatively){const n=this.cueCache[t];if(n){const t=this.Cues.newCue(null,e,i,s);t.length&&n.push.apply(n,t)}else{const n=this.captionsTracks[t].track;this.Cues.newCue(n,e,i,s)}}else{var o;const n=this.Cues.newCue(null,e,i,s),r=null==(o=this.captionsProperties[t])?void 0:o.media;this.hls.trigger(a.CUES_PARSED,{type:"captions",cues:n,track:t,closedCaptions:r})}}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:n}=this,{label:r,languageCode:a}=e[t];n&&(s[t]=[],i[t]=Ll(n,"captions",r,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&&!Hr(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:n,lastSn:r}=this,{cc:a,sn:o}=e.frag,l=null!=(i=null==(s=e.part)?void 0:s.index)?i:-1;t&&n&&(o!==r+1||o===r&&l!==this.lastPartIndex+1||a!==this.lastCc)&&(t.reset(),n.reset()),this.lastCc=a,this.lastSn=o,this.lastPartIndex=l}}onFragLoaded(t,e){const{frag:i,payload:s}=e;var n;if(i.level<this.tracks.length&&i.type===f.SUBTITLE)if(s.byteLength||null!=(n=i.initSegment)&&null!=(n=n.data)&&n.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,n=this.hls;vl(i,this.initPTS[e.cc],t=>{this._appendCues(t,e.level),n.trigger(a.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:e,part:s})},t=>{n.logger.log(`Cannot parse IMSC1 (sn: ${e.sn} @${e.start}): ${t}`),n.trigger(a.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:e,part:s,error:t})})}_parseVTTs(t){var e;const{frag:i,payload:s}=t,n="part"in t?t.part:null,{initPTS:r,unparsedVttFrags:o}=this,l=r.length-1;if(!r[i.cc]&&-1===l)return void o.push(t);const d=this.hls,h=null==(e=i.initSegment)?void 0:e.data;ul(h?Vt(h,new Uint8Array(s)).buffer:s,this.initPTS[i.cc],this.vttCCs,i.cc,(n&&!h?n:i).start,t=>{this._appendCues(t,i.level),d.trigger(a.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:i,part:n})},e=>{const s=e.message.startsWith("Missing initPTS");d.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),d.trigger(a.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:i,part:n,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 n=s.default?"default":"subtitles"+e;i.trigger(a.CUES_PARSED,{type:"subtitles",cues:t,track:n,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 n=null==(s=t[i])?void 0:s.track;if(n){const t=e[i];for(let e=0;e<t.length;e++)Rl(n,t[e])}delete e[i]})}}}onBufferFlushing(t,e){const{startOffset:i,endOffset:s,endOffsetSubtitles:n,type:r}=e,{media:a}=this;if(a&&!(a.currentTime<s)){if(!r||"video"===r){const{captionsTracks:t,cueCache:e}=this;Object.keys(t).forEach(e=>_l(t[e].track,i,s)),Object.keys(e).forEach(t=>{const n=e[t];for(let t=n.length;t--;){const e=n[t];e.startTime>=i&&e.endTime<=s&&n.splice(t,1)}})}this.config.renderTextTracksNatively&&0===i&&void 0!==n&&this.tracks.forEach(t=>{var e;const s=null==(e=t.trackNode)?void 0:e.track;s&&_l(s,i,n)})}}extractCea608Data(t){const e=[[],[]],i=31&t[0];let s=2;for(let n=0;n<i;n++){const i=t[s++],n=127&t[s++],r=127&t[s++];if(0===n&&0===r)continue;if(!!(4&i)){const t=3&i;0!==t&&1!==t||(e[t].push(n),e[t].push(r))}}return e}},audioStreamController:class extends vn{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:n,timescale:r,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: ${n/r} (${n}/${r}) trackId: ${a}`),this.mainAnchor=i,this.state===pn){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===an&&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 n=(s||t).cc,r=ei(this.getLevelDetails(),n,this.getLoadPosition());r&&(this.log(`Syncing with main frag at ${r.start} cc ${r.cc}`),this.startFragRequested=!1,this.nextLoadPosition=r.start,this.resetLoadingState(),this.state===an&&this.doTickIdle())}startLoad(t,e){if(!this.levels)return this.startPosition=t,void(this.state=rn);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=an,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 an:this.doTickIdle();break;case hn:{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=pn}break}case dn:this.checkRetryDate();break;case pn:{const t=this.waitingData;if(t){const{frag:e,part:i,cache:s,complete:n}=t,r=this.mainAnchor;if(void 0!==this.initPTS[e.cc]){this.waitingData=null,this.state=ln;const t={frag:e,part:i,payload:s.flush().buffer,networkDetails:null};this._handleFragmentLoadProgress(t),n&&super._handleFragmentLoadComplete(t)}else r&&r.cc!==t.frag.cc&&this.syncWithAnchor(r,t.frag)}else this.state=an}}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:n}=this,r=e.config;if(!this.buffering||!s&&!this.primaryPrefetch&&(this.startFragRequested||!r.startFragPrefetch)||null==i||!i[n])return;const o=i[n],l=o.details;if(!l||this.waitForLive(o)||this.waitForCdnTuneIn(l))return this.state=hn,void(this.startFragRequested=!1);const d=this.getBufferOutput();this.bufferFlushed&&d&&(this.bufferFlushed=!1,this.afterBufferFlushed(d,g));const h=this.getFwdBufferInfo();if(null===h)return;if(!this.switchingTrack&&this._streamEnded(h,l))return e.trigger(a.BUFFER_EOS,{type:"audio"}),void(this.state=fn);const c=h.len,u=e.maxBufferLength,p=l.fragments,m=p[0].start,v=this.getLoadPosition(),E=this.flushing||this.switchingTrack&&!this.switchingTrack.flushImmediate?v:h.end;if(this.switchingTrack&&s){const t=v;l.PTSKnown&&t<m&&t>=this.timelineOffset&&(h.end>m||h.nextStart)&&(this.log(`Alt audio track ahead of main track, seek to start of alt audio track ${t} -> ${m} + 0.05`),s.currentTime=m+.05)}if(c>=u&&!this.switchingTrack&&E<p[p.length-1].start)return;let T=this.getNextFragment(E,l);if(T&&this.isLoopLoading(T,E)&&(T=this.getNextFragmentLoopLoading(T,l,h,f.MAIN,u)),!T)return void(this.bufferFlushed=!0);if(this.exceedsMaxBuffer(h,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!==rn&&(this.setInterval(100),this.state=an,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:n,id:r,groupId:o,track:l}=e;if(!s)return void this.warn(`Audio tracks reset while loading track ${r} "${l.name}" of "${o}"`);const d=this.mainDetails;if(!d||n.endCC>d.endCC||d.expired)return this.cachedTrackLoadedData=e,void(this.state!==rn&&(this.state=hn));this.cachedTrackLoadedData=null,this.log(`Audio track ${r} "${l.name}" of "${o}" loaded [${n.startSN},${n.endSN}]${n.lastPartSn?`[part-${n.lastPartSn}-${n.lastPartIndex}]`:""},duration:${n.totalduration}`);const h=s[r];let c=0;if(n.live||null!=(i=h.details)&&i.live){if(this.checkLiveUpdate(n),n.deltaUpdateFailed)return;var u;if(h.details)c=this.alignPlaylists(n,h.details,null==(u=this.levelLastLoaded)?void 0:u.details);n.alignedSliding||(tn(d,n,this),c=n.fragmentStart)}h.details=n,this.levelLastLoaded=h,this.startFragRequested||this.setStartPosition(d,c),this.hls.trigger(a.AUDIO_TRACK_UPDATED,{details:n,id:r,groupId:e.groupId}),this.state!==hn||this.waitForCdnTuneIn(n)||(this.state=an),this.tick()}_handleFragmentLoadProgress(t){var e;const i=t.frag,{part:s,payload:n}=t,{config:r,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 d=l.details;if(!d)return this.warn("Audio track details undefined on fragment load progress"),void this.removeUnbufferedFrags(i.start);const h=r.defaultAudioCodec||l.audioCodec||"mp4a.40.2";let c=this.transmuxer;c||(c=this.transmuxer=new Kr(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,r=-1!==e,a=new Ni(i.level,i.sn,i.stats.chunkCount,n.byteLength,e,r,i.duration);c.push(n,g,h,"",i,s,d.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 [${d.startSN} ,${d.endSN}],track ${a}`);const{cache:t}=this.waitingData=this.waitingData||{frag:i,part:s,cache:new Tn,complete:!1};t.push(new Uint8Array(n)),this.state!==rn&&(this.state=pn)}}_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===an&&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=gn;else switch(e.details){case r.FRAG_GAP:case r.FRAG_PARSING_ERROR:case r.FRAG_DECRYPT_ERROR:case r.FRAG_LOAD_ERROR:case r.FRAG_LOAD_TIMEOUT:case r.KEY_LOAD_ERROR:case r.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(f.AUDIO,e);break;case r.AUDIO_TRACK_LOAD_ERROR:case r.AUDIO_TRACK_LOAD_TIMEOUT:case r.LEVEL_PARSING_ERROR:e.levelRetry||this.state!==hn||(null==(i=e.context)?void 0:i.type)!==u.AUDIO_TRACK||(this.state=an);break;case r.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 r.BUFFER_ADD_CODEC_ERROR:case r.BUFFER_APPEND_ERROR:if("audio"!==e.parent)return;this.reduceLengthAndFlushBuffer(e)||this.resetLoadingState();break;case r.BUFFER_FULL_ERROR:if("audio"!==e.parent)return;this.reduceLengthAndFlushBuffer(e)&&(this.bufferedTrack=null,super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"));break;case r.INTERNAL_EXCEPTION:this.recoverWorkerError(e)}}onBufferFlushing(t,{type:e}){e!==p&&(this.flushing=!0)}onBufferFlushed(t,{type:e}){if(e!==p){this.flushing=!1,this.bufferFlushed=!0,this.state===fn&&(this.state=an);const t=this.getBufferOutput();t&&(this.afterBufferFlushed(t,e),this.tick())}}_handleTransmuxComplete(t){var e;const i="audio",{hls:s}=this,{remuxResult:n,chunkMeta:r}=t,o=this.getCurrentContext(r);if(!o)return void this.resetWhenMissingContext(r);const{frag:l,part:d,level:h}=o,{details:c}=h,{audio:u,text:p,id3:m,initSegment:v}=n;if(this.fragContextChanged(l)||!c)return this.fragmentTracker.removeFragment(l),void(null!=v&&v.tracks&&this.resetTransmuxer());if(this.state=cn,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(h,v.tracks,t,r),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;d&&(d.elementaryStreams[g]={startPTS:t,endPTS:e,startDTS:i,endDTS:s}),l.setElementaryStreamInfo(g,t,e,i,s),this.bufferFragmentData(u,l,d,r)}if(null!=m&&null!=(e=m.samples)&&e.length){const t=I({id:i,frag:l,details:c},m);s.trigger(a.FRAG_PARSING_METADATA,t)}if(p){const t=I({id:i,frag:l,details:c},p);s.trigger(a.FRAG_PARSING_USERDATA,t)}}_bufferInitSegment(t,e,i,s){if(this.state!==cn)return;if(e.video&&delete e.video,e.audiovideo&&delete e.audiovideo,!e.audio)return;const n=e.audio;n.id=f.AUDIO;const r=t.audioCodec;this.log(`Init audio buffer, container:${n.container}, codecs[level/parsed]=[${r}/${n.codec}]`),1===(null==r?void 0:r.split(",").length)&&(n.levelCodec=r),this.hls.trigger(a.BUFFER_CODECS,e);const o=n.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 n;if(this.switchingTrack||s===mi||s===yi)if(null!=(n=e.details)&&n.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=pn;const i=this.mainDetails;i&&i.fragmentStart!==e.details.fragmentStart&&tn(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:n,audioCodec:r,channels:a}=this.bufferedTrack;Ve({name:e,lang:i,assocLang:s,characteristics:n,audioCodec:r,channels:a},t,He)||(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,_({},t))}get nextAudioTrack(){return this.nextTrackId}},audioTrackController:class extends Vr{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:n}=e,r=this.tracksInGroup[i];if(!r||r.groupId!==s)return void this.warn(`Audio track with id:${i} and group:${s} not found in active group ${null==r?void 0:r.groupId}`);const a=r.details;r.details=e.details,this.log(`Audio track ${i} "${r.name}" lang:${r.lang} group:${s} loaded [${n.startSN}-${n.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=Ke(e,t,He);if(i>-1)o=t[i];else{const t=Ke(e,this.tracks);o=this.tracks[t]}}let s=this.findTrackId(o);-1===s&&o&&(s=this.findTrackId(null));const d={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,d);const h=this.trackId;if(-1!==s&&-1===h)this.setAudioTrack(s);else if(t.length&&-1===h){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:n.MEDIA_ERROR,details:r.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&&Ve(t,s,He))return s;const n=Ke(t,this.tracksInGroup,He);if(n>-1){const e=this.tracksInGroup[n];return this.setAudioTrack(n,"flushImmediate"in t&&t.flushImmediate),e}if(s){let s=e.loadLevel;-1===s&&(s=e.firstAutoLevel);const n=function(t,e,i,s,n){const r=e[s],a=e.reduce((t,e,i)=>{const s=e.uri;return(t[s]||(t[s]=[])).push(i),t},{})[r.uri];a.length>1&&(s=Math.max.apply(Math,a));const o=r.videoRange,l=r.frameRate,d=r.codecSet.substring(0,4),h=Ye(e,s,e=>{if(e.videoRange!==o||e.frameRate!==l||e.codecSet.substring(0,4)!==d)return!1;const s=e.audioGroups,r=i.filter(t=>ze(t.groupId,s));return Ke(t,r,n)>-1});return h>-1?h:Ye(e,s,e=>{const s=e.audioGroups,r=i.filter(t=>ze(t.groupId,s));return Ke(t,r,n)>-1})}(t,e.levels,i,s,He);if(-1===n)return null;e.nextLoadLevel=n}if(t.channels||t.audioCodec){const e=Ke(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,n=i[t],r=n.details&&!n.details.live;if(t===this.trackId&&n===s&&r)return;if(this.log(`Switching to audio-track ${t} "${n.name}" lang:${n.lang} group:${n.groupId} channels:${n.channels}`),this.trackId=t,this.currentTrack=n,this.hls.trigger(a.AUDIO_TRACK_SWITCHING,_(_({},n),{},{flushImmediate:e})),r)return;const o=this.switchParams(n.url,null==s?void 0:s.details,n.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||Ve(t,s,He)))return i}if(t){const{name:i,lang:s,assocLang:n,characteristics:r,audioCodec:a,channels:o}=t;for(let t=0;t<e.length;t++){if(Ve({name:i,lang:s,assocLang:n,characteristics:r,audioCodec:a,channels:o},e[t],He))return t}for(let i=0;i<e.length;i++){const s=e[i];if(Yr(t.attrs,s.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return i}for(let i=0;i<e.length;i++){const s=e[i];if(Yr(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,n=this.getUrlWithDirectives(t.url,e),r=t.details,o=null==r?void 0:r.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&&r.live?" age "+o.toFixed(1)+(r.type&&" "+r.type||""):""} ${n}`),this.hls.trigger(a.AUDIO_TRACK_LOADING,{url:n,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:mo,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],d=this.getObjectType(a,l),h={d:1e3*(o||a).duration,ot:d};if(d===yo||d===vo||d===Eo||null==d&&("main"===a.type||"audio"===a.type)){var i;const t=l.bitrate/1e3;h.br=[t];const{cmcd:n}=this.config,r=null!=(i=null==n?void 0:n.rtpSafetyFactor)?i:5;if(h.rtp=100*Math.round(t*r/100),d===Eo||null==d&&"main"===a.type){const t=this.getTopBandwidth()/1e3;e(t)&&(h.tb=[t]);const i=this.getLowestBandwidth()/1e3;e(i)&&(h.lb=[i])}const o=this.getBufferLength(a);if(e(o)){var s;h.bl=[o];const t=(null==(s=this.media)?void 0:s.playbackRate)||1;h.dl=100*Math.round(o/t/100)}this.playheadLevel&&(h.pb=[this.playheadLevel.bitrate/1e3]);const c=this.hls.maxAutoLevel;if(c>=0){const t=this.hls.levels[c];t&&(h.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?h.nor=[(n=c.url,r={r:`${c.byteRange[0]}-${c.byteRange[1]}`},new ra(n,r))]:h.nor=[c.url]),this.apply(t,h)}catch(t){this.hls.logger.warn("Could not generate segment CMCD data.",t)}var n,r},this.recordFragmentResponse=(t,e,i)=>{var s;const{cmcd:n}=this.config,r=null==n||null==(s=n.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&&r)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 Bo({sid:i.sessionId||this.hls.sessionId,cid:i.contentId,version:s,transmissionMode:!0===i.useHeaders?xo:Do,enabledKeys:null!=(t=i.includeKeys)?t:[...s>=Da?po:Xa],eventTargets:(null!=(e=i.eventTargets)?e:[]).map(t=>{let{includeKeys:e}=t;return _(_({},k(t,qo)),{},{enabledKeys:null!=e?e:po})})},i.loader),this.reporter.update({sf:$o,sta:this.playerState}),i.reporterCallback){const t=this.reporter,e={updateCustomData:e=>{Ko(e)&&t.update(e)},recordCustomEvent:(e,i={})=>{Ko(i)&&t.recordEvent(Oa,_({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:wo),en(i,"waiting",this.onWaiting),en(i,"play",this.onPlay),en(i,"playing",this.onPlaying),en(i,"pause",this.onPause),en(i,"seeking",this.onSeeking),en(i,"seeked",this.onSeeked),en(i,"ratechange",this.onRateChange)}onMediaDetached(){const t=this.media;t&&(sn(t,"waiting",this.onWaiting),sn(t,"play",this.onPlay),sn(t,"playing",this.onPlaying),sn(t,"pause",this.onPause),sn(t,"seeking",this.onSeeking),sn(t,"seeked",this.onSeeked),sn(t,"ratechange",this.onRateChange),this.media=null)}onMediaEnded(t,e){this.setPlayerState(_o)}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(wo)}onError(t,e){e.fatal&&(this.setPlayerState(ko),this.reporter&&this.reporter.recordEvent(Ca,{ec:[e.details]}))}onLevelSwitching(t,e){var i;if(!this.reporter)return;const s={br:[e.bitrate/1e3]},n=null==(i=e.details)?void 0:i.fragments[0];n&&(s.ot=this.getObjectType(n,e)),this.reporter.recordEvent(Pa,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: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 n=this.reporter.createRequestReport({url:t.url,headers:t.headers},e);t.url=n.url,t.headers=n.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,n=null==(e=this.hls.levels[s.level])||null==(e=e.details)?void 0:e.partList;if(n){const{sn:t}=s;for(let e=n.length-1;e>=0;e--){const s=n[e];if(s.index===i&&s.fragment.sn===t)return n[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,n=s>-1?s+1:i.levels.length;return i.levels.slice(0,n).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,n){e(t);const{onSuccess:r}=n;this.loader.load(t,s,_(_({},n),{},{onSuccess:(e,s,n,a)=>{r(e,s,n,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&li){const t=this.levels;let s=this._pathwayPriority,n=this.pathwayId;if(e.context){const{groupId:i,pathwayId:s,type:r}=e.context;i&&t?n=this.getPathwayForGroupId(i,r,n):s&&(n=s)}n in this.penalizedPathways||(this.penalizedPathways[n]=performance.now()),!s&&t&&(s=this.pathways()),s&&s.length>1&&(this.updatePathwayPriority(s),i.resolved=this.pathwayId!==n,i.resolved||e.details===r.BUFFER_APPEND_ERROR&&!e.fatal||this.warn(`Could not resolve ${e.details} ("${e.error.message}") with content-steering for Pathway: ${n} 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 n=t[s];if(n in i)continue;if(n===this.pathwayId)return;const r=this.hls.nextLoadLevel,o=this.hls.levels[r];if(e=this.getLevelsForPathway(n),e.length>0){this.log(`Setting Pathway to "${n}"`),this.pathwayId=n,Ws(e),this.hls.trigger(a.LEVELS_UPDATED,{levels:e});const t=this.hls.levels[r];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=r);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:n,"BASE-ID":r,"URI-REPLACEMENT":a}=t;if(e.some(t=>t.pathwayId===n))return;const o=this.getLevelsForPathway(r).map(t=>{const e=new Yi(t.attrs);e["PATHWAY-ID"]=n;const r=e.AUDIO&&`${e.AUDIO}_clone_${n}`,o=e.SUBTITLES&&`${e.SUBTITLES}_clone_${n}`;r&&(i[e.AUDIO]=r,e.AUDIO=r),o&&(s[e.SUBTITLES]=o,e.SUBTITLES=o);const l=Ho(t.uri,e["STABLE-VARIANT-ID"],"PER-VARIANT-URIS",a),d=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++)d.addGroupId("audio",`${t.audioGroups[e]}_clone_${n}`);if(t.subtitleGroups)for(let e=1;e<t.subtitleGroups.length;e++)d.addGroupId("text",`${t.subtitleGroups[e]}_clone_${n}`);return d});e.push(...o),Vo(this.audioTracks,i,a,n),Vo(this.subtitleTracks,s,a,n)})}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);we(s,"_HLS_pathway",this.pathwayId),we(s,"_HLS_throughput",""+t)}const n={type:u.STEERING_MANIFEST,responseType:"json",url:s.href},r=e.steeringManifestLoadPolicy.default,o=r.errorRetry||r.timeoutRetry||{},l={loadPolicy:r,timeout:r.maxLoadTimeMs,maxRetry:o.maxNumRetry||0,retryDelay:o.retryDelayMs||0,maxRetryDelay:o.maxRetryDelayMs||0},d={onSuccess:(t,e,i,n)=>{this.log(`Loaded steering manifest: "${s}"`);const r=t.data;if(1!==(null==r?void 0:r.VERSION))return void this.log(`Steering VERSION ${r.VERSION} not supported!`);this.updated=performance.now(),this.timeToLoad=r.TTL;const{"RELOAD-URI":o,"PATHWAY-CLONES":l,"PATHWAY-PRIORITY":d}=r;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 h={steeringManifest:r,url:s.toString()};this.hls.trigger(a.STEERING_MANIFEST_LOADED,h),d&&this.updatePathwayPriority(d)},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 n=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&&(n=1e3*parseFloat(e))}return void this.log(`Steering manifest ${e.url} rate limited`)}this.scheduleRefresh(this.uri||e.url,n)},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(n,l,d)}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,Vl||(i=e,Vl=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=Kl){if(t<0)return;const i=_(_({},Kl),e);this.loadingEnabled||this.startLoad(t),this.streamController.loadMediaAt(t,i)}}),Hl||(Hl=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(ql)}detachMedia(){}recoverMediaError(){}transferMedia(){return null}loadMediaAt(t){if(t<0)return null;this.loadingEnabled||this.startLoad(t),this.streamController.loadMediaAt(t)}}}(Vl)),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(Vl,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(Hl,i,t,"image-")}createInstance(t,e,i,s){const{hls:n}=this;if(!n)return null;const{url:r,userConfig:o,latestLevelDetails:l,loadLevelObj:d,loadLevel:h,bandwidthEstimate:c,sessionId:u}=n,{stats:f,variableList:g}=this;if(null==e||!e.length||!f||!r)return null;const p=`${s||""}iframe-player-${this.instanceCounter++}`,m=n.levels,v=d||m[h],y=Xe(v,o.videoPreference),E=(null==v?void 0:v.pathwayId)||".",T=new t(_(_({},o),{},{loggerId:p,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),r,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:r,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 n;const e=this.findItemIndex(s);let r=this.schedule.findItemIndexAtTime(t);if(-1===r&&(r=e+(i?-1:1),this.log(`seeked ${i?"back ":""}to position not covered by schedule ${t} (resolving from ${e} to ${r})`)),!this.isInterstitial(s)&&null!=(n=this.media)&&n.paused&&(this.shouldPlay=!1),!i&&r>e){const t=this.schedule.findJumpRestrictedIndex(e+1,r);if(t>e)return void this.setSchedulePosition(t)}return void this.setSchedulePosition(r)}const r=this.playingAsset;if(!r){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=r.timelineStart,o=r.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,r))},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,n=i.events||[],r=i.items||[],o=i.durations,l=t.map(t=>t.identifier),d=!(!n.length&&!l.length);(d||e)&&this.log(`INTERSTITIALS_UPDATED (${n.length}): ${n}\nSchedule: ${r.map(t=>rd(t))} pos: ${this.timelinePos}`),l.length&&this.log(`Removed events ${l}`);let h=null,c=null;s&&(h=this.updateItem(s,this.timelinePos),this.itemsMatch(s,h)?this.playingItem=h: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})`)}}}),d||e){if(this.hls.trigger(a.INTERSTITIALS_UPDATED,{events:n.slice(0),schedule:r.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(h,s),u&&c!==h&&this.trimInPlace(c,u),this.checkBuffer()}},this.hls=t,this.HlsPlayerClass=e,this.assetListLoader=new ad(t),this.schedule=new nd(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){sn(t,"play",this.onPlay),sn(t,"pause",this.onPause),sn(t,"seeking",this.onSeeking),sn(t,"timeupdate",this.onTimeupdate)}onMediaAttaching(t,e){const i=this.media=e.media;en(i,"seeking",this.onSeeking),en(i,"timeupdate",this.onTimeupdate),en(i,"play",this.onPlay),en(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,r,a,o)=>{if(e){let l=e[s].start;const d=e.event;if(d){if("playout"===s||d.timelineOccupancy!==Wl.Point){const t=i(r);(null==t?void 0:t.interstitial)===d&&(l+=t.assetItem.startOffset+t[o])}}else{l+=("bufferedPos"===a?n():t[a])-e.start}return l}return 0},n=()=>{const e=t.bufferedPos;return e===Number.MAX_VALUE?r("primary"):Math.max(e,0)},r=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,n)=>{var r,a;const o=t.effectivePlayingItem;if(null!=o&&null!=(r=o.event)&&r.restrictions.skip||!t.schedule)return;t.log(`seek to ${e} "${n}"`);const l=t.effectivePlayingItem,d=t.schedule.findItemIndexAtTime(e,n),h=null==(a=t.schedule.items)?void 0:a[d],c=t.getBufferingPlayer(),u=null==c?void 0:c.interstitial,f=null==u?void 0:u.appendInPlace,g=l&&t.itemsMatch(l,h);if(l&&(f||g)){const r=i(t.playingAsset),a=(null==r?void 0:r.media)||t.primaryMedia;if(a){const i="primary"===n?a.currentTime:s(l,n,t.playingAsset,"timelinePos","currentTime"),o=e-i,d=(f?i:a.currentTime)+o;if(d>=0&&(!r||f||d<=r.duration))return void(a.currentTime=d)}}if(h){let i=e;if("primary"!==n){const t=e-h[n].start;i=h.start+t}const s=!t.isInterstitial(h);if(t.isInterstitial(l)&&!l.event.appendInPlace||!s&&!h.event.appendInPlace){if(l){const r=t.findItemIndex(l);if(d>r){const e=t.schedule.findJumpRestrictedIndex(r+1,d);if(e>r)return void t.setSchedulePosition(e)}let a=0;if(s)t.timelinePos=i,t.checkBuffer();else{const t=h.event.assetList,i=e-(h[n]||h).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(d,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(),n=t.bufferingItem;var r;return n&&n===i&&(s(n,"playout",t.bufferingAsset,"bufferedPos","bufferedEnd")-n.playout.start||(null==(r=t.bufferingAsset)?void 0:r.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 n()},get currentTime(){const e=t.timelinePos;return e>0?e:0},set currentTime(t){a(t,"primary")},get duration(){return r("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 r("integrated")},get seekableStart(){return((e,i)=>{var s;if(0!==e&&"primary"!==i&&null!=(s=t.schedule)&&s.length){var n;const s=t.schedule.findItemIndexAtTime(e),r=null==(n=t.schedule.items)?void 0:n[s];if(r)return e+(r[i].start-r.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 n=this.media;!n&&null!=(t=this.bufferingItem)&&null!=(t=t.event)&&t.appendInPlace&&(n=this.primaryMedia);const r=null==(i=n)?void 0:i.currentTime;return void 0!==r&&e(r)?r: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 n=null;const r=this.hls,a=t!==r,o=a&&t.interstitial.appendInPlace,l=null==(i=this.detachedData)?void 0:i.mediaSource;let d;if(r.media)o&&(n=r.transferMedia(),this.detachedData=n),d="Primary";else{const t=this.getBufferingPlayer();t?(n=t.transferMedia(),this.detachedData=n,d=`${t}`):d=l?"detached MediaSource":"detached media"}if(!n)if(l)n=this.detachedData,this.log(`using detachedData: MediaSource ${Ue(n)}`);else if(!this.detachedData||r.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 h=n&&"mediaSource"in n&&"closed"!==(null==(s=n.mediaSource)?void 0:s.readyState);if(this.log(`${h?"transfering MediaSource":"attaching media"} to ${a?t:"Primary"} from ${d} (media.currentTime: ${e.currentTime})`),!h&&!a)return void t.attachMedia(e);const c=h&&n?_({},n):{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(!h&&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,n=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(ld("checkStart (preroll)",s));const i=t.findEventIndex(e[0].identifier);this.setSchedulePosition(i)}else if(s>=0||!this.primaryLive){this.log(ld("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(n&&!this.playingItem){this.log(ld("checkStart (playing item)",n.start));const e=t.findItemIndex(n);this.setSchedulePosition(e)}}advanceAssetBuffering(t,e){const i=t.event,s=i.findAssetIndex(e),n=td(i,s);if(i.isAssetPastPlayoutLimit(n)){if(this.schedule){var r;const e=this.getNextItemIndex(t,!0),i=null==(r=this.schedule.items)?void 0:r[e];i&&this.bufferedToItem(i)}}else this.bufferedToEvent(t,n)}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=td(t,i);if(t.isAssetPastPlayoutLimit(s)){if(this.schedule){const i=this.schedule.items;if(i){const s=i[e],n=s.event?this.getNextItemIndex(s):e+1;if(n>=i.length)return void this.setSchedulePosition(-1);const r=t.resumeTime;this.timelinePos<r&&(this.log(ld("advanceAfterAssetEnded",r)),this.timelinePos=r,t.appendInPlace&&!i[n].event&&this.hls.startLoad(r+.01),this.checkBuffer(this.bufferedPos<r)),this.setSchedulePosition(n)}}}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,n=i.getEvent(s);if(n){const e=i.findEventIndex(s),r=i.findAssetIndex(n,t);this.advanceAfterAssetEnded(n,e,r-1)}}setSchedulePosition(t,e){var i;const s=null==(i=this.schedule)?void 0:i.items;if(!s||this.playbackDisabled)return;const n=t>=0?s[t]:null;this.log(`setSchedulePosition ${t}, ${e} (${n?rd(n):n}) pos: ${this.timelinePos}`);const r=this.waitingItem||this.playingItem,o=this.playingLastItem;if(this.isInterstitial(r)){const i=r.event,c=this.playingAsset,u=null==c?void 0:c.identifier,f=u?this.getAssetPlayer(u):null;if(f&&u&&(!this.eventItemsMatch(r,n)||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} ${ed(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}),r!==this.playingItem)return void(this.itemsMatch(r,this.playingItem)&&!this.playingAsset&&this.advanceAfterAssetEnded(i,this.findItemIndex(this.playingItem),e));this.retreiveMediaSource(u,n),!f.media||null!=(l=this.detachedData)&&l.mediaSource||f.detachMedia()}if(!this.eventItemsMatch(r,n)&&(this.endedItem=r,this.playingItem=this.waitingItem=null,this.log(`INTERSTITIAL_ENDED ${i} ${rd(r)}`),i.hasPlayed=!0,this.hls.trigger(a.INTERSTITIAL_ENDED,{event:i,schedule:s.slice(0),scheduleIndex:t}),i.cue.once&&this.hls)){var d;this.updateSchedule();const t=null==(d=this.schedule)?void 0:d.items;if(n&&t){const a=this.findItemIndex(n),l=this.livePrerollResumption(i);if(void 0!==l){let e=l;const n=this.getNextItemIndex(r);if(!this.isInterstitial(s[n])){var h;const t=null==(h=this.primaryDetails)?void 0:h.fragments;if(i.snapOptions.in&&t){const i=Ze(null,t,l);i&&(e=Math.min(Math.max(s[n].start,Ql(e,i)),s[n].end))}}if(this.log(ld("live join (preroll)",e)),this.timelinePos=e,n!==a&&(n||0===n))return void this.advanceSchedule(n,t,void 0,r,o)}this.advanceSchedule(a,t,e,r,o)}return}}this.advanceSchedule(t,s,e,r,o)}advanceSchedule(t,e,i,s,n){const r=this.schedule;if(!r)return;const o=e[t]||null,l=this.primaryMedia,d=this.playerQueue;if(d.length&&d.forEach(e=>{const i=e.interstitial,s=r.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 n=o.event;if(void 0===i){const e=td(n,(i=n.cue.pre?0:r.findAssetIndex(n,this.timelinePos))-1);if(n.isAssetPastPlayoutLimit(e)||n.appendInPlace&&this.timelinePos===o.end)return void this.advanceAfterAssetEnded(n,t,i);i=e}const d=this.waitingItem;this.assetsBuffered(o,l)||this.setBufferingItem(o);let h=this.preloadAssets(n,i);if(this.eventItemsMatch(o,d||s)||(this.waitingItem=o,this.log(`INTERSTITIAL_STARTED ${rd(o)} ${n.appendInPlace?"append in place":""}`),n.hasPlayed=!1,this.hls.trigger(a.INTERSTITIAL_STARTED,{event:n,schedule:e.slice(0),scheduleIndex:t})),!n.assetListLoaded)return void this.log(`Waiting for ASSET-LIST to complete loading ${n}`);if(n.assetListLoader&&(n.assetListLoader.destroy(),n.assetListLoader=void 0),!l)return void this.log(`Waiting for attachMedia to start Interstitial ${n}`);this.waitingItem=this.endedItem=null,this.playingItem=o;const c=n.assetList[i];if(!c)return void this.advanceAfterAssetEnded(n,t,i||0);if(h||(h=this.getAssetPlayer(c.identifier)),null===h||h.destroyed){const t=n.assetList.length;this.warn(`asset ${i+1}/${t} player destroyed ${n}`),h=this.createAssetPlayer(n,c,i),h.loadSource()}if(!this.eventItemsMatch(o,this.bufferingItem)&&n.appendInPlace&&this.isAssetBuffered(c))return;this.startAssetPlayer(h,i,e,t,l),this.shouldPlay&&od(h.media)}else o?(this.resumePrimary(o,t,s),this.shouldPlay&&od(this.hls.media)):n&&this.isInterstitial(s)&&(this.endedItem=null,this.playingItem=s,s.event.appendInPlace||this.attachPrimary(r.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,n;this.playingItem=t,this.playingAsset=this.endedAsset=null,this.waitingItem=null,this.bufferedToItem(t),this.endedItem=null,this.log(`resuming ${rd(t)}`);let r=this.timelinePos;if(null!=(s=this.detachedData)&&s.mediaSource?this.primaryLive&&this.startLoadingPrimaryAt(r):((r<t.start||r>=t.end||r<this.seekableStart)&&(r=this.getPrimaryResumption(t,e),this.log(ld("resumePrimary",r)),this.timelinePos=r),this.attachPrimary(r,t)),!i)return;const o=null==(n=this.schedule)?void 0:n.items;o&&(this.log(`INTERSTITIALS_PRIMARY_RESUMED ${rd(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,n=null!=t&&t.event?this.livePrerollResumption(t.event,i):void 0;if(void 0!==n)return n;const r=this.primaryDetails;if(r){const{fragmentStart:t,edge:e}=r;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 $i.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 n=this.hls;n.media?this.checkBuffer():(this.transferMediaTo(n,s),i&&this.startLoadingPrimaryAt(t,i)),i||(this.log(ld("attachPrimary",t)),this.timelinePos=t,this.startLoadingPrimaryAt(t,i))}startLoadingPrimaryAt(t,e){const i=this.hls,{loadingEnabled:s,bufferingEnabled:n,startPosition:r}=i,a=i.hasEnoughToStart;if(this.log(`Start loading primary @${t} bufferedPos: ${this.bufferedPos} startPosition: ${r} skip seek: ${e} has enough ${a} loadingEnabled: ${s} bufferingEnabled: ${n}`),!e&&a||!s||Math.abs(r-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?rd(e):null}`),i.pauseBuffering(),void(this.bufferPastEdge=!0)}i.startLoad(t,e)}else n||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=_(_({},this.mediaSelection||this.altSelection),{},{main:i});this.mediaSelection=s;const n=this.hls.startPosition;this.schedule.parseInterstitialDateRanges(s,this.hls.config.interstitialAppendInPlace,-1===n?0:n);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?rd(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=_(_({},this.altSelection),{},{audio:i}));const n=_(_({},s),{},{audio:i});this.mediaSelection=n}onSubtitleTrackUpdated(t,e){const i=this.hls.subtitleTracks[e.id],s=this.mediaSelection;if(!s)return void(this.altSelection=_(_({},this.altSelection),{},{subtitles:i}));const n=_(_({},s),{},{subtitles:i});this.mediaSelection=n}onAudioTrackSwitching(t,e){const i=qe(e);this.playerQueue.forEach(({hls:t})=>t&&(t.setAudioOption(e)||t.setAudioOption(i)))}onSubtitleTrackSwitch(t,e){const i=qe(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=$i.bufferInfo(this.primaryMedia,i,0);if(s.end>i||(s.nextStart||0)>i){this.log(`trim buffered interstitial ${rd(t)} (was ${rd(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 n=(null==(e=this.hls)?void 0:e.liveSyncPosition)||0;null==(i=this.schedule)||i.updateSchedule(s,[],n,t)}checkBuffer(t){var e;const i=null==(e=this.schedule)?void 0:e.items;if(!i)return;const s=$i.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,n=this.bufferingItem;if(this.bufferedPos>t||!s)return;if(1===e.length&&this.itemsMatch(e[0],n))return void(this.bufferedPos=t);const r=this.playingItem,a=this.findItemIndex(r);let o=s.findItemIndexAtTime(t);if(this.bufferedPos<t){var l;const i=this.findItemIndex(n),s=Math.min(i+1,e.length-1),r=e[s];if((-1===o&&n&&t>=n.end||null!=(l=r.event)&&l.appendInPlace&&t+.01>=r.start)&&(o=s),this.isInterstitial(n)){const t=n.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(r);else{const e=this.primaryDetails;this.primaryLive&&e&&t>e.edge-e.targetduration&&r.start<e.edge+this.hls.config.interstitialLiveLookAhead&&this.isInterstitial(r)&&this.preloadAssets(r.event,0)}}else i&&r&&!this.itemsMatch(r,n)&&(o===a?this.bufferedToItem(r):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:n}=i;if(!s||!n)return e;const r=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 ${rd(t)}`+(e?` (${l.toFixed(2)} remaining)`:"")),!this.playbackDisabled)if(r){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:n.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,n=i.cue.once;if(s||!n){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,n=0===s&&!t.assetListLoader,r=t.cue.once;if(n){const n=t.timelineStart,r=this.playingItem,o=this.getBufferingPlayer();var a;if(t.appendInPlace)this.isInterstitial(r)||(null==r||null==(a=r.nextEvent)?void 0:a.identifier)!==t.identifier||this.flushFrontBuffer(n+.25);let l,d=0;if(o&&!o.interstitial.cue.pre||!this.primaryLive||(d=this.getLiveStartPos(),o&&(d+=o.remaining)),d&&!t.cue.pre&&!t.cue.post){const t=d-n;t>0&&(l=Math.round(1e3*t)/1e3)}if(this.log(`Load interstitial asset ${e+1}/${i?1:s} ${t}${d?` live-start: ${d} start-offset: ${l} (timeline-start: ${n})`:""}`),i)return this.createAsset(t,0,0,n,t.duration,i);const h=this.assetListLoader.loadAssetList(t,l);h&&(t.assetListLoader=h)}else if(!r&&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,n,r){const a={parentIdentifier:t.identifier,identifier:zl(t,r,e),duration:n,startOffset:i,timelineStart:s,uri:r};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),d=s.audioTracks[s.audioTrack],h=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=_(_({},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:d||o.audioPreference,subtitlePreference:h||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 p=new id(this.HlsPlayerClass,f,t,e);this.playerQueue.push(p),t.assetList[i]=e;let m=!0;const v=s=>{if(s.live){const e=new Error(`Interstitials MUST be VOD assets ${t}`),s={fatal:!0,type:n.OTHER_ERROR,details:r.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;(m||null===o||a>o)&&(m=!1,this.log(`Interstitial asset "${u}" duration change ${o} > ${a}`),e.duration=a,this.updateSchedule())};p.on(a.LEVEL_UPDATED,(t,{details:e})=>v(e)),p.on(a.LEVEL_PTS_UPDATED,(t,{details:e})=>v(e)),p.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)}};p.on(a.BUFFER_CODECS,y);p.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 p.once(a.MEDIA_ENDED,E(i)),p.once(a.PLAYOUT_LIMIT_REACHED,E(1/0)),p.on(a.ERROR,(e,s)=>{if(!this.schedule)return;const n=this.getAssetPlayer(u);if(s.details===r.BUFFER_STALLED_ERROR)return null!=n&&n.appendInPlace?void this.handleInPlaceStall(t):(this.onTimeupdate(),void this.checkBuffer(!0));s.details!==r.BUFFER_SEEK_OVER_HOLE&&this.handleAssetItemError(s,t,this.findEventIndex(t.identifier),i,`Asset player error ${s.error} ${t}`)}),p.on(a.DESTROYING,()=>{if(!this.getAssetPlayer(u)||!this.schedule)return;const e=new Error(`Asset player destroyed unexpectedly ${u}`),s={fatal:!0,type:n.OTHER_ERROR,details:r.INTERSTITIAL_ASSET_ITEM_ERROR,error:e};this.handleAssetItemError(s,t,this.findEventIndex(t.identifier),i,e.message)}),this.log(`INTERSTITIAL_ASSET_PLAYER_CREATED ${ed(e)}`),this.hls.trigger(a.INTERSTITIAL_ASSET_PLAYER_CREATED,{asset:e,assetListIndex:i,event:t,player:p}),p}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?rd(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,n){const{interstitial:r,assetItem:o,assetId:l}=t,d=r.assetList.length,h=this.playingAsset;this.endedAsset=null,this.playingAsset=o,(null==h?void 0:h.identifier)!==l&&(h&&(this.clearAssetPlayer(h.identifier,i[s]),delete h.error),this.log(`INTERSTITIAL_ASSET_STARTED ${e+1}/${d} ${ed(o)}`),this.hls.trigger(a.INTERSTITIAL_ASSET_STARTED,{asset:o,assetListIndex:e,event:r,schedule:i.slice(0),scheduleIndex:s,player:t})),this.bufferAssetPlayer(t,n)}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 d=s.appendInPlace;if(d&&!1===(null==l?void 0:l.interstitial.appendInPlace))return;const h=(null==l?void 0:l.tracks)||(null==(i=this.detachedData)?void 0:i.tracks)||this.requiredTracks;if(d&&a!==this.playingAsset){if(!t.tracks)return void this.log(`Waiting for track info before buffering ${t}`);if(h&&!W(h,t.tracks)){const e=new Error(`Asset ${ed(a)} SourceBuffer tracks ('${Object.keys(t.tracks)}') are not compatible with primary content tracks ('${Object.keys(h)}')`),i={fatal:!0,type:n.OTHER_ERROR,details:r.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,n=e.findAssetIndex(t,s),r=t.assetList[n];if(r){const a=this.getAssetPlayer(r.identifier);if(a){const o=a.currentTime||s-r.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,n)}}}}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,n){if(t.details===r.BUFFER_STALLED_ERROR)return;const o=e.assetList[s]||null;if(this.warn(`INTERSTITIAL_ASSET_ERROR ${o?ed(o):o} ${t.error}`),!this.schedule)return;const l=(null==o?void 0:o.identifier)||"",d=this.getAssetPlayerQueueIndex(l),h=this.playerQueue[d]||null,c=this.schedule.items,u=I({},t,{fatal:!1,errorAction:pi(!0),asset:o,assetListIndex:s,event:e,schedule:c,scheduleIndex:i,player:h});if(this.hls.trigger(a.INTERSTITIAL_ASSET_ERROR,u),!t.fatal)return;const f=this.playingAsset,g=this.bufferingAsset,p=new Error(n);if(o&&(this.clearAssetPlayer(l,null),o.error=p),e.assetList.some(t=>!t.error))for(let t=s;t<e.assetList.length;t++)this.resetAssetPlayer(e.assetList[t].identifier);else e.error=p;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,n=this.seekableStart,r=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: ${rd(i)} startPosition: ${r} seekableStart: ${n} error: ${t.error}`),-1===a&&(a=r),a=Math.max(a,n);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 n=e.event,r=n.identifier,a=e.assetListResponse.ASSETS;if(null==(i=this.schedule)||!i.hasEvent(r))return;const o=n.timelineStart,l=n.duration;let d=0;a.forEach((t,e)=>{const i=parseFloat(t.DURATION);this.createAsset(n,e,d,o+d,i,t.URI),d+=i}),n.duration=d,this.log(`Loaded asset-list with duration: ${d} (was: ${l}) ${n}`);const h=this.waitingItem,c=(null==h?void 0:h.event.identifier)===r;this.updateSchedule();const u=null==(s=this.bufferingItem)?void 0:s.event;if(c){const t=this.findEventIndex(r),e=this.getEventItem(r);if(e){if(!this.playingItem&&this.timelinePos>e.end){if(this.schedule.findItemIndexAtTime(this.timelinePos)!==t)return n.error=new Error(`Interstitial ${a.length?"no longer within playback range":"asset-list is empty"} ${this.timelinePos} ${n}`),this.log(n.error.message),this.updateSchedule(!0),void this.primaryFallback(n)}this.setBufferingItem(e)}this.setSchedulePosition(t)}else if((null==u?void 0:u.identifier)===r){const t=n.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 r.ASSET_LIST_PARSING_ERROR:case r.ASSET_LIST_LOAD_ERROR:case r.ASSET_LIST_LOAD_TIMEOUT:{const t=e.interstitial;t&&(this.updateSchedule(!0),this.primaryFallback(t));break}case r.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 jd(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=qd(t),n=["TimeOut","MaxRetry","RetryDelay","MaxRetryTimeout"];return["manifest","level","frag"].forEach(t=>{const r=`${"level"===t?"playlist":t}LoadPolicy`,a=void 0===e[r],o=[];n.forEach(i=>{const n=`${t}Loading${i}`,l=e[n];if(void 0!==l&&a){o.push(n);const t=s[r].default;switch(e[r]={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 "${r}": ${Ue(e[r])}`)}),_(_({},s),e)}function qd(t){return t&&"object"==typeof t?Array.isArray(t)?t.map(qd):Object.keys(t).reduce((e,i)=>(e[i]=qd(t[i]),e),{}):t}function Kd(t,e){const i=t.loader;if(i!==Fd&&i!==Ud)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=Fd,t.progressive=!0,t.enableSoftwareAES=!0,e.log("[config]: Progressive streaming enabled, using FetchLoader"))}}class Vd extends Vr{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=[],n={},r={};let a=!1,o=!1,l=!1,d=!1;e.levels.forEach(t=>{const e=t.attrs,h=Wd(t,i),{audioCodec:c,videoCodec:u,imageCodec:f,width:g,height:p}=t;if(!h)return void this.log(`Some or all CODECS not supported "${e.CODECS}"`);a||(a=!(!g||!p)),o||(o=!!u),l||(l=!!c),d||(d=!!f);const{CODECS:m,"FRAME-RATE":v,"HDCP-LEVEL":y,"PATHWAY-ID":E,RESOLUTION:T,"VIDEO-RANGE":S}=e,b=`${`${E||"."}-`}${t.bitrate}-${T}-${v}-${m}-${S}-${y}`;if(n[b])if(n[b].uri===t.url||t.attrs["PATHWAY-ID"])t.iframes||(n[b].addGroupId("audio",e.AUDIO),n[b].addGroupId("text",e.SUBTITLES));else{const e=r[b]+=1;t.attrs["PATHWAY-ID"]=new Array(e+1).join(".");const i=this.createLevel(t);n[b]=i,s.push(i)}else{const e=this.createLevel(t);n[b]=e,r[b]=1,s.push(e)}}),this.filterAndSortMediaOptions(s,e,a,o,l,d)}createLevel(t){const e=new Ne(t),i=t.supplemental;if(null!=i&&i.videoCodec&&!Yd(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 d;let h=[],c=[],u=t;const f=(null==(d=e.stats)?void 0:d.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))&&(!!(n=e)&&xe.indexOf(n)>-1);var n})),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:n.MEDIA_ERROR,details:r.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:e.url,error:s,reason:i})}}),void(f.end=performance.now());e.audioTracks&&(h=e.audioTracks.filter(t=>!t.audioCodec||Hd(t.audioCodec,g)),zd(h)),e.subtitles&&(c=e.subtitles,zd(c));const p=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 xe.indexOf(t.videoRange)-xe.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 m=p[0];if(this.steering&&(u=this.steering.filterParsedLevels(u),u.length!==p.length))for(let t=0;t<p.length;t++)if(p[t].pathwayId===u[0].pathwayId){m=p[t];break}this._levels=u;for(let t=0;t<u.length;t++)if(u[t]===m){var v;this._firstLevel=t;const e=m.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=>Wd(t,g));this._iframeVariants=y;const E=o&&!s,T=this.hls.config,S=!(!T.audioStreamController||!T.audioTrackController),b={levels:u,audioTracks:h,subtitleTracks:c,iframeVariants:y,sessionData:e.sessionData,sessionKeys:e.sessionKeys,firstLevel:this._firstLevel,stats:e.stats,audio:o,video:s,altAudio:S&&!E&&h.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:n.OTHER_ERROR,details:r.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],d=l.attrs["PATHWAY-ID"];if(this.currentLevelIndex=t,this.currentLevel=l,i===t&&s&&o===d)return;this.log(`Switching to level ${t} (${l.height?l.height+"p ":""}${l.videoRange?l.videoRange+" ":""}${l.codecSet?l.codecSet+" ":""}@${l.bitrate})${d?" with Pathway "+d:""} from level ${i}${o?" with Pathway "+o:""}`);const h={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,h);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:n}=e,r=e.levelInfo;var a;if(!r)return this.warn(`Invalid level index ${s}`),void(null!=(a=e.deliveryDirectives)&&a.skip&&(n.deltaUpdateFailed=!0));if(r===this.currentLevel||e.withoutMultiVariant){0===r.fragmentError&&(r.loadError=0);let t=r.details;t===e.details&&t.advanced&&(t=void 0),this.playlistLoaded(s,e,t)}else null!=(i=e.deliveryDirectives)&&i.skip&&(n.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,n=t.attrs["PATHWAY-ID"],r=t.details,o=null==r?void 0:r.age;this.log(`Loading level index ${s}${void 0!==(null==e?void 0:e.msn)?" at sn "+e.msn+" part "+e.part:""}${n?" Pathway "+n:""}${o&&r.live?" age "+o.toFixed(1)+(r.type&&" "+r.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(),n=s-this.lastABRSwitchTime,r=1e3*i;if(this.lastABRSwitchTime>-1&&n<r)return void this.warn(`Preventing ABR level switch: ${e} -> ${t} (${Math.round(n)}ms < ${r}ms / ${i}s)`);this.lastABRSwitchTime=s,this.log(`Allowing ABR level switch: ${e} -> ${t} (${Math.round(n)}ms >= ${r}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 Hd(t,e){return de(t,"audio",e)}function Yd(t,e){return de(t,"video",e)}function Wd(t,e){let{audioCodec:i,videoCodec:s}=t;i&&(t.audioCodec=i=me(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:n}=t;return!((null==n?void 0:n.length)||0||i&&!Hd(i,e)||s&&!Yd(s,e))}function zd(t){const e={};t.forEach(t=>{const i=t.groupId||"";t.id=e[i]=e[i]||0,e[i]++})}class Xd 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(Qd(t,r.KEY_LOAD_ERROR,e))}const n=t;switch(s.method){case"SAMPLE-AES":case"SAMPLE-AES-CENC":case"SAMPLE-AES-CTR":return"identity"===s.keyFormat?this.loadKeyHTTP(n):e?e.then(()=>this.loadKeyEME(n)):this.loadKeyEME(n);case"AES-128":case"AES-256":case"AES-256-CTR":return this.loadKeyHTTP(n);default:return Promise.reject(Qd(t,r.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 ${pt(i)} keyUri: ${s}`),Es.setKeyIdForUri(s,i);else{const t=Es.addKeyIdForUri(s);this.log(`Patching empty keyId with ${pt(t)} keyUri: ${s}`),i=t}t.decryptdata.keyId=i}}return this.emeController.loadKey(t).then(()=>({frag:t,keyInfo:{decryptdata:t.decryptdata}}))}return Promise.reject(Qd(t,r.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(Qd(t,r.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,_(_({},i),{},{frag:t})))}this.log(`Loading${e.keyId?" keyId: "+pt(e.keyId):""} URI: ${e.uri} from ${t.type} ${t.level}`);const n=this.config,a=new(0,n.loader)(n);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},d=n.keyLoadPolicy.default,h={loadPolicy:d,timeout:d.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},c={onSuccess:(t,i,n,a)=>{const{frag:o,keyInfo:l,url:d}=n;if(!o.decryptdata||l!==this.keyLoaderInfo[d])return s(Qd(o,r.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,n,a,o)=>{this.resetLoader(n),s(Qd(t,r.KEY_LOAD_ERROR,new Error(`HTTP Error ${e.code} loading key ${e.text}`),a,_({url:i,data:void 0},e)))},onTimeout:(e,i,n)=>{this.resetLoader(i),s(Qd(t,r.KEY_LOAD_TIMEOUT,new Error("key loading timed out"),n))},onAbort:(e,i,n)=>{this.resetLoader(i),s(Qd(t,r.INTERNAL_ABORTED,new Error("key loading aborted"),n))}};a.load(l,h,c)})}resetLoader(t){const{frag:e,keyInfo:i,url:s}=t,n=i.loader;e.keyLoader===n&&(e.keyLoader=i.loader=i.keyLoadPromise=null),delete this.keyLoaderInfo[s],n&&n.destroy()}}function Qd(t,e=r.KEY_LOAD_ERROR,i,s,a){return new Oi({type:n.NETWORK_ERROR,details:e,fatal:!1,frag:t,response:a,error:i,networkDetails:s||null})}function Zd(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 Jd(t,e){let i=t.url;return void 0!==i&&0!==i.indexOf("data:")||(i=e.url),i}class th{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,n=new(i||s)(e);return this.loaders[t.type]=n,n}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:n,url:r,deliveryDirectives:a,levelInfo:o}=e;this.load({id:i,level:s,pathwayId:n,responseType:"text",type:u.LEVEL,url:r,deliveryDirectives:a,levelOrTrack:o})}onAudioTrackLoading(t,e){const{id:i,groupId:s,url:n,deliveryDirectives:r,track:a}=e;this.load({id:i,groupId:s,level:null,responseType:"text",type:u.AUDIO_TRACK,url:n,deliveryDirectives:r,levelOrTrack:a})}onSubtitleTrackLoading(t,e){const{id:i,groupId:s,url:n,deliveryDirectives:r,track:a}=e;this.load({id:i,groupId:s,level:null,responseType:"text",type:u.SUBTITLE_TRACK,url:n,deliveryDirectives:r,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 n,r=this.getInternalLoader(t);if(r){const e=this.hls.logger,i=r.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}`),r.abort()}if(n=t.type===u.MANIFEST?s.manifestLoadPolicy.default:I({},s.playlistLoadPolicy.default,{timeoutRetry:null,errorRetry:null}),r=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);n=I({},n,{maxTimeToFirstByteMs:Math.min(e,n.maxTimeToFirstByteMs),maxLoadTimeMs:Math.min(e,n.maxTimeToFirstByteMs)})}}}const a=n.errorRetry||n.timeoutRetry||{},o={loadPolicy:n,timeout:n.maxLoadTimeMs,maxRetry:a.maxNumRetry||0,retryDelay:a.retryDelayMs||0,maxRetryDelay:a.maxRetryDelayMs||0},l={onSuccess:(t,e,i,s)=>{const n=this.getInternalLoader(i);this.resetInternalLoader(i.type);const r=t.data;e.parsing.start=performance.now(),Rs.isMediaPlaylist(r)||i.type!==u.MANIFEST?this.handleTrackOrLevelPlaylist(t,e,i,s||null,n):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)}};r.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 n=this.hls,r=t.data,o=Jd(t,i),l=Rs.parseMasterPlaylist(r,o);if(l.playlistParsingError)return e.parsing.end=performance.now(),void this.handleManifestParsingError(t,i,l.playlistParsingError,s,e);const{contentSteering:d,levels:h,iframeVariants:c,sessionData:u,sessionKeys:f,startTimeOffset:g,variableList:p}=l;this.variableList=p,h.forEach(t=>{const{unknownCodecs:e}=t;if(e){const{preferManagedMediaSource:i}=this.hls.config;let{audioCodec:s,videoCodec:n}=t;for(let r=e.length;r--;){const a=e[r];de(a,"audio",i)?(t.audioCodec=s=s?`${s},${a}`:a,oe.audio[s.substring(0,4)]=2,e.splice(r,1)):de(a,"video",i)&&(t.videoCodec=n=n?`${n},${a}`:a,oe.video[n.substring(0,4)]=2,e.splice(r,1))}}});const{AUDIO:m=[],SUBTITLES:v,"CLOSED-CAPTIONS":y}=Rs.parseMasterPlaylistMedia(r,o,l);if(m.length){m.some(t=>!t.url)||!h[0].audioCodec||h[0].attrs.AUDIO||(this.hls.logger.log("[playlist-loader]: audio codec signaled in quality level, but no embedded audio track signaled, create one"),m.unshift({type:"main",name:"main",groupId:"main",default:!1,autoselect:!1,forced:!1,id:-1,attrs:new Yi({}),bitrate:0,url:""}))}n.trigger(a.MANIFEST_LOADED,{levels:h,audioTracks:m,subtitles:v,iframeVariants:c,captions:y,contentSteering:d,url:o,stats:e,networkDetails:s,sessionData:u,sessionKeys:f,startTimeOffset:g,variableList:p})}handleTrackOrLevelPlaylist(t,i,s,n,r){const o=this.hls,{id:l,level:d,type:h}=s,c=Jd(t,s),f=e(d)?d:e(l)?l:0,g=Zd(s),p=Rs.parseLevelPlaylist(t.data,c,f,g,0,this.variableList);if(h===u.MANIFEST){const t={attrs:new Yi({}),bitrate:0,details:p,name:"",url:c};p.requestScheduled=i.loading.start+Ks(p,0),o.trigger(a.MANIFEST_LOADED,{levels:[t],audioTracks:[],iframeVariants:[],url:c,stats:i,networkDetails:n,sessionData:null,sessionKeys:null,contentSteering:null,startTimeOffset:null,variableList:null})}i.parsing.end=performance.now(),s.levelDetails=p,this.handlePlaylistLoaded(p,t,i,s,n,r)}handleManifestParsingError(t,e,i,s,o){this.hls.trigger(a.ERROR,{type:n.NETWORK_ERROR,details:r.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 d=new Error(l);this.hls.logger.warn(`[playlist-loader]: ${l}`);let h=r.UNKNOWN,c=!1;const f=this.getInternalLoader(t);switch(t.type){case u.MANIFEST:h=i?r.MANIFEST_LOAD_TIMEOUT:r.MANIFEST_LOAD_ERROR,c=!0;break;case u.LEVEL:h=i?r.LEVEL_LOAD_TIMEOUT:r.LEVEL_LOAD_ERROR,c=!1;break;case u.AUDIO_TRACK:h=i?r.AUDIO_TRACK_LOAD_TIMEOUT:r.AUDIO_TRACK_LOAD_ERROR,c=!1;break;case u.SUBTITLE_TRACK:h=i?r.SUBTITLE_TRACK_LOAD_TIMEOUT:r.SUBTITLE_LOAD_ERROR,c=!1}f&&this.resetInternalLoader(t.type);const g={type:n.NETWORK_ERROR,details:h,fatal:c,url:t.url,loader:f,context:t,error:d,networkDetails:e,stats:o};if(s){let i=t.url;e&&"url"in e&&(i=e.url),g.response=_({url:i,data:void 0},s)}this.hls.trigger(a.ERROR,g)}handlePlaylistLoaded(t,e,i,s,o,l){const d=this.hls,{type:h,level:c,levelOrTrack:g,id:p,groupId:m,deliveryDirectives:v}=s,y=Jd(e,s),E=Zd(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}`),!d.config.ignorePlaylistParsingErrors)return void d.trigger(a.ERROR,{type:n.NETWORK_ERROR,details:r.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 d.trigger(a.ERROR,{type:n.NETWORK_ERROR,details:r.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)),h){case u.MANIFEST:case u.LEVEL:if(T)if(g){if(g!==d.levels[T]){const t=d.levels.indexOf(g);t>-1&&(T=t)}}else T=0;d.trigger(a.LEVEL_LOADED,{details:t,levelInfo:g||d.levels[0],level:T||0,id:p||0,stats:i,networkDetails:o,deliveryDirectives:v,withoutMultiVariant:h===u.MANIFEST,context:s});break;case u.AUDIO_TRACK:d.trigger(a.AUDIO_TRACK_LOADED,{details:t,track:g,id:p||0,groupId:m||"",stats:i,networkDetails:o,deliveryDirectives:v,context:s});break;case u.SUBTITLE_TRACK:d.trigger(a.SUBTITLE_TRACK_LOADED,{details:t,track:g,id:p||0,groupId:m||"",stats:i,networkDetails:o,deliveryDirectives:v,context:s})}}}class eh{static get version(){return In}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 On}static get ErrorTypes(){return n}static get ErrorDetails(){return r}static get DefaultConfig(){return eh.defaultConfig?eh.defaultConfig:Gd}static set DefaultConfig(t){eh.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 Ln,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=q();if("object"==typeof console&&!0===t||"object"==typeof t){const n=["debug","log","info","warn","error"];n.forEach(e=>{s[e]=K(e,t,i)});try{s.log(`Debug logs enabled for "${e}" in hls.js version 1.7.3`)}catch(t){return q()}n.forEach(e=>{V[e]=K(e,t)})}else I(V,s);return s}(t.debug||!1,"Hls instance",t.loggerId||t.assetPlayerId),i=this.config=jd(eh.DefaultConfig,t,e);this.userConfig=t,i.progressive&&Kd(i,e);const{streamController:s,abrController:n,bufferController:r,capLevelController:o,errorController:l,fpsController:d,id3TrackController:h,iframeController:c,gapController:u}=i,f=new l(this),g=this.abrController=new n(this),p=new Ti(this),m=i.interstitialsController,v=m?this.interstitialsController=new m(this,eh):null,y=r?this.bufferController=new r(this,p):null,E=o?this.capLevelController=new o(this):null,T=d?new d(this):null,S=i.cmcdController,b=S?this.cmcdController=new S(this):null,A=new th(this),L=i.contentSteeringController,R=L?new L(this):null,_=this.levelController=new Vd(this,R),k=h?new h(this):void 0,w=new Xd(this.config,this.logger),D=this.streamController=new s(this,p,w),x=this.gapController=u?new u(this,p):void 0;E&&E.setStreamController(D);const P=[A,_,D];v&&P.splice(1,0,v),R&&P.splice(1,0,R),this.networkControllers=P;const C=[g];y&&C.push(y),x&&C.push(x),E&&C.push(E),T&&(T.setStreamController(D),C.push(T)),k&&C.push(k),C.push(p),this.audioTrackController=this.createController(i.audioTrackController,P);const M=i.audioStreamController;M&&P.push(this.audioStreamController=new M(this,p,w)),this.subtitleTrackController=this.createController(i.subtitleTrackController,P);const O=i.subtitleStreamController;O&&P.push(this.subtititleStreamController=new O(this,p,w)),this.createController(i.timelineController,C),w.emeController=this.emeController=this.createController(i.emeController,C),b&&C.push(b),this.latencyController=this.createController(i.latencyController,C),this.coreComponents=C,this.iframeController=c?new c(this,eh):void 0,P.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:n.OTHER_ERROR,details:r.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:n.OTHER_ERROR,details:r.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,n=this._url=h.buildAbsoluteURL(self.location.href,t,{alwaysNormalize:!0});this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.logger.log(`loadSource:${n}`),i&&s&&(s!==n||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!==rn}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 De.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,je(e),navigator.mediaCapabilities)}}function ih(t){const{baseUrl:e,apiKey:i,clientId:s,fetch:n,apiVersion:r}=t,a=n??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 n=function(t){let e=t.length;for(;e>0&&"/"===t[e-1];)e--;return t.slice(0,e)}(t),r=s.replace(/^\/+/,"");return`${n}/b2b/${e}/subscription/${encodeURIComponent(i)}${r.startsWith("/")?r:`/${r}`}`}(e,function(t){const e=t.toLowerCase();return"v1"===e||"v2"===e?e:"v1"}(r),s,t),d=async(t,e,i,s)=>{const n={method:t,headers:{...o,...i?.headers},...i};void 0!==s&&(n.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),n))};return{get:(t,e)=>d("GET",t,e),post:(t,e,i)=>d("POST",t,i,e),put:(t,e,i)=>d("PUT",t,i,e),patch:(t,e,i)=>d("PATCH",t,i,e),delete:(t,e)=>d("DELETE",t,e)}}eh.defaultConfig=void 0;const sh=t=>void 0!==t?.subdomain?`?subdomain=${encodeURIComponent(t.subdomain)}`:"";const nh="https://api.jaaq.app";class rh{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)}${sh(i)}`;return(await t.get(s)).collection},async getSummaryById(e,i){const s=`/collections/${encodeURIComponent(e)}/summary${sh(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 rh(t,e)}static init(t){return oh(t)}}function ah(t){return oh(t)}function oh(t){const{baseUrl:e=nh,apiKey:i,clientId:s,fetch:n,apiVersion:r="v1"}=t,a=ih({baseUrl:e,apiKey:i,clientId:s,fetch:n??globalThis.fetch,apiVersion:r});return rh.fromHttp(a,r)}function lh(t,e,i){return Math.max(e,Math.min(i,t))}!function(){if("undefined"!=typeof document){const t="jaaq-styles-styles";if(!document.getElementById(t)){const e=document.createElement("style");e.id=t,e.textContent=".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",document.head.appendChild(e)}}}();var dh=".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";!function(){if("undefined"!=typeof document){const t="jaaq-styles-styles";if(!document.getElementById(t)){const e=document.createElement("style");e.id=t,e.textContent=".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",document.head.appendChild(e)}}}();class hh{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=ah({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 n=document.createElement("button");n.className="jaaq-center-play-btn",n.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 ',n.setAttribute("aria-label","Play video"),this.elements.centerPlayBtn=n,e.appendChild(n);const r=document.createElement("div");r.className="jaaq-gradient-overlay",this.elements.gradientOverlay=r;const a=document.createElement("div");a.className="jaaq-caption-display",a.style.display="none",this.elements.captionDisplay=a,r.appendChild(a);const o=document.createElement("div");o.className="jaaq-video-title",this.elements.videoTitle=o,r.appendChild(o);const l=document.createElement("div");l.className="jaaq-video-author",this.elements.videoAuthor=l,r.appendChild(l);const d=document.createElement("div");d.className="jaaq-video-description",this.elements.videoDescription=d,r.appendChild(d),e.appendChild(r);const h=document.createElement("div");h.className="jaaq-loading",this.elements.loading=h,e.appendChild(h);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 p=document.createElement("button");p.className="jaaq-control-btn",p.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 ',p.setAttribute("aria-label","Mute"),this.elements.volumeBtn=p,f.appendChild(p);const m=document.createElement("div");m.className="jaaq-progress-bar",this.elements.progressBar=m;const v=document.createElement("div");v.className="jaaq-progress-filled",this.elements.progressFilled=v,m.appendChild(v),f.appendChild(m);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(eh.isSupported()){this.hls&&this.hls.destroy();const t=new eh({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(eh.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(eh.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[n,r]=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(n),l=a(r);s++;const d=[];for(;s<i.length&&""!==i[s].trim();)d.push(i[s].trim()),s++;d.length>0&&e.push({start:o,end:l,text:d.join(" ")})}s++}return e}updateOverlayContent(t){const e=!1!==this.config.showLogo,i=!1!==this.config.showTitle,s=!1!==this.config.showAuthor,n=!1!==this.config.showDescription,r=!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||"",n=s?`${e} - ${s}`:e;this.elements.videoTitle.textContent=n,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=n&&e?"block":"none"}this.elements.captionsBtn&&(this.elements.captionsBtn.style.display=r?"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*lh(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=lh(t,0,1),this.videoElement.muted=0===t)}toggleMute(){this.videoElement&&(this.videoElement.muted=!this.videoElement.muted)}seek(t){this.videoElement&&(this.videoElement.currentTime=lh(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=""}}function ch(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).JaaqVanilla={})}(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 n=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}({}),r=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,d={exports:{}};var h=(l||(l=1,function(t){var e,i,s,n,r;e=/^(?=((?:[a-zA-Z0-9+\-.]+:)?))\1(?=((?:\/\/[^\/?#]*)?))\2(?=((?:(?:[^?#\/]*\/)*[^;?#\/]*)?))\3((?:;[^?#]*)?)(\?[^#]*)?(#[^]*)?$/,i=/^(?=([^\/?#]*))\1([^]*)$/,s=/(?:\/|^)\.(?=\/)/g,n=/(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g,r={buildAbsoluteURL:function(t,e,s){if(s=s||{},t=t.trim(),!(e=e.trim())){if(!s.alwaysNormalize)return t;var n=r.parseURL(t);if(!n)throw new Error("Error trying to parse base URL.");return n.path=r.normalizePath(n.path),r.buildURLFromParts(n)}var a=r.parseURL(e);if(!a)throw new Error("Error trying to parse relative URL.");if(a.scheme)return s.alwaysNormalize?(a.path=r.normalizePath(a.path),r.buildURLFromParts(a)):e;var o=r.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 d={scheme:o.scheme,netLoc:a.netLoc,path:null,params:a.params,query:a.query,fragment:a.fragment};if(!a.netLoc&&(d.netLoc=o.netLoc,"/"!==a.path[0]))if(a.path){var h=o.path,c=h.substring(0,h.lastIndexOf("/")+1)+a.path;d.path=r.normalizePath(c)}else d.path=o.path,a.params||(d.params=o.params,a.query||(d.query=o.query));return null===d.path&&(d.path=s.alwaysNormalize?r.normalizePath(a.path):a.path),r.buildURLFromParts(d)},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(n,"")).length;);return t.split("").reverse().join("")},buildURLFromParts:function(t){return t.scheme+t.netLoc+t.path+t.params+t.query+t.fragment}},t.exports=r}(d)),d.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",p="video",m="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,[p]:null,[m]: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=h.buildAbsoluteURL(this.baseurl,this.relurl,{alwaysNormalize:!0})),this._url||""}set url(t){this._url=t}clearElementaryStreamInfo(){const{elementaryStreams:t}=this;t[g]=null,t[p]=null,t[m]=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,n,r=!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,n)):a[t]={startPTS:e,endPTS:i,startDTS:s,endDTS:n,partial:r}}}class b extends v{constructor(t,e,i,s,n){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 r=t.enumeratedString("BYTERANGE");r&&this.setByteRange(r,n),n&&(this.fragOffset=n.fragOffset+n.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 _(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 k(t,e){if(null==t)return{};var i,s,n=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 r=Object.getOwnPropertySymbols(t);for(s=0;s<r.length;s++)i=r[s],-1===e.indexOf(i)&&{}.propertyIsEnumerable.call(t,i)&&(n[i]=t[i])}return n}function w(t){switch(t.details){case r.FRAG_LOAD_TIMEOUT:case r.KEY_LOAD_TIMEOUT:case r.LEVEL_LOAD_TIMEOUT:case r.MANIFEST_LOAD_TIMEOUT:case r.AUDIO_TRACK_LOAD_TIMEOUT:case r.SUBTITLE_TRACK_LOAD_TIMEOUT:case r.ASSET_LIST_LOAD_TIMEOUT:return!0}return!1}function D(t){return t.details.startsWith("key")}function x(t){return D(t)&&!!t.frag&&!t.frag.decryptdata}function P(t,e){const i=w(e);return t.default[(i?"timeout":"error")+"Retry"]}function C(t,e){const i="linear"===t.backoff?1:Math.pow(2,e);return Math.min(i*t.retryDelayMs,t.maxRetryDelayMs)}function M(t){return _(_({},t),{errorRetry:null,timeoutRetry:null})}function O(t,e,i,s){if(!t)return!1;const n=null==s?void 0:s.code,r=e<t.maxNumRetry&&(function(t){return F(t)||!!t&&(t<400||t>499)}(n)||!!i);return t.shouldRetry?t.shouldRetry(t,e,i,s,r):r}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_:n}=this;i.halfLife!==t&&(this.slow_=new $(t,i.getEstimate(),i.getTotalWeight())),s.halfLife!==e&&(this.fast_=new $(e,s.getEstimate(),s.getTotalWeight())),n.halfLife!==t&&(this.ttfb_=new $(t,n.getEstimate(),n.getTotalWeight()))}sample(t,e){if(e<=0)return;const i=Math.min(this.minDelayMs_,e/1e5),s=8*e,n=Math.max(t,i)/1e3,r=s/n;this.fast_.sample(n,r),this.slow_.sample(n,r)}sampleTTFB(t){const e=t/1e3,i=Math.sqrt(2)*Math.exp(-Math.pow(e,2)/2);this.ttfb_.sample(i,Math.max(t,5))}canEstimate(){return this.fast_.getTotalWeight()>=this.minWeight_}getEstimate(){return this.canEstimate()?Math.min(this.fast_.getEstimate(),this.slow_.getEstimate()):this.defaultEstimate_}getEstimateTTFB(){return this.ttfb_.getTotalWeight()>=this.minWeight_?this.ttfb_.getEstimate():this.defaultTTFB_}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(){},j={trace:G,debug:G,log:G,warn:G,info:G,error:G};function q(){return I({},j)}function K(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 V=q();const H=V;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),n=i.length,r=s.length;return!n||!r||n===r&&!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",J="utf-8";function Z(t,e){if(t<0)return-Z(-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 nt(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 rt(t,e){const i=e;let s=0;for(;et(t,e);){s+=10;s+=it(t,e+6),nt(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 n=(r=t,z(r)?r:r.buffer);var r;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,d=(o+e)/a,h=Math.floor(Math.max(0,Math.min(d,l)));var c;return new s(n,h,Math.floor(Math.min(h+Math.max(i,0),l))-h)}(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:n}=e;if(!n){const t=i.getUint8(0),e=i.getUint8(1);239==t&&187==e&&191==i.getUint8(2)?(n=J,s=3):254==t&&255==e?(n=X,s=2):255==t&&254==e?(n=Q,s=2):n=J}if("undefined"!=typeof TextDecoder)return new TextDecoder(n).decode(i);const{byteLength:r}=i,a=n!==X;let o,l="";for(;s<r;){switch(n){case J:if(o=i.getUint8(s),o<128)s++;else if(o>=194&&o<=223)if(s+1<r){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<=r-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<=r-1){const t=i.getUint8(s+1),e=i.getUint8(s+2),n=i.getUint8(s+3);t>=128&&t<=191&&e>=128&&e<=191&&n>=128&&n<=191?(o=(7&o)<<18|(63&t)<<12|(63&e)<<6|63&n,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:J});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)),n=t.data[2+i],r=t.data.subarray(3+i).indexOf(0);if(-1===r)return;const a=ot(at(t.data,3+i,r));let o;var l;return"--\x3e"===s?o=ot(at(t.data,4+i+r)):o=z(l=t.data.subarray(4+i+r))?l:0==l.byteOffset&&l.byteLength==l.buffer.byteLength?l.buffer:new Uint8Array(l).buffer,e.mimeType=s,e.pictureType=n,e.description=a,e.data=o,e}function dt(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 n=ot(i.subarray(e));return{key:t.type,info:s,data:n}}const e=ot(t.data.subarray(1));return{key:t.type,info:"",data:e}}(t)}function ht(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 n=e+s;for(;e+10<n;){const s=ht(t.subarray(e)),n=dt(s);n&&i.push(n),e+=s.size+10}nt(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 pt(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 mt(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 _t(t,e,i){t[e]=i>>24,t[e+1]=i>>16&255,t[e+2]=i>>8&255,t[e+3]=255&i}function kt(t,e,i){const s=e.byteOffset-t.byteOffset-8,n=8+i,r=e.byteLength+8-n;r<8||(_t(t,s,n),_t(t,s+n,r),_t(t,s+n+4,Tt.free))}function wt(t,e){return[t.byteOffset-e-8,t.byteOffset-e+t.byteLength]}function Dt(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 n=0,r=0;for(let i=0;i<e.length;i++){const[a,o]=e[i];s.set(t.subarray(n,a),r),r+=a-n,n=o}s.set(t.subarray(n),r);return{result:s,dropped:i,droppedBefore:t=>e.reduce((e,[i,s])=>s<=t?e+s-i:e,0)}}function xt(t,e){const i=[];return e.length?(Pt(t,e,0,0,t.byteLength,i),i):i}function Pt(t,e,i,s,n,r){const a=e[i];if(4!==(null==a?void 0:a.length))return;const o=a.charCodeAt(0),l=a.charCodeAt(1),d=a.charCodeAt(2),h=a.charCodeAt(3),c=e.length-1;for(let a=s;a<n;){const s=a+8<=n,u=a+4<=n?16777216*t[a]+(t[a+1]<<16|t[a+2]<<8|t[a+3]):At(t,a),f=u>1?a+u:n;if(s&&t[a+4]===o&&t[a+5]===l&&t[a+6]===d&&t[a+7]===h){const s=Math.min(f,n);i===c?r.push(t.subarray(a+8,s)):Pt(t,e,i+1,a+8,s,r)}a=f}}function Ct(t){const e=[],i=t[0];let s=8;const n=At(t,s);s+=4;let r=0,a=0;0===i?(r=At(t,s),a=At(t,s+4),s+=8):(r=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 r=At(t,i);i+=4;const a=2147483647&r;if(1===(2147483648&r)>>>31)return H.warn("SIDX has hierarchical references (not supported)"),null;const l=At(t,i);i+=4,e.push({referenceSize:a,subsegmentDuration:l,info:{duration:l/n,start:o,end:o+a-1}}),o+=a,i+=4,s=i}return{earliestPresentationTime:r,timescale:n,version:i,referencesCount:l,references:e}}function Mt(t){const e=[],i=xt(t,["moov","trak"]);for(let t=0;t<i.length;t++){const s=i[t],n=xt(s,["tkhd"])[0];if(n){let t=n[0];const i=At(n,0===t?12:20),r=xt(s,["mdia","mdhd"])[0];if(r){t=r[0];const n=At(r,0===t?12:20),a=xt(s,["mdia","hdlr"])[0];if(a){const t=yt(a.subarray(8,12)),r={soun:g,vide:p}[t],o=Ot(xt(s,["mdia","minf","stbl","stsd"])[0]);r?(e[i]={timescale:n,type:r,stsd:o},e[r]=_({timescale:n,id:i},o)):e[i]={timescale:n,type:t,stsd:o}}}}}return xt(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 n,r=s;const a="enca"===s||"encv"===s;if(a){const t=xt(e,[s])[0];xt(t.subarray("enca"===s?28:78),["sinf"]).forEach(t=>{const e=xt(t,["schm"])[0];if(e){const i=yt(e.subarray(4,8));if("cbcs"===i||"cenc"===i){const e=xt(t,["frma"])[0];e&&(r=yt(e))}}})}const o=r;switch(r){case"avc1":case"avc2":case"avc3":case"avc4":{const t=xt(i,["avcC"])[0];t&&t.length>3&&(r+="."+$t(t[1])+$t(t[2])+$t(t[3]),n=Ft("avc1"===o?"dva1":"dvav",i));break}case"mp4a":{const t=xt(e,[s])[0],i=xt(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(r+="."+$t(s),t+=12,5!==i[t++])break;t=Nt(i,t);const n=i[t++];let a=(248&n)>>3;31===a&&(a+=1+((7&n)<<3)+((224&i[t])>>5)),r+="."+a}break}case"hvc1":case"hev1":{const t=xt(i,["hvcC"])[0];if(t&&t.length>12){const e=t[1],i=["","A","B","C"][e>>6],s=31&e,n=At(t,2),a=(32&e)>>5?"H":"L",o=t[12],l=t.subarray(6,12);r+="."+i+s,r+="."+function(t){let e=0;for(let i=0;i<32;i++)e|=(t>>i&1)<<31-i;return e>>>0}(n).toString(16).toUpperCase(),r+="."+a+o;let d="";for(let t=l.length;t--;){const e=l[t];if(e||d){d="."+e.toString(16).toUpperCase()+d}}r+=d}n=Ft("hev1"==o?"dvhe":"dvh1",i);break}case"dvh1":case"dvhe":case"dvav":case"dva1":case"dav1":r=Ft(r,i)||r;break;case"vp09":{const t=xt(i,["vpcC"])[0];if(t&&t.length>6){const e=t[4],i=t[5],s=t[6]>>4&15;r+="."+Bt(e)+"."+Bt(i)+"."+Bt(s)}break}case"av01":{const t=xt(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,d=2===e&&o?l?12:10:o?10:8,h=(16&t[2])>>4,c=(8&t[2])>>3,u=(4&t[2])>>2,f=3&t[2],g=1,p=1,m=1,v=0;r+="."+e+"."+Bt(s)+a+"."+Bt(d)+"."+h+"."+c+u+f+"."+Bt(g)+"."+Bt(p)+"."+Bt(m)+"."+v,n=Ft("dav1",i)}break}}return{codec:r,encrypted:a,supplemental:n}}function Ft(t,e){const i=xt(e,["dvvC"]),s=i.length?i[0]:xt(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){xt(t,["moov","trak"]).forEach(t=>{const i=xt(t,["mdia","minf","stbl","stsd"])[0];if(!i)return;const s=i.subarray(8);let n=xt(s,["enca"]);const r=n.length>0;r||(n=xt(s,["encv"])),n.forEach(t=>{xt(r?t.subarray(28):t.subarray(78),["sinf"]).forEach(t=>{const i=Gt(t);i&&e(i,r)})})})}function Gt(t){const e=xt(t,["schm"])[0];if(e){const i=yt(e.subarray(4,8));if("cbcs"===i||"cenc"===i){const e=xt(t,["schi","tenc"])[0];if(e)return e}}}let jt;function qt(t){if("undefined"==typeof TextDecoder)return ot(t);return(jt||(jt=new TextDecoder("utf-8"))).decode(t).replace(/\0/g,"")}function Kt(t,i,s,n,r){const a={};let o=!1;const l=function(t){const e=t.byteLength,i=[];for(let s=0;s<e;){const n=s+8<=e,r=s+4<=e?16777216*t[s]+(t[s+1]<<16|t[s+2]<<8|t[s+3]):At(t,s),a=r>1?s+r:e;if(n&&109===t[s+4]&&111===t[s+5]&&111===t[s+6]&&102===t[s+7]){const n=Math.min(a,e);for(let e=s+8;e<n;){const r=e+8<=n,a=e+4<=n?16777216*t[e]+(t[e+1]<<16|t[e+2]<<8|t[e+3]):At(t,e),o=a>1?e+a:n;if(r&&116===t[e+4]&&114===t[e+5]&&97===t[e+6]&&102===t[e+7]){const r=Math.min(o,n);let a,l;const d=[];for(let i=e+8;i<r;){const e=i+8<=r,s=i+4<=r?16777216*t[i]+(t[i+1]<<16|t[i+2]<<8|t[i+3]):At(t,i),n=s>1?i+s:r;if(e&&116===t[i+4]){const e=Math.min(n,r);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]&&d.push(t.subarray(i+8,e))}i=n}i.push({moofOffset:t.byteOffset+s,tfdt:a,tfhd:l,truns:d})}e=o}}s=a}return i}(t),d=t.byteLength;for(let u=0;u<l.length;u++){const{moofOffset:f,tfdt:g,tfhd:m,truns:v}=l[u],y=At(m,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),r&&e(S)&&(r.timeOffset=S/r.timescale)}const b=(null==r?void 0:r.trackId)===y&&E.type===p,A=E.default,L=16777215&At(m,0);let I,R=(null==A?void 0:A.duration)||0,_=(null==A?void 0:A.sampleSize)||0,k=8;1&L&&(k+=8),2&L&&(k+=4),8&L&&(R=At(m,k),I=m.byteOffset-t.byteOffset+k,k+=4),16&L&&(_=At(m,k));let w=0;const D=!!(1&L),x=!D&&!!(131072&L);D?(w=At(m,8),w*=Math.pow(2,32),w+=At(m,12)):x&&(w=f);let P=S||0,C=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],p=2&s[2],m=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,k=w+u;if(!n&&0===s[1]&&6===s[2]&&1===s[3]){var h,c;const i=P,n=k,o=E;let l=-1,u=0,f=0,g=null!=(h=null==r?void 0:r.timeOffset)?h:0;const p=R/(null!=(c=null==r?void 0:r.timescale)?c:1),m=!0===(null==r?void 0:r.isHEVCFlavor),v=m?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),n=-1===l&&void 0===T.keyFrameIndex&&!(1&s[E+5]);E+=8;const a=k+i;if(b){if(i>0){let e=k;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],n=m?s>>1&63:31&s;(m?39===n||40===n:6===n)&&Wt(t.subarray(e,e+i),v,g,r.samples),e+=i}while(e<a)}g+=p}k=a,n&&(l=e,u=k)}if(k<=d)f=a;else{let t=n,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>d)break;f=i+1,e+=8}}if(b&&(r.timeOffset=g),-1!==l&&u<=d&&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;P=i+y,C+=y;continue}n&&(S=[],A={sampleOffset:k,samples:S,defaultSampleDurationOffset:I},k<=d&&T.trun.push(A));for(let i=0;i<a;i++){let a,o,l;g?(n&&(a=s.byteOffset-t.byteOffset+E),M=At(s,E),E+=4):M=R,p?(L=At(s,E),E+=4):L=_,m&&(l=1&s[E+1]?1:0,n&&(o={isNonSync:l,dependsOn:1==(3&s[E])?1:2}),E+=4);let h=0;if(y){h=0===s[0]?At(s,E):Rt(s,E),E+=4}if(b){let e=k,i=0;for(;i<L;){const s=At(t,e);e+=4,Yt(r.isHEVCFlavor,t[e])&&Wt(t.subarray(e,e+s),r.isHEVCFlavor?2:1,r.timeOffset+h/r.timescale,r.samples),e+=s,i+=s+4}r.timeOffset+=M/r.timescale}if(k+=L,k<=d){A&&void 0!==a&&(A.lastSampleDurationOffset=a),0===l&&void 0===T.keyFrameIndex&&(T.keyFrameIndex=i,T.keyFrameStart=P);const t=P+h;(!e(T.ptsMin)||t<T.ptsMin)&&(T.ptsMin=t),(!e(T.ptsMax)||t+M>T.ptsMax)&&(T.ptsMax=t+M),S&&(S[i]={cts:h,duration:M,flags:o,size:L})}P+=M,C+=M}!C&&R&&(C+=R*a)}T.duration+=C,T.duration&&(o=!0)}if(!o){let i=1/0,s=0;const n=xt(t,["sidx"]);for(let t=0;t<n.length;t++){const e=Ct(n[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 Vt(t,e){const i=new Uint8Array(t.length+e.length);return i.set(t),i.set(e,t.length),i}function Ht(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 n=zt(t);let r=0;r+=e;let a=0,o=0,l=0;for(;r<n.length;){a=0;do{if(r>=n.length)break;l=n[r++],a+=l}while(255===l);o=0;do{if(r>=n.length)break;l=n[r++],o+=l}while(255===l);const t=n.length-r;let e=r;if(o<t)r+=o;else if(o>t){H.error(`Malformed SEI payload. ${o} is too small, only ${t} bytes left to parse.`);break}if(4===a){if(181===n[e++]){const t=bt(n,e);if(e+=2,49===t){const t=At(n,e);if(e+=4,1195456820===t){const t=n[e++];if(3===t){const r=n[e++],o=64&r,l=o?2+3*(31&r):0,d=new Uint8Array(l);if(o){d[0]=r;for(let t=1;t<l;t++)d[t]=n[e++]}s.push({type:t,payloadType:a,pts:i,bytes:d})}}}}}else if(5===a&&o>16){const t=[];for(let i=0;i<16;i++){const s=n[e++].toString(16);t.push(1==s.length?"0"+s:s),3!==i&&5!==i&&7!==i&&9!==i||t.push("-")}const r=o-16,l=new Uint8Array(r);for(let t=0;t<r;t++)l[t]=n[e++];s.push({payloadType:a,pts:i,uuid:t.join(""),userData:qt(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 n=e-i.length,r=new Uint8Array(n);let a=0,o=0;for(let e=0;e<n;o++,e++)o===i[a]&&(o++,a++),r[e]=t[o];return r}function Xt(t,e,i){if(16!==t.byteLength)throw new RangeError("Invalid system id");let s,n,r;s=0,n=new Uint8Array,r=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,n=i;for(;n--;)s+=e[n].byteLength;const r=new Uint8Array(s);for(r[0]=s>>24&255,r[1]=s>>16&255,r[2]=s>>8&255,r[3]=255&s,r.set(t,4),n=0,s=8;n<i;n++)r.set(e[n],s),s+=e[n].byteLength;return r}([112,115,115,104],new Uint8Array([0,0,0,0]),t,r,n,a,i)}function Qt(t){const e=[];if(t instanceof ArrayBuffer){const i=t.byteLength;let s=0;for(;s+32<i;){const i=Jt(new DataView(t,s));e.push(i),s+=i.size}}return e}function Jt(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 n=t.getUint32(8)>>>24;if(0!==n&&1!==n)return{offset:i,size:e};const r=t.buffer,a=pt(new Uint8Array(r,i+12,16));let o=null,l=null,d=0;if(0===n)d=28;else{const n=t.getUint32(28);if(!n||s<32+16*n)return{offset:i,size:e};o=[];for(let t=0;t<n;t++)o.push(new Uint8Array(r,i+32+16*t,16));d=32+16*n}if(!d)return{offset:i,size:e};const h=t.getUint32(d);return e-32<h?{offset:i,size:e}:(l=new Uint8Array(r,i+d+4,h),0===n&&(o=function(t){const e=[];for(let i=0;i<t.length;){const s=t[i++],n=7&s;if(0===n){for(;128&t[i++];);continue}if(2!==n){i+=1===n?8:4;continue}let r=0;for(let e=0,s=128;128&s;e+=7)r|=(127&(s=t[i++]))<<e;if(s>>3==2)if(32===r){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===r&&e.push(t.subarray(i,i+16));i+=r}return e}(l)),{version:n,systemId:a,kids:o,data:l,offset:i,size:e})}const Zt=ne("userAgent"),te=ne("vendor");let ee,ie,se;function ne(t){try{return navigator[t]||""}catch(t){}return""}function re(){if(void 0===ee){const t=Zt.match(/Chrome\/(\d+)/i);ee=t?parseInt(t[1]):0}return ee}function ae(){return/\(Windows.+Firefox\//i.test(Zt)}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 de(t,e,i=!0){return!t.split(",").some(t=>!he(t,e,i))}function he(t,e,i=!0){var s;const n=Y(i);return null!=(s=null==n?void 0:n.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&&Ht(i)?9:oe.video[i];return s?(2*s+t)/(t?3:2):(oe.audio[i]+t)/(t?2:1)},0)}const ge={};const pe=/flac|opus|mp4a\.40\.34/i;function me(t,e=!0){return t.replace(pe,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 n=0;n<i.length;n++){var s;if(he(i[n],"audio",e))return ge[t]=i[n],i[n];if("mp3"===i[n]&&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)&&he(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,n,r,a){const o=t.videoCodec,l=t.audioCodec?t.audioGroups:null,d=null==a?void 0:a.audioCodec,h=null==a?void 0:a.channels,c=h?parseInt(h):d?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=>Ht(t))||t.width>1920&&t.height>1088||t.height>1920&&t.width>1088||t.frameRate>Math.max(n,30)||"SDR"!==t.videoRange&&t.videoRange!==s||t.bitrate>Math.max(r,8e6))||!!u&&e(c)&&Object.keys(u).some(t=>parseInt(t)>c)}function Re(t,e,i,s={}){const n=t.videoCodec;if(!n&&!t.audioCodec||!i)return Promise.resolve(Ae);const r=[],a=function(t){var e;const i=null==(e=t.videoCodec)?void 0:e.split(","),s=ke(t),n=t.width||640,r=t.height||480,a=t.frameRate||30,o=t.videoRange.toLowerCase();return i?i.map(t=>{const e={contentType:ce(Ee(t),"video"),width:n,height:r,bitrate:s,framerate:a};return"sdr"!==o&&(e.transferFunction=o),e}):[]}(t),o=a.length,l=function(t,e,i){var s;const n=null==(s=t.audioCodec)?void 0:s.split(","),r=ke(t);if(n&&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||"");n.forEach(e=>{const n={contentType:ce(e,"audio"),bitrate:i?_e(e,r):r};s&&(n.channels=""+s),t.push(n)})}return t},t):t},[]);return[]}(t,e,o>0),d=l.length;for(let t=o||1*d||1;t--;){const e={type:"media-source"};if(o&&(e.video=a[t%o]),d){e.audio=l[t%d];const i=e.audio.bitrate;e.video&&i&&(e.video.bitrate-=i)}r.push(e)}if(n){const t=navigator.userAgent;if(n.split(",").some(t=>Ht(t))&&ae())return Promise.resolve(Le(new Error(`Overriding Windows Firefox HEVC MediaCapabilities result based on user-agent string: (${t})`),r))}return Promise.all(r.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:r,decodingInfoResults:t})).catch(t=>({supported:!1,configurations:r,decodingInfoResults:[],error:t}))}function _e(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 ke(t){return 1e3*Math.ceil(Math.max(.9*t.bitrate,t.averageBitrate)/1e3)||1}function we(t,e,i){const s=encodeURIComponent(e),n=`${s}=${encodeURIComponent(i)}`;let r=!1;const a=[];t.search.substring(1).split("&").forEach(t=>{t===s||t.startsWith(s+"=")?r||(a.push(n),r=!0):t&&a.push(t)}),r||a.push(n),t.search=a.join("&")}const De=["NONE","TYPE-0","TYPE-1",null];const xe=["SDR","PQ","HLG"];var Pe="",Ce="YES",Me="v2";function Oe(t){const{canSkipUntil:e,canSkipDateRanges:i,age:s}=t;return e&&s<e/2?i?Me:Ce:Pe}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&&we(e,"_HLS_msn",this.msn.toString()),void 0!==this.part&&we(e,"_HLS_part",this.part.toString()),this.skip&&we(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||xe.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){H.log(`[abr] start candidates with "${t}" ignored because ${e}`)}function je(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 qe(t){if(!t)return t;const{lang:e,assocLang:i,characteristics:s,channels:n,audioCodec:r}=t;return{lang:e,assocLang:i,characteristics:s,channels:n,audioCodec:r}}function Ke(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(Ve(t,e[s],i))return s}return-1}function Ve(t,e,i){const{groupId:s,name:n,lang:r,assocLang:a,default:o}=t,l=t.forced;return(void 0===s||e.groupId===s)&&(void 0===n||e.name===n)&&(void 0===r||function(t,e="--"){if(t.length===e.length)return t===e;return t.startsWith(e)||e.startsWith(t)}(r,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 He(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 n=null==(i=this.tracks[t])?void 0:i.buffer;null!=n&&n.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 Je=function(t,e){let i=0,s=t.length-1,n=null,r=null;for(;i<=s;){n=(i+s)/2|0,r=t[n];const a=e(r);if(a>0)i=n+1;else{if(!(a<0))return r;s=n-1}}return null};function Ze(t,e,i=0,s=0,n=.005){let r=null;if(t){r=e[1+t.sn-e[0].sn]||null;const s=t.endDTS-i;s>0&&s<15e-7&&(i+=15e-7),r&&t.level!==r.level&&r.end<=t.end&&(r=e[2+t.sn-e[0].sn]||null)}else 0===i&&0===e[0].start&&(r=e[0]);if(r&&((!t||t.level===r.level)&&0===ti(i,s,r)||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}(r,t,Math.min(n,s))))return r;const a=Je(e,ti.bind(null,i,s));return!a||a===t&&r?r: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:n}=t;let r;return n&&(s=s.concat(n)),Je(s,t=>t.cc<e?1:t.cc>e?-1:(r=t,t.end<=i?1:t.start>i?-1:0)),r||null}return null}function si(t,e){return e===t.endSN&&t.fragmentHint?t.fragmentHint:t.fragments[1+e-t.startSN]||null}var ni=0,ri=2,ai=3,oi=5,li=0,di=1,hi=2,ci=4,ui=8,fi=16;function gi(t){const e=t.details;return e===r.BUFFER_ADD_CODEC_ERROR||e===r.MEDIA_SOURCE_REQUIRES_RESET||e===r.BUFFER_APPEND_ERROR&&!pi(t)}function pi(t){return t.details===r.BUFFER_APPEND_ERROR&&("QuotaExceededError"===t.error.name||"InvalidStateError"===t.error.name)}function mi(t){const e={action:ni,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,n=[];if(i)for(let r=0;r<t.length;r++){e>=t[r].start&&e<=t[r].end&&(s=r);const a=n.length;if(a){const e=n[a-1].end;t[r].start-e<i?t[r].end>e&&(n[a-1].end=t[r].end):n.push(t[r])}else n.push(t[r])}else n=t;let r,a=0,o=e,l=e;for(let t=0;t<n.length;t++){const d=n[t].start,h=n[t].end;if(-1===s&&e>=d&&e<=h&&(s=t),e+i>=d&&e<h)o=d,l=h,a=l-e;else if(e+i<d){r=d;break}}return{len:a,start:o||0,end:l||0,nextStart:r,buffered:t,bufferedIndex:s}}static getBuffered(t){try{return t.buffered||yi}catch(t){return H.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 _i(t){const e=t.querySelectorAll("source");[].slice.call(e).forEach(e=>{t.removeChild(e)})}function ki(t){return"audio"===t?1:0}function wi(t,e){return`${t?"":" - triggering recovery"}${e?" with HTMLMediaElement Error: "+e.message:""}`}function Di(t){return`${t.type}_${t.sn}_${t.level}`}function xi(t,e){const{start:i,end:s}=e;let n=0;for(let e=0;e<t.length;e++){const r=t[e];if(r.start>=s)break;const a=Math.max(i,r.start),o=Math.min(s,r.end);o>a&&(n+=o-a)}return n}function Pi(t,e){return e.duration-t<=.05}var Ci="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,n=Object.keys(s);for(let r=n.length;r--;){const a=s[n[r]];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,n,r){this.timeRanges&&(this.timeRanges[t]=e);const o=(null==n?void 0:n.fragment.sn)||-1;Object.keys(this.fragments).forEach(n=>{const l=this.fragments[n];if(!l||!this.hls)return;const d=l.body;if(o>=d.sn)return;if(!l.buffered&&(!l.loaded||r))return void(d.type===i&&this.removeFragment(d));const h=l.range[t];if(h)if(0!==h.time.length){if(h.time.some(t=>{const i=!this.isTimeBuffered(t.startPTS,t.endPTS,e);return i&&this.removeFragment(d),i}),s&&s!==d&&re()){const t=s.endPTS,e=d.startPTS;if(t&&e&&l.range.video){const i=e-t;i<0&&i>-.1&&(this.removeFragment(d),this.hls.trigger(a.BUFFER_FLUSHING,{startOffset:t+.004,endOffset:1/0,type:"video"}))}}}else this.removeFragment(d)})}detectPartialFragments(t){const e=this.timeRanges,{frag:i,part:s,id:n}=t;if(!e||!y(i))return;const r=Bi(i),a=this.fragments[r];if(!a||a.buffered&&i.gap)return;const o=!i.relurl;Object.keys(e).forEach(t=>{const r=i.elementaryStreams[t];if(!r)return;const l=e[t],d=o||!0===r.partial;a.range[t]=this.getBufferedTimes(i,s,d,l),this.detectEvictedFragments(t,l,n,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 n=null==(s=a.range[e])?void 0:s.time,r=0===n.length||1===n.length&&n[0].endPTS-n[0].startPTS<t;return r&&this.addAsGap(i),r})}}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 n={time:[],partial:i},r=t.start,a=t.end,o=t.minEndPTS||a,l=t.maxStartPTS||r;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){n.time.push({startPTS:Math.max(r,s.start(t)),endPTS:Math.min(a,s.end(t))});break}if(r<i&&a>e){const e=Math.max(r,s.start(t)),i=Math.min(a,s.end(t));i>e&&(n.partial=!0,n.time.push({startPTS:e,endPTS:i}))}else if(a<=e)break}return n}getPartialFragment(t){let e,i,s,n=null,r=0;const{bufferPadding:a,fragments:o}=this;return Object.keys(o).forEach(l=>{const d=o[l];d&&$i(d)&&(i=d.body.start-a,s=d.body.end+a,t>=i&&t<=s&&(e=Math.min(t-i,s-t),r<=e&&(n=d.body,r=e)))}),n}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:Ci}isTimeBuffered(t,e,i){let s,n;for(let r=0;r<i.length;r++){if(s=i.start(r)-this.bufferPadding,n=i.end(r)+this.bufferPadding,t>=s&&e<=n)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,n=Bi(i);this.fragments[n]={body:i,appendedPTS:null,loaded:s,buffered:!1,range:Object.create(null)}}onBufferAppended(t,e){const{frag:i,part:s,timeRanges:n}=e;if(!y(i))return;const r=i.type;if(s){let t=this.activePartLists[r];t||(this.activePartLists[r]=t=[]),t.push(s)}this.timeRanges=n}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 n=e[i[s]];if((null==n?void 0:n.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 n=0,r=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 d=l.body;if(d.gap)return 0;const h=d.hasStats&&d.stats.loaded||d.byteLength||d.bitrate&&8*d.bitrate*d.duration;if(d.end<=t&&h&&(n+=h,r=Math.max(r,d.end),n>=i))return r}return r>0?r:0}removeFragmentsInRange(t,e,i,s,n){s&&!this.hasGaps||Object.keys(this.fragments).forEach(r=>{const a=this.fragments[r];if(!a)return;const o=a.body;o.type!==i||s&&!o.gap||o.start<e&&o.end>t&&(a.buffered||n)&&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,n;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!=(n=t.range.subs)&&n.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,ji=1;class qi{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 ji: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],n=i[1],r=i[2],a=i[3],o=this.invSubMix,l=o[0],d=o[1],h=o[2],c=o[3],u=new Uint32Array(256);let f=0,g=0,p=0;for(p=0;p<256;p++)u[p]=p<128?p<<1:p<<1^283;for(p=0;p<256;p++){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],p=u[o],m=u[p];let v=257*u[i]^16843008*i;s[f]=v<<24|v>>>8,n[f]=v<<16|v>>>16,r[f]=v<<8|v>>>24,a[f]=v,v=16843009*m^65537*p^257*o^16843008*f,l[i]=v<<24|v>>>8,d[i]=v<<16|v>>>16,h[i]=v<<8|v>>>24,c[i]=v,f?(f=o^u[u[u[m^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 n=this.keySize=e.length;if(4!==n&&6!==n&&8!==n)throw new Error("Invalid aes key size="+n);const r=this.ksRows=4*(n+6+1);let a,o;const l=this.keySchedule=new Uint32Array(r),d=this.invKeySchedule=new Uint32Array(r),h=this.sBox,c=this.rcon,u=this.invSubMix,f=u[0],g=u[1],p=u[2],m=u[3];let v,y;for(a=0;a<r;a++)a<n?v=l[a]=e[a]:(y=v,a%n===0?(y=y<<8|y>>>24,y=h[y>>>24]<<24|h[y>>>16&255]<<16|h[y>>>8&255]<<8|h[255&y],y^=c[a/n|0]<<24):n>6&&a%n===4&&(y=h[y>>>24]<<24|h[y>>>16&255]<<16|h[y>>>8&255]<<8|h[255&y]),l[a]=v=(l[a-n]^y)>>>0);for(o=0;o<r;o++)a=r-o,y=3&o?l[a]:l[a-4],d[o]=o<4||a<=4?y:f[h[y>>>24]]^g[h[y>>>16&255]]^p[h[y>>>8&255]]^m[h[255&y]],d[o]=d[o]>>>0}networkToHostOrderSwap(t){return t<<24|(65280&t)<<8|(16711680&t)>>8|t>>>24}decrypt(t,e,i){const s=this.keySize+6,n=this.invKeySchedule,r=this.invSBox,a=this.invSubMix,o=a[0],l=a[1],d=a[2],h=a[3],c=this.uint8ArrayToUint32Array_(i);let u=c[0],f=c[1],g=c[2],p=c[3];const m=new Int32Array(t),v=new Int32Array(m.length);let y,E,T,S,b,A,L,I,R,_,k,w,D,x;const P=this.networkToHostOrderSwap;for(;e<m.length;){for(R=P(m[e]),_=P(m[e+1]),k=P(m[e+2]),w=P(m[e+3]),b=R^n[0],A=w^n[1],L=k^n[2],I=_^n[3],D=4,x=1;x<s;x++)y=o[b>>>24]^l[A>>16&255]^d[L>>8&255]^h[255&I]^n[D],E=o[A>>>24]^l[L>>16&255]^d[I>>8&255]^h[255&b]^n[D+1],T=o[L>>>24]^l[I>>16&255]^d[b>>8&255]^h[255&A]^n[D+2],S=o[I>>>24]^l[b>>16&255]^d[A>>8&255]^h[255&L]^n[D+3],b=y,A=E,L=T,I=S,D+=4;y=r[b>>>24]<<24^r[A>>16&255]<<16^r[L>>8&255]<<8^r[255&I]^n[D],E=r[A>>>24]<<24^r[L>>16&255]<<16^r[I>>8&255]<<8^r[255&b]^n[D+1],T=r[L>>>24]<<24^r[I>>16&255]<<16^r[b>>8&255]<<8^r[255&A]^n[D+2],S=r[I>>>24]<<24^r[b>>16&255]<<16^r[A>>8&255]<<8^r[255&L]^n[D+3],v[e]=P(y^u),v[e+1]=P(S^f),v[e+2]=P(T^g),v[e+3]=P(E^p),u=R,f=_,g=k,p=w,e+=4}return v.buffer}}class Vi{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 ji: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 Hi{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,n){return this.decryptRange=n,this.useSoftware||n?new Promise((n,r)=>{const a=ArrayBuffer.isView(t)?t:new Uint8Array(t);this.softwareDecrypt(a,e,i,s);const o=this.flush();o?n(o.buffer):r(new Error("[softwareDecrypt] Failed to decrypt data"))}):this.webCryptoDecrypt(new Uint8Array(t),e,i,s)}softwareDecrypt(t,e,i,s){const{currentIV:n,currentResult:r,remainderData:a}=this;if(s!==Gi||16!==e.byteLength)return H.warn("SoftwareDecrypt: can only handle AES-128-CBC"),null;this.logOnce("JS AES decrypt"),a&&(t=Vt(a,t),this.remainderData=null);const o=this.getValidChunk(t);if(!o.length)return null;n&&(i=n);let l=this.softwareDecrypter;l||(l=this.softwareDecrypter=new Ki),l.expandKey(e);const d=r;return this.currentResult=l.decrypt(o.buffer,0,i),this.currentIV=o.slice(-16).buffer,d||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 Vi(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 qi(this.subtle,new Uint8Array(i),s).decrypt(t.buffer,e)}).catch(n=>(H.warn(`[decrypter]: WebCrypto Error, disable WebCrypto API, ${n.name}: ${n.message}`),this.onWebCryptoError(t,e,i,s)))}onWebCryptoError(t,e,i,s){const n=this.enableSoftwareAES;if(n){this.useSoftware=!0,this.logEnabled=!0,this.softwareDecrypt(t,e,i,s);const n=this.flush();if(n)return n.buffer}throw new Error("WebCrypto"+(n?" 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&&(H.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 Ji({type:n.NETWORK_ERROR,details:r.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,d=o.loader;return new Promise((h,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 d(o),f=zi(t,null,e);t.loader=u;const g=M(o.fragLoadPolicy.default),p={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 m={onSuccess:(e,i,s,n)=>{this.resetLoader(t,u);let r=e.data;s.resetIV&&t.decryptdata&&(t.decryptdata.iv=new Uint8Array(r.slice(0,16)),r=r.slice(16)),h({frag:t,part:null,payload:r,networkDetails:n})},onError:(e,i,s,o)=>{this.resetLoader(t,u),c(new Ji({type:n.NETWORK_ERROR,details:r.FRAG_LOAD_ERROR,fatal:!1,frag:t,response:_({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 Ji({type:n.NETWORK_ERROR,details:r.INTERNAL_ABORTED,fatal:!1,frag:t,error:new Error("Aborted"),networkDetails:s,stats:e}))},onTimeout:(e,i,s)=>{this.resetLoader(t,u),c(new Ji({type:n.NETWORK_ERROR,details:r.FRAG_LOAD_TIMEOUT,fatal:!1,frag:t,error:new Error(`Timeout after ${p.timeout}ms`),networkDetails:s,stats:e}))}};if(i){const e=this.gateProgress(i,s);m.onProgress=(i,s,n,r)=>e({frag:t,part:null,payload:n,networkDetails:r})}u.load(f,p,m)})}gateProgress(t,e){let i=t;if(e){const s=[];let n=!1;e.then(()=>{n=!0,s.forEach(e=>t(e)),s.length=0}).catch(()=>{}),i=e=>{n?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,d)=>{if(this.loader&&this.loader.destroy(),t.gap||e.gap)return void d(Qi(t,e));const h=this.loader=a?new a(s):new o(s),c=zi(t,e);t.loader=h;const u=M(s.fragLoadPolicy.default),f={loadPolicy:u,timeout:u.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:Yi};e.stats=h.stats,h.load(c,f,{onSuccess:(s,n,r,a)=>{this.resetLoader(t,h),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,h),d(new Ji({type:n.NETWORK_ERROR,details:r.FRAG_LOAD_ERROR,fatal:!1,frag:t,part:e,response:_({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,h),d(new Ji({type:n.NETWORK_ERROR,details:r.INTERNAL_ABORTED,fatal:!1,frag:t,part:e,error:new Error("Aborted"),networkDetails:a,stats:i}))},onTimeout:(i,s,a)=>{this.resetLoader(t,h),d(new Ji({type:n.NETWORK_ERROR,details:r.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,n=s.total;if(i.loaded+=s.loaded,n){const s=Math.round(t.duration/e.duration),r=Math.min(Math.round(i.loaded/n),s),a=(s-r)*Math.round(i.loaded/r);i.total=i.loaded+a}else i.total=Math.max(i.loaded,i.total);const r=i.loading,a=s.loading;r.start?r.first+=a.first-a.start:(r.start=a.start,r.first=a.first),r.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,n={type:u.MEDIA_FRAGMENT,frag:t,part:e,responseType:"arraybuffer",url:s.url,headers:{},rangeStart:0,rangeEnd:0},r=Xi(t,e,i);return r.resetIV&&(n.resetIV=!0),r.byteRange&&(n.rangeStart=r.byteRange.start,n.rangeEnd=r.byteRange.end),n}function Xi(t,i=null,s){const n={},r=i||t,a=r.byteRangeStartOffset,o=r.byteRangeEndOffset;var l,d;if(e(a)&&e(o))if("initSegment"!==t.sn&&!s||"AES-128"!==(d=null==(l=t.decryptdata)?void 0:l.method)&&"AES-256"!==d)n.byteRange={start:a,end:o};else{let t=16*Math.floor(a/16);const e=16*Math.ceil(o/16);n.decryptRange={start:a-t,end:o-t},t>=16&&(n.resetIV=!0,t-=16),n.byteRange={start:t,end:e}}return n}function Qi(t,e){const i=new Error(`GAP ${t.gap?"tag":"attribute"} found`),s={type:n.MEDIA_ERROR,details:r.FRAG_GAP,fatal:!1,frag:t,error:i,networkDetails:null};return e&&(s.part=e),(e||t).stats.aborted=!0,new Ji(s)}class Ji extends Error{constructor(t){super(t.error.message),this.data=void 0,this.data=t}}class Zi 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,n=-1,r=!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=n,this.partial=r,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),n=null==i?void 0:i[s];return void 0===n?(t.playlistParsingError||(t.playlistParsingError=new Error(`Missing preceding EXT-X-DEFINE tag for Variable Reference: "${s}"`)),e):n})}return e}function ns(t,e,i){let s,n,r=t.variableList;if(r||(t.variableList=r={}),"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}"`);n=t.get(s)}catch(e){t.playlistParsingError||(t.playlistParsingError=new Error(`EXT-X-DEFINE QUERYPARAM: ${e.message}`))}}else s=e.NAME,n=e.VALUE;s in r?t.playlistParsingError||(t.playlistParsingError=new Error(`EXT-X-DEFINE duplicate Variable Name declarations: "${s}"`)):r[s]=n||""}function rs(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 n=i[1].trim();let r=i[2];const a=0===r.indexOf('"')&&r.lastIndexOf('"')===r.length-1;let o=!1;if(a)r=r.slice(1,-1);else switch(n){case"IV":case"SCTE35-CMD":case"SCTE35-IN":case"SCTE35-OUT":o=!0}if(e&&(a||o))r=ss(e,r);else if(!o&&!a)switch(n){case"CLOSED-CAPTIONS":if("NONE"===r)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":H.warn(`${t}: attribute ${n} is missing quotes`)}s[n]=r}return s}}function ds(t){return"ID"!==t&&"CLASS"!==t&&"CUE"!==t&&"START-DATE"!==t&&"DURATION"!==t&&"END-DATE"!==t&&"END-ON-NEXT"!==t}function hs(t){return"SCTE35-OUT"===t||"SCTE35-IN"===t||"SCTE35-CMD"===t}class cs{constructor(t,i,s=0){var n;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!=(n=null==i?void 0:i.tagOrder)?n:s,i){const e=i.attr;for(const i in e)if(Object.prototype.hasOwnProperty.call(t,i)&&t[i]!==e[i]){H.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?(H.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 ps(t){switch(t){case"AES-128":case"AES-256":return Gi;case"AES-256-CTR":return ji;default:throw new Error(`invalid full segment method ${t}`)}}function ms(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],n=s[1];e?(t.splice(-1,1),i=vt(n)):i=function(t){const e=ms(t).subarray(0,16),i=new Uint8Array(16);return i.set(e,16-e.length),i}(n)}}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 _s(t){switch(t){case Ts.FAIRPLAY:return bs;case Ts.PLAYREADY:return As;case Ts.WIDEVINE:return Ls;case Ts.CLEARKEY:return Ss}}function ks(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 ws=null!=Es&&null!=(Ds=Es.navigator)&&Ds.requestMediaKeySystemAccess?self.navigator.requestMediaKeySystemAccess.bind(self.navigator):null;var Ds;function xs(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 Ps={};class Cs{static clearKeyUriToKeyIdMap(){Ps={}}static setKeyIdForUri(t,e){Ps[t]=e}static addKeyIdForUri(t){const e=Object.keys(Ps).length%Number.MAX_SAFE_INTEGER,i=new Uint8Array(16);return new DataView(i.buffer,12,4).setUint32(0,e),Ps[t]=i,i}constructor(t,e,i,s=[1],n=null,r){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=n,this.encrypted=!!t&&"NONE"!==t,this.isCommonEncryption=this.encrypted&&!gs(t),null!=r&&r.startsWith("0x")&&(this.keyId=new Uint8Array(mt(r)))}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&&(H.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 Cs(this.method,this.uri,"identity",this.keyFormatVersions,e)}if(this.keyId){const t=Ps[this.uri];if(t&&!us(this.keyId,t)&&Cs.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 n;const e=t[0];this.keyId=null!=(n=e.kids)&&n.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=xs(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=Ps[this.uri])),t&&(this.keyId=t,Cs.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 xs(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 h.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 n;for(;null!=(n=Os.exec(t));)if(n[1]){const t=Gs(new ls(n[1],i),n[2],e,i,s);t&&i.levels.push(t)}else if(n[3]){const t=n[3],r=n[4];switch(t){case"I-FRAME-STREAM-INF":{const t=new ls(r,i),n=Gs(t,t.URI,e,i,s,!0);n&&i.iframeVariants.push(n)}break;case"SESSION-DATA":{const t=new ls(r,i),e=t["DATA-ID"];e&&(null===i.sessionData&&(i.sessionData={}),i.sessionData[e]=t);break}case"SESSION-KEY":{const t=Ks(r,e,i);t.encrypted&&t.isSupported()?(null===i.sessionKeys&&(i.sessionKeys=[]),i.sessionKeys.push(t)):H.warn(`[Keys] Ignoring invalid EXT-X-SESSION-KEY tag: "${r}"`);break}case"DEFINE":ns(i,new ls(r,i),e);break;case"CONTENT-STEERING":{const t=new ls(r,i);i.contentSteering={uri:Us.resolve(t["SERVER-URI"],e),pathwayId:t["PATHWAY-ID"]||"."};break}case"START":i.startTimeOffset=Vs(r)}}const r=s.length>0&&s.length<i.levels.length;return i.levels=r?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 n={},r=i.levels,a={AUDIO:r.map(t=>({id:t.attrs.AUDIO,audioCodec:t.audioCodec})),SUBTITLES:r.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),r=t.TYPE;if(r){const i=a[r],s=n[r]||[];n[r]=s;const l=t.LANGUAGE,d=t["ASSOC-LANGUAGE"],h=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:r,default:t.bool("DEFAULT"),autoselect:t.bool("AUTOSELECT"),forced:t.bool("FORCED"),lang:l,url:t.URI?Us.resolve(t.URI,e):""};if(d&&(f.assocLang=d),h&&(f.channels=h),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 n}static parseLevelPlaylist(t,i,s,n,r,a){var o;const l={url:i},d=new vi(i),h=d.fragments,c=[];let u,f,g,p,m=null,v=0,y=0,E=0,T=0,A=0,L=null,R=new S(n,l),_=-1,k=!1,w=null;if($s.lastIndex=0,d.m3u8=t,d.hasVariableRefs=is(t),"#EXTM3U"!==(null==(o=$s.exec(t))?void 0:o[0]))return d.playlistParsingError=new Error("Missing format identifier #EXTM3U"),d;for(;null!==(u=$s.exec(t));){k&&(k=!1,R=new S(n,l),R.playlistOffset=E,R.setStart(E),R.sn=v,R.cc=T,A&&(R.bitrate=A),R.level=s,m&&(R.initSegment=m,m.rawProgramDateTime&&(R.rawProgramDateTime=m.rawProgramDateTime,m.rawProgramDateTime=null),w&&(R.setByteRange(w),w=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 D;R.playlistOffset=E,R.setStart(E),g&&Xs(R,g,d),R.sn=v,R.level=s,R.cc=T;const t=(" "+u[3]).slice(1);R.relurl=ss(d,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),d.iframesOnly&&e[0]&&(null==(D=m)?void 0:D.cc)!==T){const t=new S(n,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))),m=t,R.initSegment=m}h.push(R),k=!0}}else{if(u=u[0].match(Bs),!u){H.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),r=(" "+u[f+1]).slice(1),o=u[f+2]?(" "+u[f+2]).slice(1):null;switch(t){case"BYTERANGE":L?R.setByteRange(r,L):R.setByteRange(r);break;case"PROGRAM-DATE-TIME":R.rawProgramDateTime=r,R.tagList.push(["PROGRAM-DATE-TIME",r]),-1===_&&(_=h.length);break;case"PLAYLIST-TYPE":d.type&&Qs(d,t,u),d.type=r.toUpperCase();break;case"MEDIA-SEQUENCE":0!==d.startSN?Qs(d,t,u):null!==L&&Js(d,t,u),d.startSN=parseInt(r),v=d.startSN+d.skippedSegments;break;case"SKIP":{d.skippedSegments&&Qs(d,t,u);const i=new ls(r,d),s=i.decimalInteger("SKIPPED-SEGMENTS");if(e(s)){d.skippedSegments+=s;for(let t=s;t--;)h.push(null);v+=s}const n=i.enumeratedString("RECENTLY-REMOVED-DATERANGES");n&&(d.recentlyRemovedDateranges=(d.recentlyRemovedDateranges||[]).concat(n.split("\t")));break}case"TARGETDURATION":0!==d.targetduration&&Qs(d,t,u),d.targetduration=Math.max(parseInt(r),1);break;case"VERSION":null!==d.version&&Qs(d,t,u),d.version=parseInt(r);break;case"INDEPENDENT-SEGMENTS":break;case"I-FRAMES-ONLY":d.iframesOnly=!0;break;case"ENDLIST":d.live||Qs(d,t,u),d.live=!1;break;case"#":(r||o)&&R.tagList.push(o?[r,o]:[r]);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,r]),A=1e3*parseInt(r),e(A)?R.bitrate=A:A=0;break;case"DATERANGE":{const t=new ls(r,d),e=new cs(t,d.dateRanges[t.ID],d.dateRangeTagCount);d.dateRangeTagCount++,e.isValid||d.skippedSegments?d.dateRanges[e.id]=e:H.log(`Ignoring invalid DATERANGE tag: ${e.invalidReason}: ${r}`),R.tagList.push(["EXT-X-DATERANGE",r]);break}case"DEFINE":{const t=new ls(r,d);"IMPORT"in t?rs(d,t,a):ns(d,t,i)}break;case"DISCONTINUITY-SEQUENCE":0!==d.startCC&&Qs(d,t,u),d.startCC=T=parseInt(r),h.forEach(t=>t&&(t.cc=T));break;case"KEY":{const t=Ks(r,i,d);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 H.warn(`[Keys] Ignoring unsupported EXT-X-KEY tag: "${r}"`);break}case"START":d.startTimeOffset=Vs(r);break;case"MAP":{const t=new ls(r,d);if(R.duration){const e=new S(n,l);zs(e,t,s,g),m=e,R.initSegment=m,m.rawProgramDateTime&&!R.rawProgramDateTime&&(R.rawProgramDateTime=m.rawProgramDateTime)}else{const e=R.byteRangeEndOffset;if(e){const t=R.byteRangeStartOffset;w=`${e-t}@${t}`}else w=null;zs(R,t,s,g),m=R,k=!0}m.cc=T;break}case"SERVER-CONTROL":p&&Qs(d,t,u),p=new ls(r),d.canBlockReload=p.bool("CAN-BLOCK-RELOAD"),d.canSkipUntil=p.optionalFloat("CAN-SKIP-UNTIL",0),d.canSkipDateRanges=d.canSkipUntil>0&&p.bool("CAN-SKIP-DATERANGES"),d.partHoldBack=p.optionalFloat("PART-HOLD-BACK",0),d.holdBack=p.optionalFloat("HOLD-BACK",0);break;case"PART-INF":{d.partTarget&&Qs(d,t,u);const e=new ls(r);d.partTarget=e.decimalFloatingPoint("PART-TARGET");break}case"PART":{let t=d.partList;t||(t=d.partList=[]);const e=y>0?t[t.length-1]:void 0,i=y++,s=new ls(r,d),n=new b(s,R,l,i,e);t.push(n),R.duration+=n.duration;break}case"PRELOAD-HINT":{const t=new ls(r,d);d.preloadHint=t;break}case"RENDITION-REPORT":{const t=new ls(r,d);d.renditionReports=d.renditionReports||[],d.renditionReports.push(t);break}default:H.warn(`line parsed but not handled: ${u}`)}}}L&&!L.relurl?(h.pop(),E-=L.duration,d.partList&&(d.fragmentHint=L)):d.partList&&(Ws(R,L,c),R.cc=T,d.fragmentHint=R,g&&Xs(R,g,d)),d.targetduration||(d.playlistParsingError=new Error("Missing Target Duration"));const x=h.length,P=h[0],C=h[x-1];if(E+=d.skippedSegments*d.targetduration,E>0&&x&&C){d.averagetargetduration=E/x;const t=C.sn;d.endSN="initSegment"!==t?t:0,d.live||(C.endList=!0),_>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}}(h,_,_>x-1?R:null),P&&c.unshift(P))}return d.fragmentHint&&(E+=d.fragmentHint.duration),d.totalduration=E,c.length&&d.dateRangeTagCount&&P&&js(c,d),d.endCC=T,d}}function Gs(t,e,i,s,n,r){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)},d=t.decimalResolution("RESOLUTION");d&&(l.width=d.width,l.height=d.height),Hs(t.CODECS,l);const h=t["SUPPLEMENTAL-CODECS"];return h&&(l.supplemental={},Hs(h,l.supplemental)),null!=(a=l.unknownCodecs)&&a.length||n.push(l),r&&(l.iframes=!0),l}function js(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],n=e.live?1/0:e.totalduration,r=Object.keys(e.dateRanges);for(let o=r.length;o--;){const l=e.dateRanges[r[o]],d=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=qs(e,d,t,s,n);if(i){l.tagAnchor=i.ref;break}}}}function qs(t,e,i,s,n){const r=i[s];if(r){const o=r.programDateTime;if(e>=o||0===s){var a;if(e<=o+1e3*(((null==(a=i[s+1])?void 0:a.start)||n)-r.start)){const n=r.sn-t.startSN,a=t.fragments;if(n>=0&&n<a.length){if(a.length>i.length){const r=i[s+1]||a[a.length-1];for(let i=Math.min(r.sn-t.startSN,a.length-1);i>n;i--){const t=a[i].programDateTime;if(e>=t&&e<t+1e3*a[i].duration)return a[i]}}return a[n]}}}}return null}function Ks(t,e,i){var s,n;const r=new ls(t,i),a=null!=(s=r.METHOD)?s:"",o=r.URI,l=r.hexadecimalInteger("IV"),d=r.KEYFORMATVERSIONS,h=null!=(n=r.KEYFORMAT)?n:"identity";o&&r.IV&&!l&&H.error(`Invalid IV: ${r.IV}`);const c=o?Us.resolve(o,e):"",u=(d||"1").split("/").map(Number).filter(Number.isFinite);return new Cs(a,c,h,u,l,r.KEYID)}function Vs(t){const i=new ls(t).decimalFloatingPoint("TIME-OFFSET");return e(i)?i:null}function Hs(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 Js(t,e,i){t.playlistParsingError=new Error(`#EXT-X-${e} must appear before the first Media Segment (${i[0]})`)}function Zs(t,i){const s=i.startPTS;if(e(s)){let e,n=0;i.sn>t.sn?(n=s-t.start,e=t):(n=t.start-s,e=i),e.duration!==n&&e.setDuration(n)}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 tn(t,i,s,n,r,a,o,l){n-s<=0&&(l.warn("Fragment should have a positive duration",i),n=s+i.duration,a=r+i.duration);let d=s,h=n;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,d=Math.max(s,c),s=Math.min(s,c),r=void 0!==i.startDTS?Math.min(r,i.startDTS):r,h=Math.min(n,u),n=Math.max(n,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(n-i.start),i.startPTS=s,i.maxStartPTS=d,i.startDTS=r,i.endPTS=n,i.minEndPTS=h,i.endDTS=a,en(t,i,f)}function en(t,e,i){var s;const n=e.sn;if(!t||n<t.startSN||n>((null==(s=t.fragmentHint)?void 0:s.sn)||t.endSN))return 0;let r;const a=n-t.startSN,o=t.fragments;for(o[a]=e,r=a;r>0;r--)Zs(o[r],o[r-1]);for(r=a;r<o.length-1;r++)Zs(o[r],o[r+1]);return t.fragmentHint&&Zs(o[o.length-1],t.fragmentHint),t.PTSKnown=t.alignedSliding=!0,i}function sn(t,i,s){if(t===i)return;let n=null;const r=t.fragments;for(let t=r.length-1;t>=0;t--){const e=r[t].initSegment;if(e){n=e;break}}let a;t.fragmentHint&&delete t.fragmentHint.endPTS,function(t,e,i){var s;const n=e.skippedSegments,r=Math.max(t.startSN,e.startSN)-e.startSN,a=(t.fragmentHint?1:0)+(n?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,d=null!=(s=t.fragmentHint)&&s.duration?t.fragments.concat(t.fragmentHint):t.fragments;for(let s=r;s<=a;s++){const r=d[o+s];let a=l[s];if(n&&!a&&r&&(a=e.fragments[s]=r),r&&a){i(r,a,s,l);const n=r.relurl,o=a.relurl;if(n&&cn(n,o))return void(e.playlistParsingError=nn(`media sequence mismatch ${a.sn}:`,t,e,r,a));if(r.cc!==a.cc)return void(e.playlistParsingError=nn(`discontinuity sequence mismatch (${r.cc}!=${a.cc})`,t,e,r,a))}}}(t,i,(t,s,r,o)=>{if(s.cc!==t.cc&&(t.cc>s.cc||i.skippedSegments)){const e=t.cc-s.cc;for(let t=r;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,n=t.initSegment)});const o=i.fragments,l=i.fragmentHint?o.concat(i.fragmentHint):o;if(n&&l.forEach(t=>{var e;!t||t.initSegment&&t.initSegment.relurl!==(null==(e=n)?void 0:e.relurl)||(t.initSegment=n)}),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:n}=e,r=I({},t);n&&n.forEach(t=>{delete r[t]});const a=Object.keys(r).length;if(!a)return s;return Object.keys(s).forEach(t=>{const e=r[t],n=new cs(s[t].attr,e);n.isValid?(r[t]=n,e||(n.tagOrder+=a)):i.warn(`Ignoring invalid Playlist Delta Update DATERANGE tag: "${Ue(s[t].attr)}"`)}),r}(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);js(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 d;const e=on(t,i.startSN-1);i.startCC=null!=(d=null==e?void 0:e.cc)?d:o[0].cc}if(function(t,e,i){if(t&&e){let s=0;for(let n=0,r=t.length;n<r;n++){const r=t[n],a=e[n+s];r&&a&&r.index===a.index&&r.fragment.sn===a.fragment.sn?i(r,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);tn(i,a,a.startPTS,a.endPTS,a.startDTS,a.endDTS,0,s)}else rn(t,i);o.length&&(i.totalduration=i.edge-o[0].start),i.driftStartTime=t.driftStartTime,i.driftStart=t.driftStart;const h=i.advancedDateTime;if(i.advanced&&h){const t=i.edge;i.driftStart||(i.driftStartTime=h,i.driftStart=t),i.driftEndTime=h,i.driftEnd=t}else i.driftEndTime=t.driftEndTime,i.driftEnd=t.driftEnd,i.advancedDateTime=t.advancedDateTime;-1===i.requestScheduled&&(i.requestScheduled=t.requestScheduled)}function nn(t,e,i,s,n){return new Error(`${t} ${n.url}\nPlaylist starting @${e.startSN}\n${e.m3u8}\n\nPlaylist starting @${i.startSN}\n${i.m3u8}`)}function rn(t,e,i=!0,s){const n=e.startSN+e.skippedSegments-t.startSN,r=t.fragments,a=n>=0;let o=0;if(a&&n<r.length)o=r[n].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+n*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 an(t,e=1/0){let i=1e3*t.targetduration;if(t.updated){const s=t.fragments,n=4;if(s.length&&i*n>e){const t=1e3*s[s.length-1].duration;t>0&&t<i&&(i=t)}}else i/=2;return Math.round(i)}function on(t,e,i){var s;if(!t)return null;let n=t.fragments[e-t.startSN];return n||(n=t.fragmentHint,(null==(s=n)?void 0:s.sn)===e?n:i&&e<t.startSN&&i.sn===e?i:null)}function ln(t,e,i){return t?dn(t.partList,e,i):null}function dn(t,e,i){if(t)for(let s=t.length;s--;){const n=t[s];if(n.index===i&&n.fragment.sn===e)return n}return null}function hn(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 cn(t,e){return!(t===e||!e)&&un(t)!==un(e)}function un(t){return t.replace(/\?[^?]*$/,"")}function fn(t,e){for(let s=0,n=t.length;s<n;s++){var i;if((null==(i=t[s])?void 0:i.cc)===e)return t[s]}return null}function gn(t,e){const i=t.start+e;t.setStart(i)}function pn(t,e){const i=e.fragments;for(let e=0,s=i.length;e<s;e++)gn(i[e],t);e.fragmentHint&&gn(e.fragmentHint,t),e.alignedSliding=!0}function mn(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),n=fn(e.fragments,s),r=fn(t.fragments,s);if(!n||!r)return;const a=n.start-r.start;i.log(`Aligning playlists using dicontinuity sequence ${s} (diff: ${a})`),pn(a,t)}(e,t,i),e.alignedSliding||function(t,e,i){if(!t.hasProgramDateTime||!e.hasProgramDateTime)return;const s=t.fragments,n=e.fragments;if(!s.length||!n.length)return;let r,a;const o=Math.min(e.endCC,t.endCC);e.startCC<o&&t.startCC<o&&(r=fn(n,o),a=fn(s,o));r&&a||(r=n[Math.floor(n.length/2)]||n.filter(t=>!!t)[0],a=fn(s,r.cc)||s[Math.floor(s.length/2)]);const l=r.programDateTime,d=a.programDateTime;if(!l||!d)return;const h=(d-l)/1e3;if(Math.abs(h)>Math.max(60,t.totalduration))return void i.log(`Cannot align playlists using PDT without overlap (${Math.abs(h)} > ${t.totalduration})`);const c=h-(a.start-r.start);i.log(`Aligning playlists using PDT (diff: ${c})`),pn(c,t)}(e,t,i),e.alignedSliding||e.skippedSegments||rn(t,e,!1,i))}const vn="STOPPED",yn="IDLE",En="KEY_LOADING",Tn="FRAG_LOADING",Sn="FRAG_LOADING_WAITING_RETRY",bn="WAITING_TRACK",An="PARSING",Ln="PARSED",In="ENDED",Rn="ERROR",_n="WAITING_INIT_PTS",kn="WAITING_LEVEL";class wn extends Zi{constructor(t,e,i,s,n){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=vn,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:n}=this,r=i?i.currentTime:0,a=Ei.bufferInfo(s||i,r,t.maxBufferHole),o=a.len;if(this.log(`Media seeking to ${r}, state: ${n}, ${o?"in":"out of"} buffer`),this.state===In)this.resetLoadingState();else if(e){const i=t.maxFragLookUpTolerance,s=e.start-i,n=e.start+e.duration+i;if(!o||n<a.start||s>a.end){const t=r<s,i=r>n;(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&&r!==this.startPosition&&this.fragmentTracker.removeFragmentsInRange(r,1/0,this.playlistType,!0);if(r>this.lastCurrentTime&&(this.lastCurrentTime=r),!this.loadingParts){const t=Math.max(a.end,r),e=this.shouldLoadParts(this.getLevelDetails(),t);e&&(this.log(`LL-Part loading ON after seeking to ${r} with buffer @${t}`),this.loadingParts=e)}}const d=!Ei.isBuffered(i,r);this.hls.hasEnoughToStart&&!d||(this.log(`Setting ${d?"startPosition":"nextLoadPosition"} to ${r} for seek without enough to start`),this.nextLoadPosition=r,d?this.startPosition=r:this.lastCurrentTime=r),o<1&&this.state===yn&&this.tickImmediate()},this.onMediaEnded=()=>{this.log("setting startPosition to 0 because media ended"),this.startPosition=this.nextLoadPosition=this.lastCurrentTime=0},this.playlistType=n,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 Hi(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===vn)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=vn}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 n=t.buffered;this.config.maxBufferHole&&n&&n.length>1&&(t=Ei.bufferedInfo(n,t.start,0));const r=t.nextStart;if(r&&r>s&&r<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===vn&&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:n}=this,r=n.gapFragments();n.removeAllFragments(),r.forEach(t=>n.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=vn,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===Tn||!this.fragCurrent&&e===An)&&(this.fragmentTracker.removeFragment(i),this.state=yn):("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!==vn&&this.state!==Rn&&(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),n=Math.max(t.duration,s?s.len:this.config.maxBufferLength),r=this.backtrackFragment;(1===(r?t.sn-r.sn:0)||this.reduceMaxBufferLength(n,t.duration))&&i.removeFragment(t)}else 0===(null==(e=this.mediaBuffer)?void 0:e.buffered.length)?i.removeAllFragments():i.hasParts(t.type)&&(i.detectPartialFragments({frag:t,part:null,stats:t.stats,id:t.type}),i.getState(t)===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 Ji({type:n.NETWORK_ERROR,details:r.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:d}=Xi(i,null,this.iframesOnly);return this.decrypter.decrypt(new Uint8Array(s),o.key.buffer,o.iv.buffer,ps(o.method),d).catch(t=>{throw e.trigger(a.ERROR,{type:n.MEDIA_ERROR,details:r.FRAG_DECRYPT_ERROR,fatal:!1,error:t,reason:t.message,frag:i}),this.fragmentLoader.abort(),t}).then(s=>{const n=self.performance.now();return e.trigger(a.FRAG_DECRYPTED,{frag:i,part:null,payload:s,stats:{tstart:l,tdecrypt:n}}),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===vn||this.state===Rn)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:n.KEY_SYSTEM_ERROR,details:r.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=yn)}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=yn}_handleFragmentLoadComplete(t){const{transmuxer:e}=this;if(!e)return;const i=t.frag,{part:s,partsLoaded:n}=t,r=!n||0===n.length||n.some(t=>!t),{decryptRange:a}=Xi(i,s),o=new ts(i.level,i.sn,i.stats.chunkCount+1,0,s?s.index:-1,!r,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 n=null;return!t.encrypted||null!=(s=t.decryptdata)&&s.key?t.encrypted||(n=this.keyLoader.loadClear(t,e.encryptedFragments,this.startFragRequested),n&&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=En,n=this.keyLoader.load(t,i).then(t=>{if(!this.fragContextChanged(t.frag))return this.hls.trigger(a.KEY_LOADED,t),this.state===En&&(this.state=yn),t}),this.hls.trigger(a.KEY_LOADING,{frag:t})),n}_doFragLoad(t,i,s=null,n){this.fragCurrent=t;const r=i.details;if(!this.levels||!r)throw new Error(`frag load aborted, missing level${r?"":" 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=r.partList;if(e&&n){s>r.fragmentEnd&&r.fragmentHint&&(t=r.fragmentHint);const l=this.getNextPart(e,t,s);if(l>-1){const d=e[l];if(!E(t=this.fragCurrent=d.fragment,o)&&!this.shouldLoadParts(i.details,t.end))return this.log(`LL-Part loading OFF @${this.playhead} next part: ${this.fragInfo(t,!1,d)}`),this.loadingParts=!1,Promise.resolve(null);if(!this.filterReplacedPrimary(d,i.details))return Promise.resolve(null);const h=this.loadKeyFor(t,r);if(this.fragContextChanged(t))return Promise.resolve(null);let c;this.log(`Loading ${t.type} sn: ${t.sn} part: ${d.index} (${l}/${e.length-1}) of ${this.fragInfo(t,!1,d)} cc: ${t.cc} [${r.startSN}-${r.endSN}], target: ${s}${d.byteRange.length?` range:${d.byteRange.join("-")}`:""}`),this.nextLoadPosition=d.start+d.duration,this.state=Tn;const u=this.loadInitSegmentIfNeeded(t);if(h||u){const e=!!h;c=Promise.all([h,u]).then(([s])=>!e||s&&!this.fragContextChanged(s.frag)?this.doFragPartsLoad(t,d,i,n):null).catch(e=>this.handleFragLoadError(e,t))}else c=this.doFragPartsLoad(t,d,i,n).catch(e=>this.handleFragLoadError(e,t));return this.hls.trigger(a.FRAG_LOADING,{frag:t,part:d,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=r.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 d=this.loadInitSegmentIfNeeded(t),h=this.loadKeyFor(t,r,d);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==d||d.catch(()=>null),null==h||h.catch(()=>null),Promise.resolve(null);this.log(`Loading ${t.type} sn: ${t.sn} of ${this.fragInfo(t,!1)} cc: ${t.cc} ${"["+r.startSN+"-"+r.endSN+"]"}, target: ${s}${t.byteRange.length?` range:${t.byteRange.join("-")}`:""}`),e(t.sn)&&!this.bitrateTest&&(this.nextLoadPosition=t.start+t.duration),this.state=Tn;const u=this.config.progressive&&t.type!==f.SUBTITLE;let g;return g=u&&h?h.then(e=>!e||this.fragContextChanged(e.frag)?null:this.fragmentLoader.load(t,this.iframesOnly,n,d)).catch(e=>this.handleFragLoadError(e,t)):Promise.all([this.fragmentLoader.load(t,this.iframesOnly,u?n:void 0,u?d:void 0),h,d]).then(([t])=>(!u&&n&&n(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,d]).then(([t])=>t)}doFragPartsLoad(t,e,i,s){return new Promise((n,r)=>{var o;const l=[],d=null==(o=i.details)?void 0:o.partList,h=e=>{this.fragmentLoader.loadPart(t,e,s).then(s=>{l[e.index]=s;const r=s.part;this.hls.trigger(a.FRAG_LOADED,s);const o=ln(i.details,t.sn,e.index+1)||dn(d,t.sn,e.index+1);if(!o)return n({frag:t,part:r,partsLoaded:l});h(o)}).catch(r)};h(e)})}handleFragLoadError(t,e){if("data"in t){const i=t.data;i.details===r.INTERNAL_ABORTED?this.handleFragLoadAborted(e,i.part):i.type!==n.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,_(_({},i),{},{frag:e}))):this.hls.trigger(a.ERROR,i)}else this.hls.trigger(a.ERROR,{type:n.OTHER_ERROR,details:r.INTERNAL_EXCEPTION,err:t,error:t,fatal:!0});return null}_handleTransmuxerFlush(t){const e=this.getCurrentContext(t);if(!e||this.state!==An)return void(this.fragCurrent||this.state===vn||this.state===Rn||(this.state=yn));const{frag:i,part:s,level:n}=e,r=self.performance.now();i.stats.parsing.end=r,s&&(s.stats.parsing.end=r);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,n,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:n,part:r}=t;if(null==e||!e[s])return this.warn(`Levels object was unset while buffering fragment ${n} of ${this.playlistLabel()} ${s}. The current chunk will not be buffered.`),null;const a=e[s],o=a.details,l=r>-1?ln(o,n,r):null,d=l?l.fragment:on(o,n,i);return d?(i&&i!==d&&(d.stats=i.stats),{frag:d,part:l,level:a}):null}bufferFragmentData(t,e,i,s,n){if(this.state!==An)return;y(e)&&!this.fragContextChanged(e)&&(this.fragPrevious=e);const{data1:r,data2:o}=t;let l=r;if(o&&(l=Vt(r,o)),!l.length)return;const d=this.initPTS[e.cc],h=d?-d.baseTime/d.timescale:void 0,c={type:t.type,frag:e,part:i,chunkMeta:s,offset:h,parent:e.type,data:l};if(this.hls.trigger(a.BUFFER_APPENDING,c),t.dropped&&t.independent&&!i){if(n)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),n=t.duration,r=Math.min(2*this.config.maxFragLookUpTolerance,.25*n),a=Math.max(Math.min(t.start-r,s.end-r),i+r);t.start-a>r&&this.flushMainBuffer(a,t.start)}getFwdBufferInfo(t,e){var i;const s=this.playhead,n=this.lastCurrentTime>s||null!=(i=this.media)&&i.paused?0:this.config.maxBufferHole;return this.getFwdBufferInfoAtPos(t,s,e,n)}getFwdBufferInfoAtPos(t,e,i,s){const n=Ei.bufferInfo(t,e,s);if(0===n.len&&void 0!==n.nextStart){const r=this.fragmentTracker.getBufferedFrag(e,i);if(r&&(n.nextStart<=r.end||r.gap)){const i=Math.max(Math.min(n.nextStart,r.end)-e,s);return Ei.bufferInfo(t,e,i)}}return n}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 n=t.len;const r=t.bufferedIndex;for(let t=s.length-1;t>r;t--)s[t].start<i.start&&(n+=s[t].end-s[t].start);return n>=e}}return!1}reduceMaxBufferLength(t,e){const i=this.config,s=Math.max(Math.min(t-e,i.maxBufferLength),e/2),n=Math.max(t-3*e,i.maxMaxBufferLength/2,s);return n>=s&&(i.maxMaxBufferLength=n,this.warn(`Reduce max buffer length to ${n}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:n}=this,r=e.fragmentStart,a=n.lowLatencyMode&&!!e.partList;let o=null;if(e.live){const i=n.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<r){var l;o=this.getInitialLiveFragment(e);const i=this.config.startPosition,s=this.hls.startPosition,n=this.hls.liveSyncPosition,a=(null==(l=o)?void 0:l.start)||0;let d,h;if(-1!==s&&s>=r?(d=s,h=s===i?"config":"next load start"):n?(d=n,h="live edge"):(d=t,h="buffer pos"),d<a&&(d=a,h="live frag start"),d<r&&(d=r,h="playlist start"),this.startPosition!=d||this.nextLoadPosition!=d){const l=e.live&&!this.filterReplacedPrimary(o,e)?-1:d;this.log(`Setting startPosition to ${l} next load ${d} ${-1===s?"":`(from ${i}) `}based on ${h}. live edge: ${n} live frag start: ${a} playlist start: ${r} buffer pos: ${t}`),this.startPosition=l,this.nextLoadPosition=d}}}else t<=r&&(o=i[0]);if(!o){const i=this.loadingParts?e.partEnd:e.fragmentEnd;o=this.getFragmentAtPosition(t,i,e)}let d=this.filterReplacedPrimary(o,e);return!d&&o&&(d=si(e,o.sn),d&&(this.nextLoadPosition=d.start)),d}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,n){let r=null;if(t.gap&&(r=this.getNextFragment(this.nextLoadPosition,e),r&&!r.gap&&i.nextStart)){const t=this.getFwdBufferInfoAtPos(this.mediaBuffer?this.mediaBuffer:this.media,i.nextStart,s,0);if(null!==t&&i.len+t.len>=n){const t=r.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,r}get primaryPrefetch(){if(xn(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(xn(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(Dn(t,null==i?void 0:i.playerQueue,this.playhead))return null}return t}getNextPart(t,e,i){let s=-1,n=!1,r=!0;for(let a=0,o=t.length;a<o;a++){const o=t[a];if(r=r&&!o.independent,s>-1&&i<o.start)break;const l=o.loaded||o.gap;l?s=-1:(n||(o.independent||r)&&o.fragment===e)&&(s=a),n=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 n=null;if(s){if(t.hasProgramDateTime&&(n=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 n=t[e];if(ei(i,s,n))return n}return null}(i,s.endProgramDateTime,this.config.maxFragLookUpTolerance),n&&this.log(`Live playlist, switching playlist, load frag with same PDT: ${s.programDateTime}`)),!n){const e=s.sn+1;if(e>=t.startSN&&e<=t.endSN){const r=i[e-t.startSN];s.cc===r.cc&&(n=r,this.log(`Live playlist, switching playlist, load frag with next SN: ${n.sn}`))}n||(n=ii(t,s.cc,s.end),n&&this.log(`Live playlist, switching playlist, load frag with same CC: ${n.sn}`))}}else{const e=this.hls.liveSyncPosition;null!==e&&(n=this.getFragmentAtPosition(e,this.bitrateTest?t.fragmentEnd:t.edge,t))}return n}getFragmentAtPosition(t,e,i){const{config:s}=this;let{fragPrevious:n}=this,{fragments:r,endSN:a}=i;const{fragmentHint:o}=i,{maxFragLookUpTolerance:l}=s,d=i.partList,h=!!(this.loadingParts&&null!=d&&d.length&&o);let c;if(h&&!this.bitrateTest&&d[d.length-1].fragment.sn===o.sn&&(r=r.concat(o),a=o.sn),n&&this.fragmentTracker.getState(n)===Ci&&(n=null),t<e){var u;c=Ze(n,r,t,t<this.lastCurrentTime||t>e-l||null!=(u=this.media)&&u.paused||this.loadingParts||!this.startFragRequested?0:l)}else c=r[r.length-1];if(c){const t=c.sn,e=t-i.startSN,s=this.fragmentTracker.getState(c);if((s===Fi||s===Oi&&c.gap)&&(n=c),E(c,n)&&(!h||d[0].fragment.sn>t||!i.live||!d.some(e=>e.fragment.sn===t&&!e.loaded&&!e.gap))){const t=r[e+1];c=c.sn<a&&this.fragmentTracker.getState(t)!==Fi?t:null}}return c}alignPlaylists(t,i,s){const n=t.fragments.length;if(!n)return this.warn("No fragments in live playlist"),0;const r=t.fragmentStart,a=!i,o=t.alignedSliding&&e(r);if(a||!o&&!r){mn(s,t,this);const e=t.fragmentStart;return this.log(`Live playlist sliding: ${e} start-sn: ${i?i.startSN:"na"}->${t.startSN} fragments: ${n}`),e}return r}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 n=this.timelineOffset;if(-1===s){const r=null!==this.startTimeOffset,a=r?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 ${r?"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+n}this.nextLoadPosition=s+n}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!==vn&&(this.fragCurrent&&(this.fragContextChanged(t)||this.state===Sn)||(this.state=yn))}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 n;if(this.fragContextChanged(i))return void this.warn(`Frag load error must match current frag to retry ${i.relurl} > ${null==(n=this.fragCurrent)?void 0:n.relurl}`);const a=e.details===r.FRAG_GAP;a&&this.fragmentTracker.addAsGap(i);const o=e.errorAction;if(!o)return void(this.state=Rn);const{action:l,flags:d,retryCount:h=0,retryConfig:c}=o,u=!!c,f=u&&l===oi,g=u&&!o.resolved&&d&di,p=this.hls.latestLevelDetails,m=null==p?void 0:p.live;if(!f&&g&&y(i)&&m&&i.sn<p.endSN&&!x(e))this.resetFragmentErrors(t),s?s.gap=!0:this.treatAsGap(i),o.resolved=!0;else if((f||g)&&h<c.maxNumRetry){var v;const s=F(null==(v=e.response)?void 0:v.code),n=C(c,h);if(this.resetStartWhenNotLoaded(),this.retryDate=self.performance.now()+n,this.state=Sn,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 ${h+1}/${c.maxNumRetry} in ${n}ms`)}else if(c){if(this.resetFragmentErrors(t),!(h<c.maxNumRetry))return void this.warn(`${e.details} reached or exceeded max retry (${h})`);a||l===ai||(o.resolved=!0)}else this.state=l===ri?kn:Rn;this.tickImmediate()}onSourceBufferError(t,e){var i,s;const{frag:n,part:r,sourceBufferName:a}=e,o=n&&(null==(i=this.levels)||null==(i=i[n.level])?void 0:i.details);if(e.error.name!==Ii||(null==n?void 0:n.type)!==t||!y(n)||null==o||!o.live)return;const l=r?0===r.index?r:null:n,d=l&&a?null==(s=l.elementaryStreams[a])?void 0:s.startPTS:void 0;if(this.markSourceBufferErrorGap(on(o,n.sn)||n),void 0===d)return;const h=on(o,n.sn-1);h&&this.fragmentTracker.getState(h)!==Ci&&!Ei.isBuffered(this.mediaBuffer||this.media,d-this.config.maxBufferHole)&&this.markSourceBufferErrorGap(h)}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=yn)}reduceLengthAndFlushBuffer(t){if(this.state===An||this.state===Ln){const e=t.frag,i=t.parent,s=this.getFwdBufferInfo(this.mediaBuffer,i),n=s&&s.len>.5;n&&this.reduceMaxBufferLength(s.len,(null==e?void 0:e.duration)||10);const r=!n;return r?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(),r}return!1}resetFragmentErrors(t){t===f.AUDIO&&(this.fragCurrent=null),this.hls.hasEnoughToStart||(this.startFragRequested=!1),this.state!==vn&&(this.state=yn)}afterBufferFlushed(t,e){if(!t)return;const i=Ei.getBuffered(t);this.fragmentTracker.detectEvictedFragments(e,i,this.playlistType),this.state===In&&this.resetLoadingState()}resetLoadingState(){this.log("Reset loading state"),this.fragCurrent=null,this.fragPrevious=null,this.state!==vn&&(this.state=yn)}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((n,r)=>{const l=t.elementaryStreams[r];if(l){const d=l.endPTS-l.startPTS;if(d<=0)return this.warn(`Could not parse fragment ${t.sn} ${r} duration reliably (${d})`),n||!1;let h=0;return s.partial?e&&0===s.part&&(h=e.start-l.startPTS,t.startPTS=t.maxStartPTS=l.startPTS,t.startDTS=l.startDTS,0!==t.start&&t.setStart(l.startPTS),en(o,t,h)):h=tn(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:h,type:r,frag:t,part:e,start:l.startPTS,end:l.endPTS}),!0}return n},!1)){var l,d,h,c;const s=null===(null==(l=this.transmuxer)?void 0:l.error),o=null!=(null==(d=this.transmuxer)?void 0:d.error),u=(null!=(h=null==(c=this.levels)?void 0:c.length)?h: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:n.MEDIA_ERROR,details:r.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=Ln,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,n;return`${t.type} playlist ${t.level} (${i?"part":"frag"}:[${null!=(s=e&&!i?t.startPTS:(i||t).start)?s:NaN}-${null!=(n=e&&!i?t.endPTS:(i||t).end)?n: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,n=8*(i.total-i.loaded)/(this.hls.bandwidthEstimate||this.hls.config.abrEwmaDefaultEstimate);return s&&n<=.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:n,config:r,levels:a,playlistType:o}=this,l=this.getLevelDetails();if(n&&!n.paused&&a){var d;const e=o===f.AUDIO?_e(t.audioCodec,128e3):t.maxBitrate,n=1+s.ttfbEstimate/1e3,a=s.bandwidthEstimate*r.abrBandWidthUpFactor;i=n+e*(l&&(this.loadingParts?l.partTarget:l.averagetargetduration)||(null==(d=this.fragCurrent)?void 0:d.duration)||6)/a,t.details||(i+=n)}const h=this.playhead;return{fetchdelay:i,okToFlushForwardBuffer:!(null!=l&&l.live)||e.end-h>1.5*i}}scheduleTrackSwitch(t,e,i){const{media:s,playlistType:n}=this;if(!s||!t)return;const r=i?this.getBufferedFrag(this.playhead+e):null;if(r){const t=this.followingBufferedFrag(r);if(t){var a;this.abortCurrentFrag();const e=t.maxStartPTS?t.maxStartPTS:t.start,i=t.duration,s=Math.max(r.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=n===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 En:case Tn:case Sn:case An:case Ln:this.state=yn}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:n}=this;if(null!=e&&e.readyState&&t&&i&&s){const e=this.getBufferOutput(),s=this.getFwdBufferInfo(e,n);if(!s)return;const r=t[n===f.AUDIO?i.nextAudioTrack:i.nextLoadLevel],{fetchdelay:a,okToFlushForwardBuffer:o}=this.calculateOptimalSwitchPoint(r,s);this.scheduleTrackSwitch(s,a,o)}this.tickImmediate()}}function Dn(t,e,i){if(e)for(let s=e.length;s--;){const n=e[s].interstitial,r=n.startTime,a=Math.min(r+n.duration,n.resumeTime);if(n.appendInPlace){if(t.start>=r&&t.end<=a)return!0;if(i>t.start&&t.end>r&&t.start<a)return!0}}return!1}function xn(t){return!!t.interstitialsController&&!1!==t.enableInterstitialPlayback}class Pn{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 n=t[e];i.set(n,s),s+=n.length}return i}(t,e),this.reset(),i):new Uint8Array(0)}reset(){this.chunks.length=0,this.dataLength=0}}var Cn,Mn={exports:{}};var On=(Cn||(Cn=1,function(t){var e=Object.prototype.hasOwnProperty,i="~";function s(){}function n(t,e,i){this.fn=t,this.context=e,this.once=i||!1}function r(t,e,s,r,a){if("function"!=typeof s)throw new TypeError("The listener must be a function");var o=new n(s,r||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,n=[];if(0===this._eventsCount)return n;for(s in t=this._events)e.call(t,s)&&n.push(i?s.slice(1):s);return Object.getOwnPropertySymbols?n.concat(Object.getOwnPropertySymbols(t)):n},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 n=0,r=s.length,a=new Array(r);n<r;n++)a[n]=s[n].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,n,r,a){var o=i?i+t:t;if(!this._events[o])return!1;var l,d,h=this._events[o],c=arguments.length;if(h.fn){switch(h.once&&this.removeListener(t,h.fn,void 0,!0),c){case 1:return h.fn.call(h.context),!0;case 2:return h.fn.call(h.context,e),!0;case 3:return h.fn.call(h.context,e,s),!0;case 4:return h.fn.call(h.context,e,s,n),!0;case 5:return h.fn.call(h.context,e,s,n,r),!0;case 6:return h.fn.call(h.context,e,s,n,r,a),!0}for(d=1,l=new Array(c-1);d<c;d++)l[d-1]=arguments[d];h.fn.apply(h.context,l)}else{var u,f=h.length;for(d=0;d<f;d++)switch(h[d].once&&this.removeListener(t,h[d].fn,void 0,!0),c){case 1:h[d].fn.call(h[d].context);break;case 2:h[d].fn.call(h[d].context,e);break;case 3:h[d].fn.call(h[d].context,e,s);break;case 4:h[d].fn.call(h[d].context,e,s,n);break;default:if(!l)for(u=1,l=new Array(c-1);u<c;u++)l[u-1]=arguments[u];h[d].fn.apply(h[d].context,l)}}return!0},o.prototype.on=function(t,e,i){return r(this,t,e,i,!1)},o.prototype.once=function(t,e,i){return r(this,t,e,i,!0)},o.prototype.removeListener=function(t,e,s,n){var r=i?i+t:t;if(!this._events[r])return this;if(!e)return a(this,r),this;var o=this._events[r];if(o.fn)o.fn!==e||n&&!o.once||s&&o.context!==s||a(this,r);else{for(var l=0,d=[],h=o.length;l<h;l++)(o[l].fn!==e||n&&!o[l].once||s&&o[l].context!==s)&&d.push(o[l]);d.length?this._events[r]=1===d.length?d[0]:d:a(this,r)}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}(Mn)),Mn.exports),Fn=o(On);const Nn="1.7.4",$n={};function Bn(t,e){return 255===t[e]&&240==(246&t[e+1])}function Un(t,e){return 1&t[e+1]?7:9}function Gn(t,e){return(3&t[e+3])<<11|t[e+4]<<3|(224&t[e+5])>>>5}function jn(t,e){return e+1<t.length&&Bn(t,e)}function qn(t,e){if(jn(t,e)){const i=Un(t,e);if(e+i>=t.length)return!1;const s=Gn(t,e);if(s<=i)return!1;const n=e+s;return n===t.length||jn(t,n)}return!1}function Kn(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:n.MEDIA_ERROR,details:r.FRAG_PARSING_ERROR,fatal:!0,error:e,reason:e.message})}const d=1+(o>>6&3),h=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!==d&&29!==d||(f-=3);const g=(14&f)>>1,p=(1&f)<<7|h<<3;let m=0;if(1===d&&l>=6){m=5;const t=l-3;u=[m<<3|g,p|(14&t)>>1,(1&t)<<7|8,0]}else u=[d<<3|g,p];const v="mp4a.40."+(m||d);return H.log(`manifest codec:${s}, parsed codec:${v}, channels:${h}, rate:${c} (ADTS object type:${d} sampling index:${l} esds config:[${u.join(",")}])`),{config:u,samplerate:c,channelCount:h,codec:v,parsedCodec:v,manifestCodec:s}}(e,i,s,o);if(!l)return;I(t,l)}}function Vn(t){return 9216e4/t}function Hn(t,e,i,s,n){const r=s+n*Vn(t.samplerate),a=function(t,e){const i=Un(t,e);if(e+i<=t.length){const s=Gn(t,e)-i;if(s>0)return{headerLength:i,frameLength:s}}}(e,i);let o;if(a){const{frameLength:s,headerLength:n}=a,l=n+s,d=Math.max(0,i+l-e.length);d?(o=new Uint8Array(l-n),o.set(e.subarray(i+n,e.length),0)):o=e.subarray(i+n,i+l);const h={unit:o,pts:r};return d||t.samples.push(h),{sample:h,length:l,missing:d}}const l=e.length-i;o=new Uint8Array(l),o.set(e.subarray(i,e.length),0);return{sample:{unit:o,pts:r},length:l,missing:-1}}let Yn=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 Wn(t="",e=9e4){return{type:t,id:-1,pid:-1,inputTimeScale:e,sequenceNumber:-1,samples:[],dropped:0}}class zn{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=Vt(this.cachedData,t),this.cachedData=null);let s,n=rt(t,0),r=n?n.length:0;const a=this._audioTrack,o=this._id3Track,l=n?gt(n):void 0,d=t.length;for((null===this.basePTS||0===this.frameIndex&&e(l))&&(this.basePTS=Xn(l,i,this.initPTS),this.lastPTS=this.basePTS),null===this.lastPTS&&(this.lastPTS=this.basePTS),n&&n.length>0&&o.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:n,type:Yn.audioId3,duration:Number.POSITIVE_INFINITY});r<d;){if(this.canParse(t,r)){const e=this.appendFrame(a,t,r);e?(this.frameIndex++,this.lastPTS=e.sample.pts,r+=e.length,s=r):r=d}else st(t,r)?(n=rt(t,r),o.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:n,type:Yn.audioId3,duration:Number.POSITIVE_INFINITY}),r+=n.length,s=r):r++;if(r===d&&s!==d){const e=t.slice(s);this.cachedData?this.cachedData=Vt(this.cachedData,e):this.cachedData=e}}return{audioTrack:a,videoTrack:Wn(),id3Track:o,textTrack:Wn()}}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:Wn(),id3Track:this._id3Track,textTrack:Wn()}}destroy(){this.cachedData=null,this._audioTrack=this._id3Track=void 0}}const Xn=(t,i,s)=>{if(e(t))return 90*t;return 9e4*i+(s?9e4*s.baseTime/s.timescale:0)},Qn=[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],Jn=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],Zn=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],tr=[0,1,1,4];function er(t,e,i,s,n){if(i+24>e.length)return;const r=ir(e,i);if(r&&i+r.frameLength<=e.length){const a=s+n*(9e4*r.samplesPerFrame/r.sampleRate),o={unit:e.subarray(i,i+r.frameLength),pts:a,dts:a};return t.config=[],t.channelCount=r.channelCount,t.samplerate=r.sampleRate,t.samples.push(o),{sample:o,length:r.frameLength,missing:0}}}function ir(t,e){const i=t[e+1]>>3&3,s=t[e+1]>>1&3,n=t[e+2]>>4&15,r=t[e+2]>>2&3;if(1!==i&&0!==n&&15!==n&&3!==r){const a=t[e+2]>>1&1,o=t[e+3]>>6,l=1e3*Qn[14*(3===i?3-s:3===s?3:4)+n-1],d=Jn[3*(3===i?0:2===i?1:2)+r],h=3===o?1:2,c=Zn[i][s],u=tr[s],f=8*c*u,g=Math.floor(c*l/d+a)*u,p=re();return!!p&&p<=87&&2===s&&l>=224e3&&0===o&&(t[e+3]=128|t[e+3]),{sampleRate:d,channelCount:h,frameLength:g,samplesPerFrame:f}}}function sr(t,e){return!(255!==t[e]||224&~t[e+1]||!(6&t[e+1]))}function nr(t,e){return e+1<t.length&&sr(t,e)}function rr(t,e){if(e+1<t.length&&sr(t,e)){const i=4,s=ir(t,e);let n=i;null!=s&&s.frameLength&&(n=s.frameLength);const r=e+n;return r===t.length||nr(t,r)}return!1}class ar{constructor(t,e,i){this.keyData=void 0,this.decrypter=void 0,this.keyData=i,this.decrypter=new Hi(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 n=s.subarray(16,s.length-s.length%16),r=n.buffer.slice(n.byteOffset,n.byteOffset+n.length);this.decryptBuffer(r).then(n=>{const r=new Uint8Array(n);s.set(r,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,n){const r=zt(n.data),a=this.getAvcEncryptedData(r);this.decryptBuffer(a.buffer).then(a=>{n.data=this.getAvcDecryptedUnit(r,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 n=t[e].units;for(;!(i>=n.length);i++){const r=n[i];if(!(r.data.length<=48||1!==r.type&&5!==r.type||(this.decryptAvcSample(t,e,i,s,r),this.decrypter.isSync())))return}}}}const or=(t,e)=>{let i=0,s=5;e+=s;const n=new Uint32Array(1),r=new Uint32Array(1),a=new Uint8Array(1);for(;s>0;){a[0]=t[e];const o=Math.min(s,8),l=8-o;r[0]=4278190080>>>24+l<<l,n[0]=(a[0]&r[0])>>l,i=i?i<<o|n[0]:n[0],e+=1,s-=o}return i};class lr extends zn{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=dr(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=rt(t,0);if(!e)return!1;const i=e.length;if(11===t[i]&&119===t[i+1]&&void 0!==gt(e)){if(or(t,i)<16)return!0;throw new Error("Containerless ec-3 is not supported")}return!1}}function dr(t,e,i,s,n){if(i+8>e.length)return-1;if(11!==e[i]||119!==e[i+1])return-1;const r=e[i+4]>>6;if(r>=3)return-1;const a=[48e3,44100,32e3][r],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+r];if(i+l>e.length)return-1;const d=e[i+6]>>5;let h=0;2===d?h+=2:(1&d&&1!==d&&(h+=2),4&d&&(h+=2));const c=(e[i+6]<<8|e[i+7])>>12-h&1,u=[2,1,2,3,3,4,4,5][d]+c,f=e[i+5]>>3,g=7&e[i+5],p=new Uint8Array([r<<6|f<<1|g>>2,(3&g)<<6|d<<3|c<<2|o>>4,o<<4&224]),m=s+n*(1536/a*9e4),v=e.subarray(i,i+l);return t.config=p,t.channelCount=u,t.samplerate=a,t.samples.push({unit:v,pts:m}),l}const hr=/\/emsg[-/]ID3/i;function cr(t,i){return e(t.presentationTime)?t.presentationTime/t.timeScale:i+t.presentationTimeDelta/t.timeScale}class ur{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 n=t.naluState||0,r=-1===n?0:n,a=[];let o=0,l=0,d=-1,h=0;for(-1===n&&(d=0,h=this.getNALuType(e,0),l=1);l<s;){const i=e.indexOf(1,l);if(-1===i)break;l=i+1;let n=i;for(;n>0&&0===e[n-1];)n--;const c=i-n+(0===n?r:0);if(c<2)continue;const u=Math.min(c,3),f=Math.min(i-n,u),g=u-f;if(n=i-f,d>=0)a.push({data:e.subarray(d,n),type:h});else{const i=this.getLastNalUnit(t.samples);i&&(n>0?i.data=Vt(i.data,e.subarray(0,n)):g>0&&(i.data=i.data.subarray(0,i.data.byteLength-g)),i.state=0)}if(!(l<s)){o=-1,d=-1;break}d=l,h=this.getNALuType(e,l)}if(-1!==o){let t=s;for(;t>0&&0===e[t-1];)t--;o=s-t+(0===t?r:0)}if(d>=0)a.push({data:e.subarray(d),type:h,state:o});else if(0===a.length&&-1!==o){const i=this.getLastNalUnit(t.samples);i&&(i.data=Vt(i.data,e),i.state=o)}return t.naluState=o,a}}class fr{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),n=Math.min(4,e);if(0===n)throw new Error("no bytes available");s.set(t.subarray(i,i+n)),this.word=new DataView(s.buffer).getUint32(0),this.bitsAvailable=8*n,this.bytesAvailable-=n}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&&H.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 gr extends ur{parsePES(t,e,i,s,n){const r=n.iframe,a=this.parseNALu(t,i.data,s);let o,l=this.VideoSample,d=!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 n,a;switch(s.type){case 1:{if(r)break;let e=!1;o=!0;const n=s.data;if(d&&n.length>4){const t=this.readSliceType(n);2!==t&&4!==t&&7!==t&&9!==t||(e=!0)}var h;if(e)null!=(h=l)&&h.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!=(n=l)&&n.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(r)break;o=!0,Wt(s.data,1,i.pts,e.samples);break;case 7:{var c,u;o=!0,d=!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 n="avc1.";for(let t=0;t<3;t++){let e=s[t].toString(16);e.length<2&&(e="0"+e),n+=e}t.codec=n}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 fr(t);return e.readUByte(),e.readUEG(),e.readUEG()}skipScalingList(t,e){let i,s=8,n=8;for(let r=0;r<t;r++)0!==n&&(i=e.readEG(),n=(s+i+256)%256),s=0===n?s:n}readSPS(t){const e=new fr(t);let i,s,n,r=0,a=0,o=0,l=0;const d=e.readUByte.bind(e),h=e.readBits.bind(e),c=e.readUEG.bind(e),u=e.readBoolean.bind(e),f=e.skipBits.bind(e),g=e.skipEG.bind(e),p=e.skipUEG.bind(e),m=this.skipScalingList.bind(this);d();const v=d();if(h(5),f(3),d(),p(),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),p(),p(),f(1),u())for(s=3!==t?8:12,n=0;n<s;n++)u()&&m(n<6?16:64,e)}p();const y=c();if(0===y)c();else if(1===y)for(f(1),g(),g(),i=c(),n=0;n<i;n++)g();p(),f(1);const E=c(),T=c(),S=h(1);0===S&&f(1),f(1),u()&&(r=c(),a=c(),o=c(),l=c());let b=[1,1];if(u()&&u()){switch(d()){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=[d()<<8|d(),d()<<8|d()]}}return{width:Math.ceil(16*(E+1)-2*r-2*a),height:(2-S)*(T+1)*16-(S?2:4)*(o+l),pixelRatio:b}}}class pr extends ur{constructor(...t){super(...t),this.initVPS=null}parsePES(t,e,i,s){const n=this.parseNALu(t,i.data,s);let r,a=this.VideoSample,o=!1;i.data=null;const l=t=>(a=this.VideoSample=this.createVideoSample(t,i.pts,i.dts),a);n.forEach((s,n)=>{var d,h;if(this.startsNewAccessUnit(a,t,s,n)){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,r=!0;break;case 16:case 17:case 18:case 21:case 22:case 23:var c;if(r=!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:r=!0,null!=(d=a)&&d.frame&&!a.key&&(this.pushAccessUnit(a,t),a=this.VideoSample=null),a||(a=l(!0)),a.key=!0,a.frame=!0;break;case 39:r=!0,Wt(s.data,2,i.pts,e.samples);break;case 32:r=!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(r=!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(r=!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:r=!0,t.audFound=!0,null!=(h=a)&&h.frame&&(this.pushAccessUnit(a,t),a=null),a||(a=l(!1));break;default:r=!1}if(a&&r){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:n,data:r}=i;return!!(n>=32&&n<=35||39===n||n>=41&&n<=44||n>=48&&n<=55)||n<=31&&r.length>2&&!!(128&r[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 fr(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 fr(this.ebsp2rbsp(t));e.readUByte(),e.readUByte(),e.readBits(4);const i=e.readBits(3);e.readBoolean();const s=e.readBits(2),n=e.readBoolean(),r=e.readBits(5),a=e.readUByte(),o=e.readUByte(),l=e.readUByte(),d=e.readUByte(),h=e.readUByte(),c=e.readUByte(),u=e.readUByte(),f=e.readUByte(),g=e.readUByte(),p=e.readUByte(),m=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 _=e.readUEG(),k=e.readUEG(),w=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 D=e.readUEG();let x=0;for(let t=0;t<D;t++){let i=!1;if(0!==t&&(i=e.readBoolean()),i){t===D&&e.readUEG(),e.readBoolean(),e.readUEG();let i=0;for(let t=0;t<=x;t++){const t=e.readBoolean();let s=!1;t||(s=e.readBoolean()),(t||s)&&i++}x=i}else{const t=e.readUEG(),i=e.readUEG();x=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<w+4;t++)e.readBits(1);e.readBits(1)}}let P=0,C=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?(C=[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&&(C=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 n=!1;(t||s)&&(n=e.readBoolean(),n&&(e.readUByte(),e.readBits(5),e.readBoolean(),e.readBits(5)),e.readBits(4),e.readBits(4),n&&e.readBits(4),e.readBits(5),e.readBits(5),e.readBits(5));for(let r=0;r<=i;r++){O=e.readBoolean();let i=!1;O||e.readBoolean()?e.readEG():i=e.readBoolean();const r=i?1:e.readUEG()+1;if(t)for(let t=0;t<r;t++)e.readUEG(),e.readUEG(),n&&(e.readUEG(),e.readUEG()),e.skipBits(1);if(s)for(let t=0;t<r;t++)e.readUEG(),e.readUEG(),n&&(e.readUEG(),e.readUEG()),e.skipBits(1)}}}e.readBoolean()&&(e.readBoolean(),e.readBoolean(),e.readBoolean(),P=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]:"",j=a<<24|o<<16|l<<8|d;let q=0;for(let t=0;t<32;t++)q=(q|(j>>t&1)<<31-t)>>>0;let K=q.toString(16);1===r&&"2"===K&&(K="6");return{codecString:`hvc1.${G}${r}.${K}.${n?"H":"L"}${m}.B0`,params:{general_tier_flag:n,general_profile_idc:r,general_profile_space:s,general_profile_compatibility_flags:[a,o,l,d],general_constraint_indicator_flags:[h,c,u,f,g,p],general_level_idc:m,bit_depth:_+8,bit_depth_luma_minus8:_,bit_depth_chroma_minus8:k,min_spatial_segmentation_idc:P,chroma_format_idc:E,frame_rate:{fixed:O,fps:N/F}},width:B,height:U,pixelRatio:[C,M]}}readPPS(t){const e=new fr(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 n=1;return s&&i?n=0:s?n=3:i&&(n=2),{parallelismType:n}}matchSPS(t,e){return yt(t).substring(3)===yt(e).substring(3)}}const mr=188;class vr{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=vr.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-mr)+1,s=0;for(;s<i;){let n=!1,r=-1,a=0;for(let o=s;o<e;o+=mr){if(71!==t[o]||e-o!==mr&&71!==t[o+mr]){if(a)return-1;break}if(a++,-1===r&&(r=o,0!==r&&(i=Math.min(r+18612,t.length-mr)+1)),n||(n=0===yr(t,o)),n&&a>1&&(0===r&&a>2||o+mr>i))return r}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,n,r){this.pmtParsed=!1,this._pmtId=-1,this._videoTrack=vr.createTrack("video"),this._videoTrack.duration=s,this.videoIntegrityChecker="skip"===this.config.handleMpegTsVideoIntegrityErrors?new Lr(this.logger):null,this._audioTrack=vr.createTrack("audio",s),this._id3Track=vr.createTrack("id3"),this._txtTrack=vr.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,r,"SAMPLE-AES"===(null==n?void 0:n.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,n=!1){let r;s||(this.sampleAes=null);const a=this._videoTrack,o=this.videoIntegrityChecker,l=this._audioTrack,d=this._id3Track,h=this._txtTrack,c=i.iframe;let u=a.pid,f=a.pesData,g=l.pid,p=d.pid,m=this._klvPid,v=l.pesData,y=d.pesData,E=null,T=null,S=this.pmtParsed,b=this._pmtId,A=t.length;if(this.remainderData&&(A=(t=Vt(this.remainderData,t)).length,this.remainderData=null),A<mr&&!n)return this.remainderData=t,{audioTrack:l,videoTrack:a,id3Track:d,textTrack:h};const L=Math.max(0,vr.syncOffset(t));A-=(A-L)%mr,A<t.byteLength&&!n&&(this.remainderData=new Uint8Array(t.buffer,A,t.buffer.byteLength-A));let I=0;for(let e=L;e<A;e+=mr)if(71===t[e]){const n=!!(64&t[e+1]),A=yr(t,e);let I;if((48&t[e+3])>>4>1){if(I=e+5+t[e+4],I===e+mr)continue}else I=e+4;switch(A){case u:n&&(!f||null!=o&&o.isCorrupted||!(r=Ar(f,this.logger))||(this.readyVideoParser(a.segmentCodec),null!==this.videoParser&&this.videoParser.parsePES(a,h,r,!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+mr)),f.size+=e+mr-I);break;case g:if(c)break;if(n){if(v&&(r=Ar(v,this.logger)))switch(l.segmentCodec){case"aac":this.parseAACPES(l,r,i);break;case"mp3":this.parseMPEGPES(l,r);break;case"ac3":this.parseAC3PES(l,r)}v={data:[],size:0}}v&&(v.data.push(t.subarray(I,e+mr)),v.size+=e+mr-I);break;case p:if(c)break;n&&(y&&(r=Ar(y,this.logger))&&this.parseID3PES(d,r),y={data:[],size:0}),y&&(y.data.push(t.subarray(I,e+mr)),y.size+=e+mr-I);break;case m:if(c)break;n&&(E&&(r=Ar(E,this.logger))&&this.parseKlvPES(d,r),E={data:[],size:0}),E&&(E.data.push(t.subarray(I,e+mr)),E.size+=e+mr-I);break;case 0:n&&(I+=t[I]+1),b=this._pmtId=Er(t,I);break;case b:{n&&(I+=t[I]+1);const r=Tr(t,I,this.typeSupported,s,this.observer,this.logger,this.config,i);u=r.videoPid,u>0&&(a.pid=u,a.segmentCodec=r.segmentVideoCodec),g=r.audioPid,g>0&&(l.pid=g,l.segmentCodec=r.segmentAudioCodec),p=r.id3Pid,p>0&&(d.pid=p),m=r.klvPid,m>0&&(this._klvPid=m),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&&Sr(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,d.pesData=y;const R={audioTrack:l,videoTrack:a,id3Track:d,textTrack:h};return n&&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:n,textTrack:r}=t,a=s.pesData,o=i.pesData,l=n.pesData,d=this.videoIntegrityChecker;let h;if(!a||null!=d&&d.isCorrupted||!(h=Ar(a,this.logger))?s.pesData=a:(this.readyVideoParser(s.segmentCodec),null!==this.videoParser&&(this.videoParser.parsePES(s,r,h,!0,e),s.pesData=null)),o&&(h=Ar(o,this.logger))){switch(i.segmentCodec){case"aac":this.parseAACPES(i,h,e);break;case"mp3":this.parseMPEGPES(i,h);break;case"ac3":this.parseAC3PES(i,h)}i.pesData=null}else null!=o&&o.size&&this.logger.log("last AAC PES packet truncated,might overlap between fragments"),i.pesData=o;l&&(h=Ar(l,this.logger))?(this.parseID3PES(n,h),n.pesData=null):n.pesData=l}demuxSampleAes(t,e,i,s){const n=this.demux(t,i,s,!0,!this.config.progressive),r=this.sampleAes=new ar(this.observer,this.config,e);return this.decrypt(n,r)}readyVideoParser(t){null===this.videoParser&&("avc"===t?this.videoParser=new gr:"hevc"===t&&(this.videoParser=new pr))}decrypt(t,e){return new Promise(i=>{const{audioTrack:s,videoTrack:n}=t;s.samples&&"aac"===s.segmentCodec?e.decryptAacSamples(s.samples,0,()=>{n.samples?e.decryptAvcSamples(n.samples,0,0,()=>{i(t)}):i(t)}):n.samples&&e.decryptAvcSamples(n.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 n=this.aacOverFlow;let r,a,o,l=e.data;if(n){this.aacOverFlow=null;const e=n.missing,i=n.sample.unit.byteLength;if(-1===e)l=Vt(n.sample.unit,l);else{const r=i-e;n.sample.unit.set(l.subarray(0,e),r),t.samples.push(n.sample),s=n.missing}}for(r=s,a=l.length;r<a-1&&!jn(l,r);r++);if(r!==s){let t;const e=r<a-1;if(t=e?`AAC PES did not start with ADTS header,offset:${r}`:"No ADTS header found in AAC PES",Sr(this.observer,new Error(t),i,e,this.logger),!e)return}if(Kn(t,this.observer,l,r,this.audioCodec),void 0!==e.pts)o=e.pts;else{if(!n)return void this.logger.warn("[tsdemuxer]: AAC PES unknown PTS");{const e=Vn(t.samplerate);o=n.sample.pts+e}}let d,h=0;for(;r<a;){if(d=Hn(t,l,r,o,h),r+=d.length,d.missing){this.aacOverFlow=d;break}for(h++;r<a-1&&!jn(l,r);r++);}}parseMPEGPES(t,e){const i=e.data,s=i.length;let n=0,r=0;const a=e.pts;if(void 0!==a)for(;r<s;)if(nr(i,r)){const e=er(t,i,r,a,n);if(!e)break;r+=e.length,n++}else r++;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 n=i.length;let r,a=0,o=0;for(;o<n&&(r=dr(t,i,o,s,a++))>0;)o+=r}}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?Yn.emsg:Yn.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 n=e.data;if(n.length<16)return void this.logger.warn("[tsdemuxer]: KLV PES payload too short");let r=0;for(;r<n.length;){var a;if(r+16>n.length)break;const i=r;if(r+=16,r>=n.length)break;const o=n[r];r+=1;let l=0;if(128&o){const t=127&o;if(0===t||t>4||r+t>n.length){this.logger.warn("[tsdemuxer]: Invalid KLV length encoding");break}for(let e=0;e<t;e++)l=l<<8|n[r+e];r+=t}else l=o;if(r+l>n.length){this.logger.warn("[tsdemuxer]: KLV value extends beyond PES payload");break}const d=r+l,h=n.subarray(i,d),c={data:h,len:h.byteLength,pts:s,dts:null!=(a=e.dts)?a:s,type:Yn.misbklv,duration:Number.POSITIVE_INFINITY};t.samples.push(c),r=d}}}function yr(t,e){return((31&t[e+1])<<8)+t[e+2]}function Er(t,e){return(31&t[e+10])<<8|t[e+11]}function Tr(t,e,i,s,n,r,a,o){const l={audioPid:-1,videoPid:-1,id3Pid:-1,klvPid:-1,segmentVideoCodec:"avc",segmentAudioCodec:"aac"},d=e+3+((15&t[e+1])<<8|t[e+2])-4;for(e+=12+((15&t[e+10])<<8|t[e+11]);e<d;){const d=yr(t,e),h=(15&t[e+3])<<8|t[e+4];switch(t[e]){case 207:if(!s){br("ADTS AAC",r);break}case 15:-1===l.audioPid&&(l.audioPid=d);break;case 21:-1===l.id3Pid&&(l.id3Pid=d);break;case 219:if(!s){br("H.264",r);break}case 27:-1===l.videoPid&&(l.videoPid=d);break;case 3:case 4:i.mpeg||i.mp3?-1===l.audioPid&&(l.audioPid=d,l.segmentAudioCodec="mp3"):r.log("MPEG audio found, not supported in this browser");break;case 193:if(!s){br("AC-3",r);break}case 129:i.ac3?-1===l.audioPid&&(l.audioPid=d,l.segmentAudioCodec="ac3"):r.log("AC-3 audio found, not supported in this browser");break;case 6:if(h>0){let s=e+5,n=h;for(;n>2;){switch(t[s]){case 106:-1===l.audioPid&&(!0!==i.ac3?r.log("AC-3 audio found, not supported in this browser for now"):(l.audioPid=d,l.segmentAudioCodec="ac3"));break;case 5:-1===l.klvPid&&a.enableEmsgKLVMetadata&&(l.klvPid=d,r.log(`KLV metadata PID found: ${d}`))}const e=t[s+1]+2;s+=e,n-=e}}break;case 194:case 135:return Sr(n,new Error("Unsupported EC-3 in M2TS found"),o,void 0,r),l;case 36:-1===l.videoPid&&(l.videoPid=d,l.segmentVideoCodec="hevc",r.log("HEVC in M2TS found"))}e+=h+5}return l}function Sr(t,e,i,s,o){o.warn(`parsing error: ${e.message}`),t.emit(a.ERROR,a.ERROR,{type:n.MEDIA_ERROR,details:r.FRAG_PARSING_ERROR,fatal:!1,levelRetry:s,chunkMeta:i,error:e,reason:e.message})}function br(t,e){e.log(`${t} with AES-128-CBC encryption found in unencrypted stream`)}function Ar(t,e){let i,s,n,r,a,o=0;const l=t.data;if(!t||0===t.size)return null;for(;l[0].length<19&&l.length>1;)l[0]=Vt(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 d=i[7];192&d&&(r=536870912*(14&i[9])+4194304*(255&i[10])+16384*(254&i[11])+128*(255&i[12])+(254&i[13])/2,64&d?(a=536870912*(14&i[14])+4194304*(255&i[15])+16384*(254&i[16])+128*(255&i[17])+(254&i[18])/2,r-a>54e5&&(e.warn(`${Math.round((r-a)/9e4)}s delta between PTS and DTS, align them`),r=a)):a=r),n=i[8];let h=n+9;if(t.size<=h)return null;t.size-=h;const c=new Uint8Array(t.size);for(let t=0,e=l.length;t<e;t++){i=l[t];let e=i.byteLength;if(h){if(h>e){h-=e;continue}i=i.subarray(h),e-=h,h=0}c.set(i,o),o+=e}return s&&(s-=n+3),{data:c,pts:r,dts:a,len:s}}return null}class Lr{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=yr(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],n=this.lastContinuityCounter;this.lastContinuityCounter=s;const r=!!(1&i);if(!!(2&i)&&0!=t[4]&&!!(128&t[5]))return;if(n<0)return;const a=r?n+1&15:n;return s!==a?(this.logger.warn(`MPEG-TS Continuity Counter check failed for PID='${e}', CC=${s}, Expected-CC=${a} Last-CC=${n}`),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 Ir{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 Rr;const _r={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])},kr=new Uint8Array([0,0,0,0,0,0,0,0]),wr=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),Dr=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0]),xr=new Uint8Array([0,0,0,0,0,0,0,0]),Pr=new Uint8Array([0,0,0,0,0,0,0,1]),Cr=new Uint8Array([105,115,111,109]),Mr=new Uint8Array([97,118,99,49]),Or=new Uint8Array([0,0,0,1]);class Fr{static box(t,...e){let i=8,s=e.length;const n=s;for(;s--;)i+=e[s].byteLength;const r=new Uint8Array(i);for(_t(r,0,i),_t(r,4,t),s=0,i=8;s<n;s++)r.set(e[s],i),i+=e[s].byteLength;return r}static hdlr(t){return Fr.box(Tt.hdlr,_r[t])}static mdat(t){return Fr.box(Tt.mdat,t)}static mdhd(t,e){e*=t;const i=Math.floor(e/(Et+1)),s=Math.floor(e%(Et+1));return Fr.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 Fr.box(Tt.mdia,Fr.mdhd(t.timescale||0,t.duration||0),Fr.hdlr(t.type),Fr.minf(t))}static mfhd(t){return Fr.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?Fr.box(Tt.minf,Fr.box(Tt.smhd,xr),Fr.DINF,Fr.stbl(t)):Fr.box(Tt.minf,Fr.box(Tt.vmhd,Dr),Fr.DINF,Fr.stbl(t))}static moof(t,e,i){return Fr.box(Tt.moof,Fr.mfhd(t),Fr.traf(i,e))}static moov(t){let e=t.length;const i=[];for(;e--;)i[e]=Fr.trak(t[e]);return Fr.box.apply(null,[Tt.moov,Fr.mvhd(t[0].timescale||0,t[0].duration||0)].concat(i).concat(Fr.mvex(t)))}static mvex(t){let e=t.length;const i=[];for(;e--;)i[e]=Fr.trex(t[e]);return Fr.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)),n=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 Fr.box(Tt.mvhd,n)}static sdtp(t){const e=t.samples||[],i=new Uint8Array(4+e.length);let s,n;for(s=0;s<e.length;s++)n=e[s].flags,i[s+4]=n.dependsOn<<4|n.isDependedOn<<2|n.hasRedundancy;return Fr.box(Tt.sdtp,i)}static stbl(t){return Fr.box(Tt.stbl,Fr.stsd(t),Fr.box(Tt.stts,kr),Fr.box(Tt.stsc,kr),Fr.box(Tt.stsz,wr),Fr.box(Tt.stco,kr))}static avc1(t){let e,i,s,n=[],r=[];for(e=0;e<t.sps.length;e++)i=t.sps[e],s=i.byteLength,n.push(s>>>8&255),n.push(255&s),n=n.concat(Array.prototype.slice.call(i));for(e=0;e<t.pps.length;e++)i=t.pps[e],s=i.byteLength,r.push(s>>>8&255),r.push(255&s),r=r.concat(Array.prototype.slice.call(i));const a=Fr.box(Tt.avcC,new Uint8Array([1,n[3],n[4],n[5],255,224|t.sps.length].concat(n).concat([t.pps.length]).concat(r))),o=t.width,l=t.height,d=t.pixelRatio[0],h=t.pixelRatio[1];return Fr.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,Fr.box(Tt.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),Fr.box(Tt.pasp,new Uint8Array([d>>24,d>>16&255,d>>8&255,255&d,h>>24,h>>16&255,h>>8&255,255&h])))}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 Fr.box(Tt.mp4a,Fr.audioStsd(t),Fr.box(Tt.esds,Fr.esds(t)))}static mp3(t){return Fr.box(Tt[".mp3"],Fr.audioStsd(t))}static ac3(t){return Fr.box(Tt["ac-3"],Fr.audioStsd(t),Fr.box(Tt.dac3,t.config))}static stsd(t){const{segmentCodec:e}=t;if("audio"===t.type){if("aac"===e)return Fr.box(Tt.stsd,Pr,Fr.mp4a(t));if("ac3"===e&&t.config)return Fr.box(Tt.stsd,Pr,Fr.ac3(t));if("mp3"===e&&"mp3"===t.codec)return Fr.box(Tt.stsd,Pr,Fr.mp3(t))}else{if(!t.pps||!t.sps)throw new Error("video track missing pps or sps");if("avc"===e)return Fr.box(Tt.stsd,Pr,Fr.avc1(t));if("hevc"===e&&t.vps)return Fr.box(Tt.stsd,Pr,Fr.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,n=t.height||0,r=Math.floor(i/(Et+1)),a=Math.floor(i%(Et+1));return Fr.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,r>>24,r>>16&255,r>>8&255,255&r,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,n>>8&255,255&n,0,0]))}static traf(t,e){const i=Fr.sdtp(t),s=t.id,n=Math.floor(e/(Et+1)),r=Math.floor(e%(Et+1));return Fr.box(Tt.traf,Fr.box(Tt.tfhd,new Uint8Array([0,0,0,0,s>>24,s>>16&255,s>>8&255,255&s])),Fr.box(Tt.tfdt,new Uint8Array([1,0,0,0,n>>24,n>>16&255,n>>8&255,255&n,r>>24,r>>16&255,r>>8&255,255&r])),Fr.trun(t,i.length+16+20+8+16+8+8),i)}static trak(t){return t.duration=t.duration||4294967295,Fr.box(Tt.trak,Fr.tkhd(t),Fr.mdia(t))}static trex(t){const e=t.id;return Fr.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,n=12+16*s,r=new Uint8Array(n);let a,o,l,d,h,c;for(e+=8+n,r.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,d=o.size,h=o.flags,c=o.cts,r.set([l>>>24&255,l>>>16&255,l>>>8&255,255&l,d>>>24&255,d>>>16&255,d>>>8&255,255&d,h.isLeading<<2|h.dependsOn,h.isDependedOn<<6|h.hasRedundancy<<4|h.paddingValue<<1|h.isNonSync,61440&h.degradPrio,15&h.degradPrio,c>>>24&255,c>>>16&255,c>>>8&255,255&c],12+16*a);return Fr.box(Tt.trun,r)}static initSegment(t){const e=Fr.moov(t);return Vt(Fr.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 n=s.length;for(let t=0;t<i.length;t+=1){n+=3;for(let e=0;e<i[t].length;e+=1)n+=2+i[t][e].length}const r=new Uint8Array(n);r.set(s,0),n=s.length;const a=i.length-1;for(let t=0;t<i.length;t+=1){r.set(new Uint8Array([32+t|(t===a?128:0),0,i[t].length]),n),n+=3;for(let e=0;e<i[t].length;e+=1)r.set(new Uint8Array([i[t][e].length>>8,255&i[t][e].length]),n),n+=2,r.set(i[t][e],n),n+=i[t][e].length}const o=Fr.box(Tt.hvcC,r),l=t.width,d=t.height,h=t.pixelRatio[0],c=t.pixelRatio[1];return Fr.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,d>>8&255,255&d,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,Fr.box(Tt.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),Fr.box(Tt.pasp,new Uint8Array([h>>24,h>>16&255,h>>8&255,255&h,c>>24,c>>16&255,c>>8&255,255&c])))}}Rr=Fr,Fr.FTYP=Rr.box(Tt.ftyp,Cr,Or,Cr,Mr),Fr.DINF=Rr.box(Tt.dinf,Rr.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 Nr(t,e,i=1,s=!1){const n=t*e*i;return s?Math.round(n):n}function $r(t,e=!1){return Nr(t,1e3,1/9e4,e)}function Br(t){const{baseTime:e,timescale:i,trackId:s}=t;return`${e/i} (${e}/${i}) trackId: ${s}`}const Ur=8589934592;function Gr(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 jr 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?Br(e):e} > ${t?Br(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 n=s.pts,r=n-t;return r<-4294967296&&(e=!0,n=qr(n,i),r=n-t),r>0?t:n},i);return e&&this.debug("PTS rollover detected"),s}remux(t,e,i,s,n,r,a,o,l){let d,h,c,u,g,p,m=n,v=n;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,n,r));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(p=!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`),p=!1);if(this.ISGenerated){if(S&&b&&n){const i=this.getVideoStartPts(e.samples),s=(qr(t.samples[0].pts,i)-i)/e.inputTimeScale;m+=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,n,r)),h=this.remuxAudio(t,m,this.isAudioContiguous,r,E||b||o===f.AUDIO?v:void 0,l),b){const s=h?h.endPTS-h.startPTS:0;e.inputTimeScale||(this.warn("regenerate InitSegment as video detected"),c=this.generateIS(t,e,n,r)),d=this.remuxVideo(e,v,i,s,l)}}else b&&(d=this.remuxVideo(e,v,i,0,l));d&&(d.firstKeyFrame=a,d.independent=-1!==a,d.firstKeyFramePTS=s)}}return this.ISGenerated&&this._initPTS&&this._initDTS&&(i.samples.length&&(g=Kr(i,n,this._initPTS,this._initDTS)),s.samples.length&&(u=Vr(s,n,this._initPTS))),{audio:h,video:d,initSegment:c,independent:p,text:u,id3:g}}computeInitPts(t,e,i,s){const n=Math.round(i*e);let r=qr(t,n);if(r<n)for(this.log(`Adjusting PTS for rollover in timeline near ${(n-r)/e} ${s}`);r<n;)r+=Ur;return r-n}generateIS(t,i,s,n){const r=t.samples,a=i.samples,o=this.typeSupported,l={},d=this._initPTS,h=!d||n;let c,u,f,g="audio/mp4",p=-1;if(h&&(c=u=1/0),t.config&&r.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):Fr.initSegment([t]),metadata:{channelCount:t.channelCount}},h){p=t.id,f=t.inputTimeScale;const e=this.computeInitPts(r[0].pts,f,s,"audio");(!d||f!==d.timescale||0===s&&e<d.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:Fr.initSegment([i]),metadata:{width:i.width,height:i.height}},h){p=i.id,f=i.inputTimeScale;const t=this.getVideoStartPts(a),n=qr(a[0].dts,t),r=this.computeInitPts(n,f,s,"video"),o=this.computeInitPts(t,f,s,"video");if(!d||f!==d.timescale||e(c)||0===s&&o<d.baseTime){u=Math.min(u,r);const t=!d&&this.isVideoContiguous?o:r;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,h&&e(c)?(d&&this.warn(`Timestamps at playlist time: ${n?"":"~"}${s} ${c/f} != initPTS: ${d.baseTime/d.timescale} (${d.baseTime}/${d.timescale}) trackId: ${d.trackId}`),this.log(`Found initPTS at playlist time: ${s} offset: ${c/f} (${c}/${f}) trackId: ${p}`),this._initPTS={baseTime:c,timescale:f,trackId:p},this._initDTS={baseTime:u,timescale:f,trackId:p}):c=f=void 0,{tracks:l,initPTS:c,timescale:f,trackId:p}}remuxVideo(t,e,i,s,o){const l=t.inputTimeScale,d=t.samples,h=[],c=d.length,u=this._initPTS,f=u.baseTime*l/u.timescale;let g,p,m=this.nextVideoTs,v=8,y=this.videoSampleDuration,E=Number.POSITIVE_INFINITY,T=Number.NEGATIVE_INFINITY,S=!1;if(!i||null===m){const t=f+e*l,s=d[0].pts-qr(d[0].dts,d[0].pts);re()&&null!==m&&Math.abs(t-s-(m+f))<15e3?i=!0:m=t-s-f}const b=m+f;for(let t=0;t<c;t++){const e=d[t];e.pts=qr(e.pts,b),e.dts=qr(e.dts,b),e.dts<d[t>0?t-1:t].dts&&(S=!0)}S&&d.sort(function(t,e){const i=t.dts-e.dts,s=t.pts-e.pts;return i||s}),g=d[0].dts,p=d[d.length-1].dts;const A=p-g,L=A?Math.round(A/(c-1)):y||t.inputTimeScale/30;if(i){const i=g-b,s=i>L,n=i<-1;if((s||n)&&(s?this.warn(`${(t.segmentCodec||"").toUpperCase()}: ${$r(i,!0)} ms (${i}dts) hole between fragments detected at ${e.toFixed(3)}`):this.warn(`${(t.segmentCodec||"").toUpperCase()}: ${$r(-i,!0)} ms (${i}dts) overlapping between fragments detected at ${e.toFixed(3)}`),!n||b>=d[0].pts||re())){g=b;const t=d[0].pts-i;if(s)d[0].dts=g,d[0].pts=t;else{let e=!0;for(let s=0;s<d.length&&!(d[s].dts>t&&e);s++){const t=d[s].pts;if(d[s].dts-=i,d[s].pts-=i,s<d.length-1){const i=d[s+1].pts;e=i<=d[s].pts==i<=t}}}this.log(`Video: Initial PTS/DTS adjusted: ${$r(t,!0)}/${$r(g,!0)}, delta: ${$r(i,!0)} ms`)}}g=Math.max(0,g);let R=0,_=0,k=g;for(let t=0;t<c;t++){const e=d[t],i=e.units,s=i.length;let n=0;for(let t=0;t<s;t++)n+=i[t].data.length;_+=n,R+=s,e.length=n,e.dts<k?(e.dts=k,k+=L/4|0||1):k=e.dts,E=Math.min(e.pts,E),T=Math.max(e.pts,T)}p=d[c-1].dts;const w=_+4*R+8;let D;try{D=new Uint8Array(w)}catch(t){return void this.observer.emit(a.ERROR,a.ERROR,{type:n.MUX_ERROR,details:r.REMUX_ALLOC_ERROR,fatal:!1,chunkMeta:o,error:t,bytes:w,reason:`fail allocating video mdat ${w}`})}_t(D,0,w),_t(D,4,Tt.mdat);let x=!1,P=Number.POSITIVE_INFINITY,C=Number.POSITIVE_INFINITY,M=Number.NEGATIVE_INFINITY,O=Number.NEGATIVE_INFINITY;for(let t=0;t<c;t++){const e=d[t],n=e.units;let r,a=0;for(let t=0,e=n.length;t<e;t++){const e=n[t],i=e.data,s=e.data.byteLength;_t(D,v,s),v+=4,D.set(i,v),v+=s,a+=4+s}if(t<c-1)y=d[t+1].dts-e.dts,r=d[t+1].pts-e.pts;else{const i=this.config,n=t>0?e.dts-d[t-1].dts:L;if(r=t>0?e.pts-d[t-1].pts:L,i.stretchShortVideoTrack&&null!==this.nextAudioTs){const t=Math.floor(i.maxBufferHole*l),r=(s?E+s*l:this.nextAudioTs+f)-e.pts;r>t?(y=r-n,y<0?y=n:x=!0,this.log(`It is approximately ${r/90} ms to the next segment; using duration ${y/90} ms for the last video frame.`)):y=n}else y=n}let u=Math.round(e.pts-e.dts);if(P=Math.min(P,y),M=Math.max(M,y),C=Math.min(C,r),O=Math.max(O,r),!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)}h.push(Gr(e.key,y,a,u))}if(h.length){const t=re();if(t){if(t<70){const t=h[0].flags;t.dependsOn=2,t.isNonSync=0}}else if(function(){if(void 0===se){const t=Zt.match(/Safari\/(\d+)/i);se=t?parseInt(t[1]):0}return se}()&&O-C<M-P&&L/M<.025&&0===h[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=h.length;e<i;e++){const s=t+h[e].duration,n=t+h[e].cts;if(e<i-1){const t=s+h[e+1].cts;h[e].duration=t-n}else h[e].duration=e?h[e-1].duration:L;h[e].cts=0,t=s}}}y=x||!y?L:y;const F=p+y;this.nextVideoTs=m=F-f,this.videoSampleDuration=y,this.isVideoContiguous=!0,o.iframe&&(1===h.length?(h[0].duration=y=o.duration*l,this.nextVideoTs=m=g+y-f):this.warn(`Not adjusting IFrame duration (sample count ${h.length})`));const N={data1:Fr.moof(o.sn,g,I(t,{samples:h})),data2:D,startPTS:(E-f)/l,endPTS:(T+y-f)/l,startDTS:(g-f)/l,endDTS:m/l,type:"video",hasAudio:!1,hasVideo:!0,nb:h.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 d=t.inputTimeScale,h=d/(t.samplerate?t.samplerate:d),c=this.getSamplesPerFrame(t),u=c*h,f=this._initPTS,g="mp3"===t.segmentCodec&&this.typeSupported.mpeg,p=[],m=void 0!==o;let v=t.samples,y=g?0:8,E=this.nextAudioTs||-1;const T=f.baseTime*d/f.timescale,S=T+e*d;if(this.isAudioContiguous=i=i||v.length&&E>0&&(s&&Math.abs(S-(E+T))<9e3||Math.abs(qr(v[0].pts,S)-(E+T))<20*u),v.forEach(function(t){t.pts=qr(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} / ${d})`),!v.length)return;E=0===o?0:s&&!m?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 n=v[i],r=n.pts,a=r-s,o=Math.abs(1e3*a/d);if(a<=-e*u&&m)0===i&&(this.warn(`Audio frame @ ${(r/d).toFixed(3)}s overlaps marker by ${Math.round(1e3*a/d)} ms.`),this.nextAudioTs=E=r-T,s=r);else if(a>=e*u&&o<1e4&&m){let e=Math.round(a/u);for(s=r-e*u;s<T&&e&&u;)e--,s+=u;0===i&&(this.nextAudioTs=E=s-T),this.warn(`Injecting ${e} audio frames @ ${((s-T)/d).toFixed(3)}s due to ${Math.round(1e3*a/d)} ms gap.`);for(let r=0;r<e;r++){let e=Ir.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=n.unit.subarray()),v.splice(i,0,{unit:e,pts:s}),s+=u,i++}}n.pts=s,s+=u}}let b,A=null,L=null,R=0,_=v.length;for(;_--;)R+=v[_].unit.byteLength;for(let e=0,s=v.length;e<s;e++){const s=v[e],o=s.unit;let d=s.pts;if(null!==L){p[e-1].duration=Math.round((d-L)/h)}else{if(i&&"aac"===t.segmentCodec&&(d=E+T),A=d,!(R>0))return;R+=y;try{b=new Uint8Array(R)}catch(t){return void this.observer.emit(a.ERROR,a.ERROR,{type:n.MUX_ERROR,details:r.REMUX_ALLOC_ERROR,fatal:!1,chunkMeta:l,error:t,bytes:R,reason:`fail allocating audio mdat ${R}`})}g||(_t(b,0,R),_t(b,4,Tt.mdat))}b&&b.set(o,y);const u=o.byteLength;y+=u,p.push(Gr(!0,c,u,0)),L=d}const k=p.length;if(!k)return;const w=p[p.length-1];E=L-T,this.nextAudioTs=E+h*w.duration;const D=g?new Uint8Array(0):Fr.moof(t.sequenceNumber++,A/h,I({},t,{samples:p}));t.samples=[];const x=(A-T)/d,P=this.nextAudioTs/d,C={data1:D,data2:b,startPTS:x,endPTS:P,startDTS:x,endDTS:P,type:"audio",hasAudio:!0,hasVideo:!1,nb:k};return this.isAudioContiguous=!0,C}}function qr(t,e){let i;if(null===e)return t;for(i=e<t?-8589934592:Ur;Math.abs(t-e)>4294967296;)t+=i;return t}function Kr(t,e,i,s){const n=t.samples.length;if(!n)return;const r=t.inputTimeScale;for(let a=0;a<n;a++){const n=t.samples[a];n.pts=qr(n.pts-i.baseTime*r/i.timescale,e*r)/r,n.dts=qr(n.dts-s.baseTime*r/s.timescale,e*r)/r}const a=t.samples;return t.samples=[],{samples:a}}function Vr(t,e,i){const s=t.samples.length;if(!s)return;const n=t.inputTimeScale;for(let r=0;r<s;r++){const s=t.samples[r];s.pts=qr(s.pts-i.baseTime*n/i.timescale,e*n)/n}t.samples.sort((t,e)=>t.pts-e.pts);const r=t.samples;return t.samples=[],{samples:r}}function Hr(t,e,i=!1){return void 0!==(null==t?void 0:t.start)?(t.start+(i?t.duration:0))/t.timescale:e}function Yr(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 me(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 Wr;try{Wr=self.performance.now.bind(self.performance)}catch(t){Wr=Date.now}const zr=[{demux:class{constructor(t,e,i,s=H){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 n=this.videoTrack=Wn("video",1),r=this.audioTrack=Wn("audio",1),a=this.txtTrack=Wn("text",1);if(this.id3Track=Wn("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;n.id=t,n.timescale=a.timescale=e,n.codec=i,n.supplemental=s}if(o.audio){const{id:t,timescale:e,codec:i}=o.audio;r.id=t,r.timescale=e,r.codec=i}a.id=St.text,n.sampleDuration=0,n.duration=r.duration=s}resetContiguity(){this.remainderData=null}static probe(t){return function(t,e){const i=t.byteLength;for(let s=0;s<i;){const n=At(t,s);if(n>8&&At(t,s+4)===Tt[e])return!0;s=n>1?s+n:i}return!1}(t,"moof")}demux(t,e,i){this.timeOffset=e;let s=t;const n=this.videoTrack,r=this.txtTrack;if(this.config.progressive){this.remainderData&&(s=Vt(this.remainderData,t));const e=function(t){const e={valid:null,remainder:null},i=xt(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,n.samples=e.valid||new Uint8Array}else n.samples=s;const a=this.extractID3Track(n,e),o=this.parseFragment(n,r,e,i);return{videoTrack:n,audioTrack:this.audioTrack,id3Track:a,textTrack:this.txtTrack,initData:this.initData,sampleData:o}}flush(t,e){const i=this.timeOffset,s=this.videoTrack,n=this.txtTrack;s.samples=this.remainderData||new Uint8Array,this.remainderData=null;const r=this.extractID3Track(s,this.timeOffset),a=this.parseFragment(s,n,i,e);return{videoTrack:s,audioTrack:Wn(),id3Track:r,textTrack:Wn(),initData:this.initData,sampleData:a}}parseFragment(t,e,i,s){const n=this.initData;if(n&&s){const{samples:r,sampleData:a}=function(t,e,i,s,n=!1){const r=[];return{samples:r,sampleData:{includeSampleDetails:n,tracks:Kt(e.samples,i,s,n,{isHEVCFlavor:Ht(e.codec),samples:r,timeOffset:t,timescale:e.timescale,trackId:e.id})}}}(i,t,n,this.logger,s.iframe);return e.samples=r,a}e.samples=function(t,e){const i=[],s=e.samples,n=e.timescale,r=e.id;let a=!1;return xt(s,["moof"]).map(o=>{const l=o.byteOffset-8;xt(o,["traf"]).map(o=>{const d=xt(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/n})[0];return void 0!==d&&(t=d),xt(o,["tfhd"]).map(d=>{const h=At(d,4),c=16777215&At(d,0),u=!!(1&c);let f=0;const g=!!(2&c),m=!!(8&c);let v=0;const y=!!(16&c);let E=0;const T=!!(32&c),S=!u&&!!(131072&c);let b=8;h===r&&(u?(f=At(d,b),b+=4,f*=Math.pow(2,32),f+=At(d,b),b+=4):S&&(f=l),g&&(b+=4),m&&(v=At(d,b),b+=4),y&&(E=At(d,b),b+=4),T&&(b+=4),"video"===e.type&&(a=Ht(e.codec)),xt(o,["trun"]).map(r=>{const o=r[0],l=16777215&At(r,0),d=!!(1&l);let h=0;const c=!!(4&l),u=!!(256&l);let g=0;const m=!!(512&l);let y=0;const T=!!(1024&l),S=!!(2048&l);let b=0;const A=At(r,4);let L=8;d&&(h=At(r,L),L+=4),c&&(L+=4);let I=f+h;for(let l=0;l<A;l++){if(u?(g=At(r,L),L+=4):g=v,m?(y=At(r,L),L+=4):y=E,T&&(L+=4),S&&(b=0===o?At(r,L):Rt(r,L),L+=4),e.type===p){let e=0;for(;e<y;){const r=At(s,I);I+=4,Yt(a,s[I])&&Wt(s.subarray(I,I+r),a?2:1,t+b/n,i),I+=r,e+=r+4}}t+=g/n}}))})})}),i}(i,t)}extractID3Track(t,e){const s=this.id3Track;if(t.samples.length){const n=xt(t.samples,["emsg"]);n&&n.forEach(t=>{const n=function(t){const e=t[0];let s,n="",r="",a=0,o=0,l=0,d=0,h=4;if(0===e){const e=It(t,h),i=null!==e?It(t,h+e.length):null;null!==e&&null!==i?(n=e,r=i,h+=e.length+i.length,a=At(t,h),h+=4,o=At(t,h),h+=4,l=At(t,h),h+=4,d=At(t,h),h+=4):(H.warn(`Unterminated ${null===e?"scheme_id_uri":"value"} in parsing emsg box: version 0 box ends inside a string, dropping all of its fields`),h=t.length)}else if(1===e){a=At(t,h),h+=4;const e=At(t,h);h+=4;const o=At(t,h);h+=4,s=2**32*e+o,i(s)||(s=Number.MAX_SAFE_INTEGER,H.warn("Presentation time exceeds safe integer limit and wrapped to max safe integer in parsing emsg box")),l=At(t,h),h+=4,d=At(t,h),h+=4;const c=It(t,h),u=null!==c?It(t,h+c.length):null;null!==c&&(n=c,h+=c.length),null!==u?(r=u,h+=u.length):(H.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"}`),h=t.length)}return{schemeIdUri:n,value:r,timeScale:a,presentationTime:s,presentationTimeDelta:o,eventDuration:l,id:d,payload:t.subarray(h,t.byteLength)}}(t);if(hr.test(n.schemeIdUri)){const t=cr(n,e);let i=4294967295===n.eventDuration?Number.POSITIVE_INFINITY:n.eventDuration/n.timeScale;i<=.001&&(i=Number.POSITIVE_INFINITY);const r=n.payload;s.samples.push({data:r,len:r.byteLength,dts:t,pts:t,type:Yn.emsg,duration:i})}else if(this.config.enableEmsgKLVMetadata){const t=this.config.emsgKLVSchemaUri||Yn.misbklv;if(n.schemeIdUri.startsWith(t)){const t=cr(n,e);s.samples.push({data:n.payload,len:n.payload.byteLength,dts:t,pts:t,type:Yn.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:n}=this;if(null==t||!t.byteLength)return this.initTracks=void 0,void(this.initData=void 0);const{audio:r,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)||(H.log(`[eme] Patching keyId in 'enc${e?"a":"v"}>sinf>>tenc' box: ${pt(s)} -> ${pt(i)}`),t.set(i,8))})}(t,e);else{const t=r||a;null!=t&&t.encrypted&&this.warn(`Init segment with encrypted track with has no key ("${t.codec}")!`)}r&&(s=Yr(r,g,this)),a&&(n=Yr(a,p,this));const o={};r&&a?o.audiovideo={container:"video/mp4",codec:s+","+n,supplemental:a.supplemental,encrypted:a.encrypted,initSegment:t,id:"main"}:r?o.audio={container:"audio/mp4",codec:s,encrypted:r.encrypted,initSegment:t,id:"audio"}:a?o.video={container:"video/mp4",codec:n,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,n,r,a,o,l,d,h,c){var u,f;let{initPTS:g,lastEndTime:p}=this;const m={audio:void 0,video:void 0,text:void 0,id3:s,initSegment:void 0};e(p)||(p=this.lastEndTime=r||0);const v=i.samples;if(!v.length)return m;const y=this.pendingInitSegment;y&&(this.pendingInitSegment=void 0,this.generateInitSegment(y,this.decryptdata,h));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."),m;if(d.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=xt(t,["moov"]);if(1!==e.length||xt(t,["moof"]).length)return null;const i=t.byteOffset,s=[],n=[];let r=!1;const a=xt(e[0],["trak"]);for(let t=0;t<a.length;t++){const e=a[t],o=xt(e,["mdia","hdlr"])[0];if("vide"===(o?yt(o.subarray(8,12)):"")){r=!0;continue}const l=xt(e,["tkhd"])[0];if(!l)return null;const d=l[0];n.push(At(l,0===d?12:20)),s.push(wt(e,i))}if(!r||!s.length)return null;const o=xt(e[0],["mvex"])[0];let l=0;if(o){const t=xt(o,["trex"]);for(let e=0;e<t.length;e++){const r=t[e];-1!==n.indexOf(At(r,4))&&(s.push(wt(r,i)),l+=r.byteLength+8)}}const{result:d,dropped:h,droppedBefore:c}=Dt(t,s);if(_t(d,e[0].byteOffset-i-8,e[0].byteLength+8-h),o&&l){const t=o.byteOffset-i-8;_t(d,t-c(t),o.byteLength+8-l)}return d}(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,m.initSegment=E,this.emitInitSegment=!1);const A=d.iframe,L=!c||A&&!c.includeSampleDetails?function(t,e,i,s,n=!0){return Kt(t,e,s,n)}(v,T,0,this,A):c.tracks,I=T.audio?L[T.audio.id]:null,R=T.video?L[T.video.id]:null,_=!!T.audio,k=!!T.video;let w="";_&&(w+="audio"),k&&(w+="video");const D=Hr(R,1/0),x=Hr(I,1/0),P=Hr(R,0,!0),C=Hr(I,0,!0);let M=r,O=0;R&&I&&T.audio&&(x>P||D>C)&&this.warn(`audio and video track sample timestamps do not overlap. v: ${D}-${P} a: ${x}-${C}}`,R,I);const F=!!I&&(!R||!g&&x<D||!!g&&g.trackId===T.audio.id),N=F?I:R;if(!N)return this.log(`No media samples found in ${l} ${d.level} ${-1===d.part?"":`part: ${d.part} of`} sn: ${d.sn} at playlist time: ${r}`),m;let $,B=v;if(R&&R.sampleCount>=1&&T.video&&d.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 n=t[0];let r=n;for(let e=t.length;e--;)if(t[e].samples.length){r=t[e];break}const a=r.lastSampleDurationOffset,{defaultSampleDurationOffset:o}=n,l=Math.abs(d.duration-(P-D))>.05,h=s.length<R.sampleCount;if(l||h||this.videoOnlyRemux||!i){const t=h?r.sampleOffset+r.samples.reduce((t,e)=>t+e.size,0):void 0,i=l?d.duration:P-D,n=function(t,e,i,s){if(void 0!==i){const s=t[t.length-1];let n=e;for(let e=0;e<t.length-1;e++)n-=t[e].duration;return n<=0&&(n=s.duration),s.duration=n,{durationOffset:i,value:n}}if(void 0===s)return;const n=Math.round(e/t.length);for(let e=0;e<t.length;e++)t[e].duration=n;return{durationOffset:s,value:n}}(s,i*T.video.timescale,a,o),c=function(t,e,i,s,n){if(i<1)return null;const r=xt(t,["moof"]);if(1!==r.length)return null;const a=r[0],o=t.byteOffset,l=[],d=[],h=xt(a,["traf"]);let c=!0;for(let t=0;t<h.length;t++){const i=h[t],s=xt(i,["tfhd"])[0];if(!s)return null;At(s,4)===e?(l.push(i),131072&At(s,0)||(c=!1)):d.push(wt(i,o))}if(!l.length)return null;if(d.length&&!c)return null;if(void 0!==s){let e=i;for(let i=0;i<l.length;i++){const s=l[i];let n=0;const r=xt(s,["trun"]);for(let i=0;i<r.length;i++){const s=r[i],a=Math.min(e,At(s,4));if(a){_t(t,s.byteOffset-o+4,a);const e=16777215&At(s,0);kt(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 _t(t,s.byteOffset-o-4,Tt.free);e-=a,n+=a}const a=xt(s,["senc"])[0];a&&_t(t,a.byteOffset-o+4,n);const d=xt(s,["saiz"])[0];if(d){let e=4;1&(d[1]<<16|d[2]<<8|d[3])&&(e+=8);const i=d[e];e+=1,_t(t,d.byteOffset-o+e,n),kt(t,d,e+4+(0===i?n:0))}}const n=xt(t,["mdat"]);if(1===n.length){const e=n[0].byteOffset-o-8;_t(t,e,s-e)}}let u=t,f=0,g=()=>0;if(d.length){({result:u,dropped:f,droppedBefore:g}=Dt(t,d)),_t(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=xt(e,["trun"]);for(let t=0;t<s.length;t++){const e=s[t];1&At(e,0)&&_t(u,e.byteOffset-o-i+8,At(e,8)-f)}if(i){const t=xt(e,["saio"]);for(let e=0;e<t.length;e++){const s=t[e],n=0===s[0]?4:8;let r=1&At(s,0)?12:4,a=At(s,r);for(r+=4;a--;r+=n){const t=r+n-4;_t(u,s.byteOffset-o-i+t,At(s,t)-i)}}}}}if(n){const{durationOffset:t,value:e}=n;_t(u,t-g(t),e)}return void 0!==s?u.subarray(0,s-f):u}(v,T.video.id,s.length,t,n);c?(B=c,$=function(t,e){let i=t,s=t;for(let t=0;t<e.length;t++){const{cts:n,duration:r}=e[t];s=Math.max(s,i+(n||0)+r),i+=r}return s}(e,s)):this.warn(`IFrame remux skipped (sn ${d.sn}); using native sample duration`),O=c&&n?i:P-D}else O=P-D}else this.warn(`Could not remux IFrame track fragment (no samples in range, trun count ${t.length})`),O=P-D}else O=F?C-x:P-D;if(this.videoOnlyRemux&&B===v)return this.warn(`Dropping muxed I-Frame fragment that could not be remuxed to video-only (sn: ${d.sn})`),m;const U=N.timescale,G=N.start-r*U,j=F?T.audio.id:T.video.id;M=N.start/U;if(!(!!g&&d.id>1)&&(a||!g)&&(function(t,e,i,s){if(null===t)return!0;const n=Math.max(s,1),r=e-t.baseTime/t.timescale;return Math.abs(r-i)>=n}(g,M,r,O)||U!==g.timescale)){let t=!1;const e=F?"audio":"video";if(g){const i=0!==r?M/r:1+M/1;t=M>=0&&Math.abs(1-i)<.001,this.log(`${e} timestamps in track ${j} at playlist time: ${a?"":"~"}${r} maps to ${M} with initPTS: ${g.baseTime/g.timescale} (${G/U-g.baseTime/g.timescale}s diff) (${w}) drift estimate: ${i} ${t?"(ignoring drift)":"remapping timestamps (initPTS)"}`)}t||(this.log(`Found initPTS in ${e} track ${j} at playlist time: ${r} offset: ${M-r} (${G}/${U})`),g=null,E.initPTS=G,E.timescale=U,E.trackId=j)}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 q=M-g.baseTime/g.timescale,K=q+O,V=k&&void 0!==(null==N?void 0:N.ptsMin)?N.ptsMin/N.timescale-g.baseTime/g.timescale:q,H=void 0!==$&&R?$/R.timescale-g.baseTime/g.timescale:k&&null!=N&&N.ptsMax?N.ptsMax/N.timescale-g.baseTime/g.timescale:K;O>0?this.lastEndTime=K:(this.warn("Duration parsed from mp4 should be greater than zero"),this.resetNextTimestamp());const Y={data1:B,data2:void 0,startPTS:V,startDTS:q,endPTS:H,endDTS:K,type:w,hasAudio:_,hasVideo:k,nb:1,dropped:0,encrypted:!!T.audio&&T.audio.encrypted||!!T.video&&T.video.encrypted};m.audio=_&&!k?Y:void 0,m.video=k?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||(m.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 m.initSegment=E,m.id3=Kr(s,r,g,g),n.samples.length&&(m.text=Vr(n,r,g)),m}}},{demux:vr,remux:jr},{demux:class extends zn{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=rt(t,0);let s=(null==i?void 0:i.length)||0;if(rr(t,s))return!1;for(let i=t.length;s<i;s++)if(qn(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)&&Bn(t,e)&&Gn(t,e)<=t.length-e}(t,e)}appendFrame(t,e,i){Kn(t,this.observer,e,i,t.manifestCodec);const s=Hn(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),n=this.sampleAes=new ar(this.observer,this.config,e);return new Promise(t=>{n.decryptAacSamples(s.audioTrack.samples,0,()=>{t(s)})})}},remux:jr},{demux:class extends zn{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=rt(t,0);let i=(null==e?void 0:e.length)||0;if(e&&11===t[i]&&119===t[i+1]&&void 0!==gt(e)&&or(t,i)<=16)return!1;for(let e=t.length;i<e;i++)if(rr(t,i))return H.log("MPEG Audio sync word found !"),!0;return!1}canParse(t,e){return function(t,e){return sr(t,e)&&4<=t.length-e}(t,e)}appendFrame(t,e,i){if(null!==this.basePTS)return er(t,e,i,this.basePTS,this.frameIndex)}},remux:jr}];zr.splice(2,0,{demux:lr,remux:jr});class Xr{constructor(t,e,i,s,n,r){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=n,this.logger=r}configure(t){this.transmuxConfig=t,this.decrypter&&this.decrypter.reset()}push(t,e,i,s){if(!this.observer)return Qr(i);const o=i.transmuxing;o.executeStart=Wr();const l=new Uint8Array(t),{currentTransmuxState:d,transmuxConfig:h}=this;s&&(this.currentTransmuxState=s);const{contiguous:c,discontinuity:u,trackSwitch:f,accurateTimeOffset:g,timeOffset:p,initSegmentChange:m}=s||d,{audioCodec:v,videoCodec:y,defaultInitPts:E,duration:T,initSegmentData:S}=h,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=ps(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&&vr.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:n.MEDIA_ERROR,details:r.FRAG_PARSING_ERROR,fatal:!1,error:e,reason:e.message}),o.executeEnd=Wr(),Qr(i)}(u||f||m||A)&&this.resetInitSegment(S,v,y,T,e,i),(u||m||A)&&this.resetInitialTimestamp(E),c||this.resetContiguity();const L=this.transmux(l,b,p,g,i);this.asyncResult=Jr(L);const I=this.currentTransmuxState;return I.contiguous=!0,I.discontinuity=!1,I.trackSwitch=!1,o.executeEnd=Wr(),L}flush(t){const e=t.transmuxing;e.executeStart=Wr();const{decrypter:i,currentTransmuxState:s,decryptionPromise:n}=this;if(n)return this.asyncResult=!0,n.then(()=>this.flush(t));const r=[],{timeOffset:a}=s;if(i){const e=i.flush();e&&r.push(this.push(e.buffer,null,t))}const{demuxer:o,remuxer:l}=this;if(!o||!l){e.executeEnd=Wr();const i=[Qr(t)];return this.asyncResult?Promise.resolve(i):i}const d=o.flush(a,t);return Jr(d)?(this.asyncResult=!0,d.then(e=>(this.flushRemux(r,e,t),r))):(this.flushRemux(r,d,t),this.asyncResult?Promise.resolve(r):r)}flushRemux(t,e,i){if(!this.remuxer)return;const{audioTrack:s,videoTrack:n,id3Track:r,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 d=this.remuxer.remux(s,n,r,a,l,o,!0,this.id,i,e.initData,e.sampleData);t.push({remuxResult:d,chunkMeta:i}),i.transmuxing.executeEnd=Wr()}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,n,r){const{demuxer:a,remuxer:o}=this;a&&o&&(a.resetInitSegment(t,e,i,s,n,r),o.resetInitSegment(t,e,i,n))}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,n){let r;return r="SAMPLE-AES"===(null==e?void 0:e.method)?this.transmuxSampleAes(t,e,i,s,n):this.transmuxUnencrypted(t,i,s,n),r}transmuxUnencrypted(t,e,i,s){const{demuxer:n,remuxer:r}=this;if(!n||!r)return Qr(s);const a=n.demux(t,e,s,!1,!this.config.progressive),{audioTrack:o,videoTrack:l,id3Track:d,textTrack:h}=a;return{remuxResult:r.remux(o,l,d,h,e,i,!1,this.id,s,a.initData,a.sampleData),chunkMeta:s}}transmuxSampleAes(t,e,i,s,n){return this.demuxer?this.demuxer.demuxSampleAes(t,e,i,n).then(t=>({remuxResult:this.remuxer.remux(t.audioTrack,t.videoTrack,t.id3Track,t.textTrack,i,s,!1,this.id,n,t.initData,t.sampleData),chunkMeta:n})):Promise.reject(new Error("no demuxer"))}configureTransmuxer(t){const{config:e,observer:i,typeSupported:s}=this;if(!i)return;let n;try{for(let e=0,i=zr.length;e<i;e++){var r;if(null!=(r=zr[e].demux)&&r.probe(t,this.logger)){n=zr[e];break}}}catch(t){return t}if(!n)return new Error("Failed to find demuxer by probing fragment data");const a=this.demuxer,o=this.remuxer,l=n.demux,d=n.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 d||(this.logger.log(`Using ${d.name}`),this.remuxer=new d(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 Hi(this.config)),t}}const Qr=t=>({remuxResult:{},chunkMeta:t});function Jr(t){return"then"in t&&t.then instanceof Function}class Zr{constructor(t,e,i,s,n){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=n||null}}class ta{constructor(t,e,i,s,n,r){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=n,this.initSegmentChange=r}}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:n.OTHER_ERROR,details:r.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 Fn,this.observer.on(a.FRAG_DECRYPTED,l),this.observer.on(a.ERROR,l);const d=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=$n[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 $n[t]=s,s}(o.workerPath)):(i.log(`injecting Web Worker for "${e}"`),this.workerContext=function(){const t=$n[Nn];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 $n[Nn]=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:d,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 Xr(this.observer,d,o,"",e,t.logger)}return}}this.transmuxer=new Xr(this.observer,d,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=$n[t||Nn];if(e&&1===e.clientCount--){const{worker:i,objectURL:s}=e;delete $n[t||Nn],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,n,r,a,o,l,d){var h,c;l.transmuxing.start=self.performance.now();const{instanceNo:u,transmuxer:f}=this,g=r?r.start:n.start,p=n.decryptdata,m=this.frag,v=!m||n.cc!==m.cc,y=!m||l.level!==m.level,E=m?l.sn-m.sn:-1,T=this.part?l.part-this.part.index:-1,S=0===E&&l.id>1&&l.id===(null==m?void 0:m.stats.chunkCount),b=!y&&(1===E||0===E&&(1===T||S&&T<=0)),A=self.performance.now();(y||E||0===n.stats.parsing.start)&&(n.stats.parsing.start=A),!r||!T&&b||(r.stats.parsing.start=A);const L=!(m&&(null==(h=n.initSegment)?void 0:h.url)===(null==(c=m.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 ${n.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 Zr(i,s,e,a,d);this.configureTransmuxer(t)}if(this.frag=n,this.part=r,this.workerContext)this.workerContext.worker.postMessage({instanceNo:u,cmd:"demux",data:t,decryptdata:p,chunkMeta:l,state:I},t instanceof ArrayBuffer?[t]:[]);else if(f){const e=f.push(t,p,l,I);Jr(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);Jr(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:n.MEDIA_ERROR,details:r.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 n=-1;for(let i=0;i<s.length;i++){const r=s[i];let a;try{a=new self.URL(r.URI,e.url).href}catch(t){this.warn(`Could not construct new URL for Rendition Report: ${t}`),a=r.URI||""}if(a===t){n=i;break}a===t.substring(0,a.length)&&(n=i)}if(-1!==n){const t=s[n],r=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(r,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,d=self.performance.now(),h=o.loading.first?Math.max(0,Math.floor(d-o.loading.first)):0;s.advancedDateTime=Date.now()-h;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:n.NETWORK_ERROR,details:r.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){sn(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:n.NETWORK_ERROR,details:r.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,p=g?g.end-g.len:0,m=an(s,1e3*(s.edge-p));s.requestScheduled+m<d?s.requestScheduled=d:s.requestScheduled<=d&&(s.requestScheduled+=m);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,n=s.lastPartSn,r=s.endSN,a=s.lastPartIndex,o=n===r;-1!==a?o?(E=r+1,T=t?0:a):(E=n,T=t?a+1:s.maxPartIndex):E=r+1;const l=s.age,h=l+s.ageHeader;let u=Math.min(h-s.partTarget,1.5*s.targetduration);if(u>0){if(h>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&&h-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=d,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(m-2*h,m/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 n=self.performance.now(),r=s.requestScheduled;if(n>=r&&!this.loadingSync)return this.loadingSync=!0,this.loadingPlaylist(t,e),void(this.loadingSync=!1);const a=Math.max(r-n,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 n=Oe(t);return null!=e&&e.skip&&t.deltaUpdateFailed&&(i=e.msn,s=e.part,n=Pe),new Fe(i,s,n)}checkRetry(t){const e=t.details,i=w(t),s=t.errorAction,{action:n,retryCount:r=0,retryConfig:a}=s||{},o=!!s&&!!a&&(n===oi||!s.resolved&&n===ri);if(o){var l;if(r>=a.maxNumRetry)return!1;if(i&&null!=(l=t.context)&&l.deliveryDirectives)this.warn(`Retrying playlist loading ${r+1}/${a.maxNumRetry} after "${e}" without delivery-directives`),this.loadPlaylist();else{var d;const i=F(null==(d=t.response)?void 0:d.code);if(this.clearTimer(),i)this.log("Waiting for connection (offline)"),t.reason="offline",this.timer=self.setTimeout(()=>this.checkOfflineStatus(),1e3);else{const t=C(a,r);this.warn(`Retrying playlist loading ${r+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 na(t,e){if(t.length!==e.length)return!1;for(let i=0;i<t.length;i++)if(!ra(t[i].attrs,e[i].attrs))return!1;return!0}function ra(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 n=t.length-1;const r=Math.max(e,i);for(let e=0;e<t.length;e+=1){const i=t[e];if((i.width>=r||i.height>=r)&&s(i,t[e+1])){n=e;break}}return n}}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} "${n=e,Array.isArray(n)?JSON.stringify(n):n instanceof Map?"Map{}":n instanceof Set?"Set{}":"object"==typeof n?JSON.stringify(n):String(n)}" as ${i}`,{cause:s});var n}const da="Bare Item";const ha=/[\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 pa(t){const e=Z(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 ma(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,da);return Number.isInteger(t)?ga(t):pa(t);case"string":return function(t){if(ha.test(t))throw ua(t,"String");return`"${t.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}(t);case"symbol":return ma(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 ma(t);default:throw ua(t,da)}}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),_a=t=>Array.isArray(t)?t.map(Ra):Ra(t),ka=(t,e)=>Array.isArray(t)?t.map(t=>ka(t,e)):t instanceof oa&&"string"==typeof t.value?new oa(ka(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 n=i.pathname.split("/").slice(1),r=s.pathname.split("/").slice(1,-1),a=Math.min(n.length,r.length);for(let t=0;t<a&&n[t]===r[t];t++)n.shift(),r.shift();for(;r.length;)r.shift(),n.unshift("..");return n.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),wa=t=>t instanceof oa?new oa(100*Math.round(t.value/100),t.params):100*Math.round(t/100),Da=t=>Array.isArray(t)?t.map(wa):wa(t),xa={br:_a,d:_a,bl:Da,dl:Da,mtp:Da,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])),ka(i,e)},rtp:Da,tb:_a},Pa=2,Ca="rr",Ma="bc",Oa="e",Fa=Ca,Na="ce",$a=new Map([["ps","sta"],["pr","pr"],["c","cid"],["b","bg"],["bc","br"]]),Ba="event",Ua="request",Ga=["cen","e","h","ts"],ja=["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"],qa=/^[a-zA-Z0-9-.]+-[a-zA-Z0-9-.]+$/;function Ka(t){return qa.test(t)}const Va=new Set(ja);function Ha(t){return Va.has(t)||Ka(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"]),Ja=["bl","br","bs","cid","d","dl","mtp","nor","nrr","ot","pr","rtp","sf","sid","st","su","tb","v"],Za=new Set(Ja);function to(t){return Za.has(t)||Ka(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 no={[Ba]:function(t){return Ha(t)||za(t)||Xa.has(t)},[Ua]:Ha};function ro(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]),ro(i)}return t instanceof oa?t.value:t}function ao(t,i={}){const s={};if(null==t||"object"!=typeof t)return s;const n=i.version||t.v||Pa,r=i.reportingMode||Ua,a=1===n?function(t){const e={};for(const[s,n]of Object.entries(t))if(null!=n)if("nor"===s){const t=(Array.isArray(n)?n:[n])[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]=ro(n,t.ot):e[s]=n;else e[s]=n;return e}(t):t,o=1===n?to:no[r];let l=Object.keys(a).filter(o);a.e&&a.e!==Ca&&(l=l.filter(t=>!za(t)));const d=i.filter;"function"==typeof d&&(l=l.filter(d));const h=r===Ba;if(h){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;n>1&&!l.includes("v")&&l.push("v");const c={version:n,reportingMode:r,baseUrl:i.baseUrl};l.sort();for(const t of l){var u,f;let r=a[t];const o=null!=(u=null==(f=i.formatters)?void 0:f[t])?u:xa[t];if("function"==typeof o&&(r=o(r,c)),"v"===t){if(1===n)continue;r=n}if("pr"===t&&1===r&&(!h||"pr"!==a.e))continue;h&&"ts"===t&&!e(r)&&(r=Date.now());const l=h&&!1===r&&"bg"===t&&"b"===a.e;(so(r)||l)&&(io(t)&&"string"==typeof r&&(r=new ca(r)),s[t]=r)}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),n=e?(r=e,Object.keys(r).reduce((t,e)=>{var i;return null==(i=r[e])||i.forEach(i=>t[i]=e),t},{})):{};var r;for(const e of s){var a;const s=fo[e]||n[e]||uo;(null!=(a=i[s])?a:i[s]={})[e]=t[e]}return i}const po="CMCD";function mo(t){return ba(t,{whitespace:!1})}const vo=[...Ja,...ja,...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",_o="r",ko="a",wo="e",Do="f",xo="d",Po="query",Co="headers";function Mo(t,e,i){var s;const n=new Set(null!=(s=e.enabledKeys)?s:[]);return{version:e.version||Pa,reportingMode:t,filter:t=>n.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],n=e[i];if(s===n)continue;if("number"==typeof s||"number"==typeof n)return!1;if(s.value!==n.value)return!1;const r=s.params,a=n.params,o=r&&Object.keys(r)[0],l=a&&Object.keys(a)[0];if(o!==l)return!1;if(void 0!==o&&void 0!==l&&r&&a&&r[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=k(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=Pa,eventTargets:i=[],sid:s=tt(),transmissionMode:n=Po}=t;return _(_({},k(t,La)),{},{version:e,transmissionMode:n,sid:s,eventTargets:i.reduce((t,e)=>{var i,s,n;return null!=e&&e.url&&null!=(i=e.events)&&i.length&&t.push({version:e.version||Pa,enabledKeys:(null==(s=e.enabledKeys)?void 0:s.slice())||[],url:e.url,events:e.events.slice(),interval:null!=(n=e.interval)?n: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=_(_(_({},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 n=this.data[t];if(void 0===n)return;if(i.equal(n,this.lastEmitted[t]))return;I(this.lastEmitted,{[t]:i.snapshot(n)})}this.eventTargets.forEach((i,s)=>{this.recordTargetEvent(i,s,t,e)}),this.processEventTargets()}recordTargetEvent(t,e,i,s={}){var n;if(!e.events.includes(i))return;const r=_(_(_({},this.data),s),{},{e:i,ts:null!=(n=s.ts)?n:Date.now(),sn:t.sn++});isNaN(this.msd)||t.msdSent||(r.msd=this.msd,t.msdSent=!0),t.queue.push(r)}recordResponseReceived(t,e={}){var i,s,n;const{request:r}=t,a=null!=(i=e.url)?i:null==r?void 0:r.url;if(!a)return;const o=new URL(a);o.searchParams.delete(po);const l={url:o.toString(),rc:t.status},d=t.resourceTiming;d&&(null!=d.startTime&&(l.ts=Math.round(this.timeOrigin+d.startTime),null!=d.responseStart&&(l.ttfb=Math.round(d.responseStart-d.startTime))),null!=d.duration&&(l.ttlb=Math.round(d.duration)));const h=null!=(s=null==(n=r.customData)?void 0:n.cmcd)?s:{};this.recordEvent(Ca,_(_(_({},h),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:n={}}=t,r=_(_({},k(t,Ia)),{},{headers:_({},n),customData:_(_({},s),{},{cmcd:{}})});if(null==(i=this.config.enabledKeys)||!i.length||!r.url)return r;const a=new URL(r.url),o=_(_(_({},this.data),e),{},{sn:this.requestTarget.sn++}),l=Mo(Ua,this.config,r.url);isNaN(this.msd)||this.requestTarget.msdSent||(o.msd=this.msd,this.requestTarget.msdSent=!0);const d=r.customData.cmcd=ao(o,l);switch(this.config.transmissionMode){case Po:const t=mo(d);t&&(a.searchParams.set(po,t),r.url=a.toString());break;case Co:I(r.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}(d,l.customHeaderMap))}return r}processEventTargets(t=!1){let e=!1;this.eventTargets.forEach((i,s)=>{const{queue:n}=i;if(!n.length)return;if(n.length<s.batchSize&&!t)return;const r=t?n.length:s.batchSize,a=n.splice(0,r);this.sendEventReport(s,a).catch(()=>{i.queue.unshift(...a)}),e||(e=n.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?mo(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",jo="v",qo="l",Ko="ll";new Set(Ja),new Set(vo);const Vo=["includeKeys"];function Ho(t){return Object.keys(t).every(Ka)}function Yo(t,e,i,s){t&&Object.keys(e).forEach(n=>{const r=t.filter(t=>t.groupId===n).map(t=>{const r=I({},t);return r.details=void 0,r.attrs=new ls(r.attrs),r.url=r.attrs.URI=Wo(t.url,t.attrs["STABLE-RENDITION-ID"],"PER-RENDITION-URIS",i),r.groupId=r.attrs["GROUP-ID"]=e[n],r.attrs["PATHWAY-ID"]=s,r});t.push(...r)})}function Wo(t,e,i,s){if(e){const{[i]:t}=s;if(t){const i=t[e];if(i)return i}}const{HOST:n,PARAMS:r}=s,a=new self.URL(t);return n&&(a.hostname=n),r&&Object.keys(r).sort().forEach(t=>{t&&we(a,t,r[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 Fn,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=ks(this.config));const e=t.map(_s).filter(t=>!!t);this.keyFormatPromise=this.getKeyFormatPromise(e)}this.keyFormatPromise.then(n=>{let r;const a=Is(n),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");r=new Uint8Array(e.subarray(8,24))}catch(t){return void this.warn(`${s} Failed to parse sinf: ${t}`)}else if(a===Ts.PLAYREADY)r=xs(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];r=null!=(l=e.kids)&&l.length?e.kids[0]:null}}let d;if(r){const t=pt(r);for(let s=0;s<o.length;s++){const n=o[s];if(n.keyId&&(us(r,n.keyId)||-1!==n.uri.replace(/-/g,"").indexOf(t))){n.pssh||(n.scheme=e,n.pssh=new Uint8Array(i),n.keyId=r,Cs.setKeyIdForUri(n.uri,r)),d=this.getSessionForKey(n,"encrypted-event-key-match");break}}}if(!d){var h,c;if(o.length)return(h=o[0]).scheme||(h.scheme=e),(c=o[0]).pssh||(c.pssh=new Uint8Array(i)),this.getSessionForKey(o[0],"encrypted-event-no-match");if(r)throw new Error(`Key ID ${pt(r)} not encountered in playlist`);this.log(`Ignoring "${t.type}" event - could not determine keyId`)}return d}).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:n.KEY_SYSTEM_ERROR,details:r.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===ws&&"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 n=function(t,e,i,s){let n;switch(t){case Ts.FAIRPLAY:n=["cenc","sinf"];break;case Ts.WIDEVINE:case Ts.PLAYREADY:n=["cenc"];break;case Ts.CLEARKEY:n=["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}))}]}(n,e,i,s)}(t,e,i,this.config.drmSystemOptions||{});let r=this.keySystemAccessPromises[t],a=null==(s=r)?void 0:s.keySystemAccess;if(!a){this.log(`Requesting encrypted media "${t}" key-system access with config: ${Ue(n)}`),a=this.requestMediaKeySystemAccess(t,n);const e=r=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 n=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 n.catch(e=>{this.error(`Failed to create media-keys for "${t}"}: ${e}`)}),n})}return a.then(()=>r.mediaKeys)}getMediaKeySessionContext(t,e,i,s){const{mediaKeySessions:n}=this,r=` key-session "${t}" keyId: ${pt(i.keyId||[])} keyUri: ${i.uri} for "${s}"`;for(let t=0;t<n.length;t++){const e=n[t];if(!e.initialized&&e.createdFor.levelKey.uri===i.uri)return this.log(`Reusing${r}`),e}this.log(`Creating${r}`);const a=e.createSession(),o={keySystem:t,mediaKeys:e,mediaKeysSession:a,keyRequests:{},keyStatuses:{},createdFor:{levelKey:i,reason:s},initialized:!1};return n.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 ${pt(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})=>_s(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=_s(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=ks(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,n=e.length;s<n;s++){const r=e[s];if(t.cc<=r.cc&&(!y(t)||!y(r)||t.sn<r.sn)||!i&&s==n-1)return this.selectKeySystemFormat(r).then(t=>{if(!this.hls)return;r.setKeyFormat(t);const e=Is(t);return e?this.getKeySystemAccess([e]):void 0})}if(this.config.requireKeySystemAccessOnStart){const t=ks(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=Jo(t,e[i]);if(s)return s}}loadKey(t){const e=t.decryptdata,i=this.getKeyStatus(e);if("internal-error"===i){const s=Zo(i,e);return s.data.frag=t,this.error(`${s.message} (${pt(e.keyId||[])})`),Promise.reject(s)}const s=t.type,n=this.activeKeys,r=n[s];r&&!e.matches(r.decryptdata)&&(n.previous||(n.previous=[]),n.previous.push(r),delete n[s]),n[s]||(n[s]=t);for(let t=this.mediaKeySessions.length;t--;){const i=this.mediaKeySessions[t];if(e.keyId&&"expired"===i.keyStatuses[pt(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,n=this.sessionSetupByUri[s];let r;r=void 0===n?this.resolveSessionForKey(t,e):n.catch(()=>{}).then(()=>(this.throwIfDestroyed(),this.resolveSessionForKey(t,e))),this.sessionSetupByUri[s]=r;const a=()=>{this.sessionSetupByUri[s]===r&&delete this.sessionSetupByUri[s]};return r.then(a,a),r}findContextForKey(t){const{mediaKeySessions:e}=this;for(let i=e.length;i--;){const s=e[i];if(Jo(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(Jo(t,s))return s;const n=this.getUsableKeyPromise(s,t,e);if(n)return n}return this.attemptSetMediaKeys(i,s).then(()=>(this.throwIfDestroyed(),this.getMediaKeySessionContext(i,s,t,e))).then(i=>{this.throwIfDestroyed();const s=t.scheme||"cenc",n=t.pssh?t.pssh.buffer:null;return this.generateRequestWithPreferredKeySession(i,t,s,n,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 pt(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?` (${pt(i.keyId||[])})`:""}`),this.hls.trigger(a.ERROR,t.data)}else this.error(t.message),this.hls.trigger(a.ERROR,{type:n.KEY_SYSTEM_ERROR,details:r.KEY_SYSTEM_NO_KEYS,error:t,fatal:!0,reason:`${t.name}: ${t.message}`})}getKeySystemForKeyPromise(t){const e=Is(t.keyFormat),i=e?[e]:ks(this.config);return this.attemptKeySystemAccess(i)}getKeySystemSelectionPromise(t){if(t.length||(t=ks(this.config)),0===t.length)throw new Xo({type:n.KEY_SYSTEM_ERROR,details:r.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,n){var r;const a=null==(r=this.config.drmSystems)||null==(r=r[t.keySystem])?void 0:r.generateRequest;if(a)try{const r=a.call(this.hls,i,s,I({},t,{decryptdata:e,reason:n}),n);if(!r)throw new Error("Invalid response from configured generateRequest filter");e.scheme=r.initDataType?r.initDataType:"cenc";const o=r.initData?r.initData:null;return e.pssh=o?new Uint8Array(o):null,r}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,n){const r=this.getUsableKeyPromise(t,e,n);if(r)return r;const a=this.filterInitData(t,e,i,s,n);if(a&&(s=a.initData?a.initData:null,i=a.initDataType),null===s)return n.startsWith("encrypted-event")?Promise.reject(new Error(`missing initialization data for "${n}"`)):(this.log(`Skipping key-session request for "${n}" (no initData)`),Promise.resolve(t));const o=e.uri,l=new zo;t.keyRequests[o]=l;const d=i=>{const s=t.mediaKeysSession;if(!s){const t=new Error("invalid state");return void(l.errored=t)}const{messageType:n,message:r}=i;l.status=n,this.log(`"${n}" message event for session "${s.sessionId}" message size: ${r.byteLength}`),"license-request"===n||"license-renewal"===n?this.renewLicense(t,e,r).catch(e=>{l.errored=e,l.hasListeners||this.handleError(e),this.removeSession(t)}):"license-release"===n?t.keySystem===Ts.FAIRPLAY&&this.updateKeySession(t,e,ms("acknowledged")).then(()=>this.removeSession(t)).catch(t=>this.handleError(t)):this.warn(`unhandled media key message type "${n}"`)};l.onmessage=d,Ti(t.mediaKeysSession,"message",d);return this.generateRequest(t,e,i,s,n,!1)}generateRequest(t,e,i,s,a,o){if(o){const n=this.filterInitData(t,e,i,s,a);n&&(s=n.initData?n.initData:s,i=n.initDataType)}const l=e.uri,d=t.keyRequests[l],h=pt(e.keyId||[]),c=t=>{let i;t.startsWith("usable")?d.resolve():"internal-error"===t||"output-restricted"===t||"output-downscaled"===t?i=Zo(t,e):"expired"===t?i=new Error(`key expired (keyId: ${h})`):"released"===t?i=new Error("key released"):"status-pending"===t||this.warn(`unhandled key status change "${t}" (keyId: ${h})`),i&&(d.errored=i,d.hasListeners||this.handleError(i))},u=i=>{if(!t.mediaKeysSession){const t=new Error("invalid state");return void(d.errored=t)}const s=t.keyStatuses=this.getKeyStatuses(t);if(!Object.keys(s).some(t=>"status-pending"!==s[t]))return;const n=this.activeLevelKeys();for(let i=0;i<n.length;i++){const a=pt(n[i].keyId||[]);if("expired"===s[a]){var r;this.log(`Expired key ${Ue(s)} in key-session "${null==(r=t.mediaKeysSession)?void 0:r.sessionId}"`),this.renewKeySession(e,t).catch(t=>this.handleError(t));break}}let a=s[h];if(a)c(a);else{var o;const i=1e3;t.keyStatusTimeouts||(t.keyStatusTimeouts={}),(o=t.keyStatusTimeouts)[h]||(o[h]=self.setTimeout(()=>{var s;if(!t.mediaKeysSession)return;const n=this.getKeyStatus(e);var r;if(n&&"status-pending"!==n)return this.log(`No status for keyId ${h} in key-session "${null==(r=t.mediaKeysSession)?void 0:r.sessionId}". Using session key-status ${n} from other session.`),c(n);this.log(`key status for ${h} 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 ${h} (${Ue(s)}).`)}};d.onkeystatuseschange=u,Ti(t.mediaKeysSession,"keystatuseschange",u);const f=d.useable;return this.log(`Generating key-session request for "${a}" keyId: ${h} URI: ${l} (init data type: ${i} length: ${s.byteLength})`),d.status="started",t.initialized=!0,t.mediaKeysSession.generateRequest(i,s).then(()=>{var e;d.status="generated",this.log(`Request generated for key-session "${null==(e=t.mediaKeysSession)?void 0:e.sessionId}" keyId: ${h} URI: ${l}`)}).catch(t=>{throw this.log(`mediaKeysSession.generateRequest failed: ${t}`),new Xo({type:n.KEY_SYSTEM_ERROR,details:r.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!==r.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED&&s!==r.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,n)=>{if("string"==typeof n&&"object"==typeof s){const t=n;n=s,s=t}const r="buffer"in n?new Uint8Array(n.buffer,n.byteOffset,n.byteLength):new Uint8Array(n);if(t.keySystem===Ts.PLAYREADY&&16===r.length){const t=pt(r);e[t]=s,vs(r)}const a=pt(r);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},d=e.certLoadPolicy.default,h={loadPolicy:d,timeout:d.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},c={onSuccess:(t,e,i,s)=>{a(t.data)},onError:(e,i,a,d)=>{o(new Xo({type:n.KEY_SYSTEM_ERROR,details:r.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:a,response:_({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:n.KEY_SYSTEM_ERROR,details:r.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,h,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(n=>{this.log(`setServerCertificate ${n?"success":"not supported by CDM"} (${i.byteLength}) on "${e}"`),s(t)}).catch(t=>{a(new Xo({type:n.KEY_SYSTEM_ERROR,details:r.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:n.KEY_SYSTEM_ERROR,details:r.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"),n=s.querySelectorAll("HttpHeader");if(n.length>0){let e;for(let i=0,s=n.length;i<s;i++){var r,a;e=n[i];const s=null==(r=e.querySelector("name"))?void 0:r.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 ms(atob(l))}setupLicenseXHR(t,e,i,s,n){const r=this.config.licenseXhrSetup;return r?Promise.resolve().then(()=>(this.throwIfDestroyed(),r.call(this.hls,t,e,_(_({},i),{},{decryptdata:s}),n))).catch(a=>{if(!i.mediaKeysSession)throw a;return t.open("POST",e,!0),r.call(this.hls,t,e,_(_({},i),{},{decryptdata:s}),n)}).then(i=>{t.readyState||t.open("POST",e,!0);return{xhr:t,licenseChallenge:i||n}}):(t.open("POST",e,!0),Promise.resolve({xhr:t,licenseChallenge:n}))}requestLicense(t,e,i){return new Promise((s,a)=>{const o=function(t,e){const{drmSystems:i,widevineLicenseUrl:s}=e,n=null==i?void 0:i[t];if(n)return n.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 d=this.config.keyLoadPolicy.default,h=new XMLHttpRequest;h.responseType="arraybuffer",h.onreadystatechange=()=>{if(!this.hls||!t.mediaKeysSession)return a(new Error("invalid state"));if(4===h.readyState)if(200===h.status){l.requestErrors=[];let i=h.response;this.log(`License received ${i instanceof ArrayBuffer?i.byteLength:i}`);const n=this.config.licenseResponseCallback;if(n)try{i=n.call(this.hls,h,o,_(_({},t),{},{decryptdata:e}))}catch(t){this.error(t)}s(i)}else{const c=d.errorRetry,u=c?c.maxNumRetry:0;if(l.requestErrors.push({status:h.status,message:h.statusText}),l.requestErrors.length>u||h.status>=400&&h.status<500)a(new Xo({type:n.KEY_SYSTEM_ERROR,details:r.KEY_SYSTEM_LICENSE_REQUEST_FAILED,decryptdata:e,fatal:!0,networkDetails:h,response:{url:o,data:void 0,code:h.status,text:h.statusText}},`License Request XHR failed (${o}). Status: ${h.status} (${h.statusText})`));else{const n=u-l.requestErrors.length;this.warn(`Retrying license request, ${n} attempts left`),this.requestLicense(t,e,i).then(s,a)}}},l.licenseXhr&&l.licenseXhr.readyState!==XMLHttpRequest.DONE&&l.licenseXhr.abort(),l.licenseXhr=h,this.setupLicenseXHR(h,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=[],Cs.clearKeyUriToKeyIdMap()),t||(this.mediaKeys=null);const l=o.length,d=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:n.OTHER_ERROR,details:r.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(d)).catch(t=>{this.log(`Could not close sessions and clear media keys: ${t}`),this.hls&&this.hls.trigger(a.ERROR,{type:n.OTHER_ERROR,details:r.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:n.OTHER_ERROR,details:r.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:n.OTHER_ERROR,details:r.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error(`Could not close session: ${t}`)})})}return Promise.resolve()}}function Jo(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[pt(i)]}}function Zo(t,e){const i="output-restricted"===t,s=i?r.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:r.KEY_SYSTEM_STATUS_INTERNAL_ERROR;return new Xo({type:n.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 n(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 r(e,r,a){const o=this,l={enumerable:!0};o.hasBeenReset=!1;let d="",h=!1,c=e,u=r,f=a,g=null,p="",m=!0,v="auto",y="start",E=50,T="middle",S=50,b="middle";Object.defineProperty(o,"id",n({},l,{get:function(){return d},set:function(t){d=""+t}})),Object.defineProperty(o,"pauseOnExit",n({},l,{get:function(){return h},set:function(t){h=!!t}})),Object.defineProperty(o,"startTime",n({},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",n({},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",n({},l,{get:function(){return f},set:function(t){f=""+t,this.hasBeenReset=!0}})),Object.defineProperty(o,"region",n({},l,{get:function(){return g},set:function(t){g=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"vertical",n({},l,{get:function(){return p},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.");p=s,this.hasBeenReset=!0}})),Object.defineProperty(o,"snapToLines",n({},l,{get:function(){return m},set:function(t){m=!!t,this.hasBeenReset=!0}})),Object.defineProperty(o,"line",n({},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",n({},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",n({},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",n({},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",n({},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",n({},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 r.prototype.getCueAsHTML=function(){return self.WebVTT.convertCueToDOMTree(self,this.text)},r}();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 nl(t,e,i,s){const n=s?t.split(s):[t];for(const t in n){if("string"!=typeof n[t])continue;const s=n[t].split(i);if(2!==s.length)continue;e(s[0],s[1])}}const rl=new tl(0,0,""),al="middle"===rl.align?"middle":"center";function ol(t,e,i){const s=t;function n(){const e=il(t);if(null===e)throw new Error("Malformed timestamp: "+s);return t=t.replace(/^[^\sa-zA-Z-]+/,""),e}function r(){t=t.replace(/^\s+/,"")}if(r(),e.startTime=n(),r(),"--\x3e"!==t.slice(0,3))throw new Error("Malformed time stamp (time stamps must be separated by '--\x3e'): "+s);t=t.slice(3),r(),e.endTime=n(),r(),function(t,e){const s=new sl;nl(t,function(t,e){let n;switch(t){case"region":for(let n=i.length-1;n>=0;n--)if(i[n].id===e){s.set(t,i[n].region);break}break;case"vertical":s.alt(t,e,["rl","lr"]);break;case"line":n=e.split(","),s.integer(t,n[0]),s.percent(t,n[0])&&s.set("snapToLines",!1),s.alt(t,n[0],["auto"]),2===n.length&&s.alt("lineAlign",n[1],["start",al,"end"]);break;case"position":n=e.split(","),s.percent(t,n[0]),2===n.length&&s.alt("positionAlign",n[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 n=s.get("line","auto");"auto"===n&&-1===rl.line&&(n=-1),e.line=n,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 r=s.get("position","auto");"auto"===r&&50===rl.position&&(r="start"===e.align||"left"===e.align?0:"end"===e.align||"right"===e.align?100:50),e.position=r}(t,e)}function ll(t){return t.replace(/<br(?: \/)?>/gi,"\n")}class dl{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){nl(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 n=!1;for(;e.buffer;){if(!/\r\n|\n/.test(e.buffer))return this;switch(n?n=!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&&(n=!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 hl(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 hl(t.toString())+hl(e.toString())+hl(i)}function gl(t,i,s,n,r,a,o){const l=new dl,d=ot(new Uint8Array(t)).trim().replace(cl,"\n").split("\n"),h=[],c=i?function(t,e=1){return Nr(t,9e4,1/e)}(i.baseTime,i.timescale):0;let u,f="00:00.000",g=0,p=0,m=!1,v=!0;l.oncue=function(t){const e=s[n];let a=s.ccOffset;const o=(g-c)/9e4;if(m){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,d=qr(9e4*(t.startTime+a-p),9e4*r)/9e4;t.startTime=Math.max(d,0),t.endTime=Math.max(d+l,0);const f=t.text.replace(/^[ \t\r\n\f]+|[ \t\r\n\f]+$/g,"");t.text=decodeURIComponent(encodeURIComponent(f)),t.id?n&&(t.id=`hlsjscc${n}_${t.id}`):t.id=fl(t.startTime,t.endTime,f.trim()),t.endTime>0&&h.push(t)},l.onparsingerror=function(t){u=t},l.onflush=function(){u?o(u):a(h)},d.forEach(t=>{if(v){if(t.startsWith("X-TIMESTAMP-MAP=")){v=!1,m=!0,t.slice(16).split(",").forEach(t=>{t.startsWith("LOCAL:")?f=t.slice(6):t.startsWith("MPEGTS:")&&(g=parseInt(t.slice(7)))});try{p=function(t){let i=parseInt(t.slice(-3));const s=parseInt(t.slice(-6,-4)),n=parseInt(t.slice(-9,-7)),r=t.length>9?parseInt(t.substring(0,t.indexOf(":"))):0;if(!(e(i)&&e(s)&&e(n)&&e(r)))throw Error(`Malformed X-TIMESTAMP-MAP: Local:${t}`);return i+=1e3*s,i+=6e4*n,i+=36e5*r,i}(f)/1e3}catch(t){u=t}return}""===t&&(v=!1)}l.parse(t+"\n")}),l.flush()}const pl="stpp.ttml.im1t",ml=/^(\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 n=xt(new Uint8Array(t),["mdat"]);if(0===n.length)return void s(new Error("Could not parse IMSC1 mdat"));const r=n.map(t=>ot(t)),a=function(t,e,i=1,s=!1){return Nr(t,e,1/i,s)}(e.baseTime,1,e.timescale);try{r.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 n={frameRate:30,subFrameRate:1,tickRate:1},r=Object.keys(n).reduce((t,e)=>(t[e]=s.getAttribute(`ttp:${e}`)||n[e],t),{}),a=(s.getAttribute("ttp:frameRateMultiplier")||"").trim().split(/\s+/).map(Number);2===a.length&&a[0]>0&&a[1]>0&&(r.frameRate=Number(r.frameRate)*a[0]/a[1]);!s.getAttribute("ttp:tickRate")&&s.getAttribute("ttp:frameRate")&&(r.tickRate=Number(r.frameRate)*Number(r.subFrameRate));const o="preserve"!==s.getAttribute("xml:space"),l=Sl(Tl(s,"styling","style")),d=Sl(Tl(s,"layout","region")),h=Tl(s,"body","[begin]");return[].map.call(h,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"),r),n=Il(t.getAttribute("dur"),r);let a=Il(t.getAttribute("end"),r);if(null===s)throw Ll(t);if(null===a){if(null===n)throw Ll(t);a=s+n}const h=new tl(s-e,a-e,i);h.id=fl(h.startTime,h.endTime,h.text);const c=function(t,e,i){const s="http://www.w3.org/ns/ttml#styling";let n=null;const r=["displayAlign","textAlign","color","backgroundColor","fontSize","fontFamily"],a=null!=t&&t.hasAttribute("style")?t.getAttribute("style"):null;a&&i.hasOwnProperty(a)&&(n=i[a]);return r.reduce((i,r)=>{const a=Al(e,s,r)||Al(t,s,r)||Al(n,s,r);return a&&(i[r]=a),i},{})}(d[t.getAttribute("region")],l[t.getAttribute("style")],l),{textAlign:u}=c;if(u){const t=yl[u];t&&(h.lineAlign=t),h.align=u}return I(h,c),h}).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 n;return"br"===i.nodeName&&s?t+"\n":null!=(n=i.childNodes)&&n.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(ml.test(t))return function(t,e){const i=ml.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="",n="disabled"){const r=t.ownerDocument.createElement("track");return r.kind=e,r.label=i,s&&(r.srclang=s),r.src="data:,WEBVTT",r.track.mode=n,t.appendChild(r),r}function _l(t){return t.forced&&(te.indexOf("Apple")>-1||/iPhone|iPad|iPod/.test(Zt))?"forced":t.characteristics&&/transcribes-spoken-dialog/gi.test(t.characteristics)&&/describes-music-and-sound/gi.test(t.characteristics)?"captions":"subtitles"}function kl(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){H.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){H.debug(`[texttrack-utils]: Legacy TextTrackCue fallback failed: ${t}`)}}"disabled"===i&&(t.mode=i)}function wl(t,e,i,s){const n=t.mode;if("disabled"===n&&(t.mode="hidden"),t.cues&&t.cues.length>0){const n=function(t,e,i){const s=[],n=function(t,e){if(e<=t[0].startTime)return 0;const i=t.length-1;if(e>t[i].endTime)return-1;let s,n=0,r=i;for(;n<=r;)if(s=Math.floor((r+n)/2),e<t[s].startTime)r=s-1;else{if(!(e>t[s].startTime&&n<i))return s;n=s+1}return t[n].startTime-e<e-t[r].startTime?n:r}(t,e);if(n>-1)for(let r=n,a=t.length;r<a;r++){const n=t[r];if(n.startTime>=e&&n.endTime<=i)s.push(n);else if(n.startTime>i)return s}return s}(t.cues,e,i);for(let e=0;e<n.length;e++)s&&!s(n[e])||t.removeCue(n[e])}"disabled"===n&&(t.mode=n)}function Dl(t,e){const i=xl(t.main);if(i&&i.start<=e)return i;const s=xl(t.audio);return s&&s.start<=e?s:null}function xl(t){if(!t)return null;switch(t.state){case yn:case vn:case In:case Rn:return null}return t.frag}function Pl(t,e){return e.getAppendedFrag(t,f.MAIN)||e.getPartialFragment(t)}function Cl(t,e,i,s){const n=s.latestLevelDetails,r=Pl(e,i);if(xn(s.config)&&!t.nextStart&&n&&r&&s.interstitialsManager){const i="type"in r?r:r.fragment,a=si(n,i.sn);(null==a?void 0:a.level)===i.level&&Dn(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,n){let r=new t(e,i,"");try{r.value=s,n&&(r.type=n)}catch(a){r=new t(e,i,Ue(n?_({type:n},s):s))}return r}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 jl extends wn{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=yn,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=vn}stopLoad(){this._forceStartLoad=!1,super.stopLoad()}doTick(){switch(this.state){case kn:{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=yn;break}if(this.hls.nextLoadLevel!==this.level){this.state=yn;break}break}case Sn:this.checkRetryDate()}this.state===yn&&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 n=this.buffering?t.nextLoadLevel:t.loadLevel;if(null==i||!i[n])return;const r=i[n],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=In)}if(!this.buffering)return;t.loadLevel!==n&&-1===t.manualLevel&&this.log(`Adapting to level ${n} from level ${this.level}`),this.level=t.nextLoadLevel=n;const d=r.details;if(!d||this.state===kn||this.waitForLive(r))return this.level=n,this.state=kn,void(this.startFragRequested=!1);const h=o.len,c=this.getMaxBufferLength(r.maxBitrate);if(h>=c)return;this.backtrackFragment&&this.backtrackFragment.start>o.end&&(this.backtrackFragment=void 0);const u=this.backtrackFragment?this.backtrackFragment.start:o.end;let m=this.getNextFragment(u,d);if(this.couldBacktrack&&!this.fragPrevious&&m&&y(m)&&this.fragmentTracker.getState(m)!==Fi){var v;const t=(null!=(v=this.backtrackFragment)?v:m).sn-d.startSN,e=d.fragments[t-1];e&&m.cc===e.cc&&(m=e,this.fragmentTracker.removeFragment(e))}else this.backtrackFragment&&o.len&&(this.backtrackFragment=void 0);if(m&&this.isLoopLoading(m,u)){if(!m.gap){const t=this.audioOnly&&!this.altAudio?g:p,e=(t===p?this.videoBuffer:this.mediaBuffer)||this.media;e&&this.afterBufferFlushed(e,t)}m=this.getNextFragmentLoopLoading(m,d,o,f.MAIN,c)}m&&(this.exceedsMaxBuffer(o,c,m)||this.loadFragment(m,r,u))}loadFragment(t,e,i){const s=this.fragmentTracker.getState(t);s===Ci||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 n=e.levels[t].audioCodec;n&&(i=i||-1!==n.indexOf("mp4a.40.2"),s=s||-1!==n.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!==yn)return;const s=e.levelInfo;(!s.details||s.details.live&&(this.levelLastLoaded!==s||s.details.expired)||this.waitForCdnTuneIn(s.details))&&(this.state=kn)}onLevelLoaded(t,e){var i;const{levels:s,startFragRequested:n}=this,r=e.level,o=e.details,l=o.totalduration;if(!s)return void this.warn(`Levels were reset while loading level ${r}`);this.log(`Level ${r} loaded [${o.startSN},${o.endSN}]${o.lastPartSn?`[part-${o.lastPartSn}-${o.lastPartIndex}]`:""}, cc [${o.startCC}, ${o.endCC}] duration:${l}`);const d=e.levelInfo,h=this.fragCurrent;!h||this.state!==Tn&&this.state!==Sn||h.level!==e.level&&h.loader&&this.abortCurrentFrag();let c=0;if(o.live||null!=(i=d.details)&&i.live){var u;if(this.checkLiveUpdate(o),o.deltaUpdateFailed)return;c=this.alignPlaylists(o,d.details,null==(u=this.levelLastLoaded)?void 0:u.details)}if(d.details=o,this.levelLastLoaded=d,n||this.setStartPosition(o,c),this.hls.trigger(a.LEVEL_UPDATED,{details:o,level:r}),this.state===kn){if(this.waitForCdnTuneIn(o))return;this.state=yn}n&&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,n=this.playhead,r=t.fragmentStart,a=t.edge,o=n>=r-e.maxFragLookUpTolerance&&n<=a;if(null!==s&&i.duration>s&&(n<s||!o)){const r=void 0!==e.liveMaxLatencyDuration?e.liveMaxLatencyDuration:e.liveMaxLatencyDurationCount*t.targetduration;if((!o&&i.readyState<4||n<a-r)&&(this._hasEnoughToStart||(this.nextLoadPosition=s),i.readyState))if(this.warn(`Playback: ${n} 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<=n)return void(i.currentTime=s);const{nextStart:e}=Ei.bufferedInfo(t.buffered,n,0);e&&(i.currentTime=e)}else i.currentTime=s}}_handleFragmentLoadProgress(t){var e;const i=t.frag,{part:s,payload:n}=t,{levels:r}=this;if(!r)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=r[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,d=o.PTSKnown||!o.live,h=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,p=-1!==g,{decryptRange:m,byteRange:v}=Xi(i,s,this.iframesOnly),y=new ts(i.level,i.sn,i.stats.chunkCount,v?v.end-v.start:n.byteLength,g,p,i.duration,this.iframesOnly,m),E=this.initPTS[i.cc];u.push(n,h,c,l,i,s,o.totalduration,d,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,n,r=!1;for(const t in i){const e=i[t];if("main"===e.id){if(n=t,s=e,"video"===t){const e=i[t];e&&(this.videoBuffer=e.buffer)}}else r=!0}r&&s?(this.log(`Alternate track found, use ${n}.buffered to schedule main fragment loading`),this.mediaBuffer=s.buffer):this.mediaBuffer=this.media}onFragBuffered(t,e){const{frag:i,part:s}=e,n=i.type===f.MAIN;if(n){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===Ln&&(this.state=yn));let t=!1;if(y(i)&&(t=!!i.gap&&!i.tagList.some(t=>"GAP"===t[0])),this.fragBufferedComplete(i,s),t){var r;i.stats.retry++;const t=null==(r=this.levels)?void 0:r[i.level];t&&t.fragmentError++}}const a=this.media;a&&(!this._hasEnoughToStart&&Ei.getBuffered(a).length&&(this.seekToStartPos(),this._hasEnoughToStart=!0),n&&this.tick())}get hasEnoughToStart(){return this._hasEnoughToStart}onError(t,e){var i;if(e.fatal)this.state=Rn;else switch(e.details){case r.FRAG_GAP:case r.FRAG_PARSING_ERROR:case r.FRAG_DECRYPT_ERROR:case r.FRAG_LOAD_ERROR:case r.FRAG_LOAD_TIMEOUT:case r.KEY_LOAD_ERROR:case r.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(f.MAIN,e);break;case r.LEVEL_LOAD_ERROR:case r.LEVEL_LOAD_TIMEOUT:case r.LEVEL_PARSING_ERROR:e.levelRetry||this.state!==kn||(null==(i=e.context)?void 0:i.type)!==u.LEVEL||(this.state=yn);break;case r.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 r.MEDIA_SOURCE_REQUIRES_RESET:this.onSourceBufferError(f.MAIN,e);break;case r.BUFFER_ADD_CODEC_ERROR:case r.BUFFER_APPEND_ERROR:if("main"!==e.parent)return;this.reduceLengthAndFlushBuffer(e)&&this.resetLoadingState();break;case r.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 r.INTERNAL_EXCEPTION:this.recoverWorkerError(e)}}onFragLoadEmergencyAborted(){this.state=yn,this._hasEnoughToStart||(this.startFragRequested=!1,this.nextLoadPosition=this.lastCurrentTime),this.tickImmediate()}onBufferFlushed(t,{type:e}){if(e!==g||!this.altAudio){const t=(e===p?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 n=this.getLevelDetails(),r=Ei.getBuffered(t),a=r.length?r.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==n?void 0:n.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=yn,this.startFragRequested=!1,this.bitrateTest=!1;const n=s.stats;n.parsing.start=n.parsing.end=n.buffering.start=n.buffering.end=self.performance.now(),i.trigger(a.FRAG_LOADED,t),s.bitrateTest=!1}).catch(e=>{this.state!==vn&&this.state!==Rn&&(this.warn(e),this.resetFragmentLoading(t))})}_handleTransmuxComplete(t){const i=this.playlistType,{hls:s}=this,{remuxResult:n,chunkMeta:r}=t,o=this.getCurrentContext(r);if(!o)return void this.resetWhenMissingContext(r);const{frag:l,part:d,level:h}=o,{video:c,text:u,id3:f,initSegment:p}=n,{details:m}=h,v=this.altAudio?void 0:n.audio;if(this.fragContextChanged(l))this.fragmentTracker.removeFragment(l);else{if(this.state=An,p){const t=p.tracks;if(t){const e=l.initSegment||l;if(this.unhandledEncryptionError(p,l))return;this._bufferInitSegment(h,t,e,r),s.trigger(a.FRAG_PARSING_INIT_SEGMENT,{frag:e,id:i,tracks:t})}const n=p.initPTS,o=p.timescale,d=this.initPTS[l.cc];if(e(n)&&(!d||d.baseTime!==n||d.timescale!==o)){const t=p.trackId;this.initPTS[l.cc]={baseTime:n,timescale:o,trackId:t};const e=this.initPTS.slice(0);s.trigger(a.INIT_PTS_FOUND,{timestampOffsets:e,frag:l,id:i,initPTS:n,timescale:o,trackId:t})}}if(c&&m){v&&"audiovideo"===c.type&&this.logMuxedErr(l);const t=m.fragments[l.sn-1-m.startSN],e=l.sn===m.startSN,i=!t||l.cc>t.cc;if(!1!==n.independent){const{startPTS:t,endPTS:s,startDTS:n,endDTS:a}=c;if(d)d.elementaryStreams[c.type]={startPTS:t,endPTS:s,startDTS:n,endDTS:a};else if(c.firstKeyFrame&&c.independent&&1===r.id&&!i&&(this.couldBacktrack=!0),c.dropped&&c.independent){const n=this.getMainFwdBufferInfo(),r=(n?n.end:this.getLoadPosition())+this.config.maxBufferHole,o=c.firstKeyFramePTS?c.firstKeyFramePTS:t;if(!e&&r<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-(m.appliedTimelineOffset||0)>2&&(l.gap=!0);l.setElementaryStreamInfo(c.type,t,s,n,a),this.backtrackFragment&&(this.backtrackFragment=l),this.bufferFragmentData(c,l,d,r,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;d&&(d.elementaryStreams[g]={startPTS:t,endPTS:e,startDTS:i,endDTS:s}),l.setElementaryStreamInfo(g,t,e,i,s),this.bufferFragmentData(v,l,d,r)}if(m&&null!=f&&f.samples.length){const t={id:i,frag:l,details:m,samples:f.samples};s.trigger(a.FRAG_PARSING_METADATA,t)}if(m&&u){const t={id:i,frag:l,details:m,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!==An)return;this.audioOnly=!!e.audio&&!e.video,this.altAudio&&!this.audioOnly&&(delete e.audio,e.audiovideo&&this.logMuxedErr(i));const{audio:n,video:r,audiovideo:o}=e;if(n){const i=t.audioCodec;let s=ve(n.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=n.metadata;t&&"channelCount"in t&&1!==(t.channelCount||1)&&!function(){if(void 0===ie){const t=Zt.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(Zt)&&"audio/mpeg"!==n.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}"`),n.levelCodec=s,n.id=f.MAIN,this.log(`Init audio buffer, container:${n.container}, codecs[selected/level/parsed]=[${s||""}/${i||""}/${n.codec}]`),delete e.audiovideo}if(r){r.levelCodec=t.videoCodec,r.id=f.MAIN;const i=r.codec;if(4===(null==i?void 0:i.length))switch(i){case"hvc1":case"hev1":r.codec="hvc1.1.6.L120.90";break;case"av01":r.codec="av01.0.04M.08";break;case"avc1":r.codec="avc1.42e01e"}this.log(`Init video buffer, container:${r.container}, codecs[level/parsed]=[${t.videoCodec||""}/${i}]${r.codec!==i?" parsed-corrected="+r.codec:""}${r.supplemental?" supplemental="+r.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 n=e[t].initSegment;null!=n&&n.byteLength&&this.hls.trigger(a.BUFFER_APPENDING,{type:t,data:n,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=yn}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 ql extends jl{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 vn:case In:case Rn:this.state=yn}this.state===yn?(this.hls.resumeBuffering(),this.tick(),this.currentOp=[s,e]):this.nextOp=[s,e],this.hls.off(a.BUFFERED_TO_END,this.onBufferedToEnd);const n=this.media;if(i&&n){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,n=void 0!==s?s:e.duration;t>=n&&(t=n-.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!==Ci&&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=Tn;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=vn,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 Kl extends ql{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 vn:case In:case Rn:this.state=yn}if(this.state===yn){if(this.hls.resumeBuffering(),this.media||(this.media={}),this.tick(),this.state===yn){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 n=this._img;if(n&&s){const r=self.performance.now();(e?e.stats:t.stats).buffering.start=t.stats.buffering.start=r,n.onload=()=>{if(!this.hls)return;const s=this.hls.levels[t.level];null!=s&&s.fragmentError&&(s.fragmentError=0,t.stats.retry=0);const n=self.performance.now(),r=e?e.stats:t.stats;r.buffering.end=t.stats.buffering.end=n,this.hls.trigger(a.FRAG_BUFFERED,{frag:t,part:e,stats:r,id:t.type,chunkMeta:i})},n.onerror=()=>{this.handleError("Image decode error",t,e,i)};const o=n.src;o&&self.URL.revokeObjectURL(o);const l=new Blob([s],{type:"image/jpeg"});n.src=self.URL.createObjectURL(l)}else this.state=vn,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:n.MEDIA_ERROR,details:r.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 n=xt(new Uint8Array(t.data1),["mdat"]);if(0===n.length)return void this.handleError("Could not find I-Frame mdat",e,i,s);const r=e;this.cacheSet(r,n[0]),this.updateImage(r,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",Hl={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}-${hl(e)}`}class Jl{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 td(e,t)?Zl(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-Zl(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 td(e,t)?Zl(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 Zl(t,e){return t-e.start<e.duration/2&&!(Math.abs(t-(e.start+e.duration))<zl)?e.start:e.start+e.duration}function td(t,e){return e>t.start-zl&&e<t.start+t.duration+zl}function ed(t,e,i){const s=new self.URL(t,i);return"data:"!==s.protocol&&we(s,"_HLS_primary_id",e),s}function id(t,e){for(;null!=(i=t.assetList[++e])&&i.error;)var i;return e}function sd(t){const e=t.timelineStart,i=t.duration||0;return`["${t.identifier}" ${e.toFixed(2)}-${(e+i).toFixed(2)}]`}class nd{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 n=this.hls=new t(e);this.interstitial=i,this.assetItem=s;const r=()=>{this.hasDetails=!0};n.once(a.LEVEL_LOADED,r),n.once(a.AUDIO_TRACK_LOADED,r),n.once(a.SUBTITLE_TRACK_LOADED,r),n.on(a.MEDIA_ATTACHING,(t,{media:e})=>{this.removeMediaListeners(),this.mediaAttached=e;this.interstitial.playoutLimit&&(e.addEventListener("timeupdate",this.checkPlayout),this.appendInPlace&&n.on(a.BUFFER_APPENDED,()=>{const t=this.bufferedEnd;this.reachedPlayout(t)&&(this._bufferedEosTime=t,n.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=ed(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),n=this.timelineOffset+(e||0),r=Ei.bufferInfo(t,n,.02);return this.getAssetTime(r.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: ${sd(this.assetItem)} ${null==(t=this.hls)?void 0:t.sessionId} ${this.appendInPlace?"append-in-place":""}`}}const rd=.033;class ad 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!=(n=s[i])&&n.event;){var n;i--}return i}findItemIndexAtTime(t,e){const i=this.items;if(i)for(let s=0;s<i.length;s++){let n=i[s];e&&"primary"!==e&&(n=n[e]);const r=n.start,a=i[s].event,o=null!=a&&a.cue.pre?a.duration:n.end;if(t===r||t>r&&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 n=i[t];if(!n.error){const i=n.timelineStart;if(e===i||e>i&&(e<i+(n.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:n}=s,r=this.events,a=this.parseDateRanges(n,{url:s.url},e),o=Object.keys(n),l=r?r.filter(t=>-1===o.indexOf(t.identifier)):[];a.length&&a.sort((t,e)=>{const i=t.cue.pre,s=t.cue.post,n=e.cue.pre,r=e.cue.post;if(i&&!n)return-1;if(n&&!i)return 1;if(s&&!r)return 1;if(r&&!s)return-1;if(!(i||n||s||r)){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 n=this.events||[];if(n.length||e.length||this.length<2){const r=this.items,a=this.parseSchedule(n,t,i);(s||e.length||(null==r?void 0:r.length)!==a.length||a.some((t,e)=>Math.abs(t.playout.start-r[e].playout.start)>.005||Math.abs(t.playout.end-r[e].playout.end)>.005))&&(this.items=a,this.onScheduleUpdate(e,r))}}parseDateRanges(t,e,i){const s=[],n=Object.keys(t);for(let r=0;r<n.length;r++){const a=n[r],o=t[a];if(o.isInterstitial){let t=this.eventMap[a];t?t.setDateRange(o):(t=new Jl(o,e),this.eventMap[a]=t,!1===i&&(t.appendInPlace=i)),s.push(t)}}return s}parseSchedule(t,e,i=0){const s=[],n=e.main.details,r=n.live?1/0:n.edge;let a=0;if((t=t.filter(t=>!(t.error||t.cue.once&&t.hasPlayed))).length){this.resolveOffsets(t,e);let l=0,d=0;if(t.forEach((e,o)=>{const h=e.cue.pre,c=e.cue.post,u=t[o-1]||null,f=e.appendInPlace,g=c?r:e.startOffset,p=e.duration,m=e.timelineOccupancy===Xl.Range?p:0,v=h&&n.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+p:g+y;if(h||!c&&g<=0){const t=d;d+=m,e.timelineStart=T;const i=a;a+=p,s.push({event:e,start:T,end:S,playout:{start:i,end:a},integrated:{start:t,end:d}})}else{if(!(g<=r))return;{if(!E){const i=g-l;if(i>rd){const n=l,r=d;d+=i;const h=a;a+=i;const c={previousEvent:t[o-1]||null,nextEvent:e,start:n,end:n+i,playout:{start:h,end:a},integrated:{start:r,end:d}};s.push(c)}else i>0&&u&&(u.cumulativeDuration+=i,s[s.length-1].end=g)}c&&(S=T),e.timelineStart=T;const i=d;d+=m;const n=a;a+=p,s.push({event:e,start:T,end:S,playout:{start:n,end:a},integrated:{start:i,end:d}})}}const b=v||e.resumeTime;l=c||b>r?r:!h&&S&&e.appendInPlaceStarted&&b-S>rd?S:b}),l<r){var o;const t=l,e=d,i=r-l;d+=i;const n=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:n,end:a},integrated:{start:e,end:d}})}this.setDurations(r,a,d)}else{const t=0;s.push({previousEvent:null,nextEvent:null,start:t,end:r,playout:{start:t,end:r},integrated:{start:t,end:r}}),this.setDurations(r,r,r)}return s}setDurations(t,e,i){this.durations={primary:t,playout:e,integrated:i}}resolveOffsets(t,i){const s=i.main.details,n=s.live?1/0:s.edge;let r=0,a=-1;t.forEach((o,l)=>{const d=o.cue.pre,h=o.cue.post,c=d?0:h?n:o.startTime;this.updateAssetDurations(o);if(a===c?o.cumulativeDuration=r:(r=0,a=c),!h&&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<rd&&(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;r+=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 n=e[s].details,r=n.edge;if(i>=r)return this.log(`"${t.identifier}" resumption ${i} past ${s} playlist end ${r}`),!1;const a=Ze(null,n.fragments,i);if(!a)return this.log(`"${t.identifier}" resumption ${i} does not align with any fragments in ${s} playlist (${n.fragStart}-${n.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,n=!1;for(let r=0;r<t.assetList.length;r++){const a=t.assetList[r],o=e+i;a.startOffset=i,a.timelineStart=o,s||(s=null===a.duration),n||(n=!!a.error);i+=a.error?0:a.duration||0}t.duration=s&&!n?Math.max(i,t.duration):i}removeEvent(t){t.reset(),delete this.eventMap[t.identifier]}}function od(t){return`[${t.event?'"'+t.event.identifier+'"':"primary"}: ${t.start.toFixed(2)}-${t.end.toFixed(2)}]`}class ld{constructor(t){this.hls=void 0,this.hls=t}destroy(){this.hls=null}loadAssetList(t,e){const i=t.assetListUrl;let s;try{s=ed(i,this.hls.sessionId,t.baseUrl)}catch(e){const s=this.assignAssetListError(t,r.ASSET_LIST_LOAD_ERROR,e,i);return void this.hls.trigger(a.ERROR,s)}e&&"data:"!==s.protocol&&we(s,"_HLS_start_offset",""+e);const n=this.hls.config,o=new(0,n.loader)(n),l={type:u.INTERSTITIAL_ASSET_LIST,responseType:"json",url:s.href},d=n.interstitialAssetListLoadPolicy.default,h={loadPolicy:d,timeout:d.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},c={onSuccess:(e,i,s,n)=>{const o=e.data,l=null==o?void 0:o.ASSETS;if(!Array.isArray(l)){const e=this.assignAssetListError(t,r.ASSET_LIST_PARSING_ERROR,new Error("Invalid interstitial asset list"),s.url,i,n);return void this.hls.trigger(a.ERROR,e)}t.assetListResponse=o,this.hls.trigger(a.ASSET_LIST_LOADED,{event:t,assetListResponse:o,networkDetails:n})},onError:(e,i,s,n)=>{const o=this.assignAssetListError(t,r.ASSET_LIST_LOAD_ERROR,new Error(`Error loading X-ASSET-LIST: HTTP status ${e.code} ${e.text} (${i.url})`),i.url,n,s);this.hls.trigger(a.ERROR,o)},onTimeout:(e,i,s)=>{const n=this.assignAssetListError(t,r.ASSET_LIST_LOAD_TIMEOUT,new Error(`Timeout loading X-ASSET-LIST (${i.url})`),i.url,e,s);this.hls.trigger(a.ERROR,n)}};return o.load(l,h,c),this.hls.trigger(a.ASSET_LIST_LOADING,{event:t}),o}assignAssetListError(t,e,i,s,r,a){return t.error=i,{type:n.NETWORK_ERROR,details:e,fatal:!1,interstitial:t,url:s,error:i,networkDetails:a,stats:r}}}function dd(t){var e;null==t||null==(e=t.play())||e.catch(()=>{})}function hd(t,e){return`[${t}] Advancing timeline position to ${e}`}class cd{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 ud={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},fd=t=>String.fromCharCode(ud[t]||t),gd=15,pd=42,md={17:1,18:3,21:5,22:7,23:9,16:11,19:12,20:14},vd={17:2,18:4,21:6,22:8,23:10,19:13,20:15},yd={25:1,26:3,29:5,30:7,31:9,24:11,27:12,28:14},Ed={25:2,26:4,29:6,30:8,31:10,27:13,28:15},Td=["white","green","blue","cyan","red","yellow","magenta","black","transparent"];class Sd{constructor(){this.time=null,this.verboseLevel=0}log(t,e){if(this.verboseLevel>=t){const i="function"==typeof e?e():e;H.log(`${this.time} [${t}] ${i}`)}}}const bd=function(t){const e=[];for(let i=0;i<t.length;i++)e.push(t[i].toString(16));return e},Ad=Object.freeze({foreground:"white",underline:!1,italics:!1,background:"black",flash:!1});class Ld{constructor(){this.styles=Ad}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=Ad}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 Id{constructor(){this.uchar=" ",this.penState=new Ld}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 Rd{constructor(t){this.chars=[],this.pos=0,this.currPenState=new Ld,this.cueStartTime=null,this.logger=void 0;for(let t=0;t<pd;t++)this.chars.push(new Id);this.logger=t}equals(t){const e=this.chars,i=t.chars;for(let t=0;t<pd;t++){const s=e[t],n=i[t];if(s.uchar!==n.uchar)return!1;const r=s.penState.styles,a=n.penState.styles;if(r!==a&&(r.foreground!==a.foreground||r.underline!==a.underline||r.italics!==a.italics||r.background!==a.background||r.flash!==a.flash))return!1}return!0}copy(t){for(let e=0;e<pd;e++)this.chars[e].copy(t.chars[e])}isEmpty(){const t=this.chars;for(let e=0;e<pd;e++){const i=t[e];if(" "!==i.uchar)return!1;const s=i.penState.styles;if(s!==Ad&&("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>=pd&&(this.logger.log(3,"Too large cursor position "+this.pos),this.pos=41)}moveCursor(t){const e=Math.min(this.pos+t,pd);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=fd(t);this.pos>=pd?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<pd;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<pd;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 _d{constructor(t){this.rows=[],this.currRow=14,this.nrRollUpRows=null,this.lastOutputScreen=null,this.logger=void 0;for(let e=0;e<gd;e++)this.rows.push(new Rd(t));this.logger=t}reset(){for(let t=0;t<gd;t++)this.rows[t].clear();this.currRow=14}equals(t){let e=!0;for(let i=0;i<gd;i++)if(!this.rows[i].equals(t.rows[i])){e=!1;break}return e}copy(t){for(let e=0;e<gd;e++){const i=this.rows[e].chars,s=t.rows[e].chars;for(let t=0;t<pd;t++){const e=i[t],n=s[t];e.uchar=n.uchar,e.penState.styles=n.penState.styles}}}isEmpty(){let t=!0;for(let e=0;e<gd;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<gd;t++)this.rows[t].clear();const t=this.currRow+1-this.nrRollUpRows,i=this.lastOutputScreen;if(i){const s=i.rows[t].cueStartTime,n=this.logger.time;if(null!==s&&null!==n&&s<n)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<gd;i++){const n=this.rows[i].getTextString();n&&(s=i+1,t?e.push("Row "+s+": '"+n+"'"):e.push(n.trim()))}return e.length>0&&(i=t?"["+e.join(" | ")+"]":e.join("\n")),i}getTextAndFormat(){return this.rows}}class kd{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 _d(i),this.nonDisplayedMemory=new _d(i),this.lastOutputScreen=new _d(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 wd{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 Sd,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 kd(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 n=!1,r=null;if(0===i&&0===s)continue;this.logger.log(3,()=>"["+bd([e[t],e[t+1]])+"] -> ("+bd([i,s])+")");const a=this.cmdHistory;if(i>=16&&i<=31){if(xd(i,s,a)){Dd(null,null,a),this.logger.log(3,()=>"Repeated command ("+bd([i,s])+") is dropped");continue}Dd(i,s,this.cmdHistory),n=this.parseCmd(i,s),n||(n=this.parseMidrow(i,s)),n||(n=this.parsePAC(i,s)),n||(n=this.parseBackgroundAttributes(i,s))}else Dd(null,null,a);if(!n&&(r=this.parseChars(i,s),r)){const t=this.currentChannel;if(t&&t>0){this.getChannel(t).insertChars(r)}else this.logger.log(2,"No channel found yet. TEXT-MODE?")}n||r||this.logger.log(2,()=>"Couldn't parse cleaned data "+bd([i,s])+" orig: "+bd([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 ("+bd([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?md[t]:yd[t]:1===s?vd[t]:Ed[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,n=null;if(t>=25?(i=2,n=t-8):(i=1,n=t),n>=17&&n<=19){let t;t=17===n?e+80:18===n?e+112:e+144,this.logger.log(2,()=>"Special char '"+fd(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 = "+bd(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=Td[i],e%2==1&&(s.background=s.background+"_semi")):45===e?s.background="transparent":(s.foreground="black",47===e&&(s.underline=!0));const n=t<=23?1:2;return this.getChannel(n).setBkgData(s),!0}reset(){for(let t=0;t<Object.keys(this.channels).length;t++){const e=this.channels[t];e&&e.reset()}Dd(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 Dd(t,e,i){i.a=t,i.b=e}function xd(t,e,i){return i.a===t&&i.b===e}class Pd{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 Cd(t,e,i,s){return Math.min(e,s)-Math.max(t,i)}const Md=/\s/,Od={newCue(t,e,i,s){const n=[];let r,a,o,l,d;const h=self.VTTCue||self.TextTrackCue;for(let u=0;u<s.rows.length;u++)if(r=s.rows[u],o=!0,l=0,d="",!r.isEmpty()){var c;for(let t=0;t<r.chars.length;t++)Md.test(r.chars[t].uchar)&&o?l++:(d+=r.chars[t].uchar,o=!1);r.cueStartTime=e,e===i&&(i+=1e-4),l>=16?l--:l++;const s=ll(d.trim()),f=fl(e,i,s);null!=t&&null!=(c=t.cues)&&c.getCueById(f)||(a=new h(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)),n.push(a))}return t&&n.length&&(n.sort((t,e)=>"auto"===t.line||"auto"===e.line?0:t.line>8&&e.line>8?e.line-t.line:t.line-e.line),n.forEach(e=>kl(t,e))),n}};class Fd{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;H.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=C(t,i.retry),i.retry++,H.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 Nd=/(\d+)-(\d+)\/(\d+)/;class $d extends Fd{constructor(t){super(),this.fetchSetup=void 0,this.request=null,this.response=null,this.controller=null,this.fetchSetup=t.fetchSetup||Bd}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 n=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),r="arraybuffer"===i.responseType,a=r?"byteLength":"length",{maxTimeToFirstByteMs:o,maxLoadTimeMs:l}=t.loadPolicy;this.request=this.fetchSetup(i,n),self.clearTimeout(this.requestTimeout),t.timeout=o&&e(o)?o:l,this.requestTimeout=self.setTimeout(()=>{this.loadtimeout()},t.timeout);(Jr(this.request)?this.request.then(self.fetch):self.fetch(this.request)).then(n=>{var a;this.response=n;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)),!n.ok){const{status:t,statusText:e}=n;throw new Ud(e||"fetch, bad network response",t,n)}s.loading.first=o,s.total=function(t){const i=t.get("Content-Range");if(i){const t=function(t){const e=Nd.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)}(n.headers)||s.total;const d=null==(a=this.callbacks)?void 0:a.onProgress;return d&&e(t.highWaterMark)?this.loadProgressively(n,s,i,t.highWaterMark,d):r?n.arrayBuffer():"json"===i.responseType?n.json():n.text()}).then(n=>{var r,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 d=n[a];d&&(s.loaded=s.total=d);const h={url:l.url,data:n,code:l.status},c=null==(r=this.callbacks)?void 0:r.onProgress;c&&!e(t.highWaterMark)&&c(s,i,n,l),null==(o=this.callbacks)||o.onSuccess(h,s,i,l)}).catch(e=>{if(self.clearTimeout(this.requestTimeout),s.aborted)return;const n=e&&e.code||0,r=e?e.message:null,a=t.loadPolicy.errorRetry;var o;O(a,s.retry,!1,{url:i.url,data:void 0,code:n})?this.retry(a):(H.error(`${n} while loading ${i.url}`),null==(o=this.callbacks)||o.onError({code:n,text:r},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,n){const r=new Pn,a=t.body.getReader(),o=()=>a.read().then(a=>{if(a.done)return r.dataLength&&n(e,i,r.flush().buffer,t),Promise.resolve(new ArrayBuffer(0));const l=a.value,d=l.length;return e.loaded+=d,d<s||r.dataLength?(r.push(l),r.dataLength>=s&&n(e,i,r.flush().buffer,t)):n(e,i,l.buffer,t),o()}).catch(()=>Promise.reject());return o()}}function Bd(t,e){return new self.Request(t.url,e)}class Ud extends Error{constructor(t,e,i){super(t),this.code=void 0,this.details=void 0,this.code=e,this.details=i}}const Gd=/^age:\s*[\d.]+\s*$/im;class jd extends Fd{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 n=this.xhrSetup;n?Promise.resolve().then(()=>{if(this.loader===i&&!this.stats.aborted)return n.call(this,i,e.url,e)}).catch(t=>{if(this.loader===i&&!this.stats.aborted)return i.open("GET",e.url,!0),n.call(this,i,e.url,e)}).then(()=>{this.loader!==i||this.stats.aborted||this.openAndSendXhr(i,e,t)}).catch(t=>{var n;null==(n=this.callbacks)||n.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 n=i.headers,{maxTimeToFirstByteMs:r,maxLoadTimeMs:a}=s.loadPolicy;if(n)for(const e in n)t.setRequestHeader(e,n[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=r&&e(r)?r: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,n=this.config;if(!i.aborted&&s>=2&&(0===i.loading.first&&(i.loading.first=Math.max(self.performance.now(),i.loading.start),n.timeout!==n.loadPolicy.maxLoadTimeMs&&(self.clearTimeout(this.requestTimeout),n.timeout=n.loadPolicy.maxLoadTimeMs,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),n.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 n=null!=l?l:e.response;if(null!=n){var r,a;i.loading.end=Math.max(self.performance.now(),i.loading.first);const o="arraybuffer"===e.responseType?n.byteLength:n.length;i.loaded=i.total=o,i.bwEstimate=8e3*i.total/(i.loading.end-i.loading.first);const l=null==(r=this.callbacks)?void 0:r.onProgress;l&&l(i,t,n,e);const d={url:e.responseURL,data:n,code:s};return t.rangeEnd&&o!==t.rangeEnd-t.rangeStart&&H.warn(`Payload length ${o} does not match requested Range: bytes=${t.rangeStart}-${t.rangeEnd-1}`),void(null==(a=this.callbacks)||a.onSuccess(d,i,t,e))}}const d=n.loadPolicy.errorRetry;var o;if(O(d,i.retry,!1,{url:t.url,data:void 0,code:s}))this.retry(d);else H.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&&Gd.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 qd=_(_({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:jd,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:ws,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:jl,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:n,hls:r}=this;if(!r)return;const{autoLevelEnabled:o,media:l}=r;if(!s||!l)return;const d=performance.now(),h=n?n.stats:s.stats,c=n?n.duration:s.duration,u=d-h.loading.start,f=r.minAutoLevel,g=s.level,p=this._nextAutoLevel;if(h.aborted||h.loaded&&h.loaded===h.total||g<=f)return this.clearTimer(),void(this._nextAutoLevel=-1);if(!o)return;const m=p>-1&&p!==g,v=!!t||m;if(!v&&(l.paused||!l.playbackRate||!l.readyState))return;const y=r.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=h.loading.first?h.loading.first-h.loading.start:-1,A=h.loaded&&b>-1,L=this.getBwEstimate(),I=r.levels,R=I[g],_=Math.max(h.loaded,Math.round(c*(s.bitrate||R.averageBitrate)/8));let k=A?u-b:u;k<1&&A&&(k=Math.min(u,8*h.loaded/L));const w=A?1e3*h.loaded/k:0,D=E/1e3,x=w?(_-h.loaded)/w:8*_/L+D;if(x<=S)return;const P=w?8*w:L,C=!0===(null==(i=(null==t?void 0:t.details)||r.latestLevelDetails)?void 0:i.live),M=r.config.abrBandWidthUpFactor;let O,F=Number.POSITIVE_INFINITY;for(O=g-1;O>f;O--){const t=I[O].maxBitrate,e=!I[O].details||C;if(F=this.getTimeToLoadFrag(D,P,c*t,e),F<Math.min(S,c+D))break}if(F>=x)return;if(F>10*c)return;A?this.bwEstimator.sample(u-Math.min(E,b),h.loaded):this.bwEstimator.sampleTTFB(u);const N=I[O].maxBitrate;this.getBwEstimate()*M>N&&(this.firstAutoFloor=Math.min(O,r.firstLevel),this.resetEstimator(N));const $=this.findBestLevel(N,f,O,0,S,1,1);$>-1&&(O=$),this.warn(`Fragment ${s.sn}${n?" part "+n.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: ${x.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`),r.nextLoadLevel=r.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)}}};m||x>2*F?B():this.timer=self.setInterval(B,1e3*F),r.trigger(a.FRAG_LOAD_EMERGENCY_ABORTED,{frag:s,part:n,stats:h})},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 r.BUFFER_ADD_CODEC_ERROR:case r.BUFFER_APPEND_ERROR:this.lastLoadedFragLevel=-1,this.firstSelection=-1;break;case r.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,n=e-i.loading.start,r=i.loading.first?i.loading.first-i.loading.start:-1;if(i.loaded&&r>-1){const t=this.bwEstimator.getEstimateTTFB();this.bwEstimator.sample(n-Math.min(t,r),i.loaded)}else this.bwEstimator.sampleTTFB(n)}break}}}getTimeToLoadFrag(t,e,i,s){return t+i/e+(s?t+this.lastLevelLoadSec:0)}onLevelLoaded(t,i){const s=this.hls.config,{loading:n}=i.stats,r=n.end-n.first;e(r)&&(this.lastLevelLoadSec=r/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:n}=e,r=n?n.stats:s.stats;if(s.type===f.MAIN&&this.bwEstimator.sampleTTFB(r.loading.first-r.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=n?n.duration:s.duration,e=this.hls.levels[s.level],i=(e.loaded?e.loaded.bytes:0)+r.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:r,frag:s,part:n,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,n=null!=s&&s.stats.loaded?s.stats:i.stats;if(n.aborted)return;if(this.ignoreFragment(i))return;const r=((i.bitrate||0)>=1e5?n.parsing.end:n.loading.end)-n.loading.start-Math.min(n.loading.first-n.loading.start,this.bwEstimator.getEstimateTTFB());this.bwEstimator.sample(r,n.loaded),n.bwEstimate=this.getBwEstimate(),i.bitrateTest?this.bitrateTestDelay=r/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(),n=this.getStarvationDelay(),r=t.config.maxStarvationDelay,a=this.findBestLevel(s,i,e,n/2,r,1,1);if(a>-1)return a;const o=t.firstLevel,l=-1===this.firstAutoFloor?1/0:this.firstAutoFloor,d=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 ${d}`),d}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:n,minAutoLevel:r}=i,a=e?e.duration:t?t.duration:0,o=this.getBwEstimate(),l=this.getStarvationDelay();let d=n.abrBandWidthFactor,h=n.abrBandWidthUpFactor;if(l){const t=this.findBestLevel(o,r,s,l,0,d,h);if(t>=0)return this.rebufferNotice=-1,t}let c=a?Math.min(a,n.maxStarvationDelay):n.maxStarvationDelay;if(!l){const t=this.bitrateTestDelay;if(t){c=(a?Math.min(a,n.maxLoadingDelay):n.maxLoadingDelay)-t,this.info(`bitrate test took ${Math.round(1e3*t)}ms, set first fragment max fetchDuration to ${Math.round(1e3*c)} ms`),d=h=1}}const u=this.findBestLevel(o,r,s,l,c,d,h);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[r],g=i.loadLevelObj;return g&&(null==f?void 0:f.bitrate)<g.bitrate?r: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,n,r,a,o){const{hls:l,lastLoadedFragLevel:d,fragCurrent:h,partCurrent:c}=this;if(!l)return-1;const u=n+r,f=-1===d?l.firstLevel:d,{levels:g,allAudioTracks:p,loadLevel:m,latestLevelDetails:v,config:y}=l;if(1===g.length)return 0;const E=g[f],T=!(null==v||!v.live),S=-1===m||-1===d;let b,A="SDR",L=(null==E?void 0:E.frameRate)||0;const{audioPreference:I,videoPreference:R}=y,_=this.audioTracksByGroup||(this.audioTracksByGroup=je(p));let k=-1;if(S){if(-1!==this.firstSelection)return this.firstSelection;const n=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 n=i.audioGroups;let r=t[i.codecSet];r||(t[i.codecSet]=r={minBitrate:1/0,minHeight:1/0,minFramerate:1/0,minIndex:s,maxScore:0,videoRanges:{SDR:0},channels:{2:0},hasDefaultAudio:!n,fragmentError:0}),r.minBitrate=Math.min(r.minBitrate,i.bitrate);const a=Math.min(i.height,i.width);return r.minHeight=Math.min(r.minHeight,a),r.minFramerate=Math.min(r.minFramerate,i.frameRate),r.minIndex=Math.min(r.minIndex,s),r.maxScore=Math.max(r.maxScore,i.score),r.fragmentError+=i.fragmentError,r.videoRanges[i.videoRange]=(r.videoRanges[i.videoRange]||0)+1,n&&n.forEach(t=>{if(!t)return;const i=e.groups[t];i&&(r.hasDefaultAudio=r.hasDefaultAudio||e.hasDefaultAudio?i.hasDefault:i.hasAutoSelect||!e.hasDefaultAudio&&!e.hasAutoSelectAudio,Object.keys(i.channels).forEach(t=>{r.channels[t]=(r.channels[t]||0)+i.channels[t]}))}),t},{})}(g,_,i,s)),r=function(t,i,s,n,r){const a=Object.keys(t),o=null==n?void 0:n.channels,l=null==n?void 0:n.audioCodec,d=null==r?void 0:r.videoCodec,h=o&&2===parseInt(o);let c=!1,u=!1,f=1/0,g=1/0,p=1/0,m=1/0,v=0,y=[];const{preferHDR:E,allowedVideoRanges:T}=Be(i,r);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),p=Math.min(p,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);p=e(p)?p:s,s=Math.max(p,s),u||(i=void 0);const A=a.length>1;return{codecSet:a.reduce((e,i)=>{const n=t[i];if(i===e)return e;if(y=u?T.filter(t=>n.videoRanges[t]>0):[],A){if(n.minBitrate>s)return Ge(i,`min bitrate of ${n.minBitrate} > current estimate of ${s}`),e;if(!n.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&&!h){if(!n.channels[o])return Ge(i,`no renditions with ${o} channel sound found (channels options: ${Object.keys(n.channels)})`),e}else if((!l||h)&&c&&0===n.channels[2])return Ge(i,"no renditions with stereo sound found"),e;if(n.minHeight>S)return Ge(i,`min resolution of ${n.minHeight} > maximum of ${S}`),e;if(n.minFramerate>b)return Ge(i,`min framerate of ${n.minFramerate} > maximum of ${b}`),e;if(!y.some(t=>n.videoRanges[t]>0))return Ge(i,`no variants with VIDEO-RANGE of ${Ue(y)} found`),e;if(d&&i.indexOf(d.substring(0,4))%5!=0)return Ge(i,`video codec preference "${d}" not found`),e;if(n.maxScore<v)return Ge(i,`max score of ${n.maxScore} < selected max of ${v}`),e}return e&&(fe(i)>=fe(e)||n.fragmentError>t[e].fragmentError)?e:(m=n.minIndex,v=n.maxScore,i)},void 0),videoRanges:y,preferHDR:E,minFramerate:g,minBitrate:p,minIndex:m}}(n,A,t,I,R),{codecSet:a,videoRanges:o,minFramerate:l,minBitrate:d,minIndex:h,preferHDR:c}=r;k=h,b=a,A=c?o[o.length-1]:o[0],L=l,t=Math.max(t,d),this.log(`picked start tier ${Ue(r)}`)}else b=null==E?void 0:E.codecSet,A=null==E?void 0:E.videoRange;const w=c?c.duration:h?h.duration:0,D=this.bwEstimator.getEstimateTTFB()/1e3,x=[];for(let l=s;l>=i;l--){var P;const i=g[l],h=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,_,A,L,t,I)?(i.supportedPromise=Re(i,_,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||h&&L>i.frameRate||!h&&L>0&&L<i.frameRate||null!=(P=i.supportedResult)&&null!=(P=P.decodingInfoResults)&&P.some(t=>!1===t.smooth))&&(!S||l!==k)){x.push(l);continue}const p=i.details,v=(c?null==p?void 0:p.partTarget:null==p?void 0:p.averagetargetduration)||w||1;let E;E=h?o*t:a*t;const R=w&&n>=2*w&&0===r?i.averageBitrate:i.maxBitrate,C=this.getTimeToLoadFrag(D,E,R*v,!p||p.live);if(E>=R&&(l===d||0===i.loadError&&0===i.fragmentError||N(i,y.errorPenaltyExpireMs))&&(C<=D||!e(C)||T&&!this.bitrateTestDelay||C<u)){const t=this.forcedAutoLevel;return l===m||-1!==t&&t===m||(x.length&&this.trace(`Skipped level(s) ${x.join(",")} of ${s} max with CODECS and VIDEO-RANGE:"${g[x[0]].codecs}" ${g[x[0]].videoRange}; not compatible with "${b}" ${A}`),this.info(`switch candidate:${f}->${l} adjustedbw(${Math.round(E)})-bitrate=${Math.round(E-R)} ttfb:${D.toFixed(1)} avgDuration:${v.toFixed(1)} maxFetchDuration:${u.toFixed(1)} fetchDuration:${C.toFixed(1)} firstSelection:${S} codecSet:${i.codecSet} videoRange:${i.videoRange} hls.loadLevel:${m}`)),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${wi(s,t)}`);this.warn(o),this.hls.trigger(a.ERROR,I({fatal:s},e,{type:n.MEDIA_ERROR,details:r.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{var n;const t=this._objectUrl=self.URL.createObjectURL(r),e=this.hls.config,s=e.emeEnabled&&i.mediaKeys?null==(n=e.emeController)?void 0:n.CDMCleanupPromise:null;s?s.then(()=>{this.hls&&this.setSource(i,r,t)}).catch(()=>{}):this.setSource(i,r,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,_i(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,n=s?Object.keys(s):null,r=n?n.length:0,o=()=>{Promise.resolve().then(()=>{this.media&&this.mediaSourceOpenOrEnded&&this._onMediaSourceOpen()})};if(s&&n&&r){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 n=t.currentTime,r=this.details,o=Math.max(n,(null==r?void 0:r.fragments[0].start)||0);return o-n>1?void this.log(`attachTransferred: waiting for playback to reach new tracks start time ${n} -> ${o}`):(this.warn(`attachTransferred: resetting MediaSource for incompatible tracks ("${Object.keys(s)}"->"${Object.keys(i)}") start time: ${o} currentTime: ${n}`),this.onMediaDetaching(a.MEDIA_DETACHING,{}),this.onMediaAttaching(a.MEDIA_ATTACHING,e),void(t.currentTime=o))}this.transferData=void 0,n.forEach(t=>{const e=t,i=s[e];if(i){const t=i.buffer;if(t){const s=this.fragmentTracker,n=i.id;if(s.hasFragments(n)||s.hasParts(n)){const i=Ei.getBuffered(t);s.detectEvictedFragments(e,i,n,null,null,!0)}const r=ki(e),a=[e,t];this.sourceBuffers[r]=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:n,_objectUrl:r}=this;if(n){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"===n.readyState;try{const e=n.sourceBuffers;for(let i=e.length;i--;)t&&e[i].abort(),n.removeSourceBuffer(e[i]);t&&n.endOfStream()}catch(t){this.warn(`onMediaDetaching: ${t.message} while calling endOfStream`)}}this.sourceBufferCount&&this.onBufferReset()}Si(n,"sourceopen",this._onMediaSourceOpen),Si(n,"sourceended",this._onMediaSourceEnded),Si(n,"sourceclose",this._onMediaSourceClose),this.appendSource&&(Si(n,"startstreaming",this._onStartStreaming),Si(n,"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||(r&&self.URL.revokeObjectURL(r),this.mediaSrc!==r||this.isMediaSourceReplaced(r)?this.warn("media|source.src was changed by a third party - skip cleanup"):(s.removeAttribute("src"),this.appendSource&&_i(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[ki(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,n=Object.keys(e);this.log(`BUFFER_CODECS: "${n}" (current SB count ${this.sourceBufferCount})`);const r="audiovideo"in e&&(s.audio||s.video)||s.audiovideo&&("audio"in e||"video"in e),a=!r&&this.sourceBufferCount&&this.media&&n.some(t=>!s[t]);r||a?this.warn(`Unsupported transition between "${Object.keys(s)}" and "${n}" SourceBuffers`):(n.forEach(t=>{var i,n;const r=e[t],{id:a,codec:o,levelCodec:l,container:d,metadata:h,supplemental:c}=r;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,p=(null==g?void 0:g.pendingCodec)||(null==g?void 0:g.codec),m=null==g?void 0:g.levelCodec;u||(u=s[t]={buffer:void 0,listeners:[],codec:o,supplemental:c,container:d,levelCodec:l,metadata:h,id:a});const v=ve(p,m),y=null==v?void 0:v.replace(Ai,"$1");let E=ve(o,l);const T=null==(n=E)?void 0:n.replace(Ai,"$1");E&&v&&y!==T&&("audio"===t.slice(0,5)&&(E=me(E,this.appendSource)),this.log(`switching codec ${p} to ${E}`),E!==(u.pendingCodec||u.codec)&&(u.pendingCodec=E),u.container=d,this.appendChangeType(t,d,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}`,n={label:`change-type=${s}`,execute:()=>{const n=this.tracks[t];if(n){const r=n.buffer;null!=r&&r.changeType&&(this.log(`changing ${t} sourceBuffer type to ${s}`),r.changeType(s),n.codec=i,n.container=e)}this.shiftAndExecuteNext(t)},onStart:()=>{},onComplete:()=>{},onError:e=>{this.warn(`Failed to change ${t} SourceBuffer type`,e)}};this.append(n,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 n={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(n,"audio",!0)}unblockAudio(){this.operationQueue&&this.operationQueue.unblockAudio()}onBufferAppending(t,i){const{tracks:s}=this,{data:o,type:l,parent:d,frag:h,part:c,chunkMeta:u,offset:f}=i,g=u.buffering[l],p=y(h)&&!c&&!h.gap&&!u.partial&&!u.iframe;let m=null,v=!1;const{sn:E,cc:T}=h,S=self.performance.now();g.start=S;const b=h.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,_=null==R?void 0:R.buffer;if(_&&"initSegment"!==E&&void 0!==f){const t=null==L?void 0:L.buffer,e=c||h;if("audio"===l&&"main"!==d&&!R.ending&&!R.ended&&t&&Ei.getBuffered(t).length){const t=e.start+.05*e.duration,i=Ei.getBuffered(_),s=this.currentOp("video");i.length||s?!Ei.isBuffered(_,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 k=(c||h).start,w={label:`append-${l}`,execute:()=>{var t;g.executeStart=self.performance.now();const i=null==(t=this.tracks[l])?void 0:t.buffer;i&&(p&&(m=Ei.timeRangesToArray(Ei.getBuffered(i)),v=Pi(xi(m,h),h)),I?this.updateTimestampOffset(i,k,.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))}),p){const t=this.getFragmentAppendProgress(h),i=e[l];if(i&&m){const e=xi(Ei.timeRangesToArray(i),h);t.progressed||(t.progressed=e-xi(m,h)>.001);const s=v&&Pi(e,h);t.fullyBuffered[l]=(void 0===t.fullyBuffered[l]||t.fullyBuffered[l])&&s}}this.hls.trigger(a.BUFFER_APPENDED,{type:l,frag:h,part:c,chunkMeta:u,parent:d,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,h.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,w,i],l)}this.warn(`QuotaExceededError on "${l}" sn: ${E} - no back buffer available to evict`)}p&&(this.getFragmentAppendProgress(h).errored=!0);const s={type:n.MEDIA_ERROR,parent:d,details:r.BUFFER_APPEND_ERROR,sourceBufferName:l,frag:h,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=r.BUFFER_FULL_ERROR);const e=++this.appendErrors[l],n=this.hls.config.appendErrorMaxRetry;this.warn(`Failed ${e}/${n+1} times to append segment in "${l}" sourceBuffer with error: ${t.message}`),e>=n&&(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${wi(s.fatal,f)}`),s.details=r.MEDIA_SOURCE_REQUIRES_RESET)}else s.errorAction=mi(!0);this.appendError=s,this.hls.trigger(a.ERROR,s),i&&this.hls&&this.trimBuffers(h.start,1)}};this.log(`queuing "${l}" append sn: ${E}${c?" p: "+c.index:""} of ${d} playlist ${h.level} cc: ${T} offset: ${f} bytes: ${o.byteLength}`),this.append(w,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 n=null==(s=this.tracks[t])?void 0:s.buffer;this.log(`Remove request ${e}-${i} from ${t} Source Buffer complete > buffer: ${n?bi(Ei.getBuffered(n)):"(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:n}=e;i&&"audio"!==i||this.unblockAudio(),i?this.append(this.getFlushOp(i,s,n),i):this.sourceBuffers.forEach(([t])=>{t&&this.append(this.getFlushOp(t,s,n),t)})}onFragParsed(t,e){const{frag:i,part:s,chunkMeta:n}=e,r=[],o=s?s.elementaryStreams:i.elementaryStreams;o[m]?r.push("audiovideo"):(o[g]&&r.push("audio"),o[p]&&r.push("video"));0===r.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,n,r),this.hls&&(this.hls.trigger(a.FRAG_BUFFERED,{frag:i,part:s,stats:e,id:i.type,chunkMeta:n}),!s&&i.gap&&e.retry&&this.log(`Nothing buffered for ${i.type} level: ${i.level} sn: ${i.sn} retries ${e.retry}`))},r).catch(t=>{this.warn(`Fragment buffered callback ${t.message}`),this.stepOperationQueue(this.sourceBufferTypes)})}onFragChanged(t,e){var i,s;const n=null==(i=this.hls)?void 0:i.config;if(!n)return;const{backBufferLength:r,frontBufferFlushThreshold:a}=n;this.trimBuffers(a,r,e.frag,e.previousFrag);const o=e.frag.elementaryStreams,{appendErrors:l}=this,d=null==(s=this.appendError)?void 0:s.sourceBufferName;Object.keys(o).forEach(t=>{o[t]&&(l[t]=0,t===d&&(this.appendError=void 0),"audio"===t||"video"===t?(l.audiovideo=0,"audiovideo"===d&&(this.appendError=void 0)):(l.audio=0,l.video=0,"audiovideo"!==d&&(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===r.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=Di(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=Di(t),l=this.fragmentAppendProgress[o];delete this.fragmentAppendProgress[o];const d=t.stats.buffering;if(d.start&&!d.first)return;const h=(null==l?void 0:l.stats)===t.stats?l:void 0;if(null!=h&&h.errored)return;const c=s.length>0&&s.every(t=>!0===(null==h?void 0:h.fullyBuffered[t]));if(null!=h&&h.progressed||c)return void delete this.appendsWithoutProgress[o];if(!h&&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:n.MEDIA_ERROR,details:r.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,n){const{hls:r,details:a,media:o}=this;if(!o||null===a)return;if(!this.sourceBufferCount)return;const l=r.config,d=o.currentTime,h=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,h);c=Math.floor(d/h)*h-t}if(s){const t=this.getLoopBackBufferFlushEnd(s,null!=n?n:null);t>0&&(c=Math.max(c,t))}if(c>0&&this.flushBackBuffer(d,h,c),e(t)&&t>0){const e=Math.max(l.maxBufferLength,t),i=Math.max(e,h),s=Math.floor(d/h)*h+i;this.flushFrontBuffer(d,h,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:n,audiovideo:r}=t.elementaryStreams;if(null!=n&&n.partial||null!=r&&r.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 n=t.start;return s?n=Math.min(n,s.startDTS):(e&&(n=Math.min(n,e.startDTS)),i&&(n=Math.min(n,i.startDTS))),n}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,n,r;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==(n=this.media)||!n.loop||!1===(null==(r=this.hls)?void 0:r.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 n=Ei.getBuffered(s),r=n.length;if(r<2)return;const o=n.start(r-1),l=n.end(r-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 n=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,n)}}return{duration:1/0}}const r=null==(t=this.overrides)?void 0:t.duration;if(r)return e(r)?{duration:r}:null;const a=this.media.duration;return n>(e(s.duration)?s.duration:0)&&n>a||!e(a)?{duration:n}:null}updateMediaSource({duration:t,start:i,end:s}){const n=this.mediaSource;n&&this.media&&"open"===n.readyState&&(n.duration!==t&&(e(t)&&this.log(`Updating MediaSource duration to ${t.toFixed(3)}`),n.duration=t),void 0!==i&&void 0!==s&&(this.log(`MediaSource duration is set to ${n.duration}. Setting seekable range to ${i}-${s}.`),n.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:n.MEDIA_ERROR,details:r.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,d=t[l];if(this.isPending(d)){const t=this.getTrackCodec(d,l),o=`${d.container};codecs=${t}`;d.codec=t,this.log(`creating sourceBuffer(${o})${this.currentOp(l)?" Queued":""} ${Ue(d)}`);try{const t=i.addSourceBuffer(o),s=ki(l),n=[l,t];e[s]=n,d.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:n.MEDIA_ERROR,details:r.BUFFER_ADD_CODEC_ERROR,fatal:!1,error:t,sourceBufferName:l,mimeType:o,parent:d.id})}this.trackSourceBuffer(l,d)}}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)&&de(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 n=ve(s,t.levelCodec);return n?"audio"===e.slice(0,5)?me(n,this.appendSource):n:""}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:n.MEDIA_ERROR,details:r.BUFFER_APPENDING_ERROR,sourceBufferName:t,error:o,fatal:!1});const l=this.currentOp(t);l&&l.onError(o)}updateTimestampOffset(t,e,i,s,n,r){const a=e-t.timestampOffset;Math.abs(a)>=i&&(this.log(`Updating ${s} SourceBuffer timestampOffset to ${e} (sn: ${n} cc: ${r})`),t.timestampOffset=e)}removeExecutor(t,i,s){const{media:n,mediaSource:r}=this,a=this.tracks[t],o=null==a?void 0:a.buffer;if(!n||!r||!o)throw new Error(`Attempting to remove from the ${t} SourceBuffer, but it does not exist`);const l=e(n.duration)?n.duration:1/0,d=e(r.duration)?r.duration:1/0,h=Math.max(0,i);var c;if(h>=d)return null==(c=this.currentOp(t))||c.onComplete(),void this.shiftAndExecuteNext(t);const u=Math.min(s,l,d);if(!(u>h)||a.ending&&!a.ended)throw new Error(`Cannot remove ${u<=h?`invalid range (${h} >= ${u}) `:""}from the ${t} SourceBuffer${a.ending?" while track ending":""}`);a.ended=!1,this.log(`Removing [${h},${u}] from the ${t} SourceBuffer`),o.remove(h,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 n=s.buffer;if(!n)return;const r=i.bind(this,t);s.listeners.push({event:e,listener:r}),Ti(n,e,r)}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 r.FRAG_LOAD_ERROR:case r.FRAG_LOAD_TIMEOUT:case r.KEY_LOAD_ERROR:case r.KEY_LOAD_TIMEOUT:return void(e.errorAction=this.getFragRetryOrSwitchAction(e));case r.FRAG_PARSING_ERROR:if(null!=(i=e.frag)&&i.gap)return void(e.errorAction=mi());case r.FRAG_GAP:case r.FRAG_DECRYPT_ERROR:return e.errorAction=this.getFragRetryOrSwitchAction(e),void(e.errorAction.action=ri);case r.PLAYLIST_UNCHANGED_ERROR:case r.LEVEL_EMPTY_ERROR:case r.LEVEL_PARSING_ERROR:{var o;const t=e.parent===f.MAIN?e.level:s.loadLevel;e.details===r.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 r.LEVEL_LOAD_ERROR:case r.LEVEL_LOAD_TIMEOUT:return void("number"==typeof(null==a?void 0:a.level)&&(e.errorAction=this.getPlaylistRetryOrSwitchAction(e,a.level)));case r.AUDIO_TRACK_LOAD_ERROR:case r.AUDIO_TRACK_LOAD_TIMEOUT:case r.SUBTITLE_LOAD_ERROR:case r.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=di)}return;case r.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:return void(e.errorAction={action:ri,flags:hi});case r.KEY_SYSTEM_SESSION_UPDATE_FAILED:case r.KEY_SYSTEM_STATUS_INTERNAL_ERROR:case r.KEY_SYSTEM_NO_SESSION:return void(e.errorAction={action:ri,flags:ci});case r.BUFFER_ADD_CODEC_ERROR:case r.REMUX_ALLOC_ERROR:case r.BUFFER_APPEND_ERROR:return void(e.errorAction||(e.errorAction=this.getLevelSwitchAction(e,e.level)));case r.MEDIA_SOURCE_REQUIRES_RESET:return e.errorAction||(e.errorAction=this.getLevelSwitchAction(e,e.level)),void(e.errorAction.flags|=fi|ui);case r.INTERNAL_EXCEPTION:case r.BUFFER_APPENDING_ERROR:case r.BUFFER_APPEND_NO_PROGRESS:case r.BUFFER_FULL_ERROR:case r.LEVEL_SWITCH_ERROR:case r.BUFFER_STALLED_ERROR:case r.BUFFER_SEEK_OVER_HOLE:case r.BUFFER_NUDGE_ON_STALL:return void(e.errorAction=mi())}e.type===n.KEY_SYSTEM_ERROR&&(e.levelRetry=!1,e.errorAction=mi())}getPlaylistRetryOrSwitchAction(t,e){const i=P(this.hls.config.playlistLoadPolicy,t),s=this.playlistError++;if(O(i,s,w(t),t.response))return{action:oi,flags:li,retryConfig:i,retryCount:s};const n=this.getLevelSwitchAction(t,e);return i&&(n.retryConfig=i,n.retryCount=s),n}getFragRetryOrSwitchAction(t){const e=this.hls,i=this.getVariantLevelIndex(t.frag),s=e.levels[i],{fragLoadPolicy:n,keyLoadPolicy:a}=e.config,o=P(D(t)?a:n,t),l=e.levels.reduce((t,e)=>t+e.fragmentError,0);if(s&&(t.details!==r.FRAG_GAP&&s.fragmentError++,!x(t))){if(O(o,l,w(t),t.response))return{action:oi,flags:li,retryConfig:o,retryCount:l}}const d=this.getLevelSwitchAction(t,i);return o&&(d.retryConfig=o,d.retryCount=l),d}getLevelSwitchAction(t,e){const i=this.hls;null==e&&(e=i.loadLevel);const s=this.hls.levels[e];if(s){var n,a;const e=t.details;s.loadError++,s.loadErrorTime=self.performance.now(),e===r.BUFFER_APPEND_ERROR&&s.fragmentError++;let d=-1;const{levels:h,loadLevel:c,minAutoLevel:g,maxAutoLevel:p}=i;i.autoLevelEnabled||i.config.preserveManualLevelOnError||(i.loadLevel=-1);const m=null==(n=t.frag)?void 0:n.type,v=(m===f.AUDIO&&e===r.FRAG_PARSING_ERROR||"audio"===t.sourceBufferName&&gi(t))&&h.some(({audioCodec:t})=>s.audioCodec!==t),y="video"===t.sourceBufferName&&gi(t)&&h.some(({codecSet:t,audioCodec:e})=>s.codecSet!==t&&s.audioCodec===e),{type:E,groupId:T}=null!=(a=t.context)?a:{};for(let n=h.length;n--;){const a=(n+c)%h.length;if(a!==c&&a>=g&&a<=p&&(0===h[a].loadError||N(h[a],i.config.errorPenaltyExpireMs))){var o,l;const i=h[a];if(e===r.FRAG_GAP&&m===f.MAIN&&t.frag){const e=h[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(m===f.AUDIO&&null!=(o=s.audioGroups)&&o.some(t=>i.hasAudioGroup(t))||m===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}d=a;break}}if(d>-1&&i.loadLevel!==d)return t.levelRetry=!0,this.playlistError=0,{action:ri,flags:li,nextAutoLevel:d}}return{action:ri,flags:di}}onErrorOut(t,e){var i,s;switch(null==(i=e.errorAction)?void 0:i.action){case ni:break;case ri:this.sendAlternateToPenaltyBox(e),e.errorAction.resolved||e.details===r.FRAG_GAP||e.details===r.PLAYLIST_UNCHANGED_ERROR||pi(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&hi){const s=this.getVariantLevelIndex(t.frag),n=e.levels[s],r=null==n?void 0:n.attrs["HDCP-LEVEL"];i.hdcpLevel=r;const a="NONE"===r;r&&!a?(e.maxHdcpLevel=De[De.indexOf(r)-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 n,r;if(this.variantHasKey(s[i],e))this.log(`Banned key found in level ${i} (${s[i].bitrate}bps) or audio group "${null==(n=s[i].audioGroups)?void 0:n.join(",")}" (${null==(r=t.frag)?void 0:r.type} fragment) ${pt(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===r.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,n=i-this.lastDroppedFrames,r=e-this.lastDecodedFrames,o=1e3*n/t,l=this.hls;if(l.trigger(a.FPS_DROP,{currentDropped:n,currentDecoded:r,totalDroppedFrames:i}),o>0&&n>l.config.fpsDroppedMonitoringThreshold*r){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:n}=e;this.id3Track||(this.id3Track=this.createTrack(this.media));const r=Ml();if(r)for(let t=0;t<n.length;t++){const e=n[t].type;if(e===Yn.emsg&&!i||!s)continue;const a=ct(n[t].data),o=n[t].pts;let l=o+n[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(r,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 n=s[i];n.type===e&&n.startTime<t&&n.endTime===Fl&&(n.endTime=t)}}onBufferFlushing(t,{startOffset:e,endOffset:i,type:s}){const{id3Track:n,hls:r}=this;if(!r)return;const{config:{enableEmsgMetadataCues:a,enableID3MetadataCues:o}}=r;if(n&&(a||o)){let t;t="audio"===s?t=>t.type===Yn.audioId3&&o:"video"===s?t=>t.type===Yn.emsg&&a:t=>t.type===Yn.audioId3&&o||t.type===Yn.emsg&&a,wl(n.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:n,enableDateRangeMetadataCues:r,interstitialsController:a}=this.hls.config;if(!r)return;const o=Ml();if(s&&n&&!a){const{fragmentStart:e,fragmentEnd:i}=t;let n=this.assetCue;n?(n.startTime=e,n.endTime=i):o&&(n=this.assetCue=Ol(o,e,i,{assetPlayerId:this.hls.config.assetPlayerId},"hlsjs.interstitial.asset"),n&&(n.id=s,this.id3Track||(this.id3Track=this.createTrack(this.media)),this.id3Track.track.addCue(n),n.addEventListener("enter",this.onEventCueEnter)))}if(!t.hasProgramDateTime)return;const{id3Track:l}=this,{dateRanges:d}=t,h=Object.keys(d);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===h.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!==h.length&&e(null==g?void 0:g.programDateTime)){this.id3Track||(this.id3Track=this.createTrack(this.media));for(let t=0;t<h.length;t++){const e=h[t],i=d[e],s=i.startTime,n=c[e],r=(null==n?void 0:n.cues)||{};let l=(null==n?void 0:n.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=h.reduce((t,e)=>{if(e!==i.id){const s=d[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 p=Object.keys(i.attr);for(let t=0;t<p.length;t++){const d=p[t];if(!ds(d))continue;const h=r[d];if(h)!l||null!=n&&n.durationKnown?Math.abs(h.startTime-s)>.01&&(h.startTime=s,h.endTime=u):h.endTime=u;else if(o){let t=i.attr[d];hs(d)&&(t=mt(t));const n=Ol(o,s,u,{key:d,data:t},Yn.dateRange);n&&(n.id=e,this.id3Track.track.addCue(n),r[d]=n,a&&("X-ASSET-LIST"!==d&&"X-ASSET-URL"!==d||n.addEventListener("enter",this.onEventCueEnter)))}}c[e]={cues:r,dateRange:i,durationKnown:l}}}}},gapController:class extends Zi{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 n=null==(i=this.hls)?void 0:i.config;if(!n)return;const r=this.media;if(!r)return;const{seeking:o}=r,l=this.seeking&&!o,d=!this.seeking&&o,h=r.paused&&!o||r.ended||0===r.playbackRate;if(this.seeking=o,t!==e)return e&&(this.ended=0),this.moved=!0,o||(this.skipRetry=this.nudgeRetry=0,n.nudgeOnVideoHole&&!h&&t>e&&this.nudgeOnVideoHole(t,e)),void(0===this.waiting&&this.stallResolved(t));if(d||l)return void(l&&this.stallResolved(t));if(h)return this.skipRetry=this.nudgeRetry=0,this.stallResolved(t),void(!this.ended&&r.ended&&this.hls&&(this.ended=t||1,this.hls.trigger(a.MEDIA_ENDED,{stalled:!1})));if(!Ei.getBuffered(r).length)return void(this.skipRetry=this.nudgeRetry=0);const c=Ei.bufferInfo(r,t,0),u=this.fragmentTracker;u&&this.hls&&Cl(c,t,u,this.hls);const f=c.nextStart||0;if(o&&u&&this.hls){const e=Dl(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=Pl(t,u);if(e>0&&(e<=i||s))return void(r.paused||this._trySkipBufferHole(s))}const p=n.detectStallWithCurrentTimeMs,m=self.performance.now(),v=this.waiting;let y=this.stalled;if(null===y){if(!(v>0&&m-v<p))return void(this.stalled=m);y=this.stalled=v}const E=m-y;if(!o&&(E>=p||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(r.currentTime!==t){const e=t;return t=r.currentTime,this.moved=!0,void this.log(`currentTime changed ${e} > ${t}`)}}const S=Ei.bufferInfo(r,t,n.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=Pl(t,this.fragmentTracker);o&&"fragment"in o?o=o.fragment:o||(o=void 0);const d=Ei.bufferInfo(this.media,t,0);this.hls.trigger(a.ERROR,{type:n.MEDIA_ERROR,details:r.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:i,reason:i.message,frag:o,buffer:d.len,bufferInfo:d})}}}}}_tryFixBufferStall(t,e,i){var s,n;const{fragmentTracker:r,media:a}=this,o=null==(s=this.hls)?void 0:s.config;if(!a||!r||!o)return;const l=null==(n=this.hls)?void 0:n.latestLevelDetails,d=Pl(i,r);if(d||null!=l&&l.live&&i<l.fragmentStart){if(this._trySkipBufferHole(d)||!this.media)return}const h=t.buffered,c=this.adjacentTraversal(t,i);(h&&h.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),n=i.getFragAtPos(s,f.MAIN);if(t&&n)return n.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:n.MEDIA_ERROR,details:r.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,d=Ei.bufferInfo(i,l,0);Cl(d,l,e,s);const h=l<d.start?d.start:d.nextStart;if(h){const u=d.len<=o.maxBufferHole,g=d.len>0&&d.len<1&&i.readyState<3,p=h-l;if(p>0&&(u||g)){if(p>o.maxBufferHole){let i=!1;if(0===l){const t=e.getAppendedFrag(0,f.MAIN);t&&h<t.end&&(i=!0)}if(!i&&t){var c;if(null==(c=s.loadLevelObj)||!c.details)return 0;if(Dl(s.inFlightFragments,h))return 0;let i=!1,n=t.end;for(;n<h;){const t=Pl(n,e),s=t?t.duration:0;if(!(s>0)){i=!0;break}n+=s}if(i)return 0}}const{nudgeMaxRetry:u,skipBufferHolePadding:g}=o,m=++this.skipRetry>u,v=Math.max(h,l)+g;if(m||(this.warn(`skipping hole, adjusting currentTime from ${l} to ${v}`),this.moved=!0,i.currentTime=v),null==t||!t.gap||m){const e=new Error(m?`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:n.MEDIA_ERROR,details:r.BUFFER_SEEK_OVER_HOLE,fatal:m,error:e,reason:e.message,buffer:d.len,bufferInfo:d};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 d=l+(s+1)*o.nudgeOffset,h=new Error(`Nudging 'currentTime' from ${l} to ${d}`);this.warn(h.message),i.currentTime=d,e.trigger(a.ERROR,{type:n.MEDIA_ERROR,details:r.BUFFER_NUDGE_ON_STALL,error:h,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:n.MEDIA_ERROR,details:r.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,n=this.computeLatency();if(null===n)return;this._latency=n;const{lowLatencyMode:r,maxLiveSyncPlaybackRate:a}=s;if(!r||1===a||!i.live)return;const o=this.targetLatency;if(null===o)return;const l=n-o,d=l<Math.min(this.maxLatency,o+i.targetduration),h=xn(s)&&!(null==(t=this.hls.interstitialsManager)||null==(t=t.playingItem)||!t.event);if(d&&l>.05&&this.forwardBufferLength>1&&!h){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:n}=t,{liveSyncDuration:r,liveSyncDurationCount:a,lowLatencyMode:o}=e,l=this.hls.userConfig;let d=o&&s||i;(this._targetLatencyUpdated||l.liveSyncDuration||l.liveSyncDurationCount||0===d)&&(d=void 0!==r?r:a*n);const h=n;return d+Math.min(this.stallCount*e.liveSyncOnStallIncrease,h)}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,n=t-e-this.edgeStalled,r=s-i.totalduration,a=s-(this.hls.config.lowLatencyMode&&i.partTarget||i.targetduration);return Math.min(Math.max(r,n),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,n=this.media||e.event.appendInPlace&&(null==s||null==(i=s.interstitialsManager)?void 0:i.playerQueue.reduce((t,e)=>t||e.media,null));s&&n&&n.playbackRate>1&&n.playbackRate<=s.config.maxLiveSyncPlaybackRate&&this.changeMediaPlaybackRate(n,1)}onError(t,e){var i;e.details===r.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:Od,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 wn{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=yn,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:n,part:r,success:a}=e;if(!a)return;const o=(i=this.tracksBuffered)[s=n.level]||(i[s]=[]);if(!o)return;let l;const d=(r||n).start;for(let t=0;t<o.length;t++)if(d>=o[t].start&&d<=o[t].end){l=o[t];break}const h=d+(r||n).duration;if(l?l.end=h:(l={start:d,end:h},o.push(l)),!r||h>=n.end-1e-6){const t=this.fragmentTracker.fragBuffered(n);r&&t&&(t.range.subs={time:[{startPTS:n.start,endPTS:h}],partial:!0}),y(n)&&!this.fragContextChanged(n)&&(this.fragPrevious=n),this.fragBufferedComplete(n,r),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===r.FRAG_GAP&&this.fragmentTracker.addAsGap(i),this.fragCurrent&&this.fragCurrent.abortRequests(),this.state!==vn&&(this.state=yn))}onSubtitleTracksUpdated(t,{subtitleTracks:e}){this.levels&&na(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!==vn&&this.setInterval(500)):this.mediaBuffer=null}onSubtitleTrackLoaded(t,e){var i;const{currentTrackId:s,levels:n}=this,{details:r,id:o}=e;if(!n)return void this.warn(`Subtitle tracks were reset while loading level ${o}`);const l=n[o];if(o>=n.length||!l)return;this.log(`Subtitle track ${o} loaded [${r.startSN},${r.endSN}]${r.lastPartSn?`[part-${r.lastPartSn}-${r.lastPartIndex}]`:""},duration:${r.totalduration}`),this.mediaBuffer=this.mediaBufferTimeRanges;const d=this.mainDetails;let h=0;if(r.live||null!=(i=l.details)&&i.live){if(r.deltaUpdateFailed)return;if(!d)return void(this.startFragRequested=!1);var c;if(l.details)h=this.alignPlaylists(r,l.details,null==(c=this.levelLastLoaded)?void 0:c.details);r.alignedSliding||(mn(d,r,this),h=r.fragmentStart)}l.details=r,this.levelLastLoaded=l,d&&!this.startFragRequested&&this.setStartPosition(d,h),o===s&&(this.hls.trigger(a.SUBTITLE_TRACK_UPDATED,{details:r,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,ps(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:n.MEDIA_ERROR,details:r.FRAG_DECRYPT_ERROR,fatal:!1,error:t,reason:t.message,frag:e,part:i}),i||(this.warn(`${t.name}: ${t.message}`),this.state=yn)})}doTick(){if(this.state===yn&&this.levels){var t;if(!this.media&&!this.primaryPrefetch&&(this.startFragRequested||!this.config.startFragPrefetch))return;const{currentTrackId:i,levels:s}=this,n=s[i],r=null==n?void 0:n.details;if(!r||this.waitForLive(n)||this.waitForCdnTuneIn(r))return void(this.startFragRequested=!1);const{config:a}=this,o=this.playhead,l=Ei.bufferedInfo(this.tracksBuffered[i]||[],o,a.maxBufferHole),{end:d,len:h}=l;if(h>Math.max(this.hls.maxBufferLength+r.levelTargetDuration,(null==(t=this.hls.mainForwardBufferInfo)?void 0:t.len)||0)||h&&!this.buffering)return;let c=this.getNextFragment(d,r);if(!c)return;if(y(c)){var e;if(c.end===l.end)return;const t=c.sn-r.startSN,i=r.fragments[t-1];c.cc!==(null==i?void 0:i.cc)||null!=(e=r.partList)&&e.length||this.fragmentTracker.getState(i)!==Ci||(c=i)}this.loadFragment(c,n,d)}}loadFragment(t,e,i){const s=this.fragmentTracker.getState(t);s!==Ci&&s!==Oi||super.loadFragment(t,e,i)}get mediaBufferTimeRanges(){return new cd(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 n;t>-1&&(this._subtitleDisplay="showing"===(null==(n=this.tracksInGroup[t].trackNode)?void 0:n.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,_l(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:n}=e,r=this.tracksInGroup[i];if(!r||r.groupId!==s)return void this.warn(`Subtitle track with id:${i} and group:${s} not found in active group ${null==r?void 0:r.groupId}`);const a=r.details;r.details=e.details,this.log(`Subtitle track ${i} "${r.name}" lang:${r.lang} group:${s} loaded [${n.startSN}-${n.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 n=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===pl?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(!n&&e){this.selectDefaultTrack=!1;const i=Ke(e,t);if(i>-1)n=t[i];else{const t=Ke(e,this.tracks);n=this.tracks[t]}}let s=this.findTrackId(n);-1===s&&n&&(s=this.findTrackId(null));const r={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,r),this.setSubtitleTrack(s),this.createTracksInGroup()}}findTrackId(t){const e=this.tracksInGroup,i=this.selectDefaultTrack;for(let s=0;s<e.length;s++){const n=e[s];if((!i||n.default)&&(i||t)&&(!t||Ve(n,t)))return s}if(t){for(let i=0;i<e.length;i++){const s=e[i];if(ra(t.attrs,s.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return i}for(let i=0;i<e.length;i++){const s=e[i];if(ra(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&&Ve(t,i))return i;const s=Ke(t,this.tracksInGroup);if(s>-1){const t=this.tracksInGroup[s];return this.setSubtitleTrack(s,!0),t}if(i)return null;{const i=Ke(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,n=this.getUrlWithDirectives(t.url,e),r=t.details,o=null==r?void 0:r.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&&r.live?" age "+o.toFixed(1)+(r.type&&" "+r.type||""):""} ${n}`),this.hls.trigger(a.SUBTITLE_TRACK_LOADING,{url:n,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 n=this.currentTrack,r=s[t]||null;if(this.trackId=t,this.currentTrack=r,i&&this.toggleTrackModes(),!r)return void(n&&this.hls.trigger(a.SUBTITLE_TRACK_SWITCH,{id:t}));const o=!!r.details&&!r.details.live;if(r===n&&o)return;this.log(`Switching to subtitle-track ${t}`+(r?` "${r.name}" lang:${r.lang} group:${r.groupId}`:""));const{id:l,groupId:d="",name:h,type:c,url:u}=r;this.hls.trigger(a.SUBTITLE_TRACK_SWITCH,{id:l,groupId:d,name:h,type:c,url:u});const f=this.switchParams(r.url,null==n?void 0:n.details,r.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 Pd(this,"textTrack1"),e=new Pd(this,"textTrack2"),i=new Pd(this,"textTrack3"),s=new Pd(this,"textTrack4");this.cea608Parser1=new wd(1,t,e),this.cea608Parser2=new wd(3,i,s)}addCues(t,e,i,s,n){let r=!1;for(let t=n.length;t--;){const s=n[t],a=Cd(s[0],s[1],e,i);if(a>=0&&(s[0]=Math.min(s[0],e),s[1]=Math.max(s[1],i),r=!0,a/(i-e)>.5))return}if(r||n.push([e,i]),this.config.renderTextTracksNatively){const n=this.cueCache[t];if(n){const t=this.Cues.newCue(null,e,i,s);t.length&&n.push.apply(n,t)}else{const n=this.captionsTracks[t].track;this.Cues.newCue(n,e,i,s)}}else{var o;const n=this.Cues.newCue(null,e,i,s),r=null==(o=this.captionsProperties[t])?void 0:o.media;this.hls.trigger(a.CUES_PARSED,{type:"captions",cues:n,track:t,closedCaptions:r})}}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:n}=this,{label:r,languageCode:a}=e[t];n&&(s[t]=[],i[t]=Rl(n,"captions",r,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&&!na(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:n,lastSn:r}=this,{cc:a,sn:o}=e.frag,l=null!=(i=null==(s=e.part)?void 0:s.index)?i:-1;t&&n&&(o!==r+1||o===r&&l!==this.lastPartIndex+1||a!==this.lastCc)&&(t.reset(),n.reset()),this.lastCc=a,this.lastSn=o,this.lastPartIndex=l}}onFragLoaded(t,e){const{frag:i,payload:s}=e;var n;if(i.level<this.tracks.length&&i.type===f.SUBTITLE)if(s.byteLength||null!=(n=i.initSegment)&&null!=(n=n.data)&&n.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)===pl?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 n=this.hls;El(i,this.initPTS[e.cc],t=>{this._appendCues(t,e.level),n.trigger(a.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:e,part:s})},t=>{n.logger.log(`Cannot parse IMSC1 (sn: ${e.sn} @${e.start}): ${t}`),n.trigger(a.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:e,part:s,error:t})})}_parseVTTs(t){var e;const{frag:i,payload:s}=t,n="part"in t?t.part:null,{initPTS:r,unparsedFrags:o}=this,l=r.length-1;if(!r[i.cc]&&-1===l)return void o.push(t);const d=this.hls,h=null==(e=i.initSegment)?void 0:e.data;gl(h?Vt(h,new Uint8Array(s)).buffer:s,this.initPTS[i.cc],this.vttCCs,i.cc,(n&&!h?n:i).start,t=>{this._appendCues(t,i.level),d.trigger(a.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:i,part:n})},e=>{const s=e.message.startsWith("Missing initPTS");d.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),d.trigger(a.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:i,part:n,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=pl,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=>kl(i,t))}else{const s=this.tracks[e];if(!s)return;const n=s.default?"default":"subtitles"+e;i.trigger(a.CUES_PARSED,{type:"subtitles",cues:t,track:n,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 n=null==(s=t[i])?void 0:s.track;if(n){const t=e[i];for(let e=0;e<t.length;e++)kl(n,t[e])}delete e[i]})}}}onBufferFlushing(t,e){const{startOffset:i,endOffset:s,endOffsetSubtitles:n,type:r}=e,{media:a}=this;if(a&&!(a.currentTime<s)){if(!r||"video"===r){const{captionsTracks:t,cueCache:e}=this;Object.keys(t).forEach(e=>wl(t[e].track,i,s)),Object.keys(e).forEach(t=>{const n=e[t];for(let t=n.length;t--;){const e=n[t];e.startTime>=i&&e.endTime<=s&&n.splice(t,1)}})}this.config.renderTextTracksNatively&&0===i&&void 0!==n&&this.tracks.forEach(t=>{var e;const s=null==(e=t.trackNode)?void 0:e.track;s&&wl(s,i,n)})}}extractCea608Data(t){const e=[[],[]],i=31&t[0];let s=2;for(let n=0;n<i;n++){const i=t[s++],n=127&t[s++],r=127&t[s++];if(0===n&&0===r)continue;if(!!(4&i)){const t=3&i;0!==t&&1!==t||(e[t].push(n),e[t].push(r))}}return e}},audioStreamController:class extends wn{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:n,timescale:r,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: ${n/r} (${n}/${r}) trackId: ${a}`),this.mainAnchor=i,this.state===_n){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===yn&&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 n=(s||t).cc,r=ii(this.getLevelDetails(),n,this.getLoadPosition());r&&this.fragmentTracker.getState(r)!==Fi&&(this.log(`Syncing with main frag at ${r.start} cc ${r.cc}`),this.startFragRequested=!1,this.nextLoadPosition=r.start,this.resetLoadingState(),this.state===yn&&this.doTickIdle())}startLoad(t,e){if(!this.levels)return this.startPosition=t,void(this.state=vn);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=yn,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 yn:this.doTickIdle();break;case bn:{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=_n}break}case Sn:this.checkRetryDate();break;case _n:{const t=this.waitingData;if(t){const{frag:e,part:i,cache:s,complete:n}=t,r=this.mainAnchor;if(void 0!==this.initPTS[e.cc]){this.waitingData=null,this.state=Tn;const t={frag:e,part:i,payload:s.flush().buffer,networkDetails:null};this._handleFragmentLoadProgress(t),n&&super._handleFragmentLoadComplete(t)}else r&&r.cc!==t.frag.cc&&this.syncWithAnchor(r,t.frag)}else this.state=yn}}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:n}=this,r=e.config;if(!this.buffering||!s&&!this.primaryPrefetch&&(this.startFragRequested||!r.startFragPrefetch)||null==i||!i[n])return;const o=i[n],l=o.details;if(!l||this.waitForLive(o)||this.waitForCdnTuneIn(l))return this.state=bn,void(this.startFragRequested=!1);const d=this.getBufferOutput();this.bufferFlushed&&d&&(this.bufferFlushed=!1,this.afterBufferFlushed(d,g));const h=this.getFwdBufferInfo();if(null===h)return;if(!this.switchingTrack&&this._streamEnded(h,l))return e.trigger(a.BUFFER_EOS,{type:"audio"}),void(this.state=In);const c=h.len,u=e.maxBufferLength,p=l.fragments,m=p[0].start,v=this.getLoadPosition(),E=this.flushing||this.switchingTrack&&!this.switchingTrack.flushImmediate?v:h.end;if(this.switchingTrack&&s){const t=v;l.PTSKnown&&t<m&&t>=this.timelineOffset&&(h.end>m||h.nextStart)&&(this.log(`Alt audio track ahead of main track, seek to start of alt audio track ${t} -> ${m} + 0.05`),s.currentTime=m+.05)}if(c>=u&&!this.switchingTrack&&E<p[p.length-1].start)return;let T=this.getNextFragment(E,l);if(T&&this.isLoopLoading(T,E)&&(T=this.getNextFragmentLoopLoading(T,l,h,f.MAIN,u)),!T)return void(this.bufferFlushed=!0);if(this.exceedsMaxBuffer(h,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!==vn&&(this.setInterval(100),this.state=yn,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:n,id:r,groupId:o,track:l}=e;if(!s)return void this.warn(`Audio tracks reset while loading track ${r} "${l.name}" of "${o}"`);const d=this.mainDetails;if(!d||n.endCC>d.endCC||d.expired)return this.cachedTrackLoadedData=e,void(this.state!==vn&&(this.state=bn));this.cachedTrackLoadedData=null,this.log(`Audio track ${r} "${l.name}" of "${o}" loaded [${n.startSN},${n.endSN}]${n.lastPartSn?`[part-${n.lastPartSn}-${n.lastPartIndex}]`:""},duration:${n.totalduration}`);const h=s[r];let c=0;if(n.live||null!=(i=h.details)&&i.live){if(this.checkLiveUpdate(n),n.deltaUpdateFailed)return;var u;if(h.details)c=this.alignPlaylists(n,h.details,null==(u=this.levelLastLoaded)?void 0:u.details);n.alignedSliding||(mn(d,n,this),c=n.fragmentStart)}h.details=n,this.levelLastLoaded=h,this.startFragRequested||this.setStartPosition(d,c),this.hls.trigger(a.AUDIO_TRACK_UPDATED,{details:n,id:r,groupId:e.groupId}),this.state!==bn||this.waitForCdnTuneIn(n)||(this.state=yn),this.tick()}_handleFragmentLoadProgress(t){var e;const i=t.frag,{part:s,payload:n}=t,{config:r,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 d=l.details;if(!d)return this.warn("Audio track details undefined on fragment load progress"),void this.removeUnbufferedFrags(i.start);const h=r.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,r=-1!==e,a=new ts(i.level,i.sn,i.stats.chunkCount,n.byteLength,e,r,i.duration);c.push(n,g,h,"",i,s,d.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 [${d.startSN} ,${d.endSN}],track ${a}`);const{cache:t}=this.waitingData=this.waitingData||{frag:i,part:s,cache:new Pn,complete:!1};t.push(new Uint8Array(n)),this.state!==vn&&(this.state=_n)}}_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===yn&&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=Rn;else switch(e.details){case r.FRAG_GAP:case r.FRAG_PARSING_ERROR:case r.FRAG_DECRYPT_ERROR:case r.FRAG_LOAD_ERROR:case r.FRAG_LOAD_TIMEOUT:case r.KEY_LOAD_ERROR:case r.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(f.AUDIO,e);break;case r.AUDIO_TRACK_LOAD_ERROR:case r.AUDIO_TRACK_LOAD_TIMEOUT:case r.LEVEL_PARSING_ERROR:e.levelRetry||this.state!==bn||(null==(i=e.context)?void 0:i.type)!==u.AUDIO_TRACK||(this.state=yn);break;case r.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 r.MEDIA_SOURCE_REQUIRES_RESET:this.onSourceBufferError(f.AUDIO,e);break;case r.BUFFER_ADD_CODEC_ERROR:case r.BUFFER_APPEND_ERROR:if("audio"!==e.parent)return;this.reduceLengthAndFlushBuffer(e)||this.resetLoadingState();break;case r.BUFFER_FULL_ERROR:if("audio"!==e.parent)return;this.reduceLengthAndFlushBuffer(e)&&(this.bufferedTrack=null,super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"));break;case r.INTERNAL_EXCEPTION:this.recoverWorkerError(e)}}onBufferFlushing(t,{type:e}){e!==p&&(this.flushing=!0)}onBufferFlushed(t,{type:e}){if(e!==p){this.flushing=!1,this.bufferFlushed=!0,this.state===In&&(this.state=yn);const t=this.getBufferOutput();t&&(this.afterBufferFlushed(t,e),this.tick())}}_handleTransmuxComplete(t){var e;const i="audio",{hls:s}=this,{remuxResult:n,chunkMeta:r}=t,o=this.getCurrentContext(r);if(!o)return void this.resetWhenMissingContext(r);const{frag:l,part:d,level:h}=o,{details:c}=h,{audio:u,text:p,id3:m,initSegment:v}=n;if(this.fragContextChanged(l)||!c)return this.fragmentTracker.removeFragment(l),void(null!=v&&v.tracks&&this.resetTransmuxer());if(this.state=An,u&&this.switchingTrack&&!this.switchingTrack.flushImmediate){const{config:t}=this,e=t.nextAudioTrackBufferFlushForwardOffset,i=Math.max(this.getLoadPosition()+e,(d||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(h,v.tracks,t,r),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;d&&(d.elementaryStreams[g]={startPTS:t,endPTS:e,startDTS:i,endDTS:s}),l.setElementaryStreamInfo(g,t,e,i,s),this.bufferFragmentData(u,l,d,r)}if(null!=m&&null!=(e=m.samples)&&e.length){const t=I({id:i,frag:l,details:c},m);s.trigger(a.FRAG_PARSING_METADATA,t)}if(p){const t=I({id:i,frag:l,details:c},p);s.trigger(a.FRAG_PARSING_USERDATA,t)}}_bufferInitSegment(t,e,i,s){if(this.state!==An)return;if(e.video&&delete e.video,e.audiovideo&&delete e.audiovideo,!e.audio)return;const n=e.audio;n.id=f.AUDIO;const r=t.audioCodec;this.log(`Init audio buffer, container:${n.container}, codecs[level/parsed]=[${r}/${n.codec}]`),1===(null==r?void 0:r.split(",").length)&&(n.levelCodec=r),this.hls.trigger(a.BUFFER_CODECS,e);const o=n.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 n;if(this.switchingTrack||s===Ci||s===Oi)if(null!=(n=e.details)&&n.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=_n;const i=this.mainDetails;i&&i.fragmentStart!==e.details.fragmentStart&&mn(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:n,audioCodec:r,channels:a}=this.bufferedTrack;Ve({name:e,lang:i,assocLang:s,characteristics:n,audioCodec:r,channels:a},t,He)||(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,_({},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:n}=e,r=this.tracksInGroup[i];if(!r||r.groupId!==s)return void this.warn(`Audio track with id:${i} and group:${s} not found in active group ${null==r?void 0:r.groupId}`);const a=r.details;r.details=e.details,this.log(`Audio track ${i} "${r.name}" lang:${r.lang} group:${s} loaded [${n.startSN}-${n.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=Ke(e,t,He);if(i>-1)o=t[i];else{const t=Ke(e,this.tracks);o=this.tracks[t]}}let s=this.findTrackId(o);-1===s&&o&&(s=this.findTrackId(null));const d={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,d);const h=this.trackId;if(-1!==s&&-1===h)this.setAudioTrack(s);else if(t.length&&-1===h){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:n.MEDIA_ERROR,details:r.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&&Ve(t,s,He))return s;const n=Ke(t,this.tracksInGroup,He);if(n>-1){const e=this.tracksInGroup[n];return this.setAudioTrack(n,"flushImmediate"in t&&t.flushImmediate),e}if(s){let s=e.loadLevel;-1===s&&(s=e.firstAutoLevel);const n=function(t,e,i,s,n){const r=e[s],a=e.reduce((t,e,i)=>{const s=e.uri;return(t[s]||(t[s]=[])).push(i),t},{})[r.uri];a.length>1&&(s=Math.max.apply(Math,a));const o=r.videoRange,l=r.frameRate,d=r.codecSet.substring(0,4),h=Ye(e,s,e=>{if(e.videoRange!==o||e.frameRate!==l||e.codecSet.substring(0,4)!==d)return!1;const s=e.audioGroups,r=i.filter(t=>ze(t.groupId,s));return Ke(t,r,n)>-1});return h>-1?h:Ye(e,s,e=>{const s=e.audioGroups,r=i.filter(t=>ze(t.groupId,s));return Ke(t,r,n)>-1})}(t,e.levels,i,s,He);if(-1===n)return null;e.nextLoadLevel=n}if(t.channels||t.audioCodec){const e=Ke(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,n=i[t],r=n.details&&!n.details.live;if(t===this.trackId&&n===s&&r)return;if(this.log(`Switching to audio-track ${t} "${n.name}" lang:${n.lang} group:${n.groupId} channels:${n.channels}`),this.trackId=t,this.currentTrack=n,this.hls.trigger(a.AUDIO_TRACK_SWITCHING,_(_({},n),{},{flushImmediate:e})),r)return;const o=this.switchParams(n.url,null==s?void 0:s.details,n.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||Ve(t,s,He)))return i}if(t){const{name:i,lang:s,assocLang:n,characteristics:r,audioCodec:a,channels:o}=t;for(let t=0;t<e.length;t++){if(Ve({name:i,lang:s,assocLang:n,characteristics:r,audioCodec:a,channels:o},e[t],He))return t}for(let i=0;i<e.length;i++){const s=e[i];if(ra(t.attrs,s.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return i}for(let i=0;i<e.length;i++){const s=e[i];if(ra(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,n=this.getUrlWithDirectives(t.url,e),r=t.details,o=null==r?void 0:r.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&&r.live?" age "+o.toFixed(1)+(r.type&&" "+r.type||""):""} ${n}`),this.hls.trigger(a.AUDIO_TRACK_LOADING,{url:n,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(_o)),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(ko)},this.onSeeking=()=>{this.initialized&&this.setPlayerState(Ro)},this.onSeeked=()=>{var t;this.initialized&&null!=(t=this.media)&&t.paused&&this.setPlayerState(ko)},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],d=this.getObjectType(a,l),h={d:1e3*(o||a).duration,ot:d};if(d===To||d===Eo||d===So||null==d&&("main"===a.type||"audio"===a.type)){var i;const t=l.bitrate/1e3;h.br=[t];const{cmcd:n}=this.config,r=null!=(i=null==n?void 0:n.rtpSafetyFactor)?i:5;if(h.rtp=100*Math.round(t*r/100),d===So||null==d&&"main"===a.type){const t=this.getTopBandwidth()/1e3;e(t)&&(h.tb=[t]);const i=this.getLowestBandwidth()/1e3;e(i)&&(h.lb=[i])}const o=this.getBufferLength(a);if(e(o)){var s;h.bl=[o];const t=(null==(s=this.media)?void 0:s.playbackRate)||1;h.dl=100*Math.round(o/t/100)}this.playheadLevel&&(h.pb=[this.playheadLevel.bitrate/1e3]);const c=this.hls.maxAutoLevel;if(c>=0){const t=this.hls.levels[c];t&&(h.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?h.nor=[(n=c.url,r={r:`${c.byteRange[0]}-${c.byteRange[1]}`},new oa(n,r))]:h.nor=[c.url]),this.apply(t,h)}catch(t){this.hls.logger.warn("Could not generate segment CMCD data.",t)}var n,r},this.recordFragmentResponse=(t,e,i)=>{var s;const{cmcd:n}=this.config,r=null==n||null==(s=n.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&&r)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?Co:Po,enabledKeys:null!=(t=i.includeKeys)?t:[...s>=Pa?vo:Ja],eventTargets:(null!=(e=i.eventTargets)?e:[]).map(t=>{let{includeKeys:e}=t;return _(_({},k(t,Vo)),{},{enabledKeys:null!=e?e:vo})})},i.loader),this.reporter.update({sf:Go,sta:this.playerState}),i.reporterCallback){const t=this.reporter,e={updateCustomData:e=>{Ho(e)&&t.update(e)},recordCustomEvent:(e,i={})=>{Ho(i)&&t.recordEvent(Na,_({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:xo),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(wo)}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(xo)}onError(t,e){e.fatal&&(this.setPlayerState(Do),this.reporter&&this.reporter.recordEvent(Oa,{ec:[e.details]}))}onLevelSwitching(t,e){var i;if(!this.reporter)return;const s={br:[e.bitrate/1e3]},n=null==(i=e.details)?void 0:i.fragments[0];n&&(s.ot=this.getObjectType(n,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?Ko:qo:jo}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 n=this.reporter.createRequestReport({url:t.url,headers:t.headers},e);t.url=n.url,t.headers=n.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,n=null==(e=this.hls.levels[s.level])||null==(e=e.details)?void 0:e.partList;if(n){const{sn:t}=s;for(let e=n.length-1;e>=0;e--){const s=n[e];if(s.index===i&&s.fragment.sn===t)return n[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,n=s>-1?s+1:i.levels.length;return i.levels.slice(0,n).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,n){e(t);const{onSuccess:r}=n;this.loader.load(t,s,_(_({},n),{},{onSuccess:(e,s,n,a)=>{r(e,s,n,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&di){const t=this.levels;let s=this._pathwayPriority,n=this.pathwayId;if(e.context){const{groupId:i,pathwayId:s,type:r}=e.context;i&&t?n=this.getPathwayForGroupId(i,r,n):s&&(n=s)}n in this.penalizedPathways||(this.penalizedPathways[n]=performance.now()),!s&&t&&(s=this.pathways()),s&&s.length>1&&(this.updatePathwayPriority(s),i.resolved=this.pathwayId!==n,i.resolved||e.details===r.BUFFER_APPEND_ERROR&&!e.fatal||this.warn(`Could not resolve ${e.details} ("${e.error.message}") with content-steering for Pathway: ${n} 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 n=t[s];if(n in i)continue;if(n===this.pathwayId)return;const r=this.hls.nextLoadLevel,o=this.hls.levels[r];if(e=this.getLevelsForPathway(n),e.length>0){this.log(`Setting Pathway to "${n}"`),this.pathwayId=n,hn(e),this.hls.trigger(a.LEVELS_UPDATED,{levels:e});const t=this.hls.levels[r];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=r);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:n,"BASE-ID":r,"URI-REPLACEMENT":a}=t;if(e.some(t=>t.pathwayId===n))return;const o=this.getLevelsForPathway(r).map(t=>{const e=new ls(t.attrs);e["PATHWAY-ID"]=n;const r=e.AUDIO&&`${e.AUDIO}_clone_${n}`,o=e.SUBTITLES&&`${e.SUBTITLES}_clone_${n}`;r&&(i[e.AUDIO]=r,e.AUDIO=r),o&&(s[e.SUBTITLES]=o,e.SUBTITLES=o);const l=Wo(t.uri,e["STABLE-VARIANT-ID"],"PER-VARIANT-URIS",a),d=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++)d.addGroupId("audio",`${t.audioGroups[e]}_clone_${n}`);if(t.subtitleGroups)for(let e=1;e<t.subtitleGroups.length;e++)d.addGroupId("text",`${t.subtitleGroups[e]}_clone_${n}`);return d});e.push(...o),Yo(this.audioTracks,i,a,n),Yo(this.subtitleTracks,s,a,n)})}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);we(s,"_HLS_pathway",this.pathwayId),we(s,"_HLS_throughput",""+t)}const n={type:u.STEERING_MANIFEST,responseType:"json",url:s.href},r=e.steeringManifestLoadPolicy.default,o=r.errorRetry||r.timeoutRetry||{},l={loadPolicy:r,timeout:r.maxLoadTimeMs,maxRetry:o.maxNumRetry||0,retryDelay:o.retryDelayMs||0,maxRetryDelay:o.maxRetryDelayMs||0},d={onSuccess:(t,e,i,n)=>{this.log(`Loaded steering manifest: "${s}"`);const r=t.data;if(1!==(null==r?void 0:r.VERSION))return void this.log(`Steering VERSION ${r.VERSION} not supported!`);this.updated=performance.now(),this.timeToLoad=r.TTL;const{"RELOAD-URI":o,"PATHWAY-CLONES":l,"PATHWAY-PRIORITY":d}=r;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 h={steeringManifest:r,url:s.toString()};this.hls.trigger(a.STEERING_MANIFEST_LOADED,h),d&&this.updatePathwayPriority(d)},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 n=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&&(n=1e3*parseFloat(e))}return void this.log(`Steering manifest ${e.url} rate limited`)}this.scheduleRefresh(this.uri||e.url,n)},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(n,l,d)}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=ql),super(t),this._url=e,this.streamController.setInitPts(i),this.streamController.initDetails=s}loadSource(){}loadMediaAt(t,e=Hl){if(t<0)return;const i=_(_({},Hl),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=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)}}}(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:n}=this;if(!n)return null;const{url:r,userConfig:o,latestLevelDetails:l,loadLevelObj:d,loadLevel:h,bandwidthEstimate:c,sessionId:u}=n,{stats:f,variableList:g}=this;if(null==e||!e.length||!f||!r)return null;const p=`${s||""}iframe-player-${this.instanceCounter++}`,m=n.levels,v=d||m[h],y=Xe(v,o.videoPreference),E=(null==v?void 0:v.pathwayId)||".",T=new t(_(_({},o),{},{loggerId:p,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),r,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:r,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 n;const e=this.findItemIndex(s);let r=this.schedule.findItemIndexAtTime(t);if(-1===r&&(r=e+(i?-1:1),this.log(`seeked ${i?"back ":""}to position not covered by schedule ${t} (resolving from ${e} to ${r})`)),!this.isInterstitial(s)&&null!=(n=this.media)&&n.paused&&(this.shouldPlay=!1),!i&&r>e){const t=this.schedule.findJumpRestrictedIndex(e+1,r);if(t>e)return void this.setSchedulePosition(t)}return void this.setSchedulePosition(r)}const r=this.playingAsset;if(!r){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=r.timelineStart,o=r.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,r))},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,n=i.events||[],r=i.items||[],o=i.durations,l=t.map(t=>t.identifier),d=!(!n.length&&!l.length);(d||e)&&this.log(`INTERSTITIALS_UPDATED (${n.length}): ${n}\nSchedule: ${r.map(t=>od(t))} pos: ${this.timelinePos}`),l.length&&this.log(`Removed events ${l}`);let h=null,c=null;s&&(h=this.updateItem(s,this.timelinePos),this.itemsMatch(s,h)?this.playingItem=h:this.waitingItem=null);const u=this.waitingItem;u&&(this.waitingItem=this.updateItem(u),this.waitingItem||s||(this.log(`INTERSTITIAL_ENDED unresolved ${od(u)}`),this.hls.trigger(a.INTERSTITIAL_ENDED,{event:u.event,schedule:r.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})`)}}}),d||e){if(this.hls.trigger(a.INTERSTITIALS_UPDATED,{events:n.slice(0),schedule:r.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(h,s),f&&c!==h&&this.trimInPlace(c,f),this.checkBuffer()}},this.hls=t,this.HlsPlayerClass=e,this.assetListLoader=new ld(t),this.schedule=new ad(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,r,a,o)=>{if(e){let l=e[s].start;const d=e.event;if(d){if("playout"===s||d.timelineOccupancy!==Xl.Point){const t=i(r);(null==t?void 0:t.interstitial)===d&&(l+=t.assetItem.startOffset+t[o])}}else{l+=("bufferedPos"===a?n():t[a])-e.start}return l}return 0},n=()=>{const e=t.bufferedPos;return e===Number.MAX_VALUE?r("primary"):Math.max(e,0)},r=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,n)=>{var r,a;const o=t.effectivePlayingItem;if(null!=o&&null!=(r=o.event)&&r.restrictions.skip||!t.schedule)return;t.log(`seek to ${e} "${n}"`);const l=t.effectivePlayingItem,d=t.schedule.findItemIndexAtTime(e,n),h=null==(a=t.schedule.items)?void 0:a[d],c=t.getBufferingPlayer(),u=null==c?void 0:c.interstitial,f=null==u?void 0:u.appendInPlace,g=l&&t.itemsMatch(l,h);if(l&&(f||g)){const r=i(t.playingAsset),a=(null==r?void 0:r.media)||t.primaryMedia;if(a){const i="primary"===n?a.currentTime:s(l,n,t.playingAsset,"timelinePos","currentTime"),o=e-i,d=(f?i:a.currentTime)+o;if(d>=0&&(!r||f||d<=r.duration))return void(a.currentTime=d)}}if(h){let i=e;if("primary"!==n){const t=e-h[n].start;i=h.start+t}const s=!t.isInterstitial(h);if(t.isInterstitial(l)&&!l.event.appendInPlace||!s&&!h.event.appendInPlace){if(l){const r=t.findItemIndex(l);if(d>r){const e=t.schedule.findJumpRestrictedIndex(r+1,d);if(e>r)return void t.setSchedulePosition(e)}let a=0;if(s)t.timelinePos=i,t.checkBuffer();else{const t=h.event.assetList,i=e-(h[n]||h).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(d,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(),n=t.bufferingItem;var r;return n&&n===i&&(s(n,"playout",t.bufferingAsset,"bufferedPos","bufferedEnd")-n.playout.start||(null==(r=t.bufferingAsset)?void 0:r.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 n()},get currentTime(){const e=t.timelinePos;return e>0?e:0},set currentTime(t){a(t,"primary")},get duration(){return r("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 r("integrated")},get seekableStart(){return((e,i)=>{var s;if(0!==e&&"primary"!==i&&null!=(s=t.schedule)&&s.length){var n;const s=t.schedule.findItemIndexAtTime(e),r=null==(n=t.schedule.items)?void 0:n[s];if(r)return e+(r[i].start-r.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 n=this.media;!n&&null!=(t=this.bufferingItem)&&null!=(t=t.event)&&t.appendInPlace&&(n=this.primaryMedia);const r=null==(i=n)?void 0:i.currentTime;return void 0!==r&&e(r)?r: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 n=null;const r=this.hls,a=t!==r,o=a&&t.interstitial.appendInPlace,l=null==(i=this.detachedData)?void 0:i.mediaSource;let d;if(r.media)o&&(n=r.transferMedia(),this.detachedData=n),d="Primary";else{const t=this.getBufferingPlayer();t?(n=t.transferMedia(),this.detachedData=n,d=`${t}`):d=l?"detached MediaSource":"detached media"}if(!n)if(l)n=this.detachedData,this.log(`using detachedData: MediaSource ${Ue(n)}`);else if(!this.detachedData||r.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 h=n&&"mediaSource"in n&&"closed"!==(null==(s=n.mediaSource)?void 0:s.readyState);if(this.log(`${h?"transfering MediaSource":"attaching media"} to ${a?t:"Primary"} from ${d} (media.currentTime: ${e.currentTime})`),!h&&!a)return void t.attachMedia(e);const c=h&&n?_({},n):{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(!h&&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,n=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(hd("checkStart (preroll)",s));const i=t.findEventIndex(e[0].identifier);this.setSchedulePosition(i)}else if(s>=0||!this.primaryLive){this.log(hd("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(n&&!this.playingItem){this.log(hd("checkStart (playing item)",n.start));const e=t.findItemIndex(n);this.setSchedulePosition(e)}}advanceAssetBuffering(t,e){const i=t.event,s=i.findAssetIndex(e),n=id(i,s);if(i.isAssetPastPlayoutLimit(n)){if(this.schedule){var r;const e=this.getNextItemIndex(t,!0),i=null==(r=this.schedule.items)?void 0:r[e];i&&this.bufferedToItem(i)}}else this.bufferedToEvent(t,n)}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=id(t,i);if(t.isAssetPastPlayoutLimit(s)){if(this.schedule){const i=this.schedule.items;if(i){const s=i[e],n=s.event?this.getNextItemIndex(s):e+1;if(n>=i.length)return void this.setSchedulePosition(-1);const r=t.resumeTime;this.timelinePos<r&&(this.log(hd("advanceAfterAssetEnded",r)),this.timelinePos=r,t.appendInPlace&&!i[n].event&&this.hls.startLoad(r+.01),this.checkBuffer(this.bufferedPos<r)),this.setSchedulePosition(n)}}}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,n=i.getEvent(s);if(n){const e=i.findEventIndex(s),r=i.findAssetIndex(n,t);this.advanceAfterAssetEnded(n,e,r-1)}}setSchedulePosition(t,e){var i;const s=null==(i=this.schedule)?void 0:i.items;if(!s||this.playbackDisabled)return;const n=t>=0?s[t]:null;this.log(`setSchedulePosition ${t}, ${e} (${n?od(n):n}) pos: ${this.timelinePos}`);const r=this.waitingItem||this.playingItem,o=this.playingLastItem;if(this.isInterstitial(r)){const i=r.event,c=this.playingAsset,u=null==c?void 0:c.identifier,f=u?this.getAssetPlayer(u):null;if(f&&u&&(!this.eventItemsMatch(r,n)||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} ${sd(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}),r!==this.playingItem)return void(this.itemsMatch(r,this.playingItem)&&!this.playingAsset&&this.advanceAfterAssetEnded(i,this.findItemIndex(this.playingItem),e));this.retreiveMediaSource(u,n),!f.media||null!=(l=this.detachedData)&&l.mediaSource||f.detachMedia()}if(!this.eventItemsMatch(r,n)&&(this.endedItem=r,this.playingItem=this.waitingItem=null,this.log(`INTERSTITIAL_ENDED ${i} ${od(r)}`),i.hasPlayed=!0,this.hls.trigger(a.INTERSTITIAL_ENDED,{event:i,schedule:s.slice(0),scheduleIndex:t}),i.cue.once&&this.hls)){var d;this.updateSchedule();const t=null==(d=this.schedule)?void 0:d.items;if(n&&t){const a=this.findItemIndex(n),l=this.livePrerollResumption(i);if(void 0!==l){let e=l;const n=this.getNextItemIndex(r);if(!this.isInterstitial(s[n])){var h;const t=null==(h=this.primaryDetails)?void 0:h.fragments;if(i.snapOptions.in&&t){const i=Ze(null,t,l);i&&(e=Math.min(Math.max(s[n].start,Zl(e,i)),s[n].end))}}if(this.log(hd("live join (preroll)",e)),this.timelinePos=e,n!==a&&(n||0===n))return void this.advanceSchedule(n,t,void 0,r,o)}this.advanceSchedule(a,t,e,r,o)}return}}this.advanceSchedule(t,s,e,r,o)}advanceSchedule(t,e,i,s,n){const r=this.schedule;if(!r)return;const o=e[t]||null,l=this.primaryMedia,d=this.playerQueue;if(d.length&&d.forEach(e=>{const i=e.interstitial,s=r.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 n=o.event;if(void 0===i){const e=id(n,(i=n.cue.pre?0:r.findAssetIndex(n,this.timelinePos))-1);if(n.isAssetPastPlayoutLimit(e)||n.appendInPlace&&this.timelinePos===o.end)return void this.advanceAfterAssetEnded(n,t,i);i=e}const d=this.waitingItem;this.assetsBuffered(o,l)||this.setBufferingItem(o);let h=this.preloadAssets(n,i);if(this.eventItemsMatch(o,d||s)||(this.waitingItem=o,this.log(`INTERSTITIAL_STARTED ${od(o)} ${n.appendInPlace?"append in place":""}`),n.hasPlayed=!1,this.hls.trigger(a.INTERSTITIAL_STARTED,{event:n,schedule:e.slice(0),scheduleIndex:t})),!n.assetListLoaded)return void this.log(`Waiting for ASSET-LIST to complete loading ${n}`);if(n.assetListLoader&&(n.assetListLoader.destroy(),n.assetListLoader=void 0),!l)return void this.log(`Waiting for attachMedia to start Interstitial ${n}`);this.waitingItem=this.endedItem=null,this.playingItem=o;const c=n.assetList[i];if(!c)return void this.advanceAfterAssetEnded(n,t,i||0);if(h||(h=this.getAssetPlayer(c.identifier)),null===h||h.destroyed){const t=n.assetList.length;this.warn(`asset ${i+1}/${t} player destroyed ${n}`),h=this.createAssetPlayer(n,c,i),h.loadSource()}if(!this.eventItemsMatch(o,this.bufferingItem)&&n.appendInPlace&&this.isAssetBuffered(c))return;this.startAssetPlayer(h,i,e,t,l),this.shouldPlay&&dd(h.media)}else o?(this.resumePrimary(o,t,s),this.shouldPlay&&dd(this.hls.media)):n&&this.isInterstitial(s)&&(this.endedItem=null,this.playingItem=s,s.event.appendInPlace||this.attachPrimary(r.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,n;this.playingItem=t,this.playingAsset=this.endedAsset=null,this.waitingItem=null,this.bufferedToItem(t),this.endedItem=null,this.log(`resuming ${od(t)}`);let r=this.timelinePos;if(null!=(s=this.detachedData)&&s.mediaSource?this.primaryLive&&this.startLoadingPrimaryAt(r):((r<t.start||r>=t.end||r<this.seekableStart)&&(r=this.getPrimaryResumption(t,e),this.log(hd("resumePrimary",r)),this.timelinePos=r),this.attachPrimary(r,t)),!i)return;const o=null==(n=this.schedule)?void 0:n.items;o&&(this.log(`INTERSTITIALS_PRIMARY_RESUMED ${od(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,n=null!=t&&t.event?this.livePrerollResumption(t.event,i):void 0;if(void 0!==n)return n;const r=this.primaryDetails;if(r){const{fragmentStart:t,edge:e}=r;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 n=this.hls;n.media?this.checkBuffer():(this.transferMediaTo(n,s),i&&this.startLoadingPrimaryAt(t,i)),i||(this.log(hd("attachPrimary",t)),this.timelinePos=t,this.startLoadingPrimaryAt(t,i))}startLoadingPrimaryAt(t,e){const i=this.hls,{loadingEnabled:s,bufferingEnabled:n,startPosition:r}=i,a=i.hasEnoughToStart;if(this.log(`Start loading primary @${t} bufferedPos: ${this.bufferedPos} startPosition: ${r} skip seek: ${e} has enough ${a} loadingEnabled: ${s} bufferingEnabled: ${n}`),!e&&a||!s||Math.abs(r-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?od(e):null}`),i.pauseBuffering(),void(this.bufferPastEdge=!0)}i.startLoad(t,e)}else n||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=_(_({},this.mediaSelection||this.altSelection),{},{main:i});this.mediaSelection=s;const n=this.hls.startPosition;this.schedule.parseInterstitialDateRanges(s,this.hls.config.interstitialAppendInPlace,-1===n?0:n);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?od(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=_(_({},this.altSelection),{},{audio:i}));const n=_(_({},s),{},{audio:i});this.mediaSelection=n}onSubtitleTrackUpdated(t,e){const i=this.hls.subtitleTracks[e.id],s=this.mediaSelection;if(!s)return void(this.altSelection=_(_({},this.altSelection),{},{subtitles:i}));const n=_(_({},s),{},{subtitles:i});this.mediaSelection=n}onAudioTrackSwitching(t,e){const i=qe(e);this.playerQueue.forEach(({hls:t})=>t&&(t.setAudioOption(e)||t.setAudioOption(i)))}onSubtitleTrackSwitch(t,e){const i=qe(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 ${od(t)} (was ${od(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 n=(null==(e=this.hls)?void 0:e.liveSyncPosition)||0;null==(i=this.schedule)||i.updateSchedule(s,[],n,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,n=this.bufferingItem;if(this.bufferedPos>t||!s)return;if(1===e.length&&this.itemsMatch(e[0],n))return void(this.bufferedPos=t);const r=this.playingItem,a=this.findItemIndex(r);let o=s.findItemIndexAtTime(t);if(this.bufferedPos<t){var l;const i=this.findItemIndex(n),s=Math.min(i+1,e.length-1),r=e[s];if((-1===o&&n&&t>=n.end||null!=(l=r.event)&&l.appendInPlace&&t+.01>=r.start)&&(o=s),this.isInterstitial(n)){const t=n.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(r);else{const e=this.primaryDetails;this.primaryLive&&e&&t>e.edge-e.targetduration&&r.start<e.edge+this.hls.config.interstitialLiveLookAhead&&this.isInterstitial(r)&&this.preloadAssets(r.event,0)}}else i&&r&&!this.itemsMatch(r,n)&&(o===a?this.bufferedToItem(r):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:n}=i;if(!s||!n)return e;const r=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 ${od(t)}`+(e?` (${l.toFixed(2)} remaining)`:"")),!this.playbackDisabled)if(r){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:n.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,n=i.cue.once;if(s||!n){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,n=0===s&&!t.assetListLoader,r=t.cue.once;if(n){const n=t.timelineStart,r=this.playingItem,o=this.getBufferingPlayer();var a;if(t.appendInPlace)this.isInterstitial(r)||(null==r||null==(a=r.nextEvent)?void 0:a.identifier)!==t.identifier||this.flushFrontBuffer(n+.25);let l,d=0;if(o&&!o.interstitial.cue.pre||!this.primaryLive||(d=this.getLiveStartPos(),o&&(d+=o.remaining)),d&&!t.cue.pre&&!t.cue.post){const t=d-n;t>0&&(l=Math.round(1e3*t)/1e3)}if(this.log(`Load interstitial asset ${e+1}/${i?1:s} ${t}${d?` live-start: ${d} start-offset: ${l} (timeline-start: ${n})`:""}`),i)return this.createAsset(t,0,0,n,t.duration,i);const h=this.assetListLoader.loadAssetList(t,l);h&&(t.assetListLoader=h)}else if(!r&&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,n,r){const a={parentIdentifier:t.identifier,identifier:Ql(t,r,e),duration:n,startOffset:i,timelineStart:s,uri:r};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),d=s.audioTracks[s.audioTrack],h=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=_(_({},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:d||o.audioPreference,subtitlePreference:h||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:hl(e.uri)})),this.getAssetPlayer(u)&&this.warn(`Duplicate date range identifier ${t} and asset ${u}`);const p=new nd(this.HlsPlayerClass,f,t,e);this.playerQueue.push(p),t.assetList[i]=e;let m=!0;const v=s=>{if(s.live){const e=new Error(`Interstitials MUST be VOD assets ${t}`),s={fatal:!0,type:n.OTHER_ERROR,details:r.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;(m||null===o||a>o)&&(m=!1,this.log(`Interstitial asset "${u}" duration change ${o} > ${a}`),e.duration=a,this.updateSchedule())};p.on(a.LEVEL_UPDATED,(t,{details:e})=>v(e)),p.on(a.LEVEL_PTS_UPDATED,(t,{details:e})=>v(e)),p.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)}};p.on(a.BUFFER_CODECS,y);p.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 p.once(a.MEDIA_ENDED,E(i)),p.once(a.PLAYOUT_LIMIT_REACHED,E(1/0)),p.on(a.ERROR,(e,s)=>{if(!this.schedule)return;const n=this.getAssetPlayer(u);if(s.details===r.BUFFER_STALLED_ERROR)return null!=n&&n.appendInPlace?void this.handleInPlaceStall(t):(this.onTimeupdate(),void this.checkBuffer(!0));s.details!==r.BUFFER_SEEK_OVER_HOLE&&this.handleAssetItemError(s,t,this.findEventIndex(t.identifier),i,`Asset player error ${s.error} ${t}`)}),p.on(a.DESTROYING,()=>{if(!this.getAssetPlayer(u)||!this.schedule)return;const e=new Error(`Asset player destroyed unexpectedly ${u}`),s={fatal:!0,type:n.OTHER_ERROR,details:r.INTERSTITIAL_ASSET_ITEM_ERROR,error:e};this.handleAssetItemError(s,t,this.findEventIndex(t.identifier),i,e.message)}),this.log(`INTERSTITIAL_ASSET_PLAYER_CREATED ${sd(e)}`),this.hls.trigger(a.INTERSTITIAL_ASSET_PLAYER_CREATED,{asset:e,assetListIndex:i,event:t,player:p}),p}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?od(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,n){const{interstitial:r,assetItem:o,assetId:l}=t,d=r.assetList.length,h=this.playingAsset;this.endedAsset=null,this.playingAsset=o,(null==h?void 0:h.identifier)!==l&&(h&&(this.clearAssetPlayer(h.identifier,i[s]),delete h.error),this.log(`INTERSTITIAL_ASSET_STARTED ${e+1}/${d} ${sd(o)}`),this.hls.trigger(a.INTERSTITIAL_ASSET_STARTED,{asset:o,assetListIndex:e,event:r,schedule:i.slice(0),scheduleIndex:s,player:t})),this.bufferAssetPlayer(t,n)}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 d=s.appendInPlace;if(d&&!1===(null==l?void 0:l.interstitial.appendInPlace))return;const h=(null==l?void 0:l.tracks)||(null==(i=this.detachedData)?void 0:i.tracks)||this.requiredTracks;if(d&&a!==this.playingAsset){if(!t.tracks)return void this.log(`Waiting for track info before buffering ${t}`);if(h&&!W(h,t.tracks)){const e=new Error(`Asset ${sd(a)} SourceBuffer tracks ('${Object.keys(t.tracks)}') are not compatible with primary content tracks ('${Object.keys(h)}')`),i={fatal:!0,type:n.OTHER_ERROR,details:r.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,n=e.findAssetIndex(t,s),r=t.assetList[n];if(r){const a=this.getAssetPlayer(r.identifier);if(a){const o=a.currentTime||s-r.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,n)}}}}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,n){if(t.details===r.BUFFER_STALLED_ERROR)return;const o=e.assetList[s]||null;if(this.warn(`INTERSTITIAL_ASSET_ERROR ${o?sd(o):o} ${t.error}`),!this.schedule)return;const l=(null==o?void 0:o.identifier)||"",d=this.getAssetPlayerQueueIndex(l),h=this.playerQueue[d]||null,c=this.schedule.items,u=I({},t,{fatal:!1,errorAction:mi(!0),asset:o,assetListIndex:s,event:e,schedule:c,scheduleIndex:i,player:h});if(this.hls.trigger(a.INTERSTITIAL_ASSET_ERROR,u),!t.fatal)return;const f=this.playingAsset,g=this.bufferingAsset,p=new Error(n);if(o&&(this.clearAssetPlayer(l,null),o.error=p),e.assetList.some(t=>!t.error))for(let t=s;t<e.assetList.length;t++)this.resetAssetPlayer(e.assetList[t].identifier);else e.error=p;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,n=this.seekableStart,r=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: ${od(i)} startPosition: ${r} seekableStart: ${n} error: ${t.error}`),-1===a&&(a=r),a=Math.max(a,n);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 n=e.event,r=n.identifier,a=e.assetListResponse.ASSETS;if(null==(i=this.schedule)||!i.hasEvent(r))return;const o=n.timelineStart,l=n.duration;let d=0;a.forEach((t,e)=>{const i=parseFloat(t.DURATION);this.createAsset(n,e,d,o+d,i,t.URI),d+=i}),n.duration=d,this.log(`Loaded asset-list with duration: ${d} (was: ${l}) ${n}`);const h=this.waitingItem,c=(null==h?void 0:h.event.identifier)===r;this.updateSchedule();const u=null==(s=this.bufferingItem)?void 0:s.event;if(c){const t=this.findEventIndex(r),e=this.getEventItem(r);if(e){if(!this.playingItem&&this.timelinePos>e.end){if(this.schedule.findItemIndexAtTime(this.timelinePos)!==t)return n.error=new Error(`Interstitial ${a.length?"no longer within playback range":"asset-list is empty"} ${this.timelinePos} ${n}`),this.log(n.error.message),this.updateSchedule(!0),void this.primaryFallback(n)}this.setBufferingItem(e)}this.setSchedulePosition(t)}else if((null==u?void 0:u.identifier)===r){const t=n.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 r.ASSET_LIST_PARSING_ERROR:case r.ASSET_LIST_LOAD_ERROR:case r.ASSET_LIST_LOAD_TIMEOUT:{const t=e.interstitial;t&&(this.updateSchedule(!0),this.primaryFallback(t));break}case r.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 Kd(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=Vd(t),n=["TimeOut","MaxRetry","RetryDelay","MaxRetryTimeout"];return["manifest","level","frag"].forEach(t=>{const r=`${"level"===t?"playlist":t}LoadPolicy`,a=void 0===e[r],o=[];n.forEach(i=>{const n=`${t}Loading${i}`,l=e[n];if(void 0!==l&&a){o.push(n);const t=s[r].default;switch(e[r]={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 "${r}": ${Ue(e[r])}`)}),_(_({},s),e)}function Vd(t){return t&&"object"==typeof t?Array.isArray(t)?t.map(Vd):Object.keys(t).reduce((e,i)=>(e[i]=Vd(t[i]),e),{}):t}function Hd(t,e){const i=t.loader;if(i!==$d&&i!==jd)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=$d,t.progressive=!0,t.enableSoftwareAES=!0,e.log("[config]: Progressive streaming enabled, using FetchLoader"))}}class Yd 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=[],n={},r={};let a=!1,o=!1,l=!1,d=!1;e.levels.forEach(t=>{const e=t.attrs,h=Xd(t,i),{audioCodec:c,videoCodec:u,imageCodec:f,width:g,height:p}=t;if(!h)return void this.log(`Some or all CODECS not supported "${e.CODECS}"`);a||(a=!(!g||!p)),o||(o=!!u),l||(l=!!c),d||(d=!!f);const{CODECS:m,"FRAME-RATE":v,"HDCP-LEVEL":y,"PATHWAY-ID":E,RESOLUTION:T,"VIDEO-RANGE":S}=e,b=`${`${E||"."}-`}${t.bitrate}-${T}-${v}-${m}-${S}-${y}`;if(n[b])if(n[b].uri===t.url||t.attrs["PATHWAY-ID"])t.iframes||(n[b].addGroupId("audio",e.AUDIO),n[b].addGroupId("text",e.SUBTITLES));else{const e=r[b]+=1;t.attrs["PATHWAY-ID"]=new Array(e+1).join(".");const i=this.createLevel(t);n[b]=i,s.push(i)}else{const e=this.createLevel(t);n[b]=e,r[b]=1,s.push(e)}}),this.filterAndSortMediaOptions(s,e,a,o,l,d)}createLevel(t){const e=new Ne(t),i=t.supplemental;if(null!=i&&i.videoCodec&&!zd(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 d;let h=[],c=[],u=t;const f=(null==(d=e.stats)?void 0:d.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))&&(!!(n=e)&&xe.indexOf(n)>-1);var n})),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:n.MEDIA_ERROR,details:r.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:e.url,error:s,reason:i})}}),void(f.end=performance.now());e.audioTracks&&(h=e.audioTracks.filter(t=>!t.audioCodec||Wd(t.audioCodec,g)),Qd(h)),e.subtitles&&(c=e.subtitles,Qd(c));const p=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 xe.indexOf(t.videoRange)-xe.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 m=p[0];if(this.steering&&(u=this.steering.filterParsedLevels(u),u.length!==p.length))for(let t=0;t<p.length;t++)if(p[t].pathwayId===u[0].pathwayId){m=p[t];break}this._levels=u;for(let t=0;t<u.length;t++)if(u[t]===m){var v;this._firstLevel=t;const e=m.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=>Xd(t,g));this._iframeVariants=y;const E=o&&!s,T=this.hls.config,S=!(!T.audioStreamController||!T.audioTrackController),b={levels:u,audioTracks:h,subtitleTracks:c,iframeVariants:y,sessionData:e.sessionData,sessionKeys:e.sessionKeys,firstLevel:this._firstLevel,stats:e.stats,audio:o,video:s,altAudio:S&&!E&&h.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:n.OTHER_ERROR,details:r.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],d=l.attrs["PATHWAY-ID"];if(this.currentLevelIndex=t,this.currentLevel=l,i===t&&s&&o===d)return;this.log(`Switching to level ${t} (${l.height?l.height+"p ":""}${l.videoRange?l.videoRange+" ":""}${l.codecSet?l.codecSet+" ":""}@${l.bitrate})${d?" with Pathway "+d:""} from level ${i}${o?" with Pathway "+o:""}`);const h={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,h);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:n}=e,r=e.levelInfo;var a;if(!r)return this.warn(`Invalid level index ${s}`),void(null!=(a=e.deliveryDirectives)&&a.skip&&(n.deltaUpdateFailed=!0));if(r===this.currentLevel||e.withoutMultiVariant){0===r.fragmentError&&(r.loadError=0);let t=r.details;t===e.details&&t.advanced&&(t=void 0),this.playlistLoaded(s,e,t)}else null!=(i=e.deliveryDirectives)&&i.skip&&(n.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,n=t.attrs["PATHWAY-ID"],r=t.details,o=null==r?void 0:r.age;this.log(`Loading level index ${s}${void 0!==(null==e?void 0:e.msn)?" at sn "+e.msn+" part "+e.part:""}${n?" Pathway "+n:""}${o&&r.live?" age "+o.toFixed(1)+(r.type&&" "+r.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(),n=s-this.lastABRSwitchTime,r=1e3*i;if(this.lastABRSwitchTime>-1&&n<r)return void this.warn(`Preventing ABR level switch: ${e} -> ${t} (${Math.round(n)}ms < ${r}ms / ${i}s)`);this.lastABRSwitchTime=s,this.log(`Allowing ABR level switch: ${e} -> ${t} (${Math.round(n)}ms >= ${r}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));hn(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 Wd(t,e){return de(t,"audio",e)}function zd(t,e){return de(t,"video",e)}function Xd(t,e){let{audioCodec:i,videoCodec:s}=t;i&&(t.audioCodec=i=me(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:n}=t;return!((null==n?void 0:n.length)||0||i&&!Wd(i,e)||s&&!zd(s,e))}function Qd(t){const e={};t.forEach(t=>{const i=t.groupId||"";t.id=e[i]=e[i]||0,e[i]++})}class Jd 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(Zd(t,r.KEY_LOAD_ERROR,e))}const n=t;switch(s.method){case"SAMPLE-AES":case"SAMPLE-AES-CENC":case"SAMPLE-AES-CTR":return"identity"===s.keyFormat?this.loadKeyHTTP(n):e?e.then(()=>this.loadKeyEME(n)):this.loadKeyEME(n);case"AES-128":case"AES-256":case"AES-256-CTR":return this.loadKeyHTTP(n);default:return Promise.reject(Zd(t,r.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 ${pt(i)} keyUri: ${s}`),Cs.setKeyIdForUri(s,i);else{const t=Cs.addKeyIdForUri(s);this.log(`Patching empty keyId with ${pt(t)} keyUri: ${s}`),i=t}t.decryptdata.keyId=i}}return this.emeController.loadKey(t).then(()=>({frag:t,keyInfo:{decryptdata:t.decryptdata}}))}return Promise.reject(Zd(t,r.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(Zd(t,r.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,_(_({},i),{},{frag:t})))}this.log(`Loading${e.keyId?" keyId: "+pt(e.keyId):""} URI: ${e.uri} from ${t.type} ${t.level}`);const n=this.config,a=new(0,n.loader)(n);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},d=n.keyLoadPolicy.default,h={loadPolicy:d,timeout:d.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},c={onSuccess:(t,i,n,a)=>{const{frag:o,keyInfo:l,url:d}=n;if(!o.decryptdata||l!==this.keyLoaderInfo[d])return this.resetLoader(n),s(Zd(o,r.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,n,a,o)=>{this.resetLoader(n),s(Zd(t,r.KEY_LOAD_ERROR,new Error(`HTTP Error ${e.code} loading key ${e.text}`),a,_({url:i,data:void 0},e)))},onTimeout:(e,i,n)=>{this.resetLoader(i),s(Zd(t,r.KEY_LOAD_TIMEOUT,new Error("key loading timed out"),n))},onAbort:(e,i,n)=>{this.resetLoader(i),s(Zd(t,r.INTERNAL_ABORTED,new Error("key loading aborted"),n))}};a.load(l,h,c)})}resetLoader(t){const{frag:e,keyInfo:i,url:s}=t,n=i.loader;e.keyLoader===n&&(e.keyLoader=i.loader=i.keyLoadPromise=null),delete this.keyLoaderInfo[s],n&&n.destroy()}}function Zd(t,e=r.KEY_LOAD_ERROR,i,s,a){return new Ji({type:n.NETWORK_ERROR,details:e,fatal:!1,frag:t,response:a,error:i,networkDetails:s||null})}function th(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 eh(t,e){let i=t.url;return void 0!==i&&0!==i.indexOf("data:")||(i=e.url),i}class ih{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,n=new(i||s)(e);return this.loaders[t.type]=n,n}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:n,url:r,deliveryDirectives:a,levelInfo:o}=e;this.load({id:i,level:s,pathwayId:n,responseType:"text",type:u.LEVEL,url:r,deliveryDirectives:a,levelOrTrack:o})}onAudioTrackLoading(t,e){const{id:i,groupId:s,url:n,deliveryDirectives:r,track:a}=e;this.load({id:i,groupId:s,level:null,responseType:"text",type:u.AUDIO_TRACK,url:n,deliveryDirectives:r,levelOrTrack:a})}onSubtitleTrackLoading(t,e){const{id:i,groupId:s,url:n,deliveryDirectives:r,track:a}=e;this.load({id:i,groupId:s,level:null,responseType:"text",type:u.SUBTITLE_TRACK,url:n,deliveryDirectives:r,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 n,r=this.getInternalLoader(t);if(r){const e=this.hls.logger,i=r.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}`),r.abort()}if(n=t.type===u.MANIFEST?s.manifestLoadPolicy.default:I({},s.playlistLoadPolicy.default,{timeoutRetry:null,errorRetry:null}),r=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);n=I({},n,{maxTimeToFirstByteMs:Math.min(e,n.maxTimeToFirstByteMs),maxLoadTimeMs:Math.min(e,n.maxTimeToFirstByteMs)})}}}const a=n.errorRetry||n.timeoutRetry||{},o={loadPolicy:n,timeout:n.maxLoadTimeMs,maxRetry:a.maxNumRetry||0,retryDelay:a.retryDelayMs||0,maxRetryDelay:a.maxRetryDelayMs||0},l={onSuccess:(t,e,i,s)=>{const n=this.getInternalLoader(i);this.resetInternalLoader(i.type);const r=t.data;e.parsing.start=performance.now(),Us.isMediaPlaylist(r)||i.type!==u.MANIFEST?this.handleTrackOrLevelPlaylist(t,e,i,s||null,n):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)}};r.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 n=this.hls,r=t.data,o=eh(t,i),l=Us.parseMasterPlaylist(r,o);if(l.playlistParsingError)return e.parsing.end=performance.now(),void this.handleManifestParsingError(t,i,l.playlistParsingError,s,e);const{contentSteering:d,levels:h,iframeVariants:c,sessionData:u,sessionKeys:f,startTimeOffset:g,variableList:p}=l;this.variableList=p,h.forEach(t=>{const{unknownCodecs:e}=t;if(e){const{preferManagedMediaSource:i}=this.hls.config;let{audioCodec:s,videoCodec:n}=t;for(let r=e.length;r--;){const a=e[r];de(a,"audio",i)?(t.audioCodec=s=s?`${s},${a}`:a,oe.audio[s.substring(0,4)]=2,e.splice(r,1)):de(a,"video",i)&&(t.videoCodec=n=n?`${n},${a}`:a,oe.video[n.substring(0,4)]=2,e.splice(r,1))}}});const{AUDIO:m=[],SUBTITLES:v,"CLOSED-CAPTIONS":y}=Us.parseMasterPlaylistMedia(r,o,l);if(m.length){m.some(t=>!t.url)||!h[0].audioCodec||h[0].attrs.AUDIO||(this.hls.logger.log("[playlist-loader]: audio codec signaled in quality level, but no embedded audio track signaled, create one"),m.unshift({type:"main",name:"main",groupId:"main",default:!1,autoselect:!1,forced:!1,id:-1,attrs:new ls({}),bitrate:0,url:""}))}n.trigger(a.MANIFEST_LOADED,{levels:h,audioTracks:m,subtitles:v,iframeVariants:c,captions:y,contentSteering:d,url:o,stats:e,networkDetails:s,sessionData:u,sessionKeys:f,startTimeOffset:g,variableList:p})}handleTrackOrLevelPlaylist(t,i,s,n,r){const o=this.hls,{id:l,level:d,type:h}=s,c=eh(t,s),f=e(d)?d:e(l)?l:0,g=th(s),p=Us.parseLevelPlaylist(t.data,c,f,g,0,this.variableList);if(h===u.MANIFEST){const t={attrs:new ls({}),bitrate:0,details:p,name:"",url:c};p.requestScheduled=i.loading.start+an(p,0),o.trigger(a.MANIFEST_LOADED,{levels:[t],audioTracks:[],iframeVariants:[],url:c,stats:i,networkDetails:n,sessionData:null,sessionKeys:null,contentSteering:null,startTimeOffset:null,variableList:null})}i.parsing.end=performance.now(),s.levelDetails=p,this.handlePlaylistLoaded(p,t,i,s,n,r)}handleManifestParsingError(t,e,i,s,o){this.hls.trigger(a.ERROR,{type:n.NETWORK_ERROR,details:r.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 d=new Error(l);this.hls.logger.warn(`[playlist-loader]: ${l}`);let h=r.UNKNOWN,c=!1;const f=this.getInternalLoader(t);switch(t.type){case u.MANIFEST:h=i?r.MANIFEST_LOAD_TIMEOUT:r.MANIFEST_LOAD_ERROR,c=!0;break;case u.LEVEL:h=i?r.LEVEL_LOAD_TIMEOUT:r.LEVEL_LOAD_ERROR,c=!1;break;case u.AUDIO_TRACK:h=i?r.AUDIO_TRACK_LOAD_TIMEOUT:r.AUDIO_TRACK_LOAD_ERROR,c=!1;break;case u.SUBTITLE_TRACK:h=i?r.SUBTITLE_TRACK_LOAD_TIMEOUT:r.SUBTITLE_LOAD_ERROR,c=!1}f&&this.resetInternalLoader(t.type);const g={type:n.NETWORK_ERROR,details:h,fatal:c,url:t.url,loader:f,context:t,error:d,networkDetails:e,stats:o};if(s){let i=t.url;e&&"url"in e&&(i=e.url),g.response=_({url:i,data:void 0},s)}this.hls.trigger(a.ERROR,g)}handlePlaylistLoaded(t,e,i,s,o,l){const d=this.hls,{type:h,level:c,levelOrTrack:g,id:p,groupId:m,deliveryDirectives:v}=s,y=eh(e,s),E=th(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}`),!d.config.ignorePlaylistParsingErrors)return void d.trigger(a.ERROR,{type:n.NETWORK_ERROR,details:r.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 d.trigger(a.ERROR,{type:n.NETWORK_ERROR,details:r.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)),h){case u.MANIFEST:case u.LEVEL:if(T)if(g){if(g!==d.levels[T]){const t=d.levels.indexOf(g);t>-1&&(T=t)}}else T=0;d.trigger(a.LEVEL_LOADED,{details:t,levelInfo:g||d.levels[0],level:T||0,id:p||0,stats:i,networkDetails:o,deliveryDirectives:v,withoutMultiVariant:h===u.MANIFEST,context:s});break;case u.AUDIO_TRACK:d.trigger(a.AUDIO_TRACK_LOADED,{details:t,track:g,id:p||0,groupId:m||"",stats:i,networkDetails:o,deliveryDirectives:v,context:s});break;case u.SUBTITLE_TRACK:d.trigger(a.SUBTITLE_TRACK_LOADED,{details:t,track:g,id:p||0,groupId:m||"",stats:i,networkDetails:o,deliveryDirectives:v,context:s})}}}class sh{static get version(){return Nn}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 Yn}static get ErrorTypes(){return n}static get ErrorDetails(){return r}static get DefaultConfig(){return sh.defaultConfig?sh.defaultConfig:qd}static set DefaultConfig(t){sh.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 Fn,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=q();if("object"==typeof console&&!0===t||"object"==typeof t){const n=["debug","log","info","warn","error"];n.forEach(e=>{s[e]=K(e,t,i)});try{s.log(`Debug logs enabled for "${e}" in hls.js version 1.7.4`)}catch(t){return q()}n.forEach(e=>{V[e]=K(e,t)})}else I(V,s);return s}(t.debug||!1,"Hls instance",t.loggerId||t.assetPlayerId),i=this.config=Kd(sh.DefaultConfig,t,e);this.userConfig=t,i.progressive&&Hd(i,e);const{streamController:s,abrController:n,bufferController:r,capLevelController:o,errorController:l,fpsController:d,id3TrackController:h,iframeController:c,gapController:u}=i,f=new l(this),g=this.abrController=new n(this),p=new Ni(this),m=i.interstitialsController,v=m?this.interstitialsController=new m(this,sh):null,y=r?this.bufferController=new r(this,p):null,E=o?this.capLevelController=new o(this):null,T=d?new d(this):null,S=i.cmcdController,b=S?this.cmcdController=new S(this):null,A=new ih(this),L=i.contentSteeringController,R=L?new L(this):null,_=this.levelController=new Yd(this,R),k=h?new h(this):void 0,w=new Jd(this.config,this.logger),D=this.streamController=new s(this,p,w),x=this.gapController=u?new u(this,p):void 0;E&&E.setStreamController(D);const P=[A,_,D];v&&P.splice(1,0,v),R&&P.splice(1,0,R),this.networkControllers=P;const C=[g];y&&C.push(y),x&&C.push(x),E&&C.push(E),T&&(T.setStreamController(D),C.push(T)),k&&C.push(k),C.push(p),this.audioTrackController=this.createController(i.audioTrackController,P);const M=i.audioStreamController;M&&P.push(this.audioStreamController=new M(this,p,w)),this.subtitleTrackController=this.createController(i.subtitleTrackController,P);const O=i.subtitleStreamController;O&&P.push(this.subtititleStreamController=new O(this,p,w)),this.createController(i.timelineController,C),w.emeController=this.emeController=this.createController(i.emeController,C),b&&C.push(b),this.latencyController=this.createController(i.latencyController,C),this.coreComponents=C,this.iframeController=c?new c(this,sh):void 0,P.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:n.OTHER_ERROR,details:r.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:n.OTHER_ERROR,details:r.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,n=this._url=h.buildAbsoluteURL(self.location.href,t,{alwaysNormalize:!0});this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.logger.log(`loadSource:${n}`),i&&s&&(s!==n||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!==vn}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 De.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,je(e),navigator.mediaCapabilities)}}function nh(t){const{baseUrl:e,apiKey:i,clientId:s,fetch:n,apiVersion:r}=t,a=n??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 n=function(t){let e=t.length;for(;e>0&&"/"===t[e-1];)e--;return t.slice(0,e)}(t),r=s.replace(/^\/+/,"");return`${n}/b2b/${e}/subscription/${encodeURIComponent(i)}${r.startsWith("/")?r:`/${r}`}`}(e,function(t){const e=t.toLowerCase();return"v1"===e||"v2"===e?e:"v1"}(r),s,t),d=async(t,e,i,s)=>{const n={method:t,headers:{...o,...i?.headers},...i};void 0!==s&&(n.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),n))};return{get:(t,e)=>d("GET",t,e),post:(t,e,i)=>d("POST",t,i,e),put:(t,e,i)=>d("PUT",t,i,e),patch:(t,e,i)=>d("PATCH",t,i,e),delete:(t,e)=>d("DELETE",t,e)}}sh.defaultConfig=void 0;const rh=t=>void 0!==t?.subdomain?`?subdomain=${encodeURIComponent(t.subdomain)}`:"";const ah="https://api.jaaq.app";class oh{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)}${rh(i)}`;return(await t.get(s)).collection},async getSummaryById(e,i){const s=`/collections/${encodeURIComponent(e)}/summary${rh(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 oh(t,e)}static init(t){return dh(t)}}function lh(t){return dh(t)}function dh(t){const{baseUrl:e=ah,apiKey:i,clientId:s,fetch:n,apiVersion:r="v1"}=t,a=nh({baseUrl:e,apiKey:i,clientId:s,fetch:n??globalThis.fetch,apiVersion:r});return oh.fromHttp(a,r)}function hh(t,e,i){return Math.max(e,Math.min(i,t))}!function(){if("undefined"!=typeof document){const t="jaaq-styles-styles";if(!document.getElementById(t)){const e=document.createElement("style");e.id=t,e.textContent=".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",document.head.appendChild(e)}}}();var ch=".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";!function(){if("undefined"!=typeof document){const t="jaaq-styles-styles";if(!document.getElementById(t)){const e=document.createElement("style");e.id=t,e.textContent=".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",document.head.appendChild(e)}}}();class uh{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=lh({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 n=document.createElement("button");n.className="jaaq-center-play-btn",n.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 ',n.setAttribute("aria-label","Play video"),this.elements.centerPlayBtn=n,e.appendChild(n);const r=document.createElement("div");r.className="jaaq-gradient-overlay",this.elements.gradientOverlay=r;const a=document.createElement("div");a.className="jaaq-caption-display",a.style.display="none",this.elements.captionDisplay=a,r.appendChild(a);const o=document.createElement("div");o.className="jaaq-video-title",this.elements.videoTitle=o,r.appendChild(o);const l=document.createElement("div");l.className="jaaq-video-author",this.elements.videoAuthor=l,r.appendChild(l);const d=document.createElement("div");d.className="jaaq-video-description",this.elements.videoDescription=d,r.appendChild(d),e.appendChild(r);const h=document.createElement("div");h.className="jaaq-loading",this.elements.loading=h,e.appendChild(h);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 p=document.createElement("button");p.className="jaaq-control-btn",p.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 ',p.setAttribute("aria-label","Mute"),this.elements.volumeBtn=p,f.appendChild(p);const m=document.createElement("div");m.className="jaaq-progress-bar",this.elements.progressBar=m;const v=document.createElement("div");v.className="jaaq-progress-filled",this.elements.progressFilled=v,m.appendChild(v),f.appendChild(m);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(sh.isSupported()){this.hls&&this.hls.destroy();const t=new sh({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(sh.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(sh.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[n,r]=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(n),l=a(r);s++;const d=[];for(;s<i.length&&""!==i[s].trim();)d.push(i[s].trim()),s++;d.length>0&&e.push({start:o,end:l,text:d.join(" ")})}s++}return e}updateOverlayContent(t){const e=!1!==this.config.showLogo,i=!1!==this.config.showTitle,s=!1!==this.config.showAuthor,n=!1!==this.config.showDescription,r=!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||"",n=s?`${e} - ${s}`:e;this.elements.videoTitle.textContent=n,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=n&&e?"block":"none"}this.elements.captionsBtn&&(this.elements.captionsBtn.style.display=r?"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*hh(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=hh(t,0,1),this.videoElement.muted=0===t)}toggleMute(){this.videoElement&&(this.videoElement.muted=!this.videoElement.muted)}seek(t){this.videoElement&&(this.videoElement.currentTime=hh(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=""}}function fh(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 uh="(prefers-reduced-motion: reduce)",fh={CREATED:1,MOUNTED:2,IDLE:3,MOVING:4,SCROLLING:5,DRAGGING:6,DESTROYED:7};function gh(t){t.length=0}function ph(t,e,i){return Array.prototype.slice.call(t,e,i)}function mh(t){return t.bind.apply(t,[null].concat(ph(arguments,1)))}var vh=setTimeout,yh=function(){};function Eh(t){return requestAnimationFrame(t)}function Th(t,e){return typeof e===t}function Sh(t){return!Rh(t)&&Th("object",t)}var bh=Array.isArray,Ah=mh(Th,"function"),Lh=mh(Th,"string"),Ih=mh(Th,"undefined");function Rh(t){return null===t}function _h(t){try{return t instanceof(t.ownerDocument.defaultView||window).HTMLElement}catch(t){return!1}}function kh(t){return bh(t)?t:[t]}function wh(t,e){kh(t).forEach(e)}function Dh(t,e){return t.indexOf(e)>-1}function xh(t,e){return t.push.apply(t,kh(e)),t}function Ph(t,e,i){t&&wh(e,function(e){e&&t.classList[i?"add":"remove"](e)})}function Ch(t,e){Ph(t,Lh(e)?e.split(" "):e,!0)}function Mh(t,e){wh(e,t.appendChild.bind(t))}function Oh(t,e){wh(t,function(t){var i=(e||t).parentNode;i&&i.insertBefore(t,e)})}function Fh(t,e){return _h(t)&&(t.msMatchesSelector||t.matches).call(t,e)}function Nh(t,e){var i=t?ph(t.children):[];return e?i.filter(function(t){return Fh(t,e)}):i}function Bh(t,e){return e?Nh(t,e)[0]:t.firstElementChild}var $h=Object.keys;function Uh(t,e,i){return t&&(i?$h(t).reverse():$h(t)).forEach(function(i){"__proto__"!==i&&e(t[i],i)}),t}function Gh(t){return ph(arguments,1).forEach(function(e){Uh(e,function(i,s){t[s]=e[s]})}),t}function jh(t){return ph(arguments,1).forEach(function(e){Uh(e,function(e,i){bh(e)?t[i]=e.slice():Sh(e)?t[i]=jh({},Sh(t[i])?t[i]:{},e):t[i]=e})}),t}function qh(t,e){wh(e||$h(t),function(e){delete t[e]})}function Kh(t,e){wh(t,function(t){wh(e,function(e){t&&t.removeAttribute(e)})})}function Vh(t,e,i){Sh(e)?Uh(e,function(e,i){Vh(t,i,e)}):wh(t,function(t){Rh(i)||""===i?Kh(t,e):t.setAttribute(e,String(i))})}function Hh(t,e,i){var s=document.createElement(t);return e&&(Lh(e)?Ch(s,e):Vh(s,e)),i&&Mh(i,s),s}function Yh(t,e,i){if(Ih(i))return getComputedStyle(t)[e];Rh(i)||(t.style[e]=""+i)}function Wh(t,e){Yh(t,"display",e)}function zh(t){t.setActive&&t.setActive()||t.focus({preventScroll:!0})}function Xh(t,e){return t.getAttribute(e)}function Qh(t,e){return t&&t.classList.contains(e)}function Zh(t){return t.getBoundingClientRect()}function Jh(t){wh(t,function(t){t&&t.parentNode&&t.parentNode.removeChild(t)})}function tc(t){return Bh((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?ph(t.querySelectorAll(e)):[]}function nc(t,e){Ph(t,e,!1)}function rc(t){return t.timeStamp}function ac(t){return Lh(t)?t:t?t+"px":""}var oc="splide",lc="data-"+oc;function dc(t,e){if(!t)throw new Error("["+oc+"] "+(e||""))}var hc=Math.min,cc=Math.max,uc=Math.floor,fc=Math.ceil,gc=Math.abs;function pc(t,e,i){return gc(t-e)<i}function mc(t,e,i,s){var n=hc(e,i),r=cc(e,i);return s?n<t&&t<r:n<=t&&t<=r}function vc(t,e,i){var s=hc(e,i),n=cc(e,i);return hc(cc(s,t),n)}function yc(t){return+(t>0)-+(t<0)}function Ec(t,e){return wh(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){wh(t,function(t){t&&wh(e,function(e){e.split(" ").forEach(function(e){var s=e.split(".");i(t,s[0],s[1])})})})}return{bind:function(i,s,n,r){e(i,s,function(e,i,s){var a="addEventListener"in e,o=a?e.removeEventListener.bind(e,i,n,r):e.removeListener.bind(e,n);a?e.addEventListener(i,n,r):e.addListener(n),t.push([e,i,s,n,o])})},unbind:function(i,s,n){e(i,s,function(e,i,s){t=t.filter(function(t){return!!(t[0]!==e||t[1]!==i||t[2]!==s||n&&t[3]!==n)||(t[4](),!1)})})},dispatch:function(t,e,i){var s,n=!0;return"function"==typeof CustomEvent?s=new CustomEvent(e,{bubbles:n,detail:i}):(s=document.createEvent("CustomEvent")).initCustomEvent(e,n,!1,i),t.dispatchEvent(s),s},destroy:function(){t.forEach(function(t){t[4]()}),gh(t)}}}var Ac="mounted",Lc="ready",Ic="move",Rc="moved",_c="click",kc="active",wc="inactive",Dc="visible",xc="hidden",Pc="refresh",Cc="updated",Mc="resize",Oc="resized",Fc="scroll",Nc="scrolled",Bc="destroy",$c="arrows:mounted",Uc="navigation:mounted",Gc="autoplay:play",jc="autoplay:pause",qc="lazyload:loaded",Kc="sk",Vc="sh",Hc="ei";function Yc(t){var e=t?t.event.bus:document.createDocumentFragment(),i=bc();return t&&t.event.on(Bc,i.destroy),Gh(i,{bus:e,on:function(t,s){i.bind(e,kh(t).join(" "),function(t){s.apply(s,bh(t.detail)?t.detail:[])})},off:mh(i.unbind,e),emit:function(t){i.dispatch(e,t,ph(arguments,1))}})}function Wc(t,e,i,s){var n,r,a=Date.now,o=0,l=!0,d=0;function h(){if(!l){if(o=t?hc((a()-n)/t,1):1,i&&i(o),o>=1&&(e(),n=a(),s&&++d>=s))return c();r=Eh(h)}}function c(){l=!0}function u(){r&&cancelAnimationFrame(r),o=0,r=0,l=!0}return{start:function(e){e||u(),n=a()-(e?o*t:0),l=!1,r=Eh(h)},rewind:function(){n=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",nu="aria-",ru=nu+"controls",au=nu+"current",ou=nu+"selected",lu=nu+"label",du=nu+"labelledby",hu=nu+"hidden",cu=nu+"orientation",uu=nu+"roledescription",fu=nu+"live",gu=nu+"busy",pu=nu+"atomic",mu=[iu,su,"disabled",ru,au,lu,du,hu,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",_u=Ru+"--prev",ku=Ru+"--next",wu=vu+"pagination",Du=wu+"__page",xu=vu+"progress"+"__bar",Pu=vu+"toggle",Cu=vu+"sr",Mu=yu+"initialized",Ou=yu+"active",Fu=yu+"prev",Nu=yu+"next",Bu=yu+"visible",$u=yu+"loading",Uu=yu+"focus-in",Gu=yu+"overflow",ju=[Ou,Bu,Fu,Nu,$u,Uu,Gu],qu={slide:bu,clone:Au,arrows:Iu,arrow:Ru,prev:_u,next:ku,pagination:wu,page:Du,spinner:vu+"spinner"};var Ku="touchstart mousedown",Vu="touchmove mousemove",Hu="touchend touchcancel mouseup click";var Yu="slide",Wu="loop",zu="fade";function Xu(t,e,i,s){var n,r=Yc(t),a=r.on,o=r.emit,l=r.bind,d=t.Components,h=t.root,c=t.options,u=c.isNavigation,f=c.updateOnMove,g=c.i18n,p=c.pagination,m=c.slideFocus,v=d.Direction.resolve,y=Xh(s,"style"),E=Xh(s,lu),T=i>-1,S=Bh(s,"."+Lu);function b(){var n=t.splides.map(function(t){var i=t.splide.Components.Slides.getAt(e);return i?i.slide.id:""}).join(" ");Vh(s,lu,Ec(g.slideX,(T?i:e)+1)),Vh(s,ru,n),Vh(s,iu,m?"button":""),m&&Kh(s,uu)}function A(){n||L()}function L(){if(!n){var i=t.index;(r=I())!==Qh(s,Ou)&&(Ph(s,Ou,r),Vh(s,au,u&&r||""),o(r?kc:wc,R)),function(){var e=function(){if(t.is(zu))return I();var e=Zh(d.Elements.track),i=Zh(s),n=v("left",!0),r=v("right",!0);return uc(e[n])<=fc(i[n])&&uc(i[r])<=fc(e[r])}(),i=!e&&(!I()||T);t.state.is([4,5])||Vh(s,hu,i||"");Vh(sc(s,c.focusableNodes||""),su,i?-1:""),m&&Vh(s,su,i?-1:0);e!==Qh(s,Bu)&&(Ph(s,Bu,e),o(e?Dc:xc,R));if(!e&&document.activeElement===s){var n=d.Slides.getAt(t.index);n&&zh(n.slide)}}(),Ph(s,Fu,e===i-1),Ph(s,Nu,e===i+1)}var r}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=h.id+"-slide"+Tc(e+1),Vh(s,iu,p?"tabpanel":"group"),Vh(s,uu,g.slide),Vh(s,lu,E||Ec(g.slideLabel,[e+1,t.length]))),l(s,"click",mh(o,_c,R)),l(s,"keydown",mh(o,Kc,R)),a([Rc,Vc,Nc],L),a(Uc,b),f&&a(Ic,A)},destroy:function(){n=!0,r.destroy(),nc(s,ju),Kh(s,mu),Vh(s,"style",y),Vh(s,lu,E||"")},update:L,style:function(t,e,i){Yh(i&&S||s,t,e)},isWithin:function(i,s){var n=gc(i-e);return T||!c.rewind&&!t.is(Wu)||(n=hc(n,t.length-n)),n<=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=Lh(t)?t:t.key,Ju[t]||t}var ef="keydown";var sf=lc+"-lazy",nf=sf+"-srcset",rf="["+sf+"], ["+nf+"]";var af=[" ","Enter"];var of=Object.freeze({__proto__:null,Media:function(t,e,i){var s=t.state,n=i.breakpoints||{},r=i.reducedMotion||{},a=bc(),o=[];function l(t){t&&a.destroy()}function d(t,e){var i=matchMedia(e);a.bind(i,"change",h),o.push([t,i])}function h(){var e=s.is(7),n=i.direction,r=o.reduce(function(t,e){return jh(t,e[1].matches?e[0]:{})},{});qh(i),c(r),i.destroy?t.destroy("completely"===i.destroy):e?(l(!0),t.mount()):n!==i.direction&&t.refresh()}function c(e,n,r){jh(i,e),n&&jh(Object.getPrototypeOf(i),e),!r&&s.is(1)||t.emit(Cc,i)}return{setup:function(){var t="min"===i.mediaQuery;$h(n).sort(function(e,i){return t?+e-+i:+i-+e}).forEach(function(e){d(n[e],"("+(t?"min":"max")+"-width:"+e+"px)")}),d(r,uh),h()},destroy:l,reduce:function(t){matchMedia(uh).matches&&(t?jh(i,r):qh(i,$h(r)))},set:c}},Direction:function(t,e,i){return{resolve:function(t,e,s){var n="rtl"!==(s=s||i.direction)||e?s===tu?0:-1:1;return eu[t]&&eu[t][n]||t.replace(/width|left|right/i,function(t,e){var i=eu[t.toLowerCase()][n]||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,n,r,a=Yc(t),o=a.on,l=a.bind,d=t.root,h=i.i18n,c={},u=[],f=[],g=[];function p(){s=y("."+Tu),n=Bh(s,"."+Su),dc(s&&n,"A track/list element is missing."),xh(u,Nh(n,"."+bu+":not(."+Au+")")),Uh({arrows:Iu,pagination:wu,prev:_u,next:ku,bar:xu,toggle:Pu},function(t,e){c[e]=y("."+t)}),Gh(c,{root:d,track:s,list:n,slides:u}),function(){var t=d.id||(r=oc,""+r+Tc(Sc[r]=(Sc[r]||0)+1)),e=i.role;var r;d.id=t,s.id=s.id||t+"-track",n.id=n.id||t+"-list",!Xh(d,iu)&&"SECTION"!==d.tagName&&e&&Vh(d,iu,e);Vh(d,uu,h.carousel),Vh(n,iu,"presentation")}(),v()}function m(t){var e=mu.concat("style");gh(u),nc(d,f),nc(s,g),Kh([s,n],e),Kh(d,t?e:["style",uu])}function v(){nc(d,f),nc(s,g),f=E(Eu),g=E(Tu),Ch(d,f),Ch(s,g),Vh(d,lu,i.label),Vh(d,du,i.labelledby)}function y(t){var e=ic(d,t);return e&&function(t,e){if(Ah(t.closest))return t.closest(e);for(var i=t;i&&1===i.nodeType&&!Fh(i,e);)i=i.parentElement;return i}(e,"."+Eu)===d?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 Gh(c,{setup:p,mount:function(){o(Pc,m),o(Pc,p),o(Cc,v),l(document,Ku+" keydown",function(t){r="keydown"===t.type},{capture:!0}),l(d,"focusin",function(){Ph(d,Uu,!!r)})},destroy:m})},Slides:function(t,e,i){var s=Yc(t),n=s.on,r=s.emit,a=s.bind,o=e.Elements,l=o.slides,d=o.list,h=[];function c(){l.forEach(function(t,e){f(t,e,-1)})}function u(){p(function(t){t.destroy()}),gh(h)}function f(e,i,s){var n=Xu(t,i,s,e);n.mount(),h.push(n),h.sort(function(t,e){return t.index-e.index})}function g(t){return t?m(function(t){return!t.isClone}):h}function p(t,e){g(e).forEach(t)}function m(t){return h.filter(Ah(t)?t:function(e){return Lh(t)?Fh(e.slide,t):Dh(kh(t),e.index)})}return{mount:function(){c(),n(Pc,u),n(Pc,c)},destroy:u,update:function(){p(function(t){t.update()})},register:f,get:g,getIn:function(t){var s=e.Controller,n=s.toIndex(t),r=s.hasFocus()?1:i.perPage;return m(function(t){return mc(t.index,n,n+r-1)})},getAt:function(t){return m(t)[0]},add:function(t,e){wh(t,function(t){if(Lh(t)&&(t=tc(t)),_h(t)){var s=l[e];s?Oh(t,s):Mh(d,t),Ch(t,i.classes.slide),n=t,o=mh(r,Mc),h=sc(n,"img"),(c=h.length)?h.forEach(function(t){a(t,"load error",function(){--c||o()})}):o()}var n,o,h,c}),r(Pc)},remove:function(t){Jh(m(t).map(function(t){return t.slide})),r(Pc)},forEach:p,filter:m,style:function(t,e,i){p(function(s){s.style(t,e,i)})},getLength:function(t){return t?l.length:h.length},isEnough:function(){return h.length>i.perPage}}},Layout:function(t,e,i){var s,n,r,a=Yc(t),o=a.on,l=a.bind,d=a.emit,h=e.Slides,c=e.Direction.resolve,u=e.Elements,f=u.root,g=u.track,p=u.list,m=h.getAt,v=h.style;function y(){s=i.direction===tu,Yh(f,"maxWidth",ac(i.width)),Yh(g,c("paddingLeft"),T(!1)),Yh(g,c("paddingRight"),T(!0)),E(!0)}function E(t){var e=Zh(f);(t||n.width!==e.width||n.height!==e.height)&&(Yh(g,"height",function(){var t="";s&&(dc(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),n=e,d(Oc),r!==(r=k())&&(Ph(f,Gu,r),d("overflow",r)))}function T(t){var e=i.padding,s=c(t?"right":"left");return e&&ac(e[s]||(Sh(e)?0:e))||"0px"}function S(){return ac(i.height||Zh(p).width*i.heightRatio)}function b(){var t=ac(i.gap);return"calc((100%"+(t&&" + "+t)+")/"+(i.perPage||1)+(t&&" - "+t)+")"}function A(){return Zh(p)[c("width")]}function L(t,e){var i=m(t||0);return i?Zh(i.slide)[c("width")]+(e?0:_()):0}function I(t,e){var i=m(t);if(i){var s=Zh(i.slide)[c("right")],n=Zh(p)[c("left")];return gc(s-n)+(e?0:_())}return 0}function R(e){return I(t.length-1)-I(0)+L(0,e)}function _(){var t=m(0);return t&&parseFloat(Yh(t.slide,c("marginRight")))||0}function k(){return t.is(zu)||R(!0)>A()}return{mount:function(){var t,e;y(),l(window,"resize load",(t=mh(d,Mc),e=Wc(0,t,null,1),function(){e.isPaused()&&e.start()})),o([Cc,Pc],y),o(Mc,E)},resize:E,listSize:A,slideSize:L,sliderSize:R,totalSize:I,getPadding:function(t){return parseFloat(Yh(g,c("padding"+(t?"Right":"Left"))))||0},isOverflow:k}},Clones:function(t,e,i){var s,n=Yc(t),r=n.on,a=e.Elements,o=e.Slides,l=e.Direction.resolve,d=[];function h(){r(Pc,c),r([Cc,Mc],f),(s=g())&&(!function(e){var s=o.get().slice(),n=s.length;if(n){for(;s.length<e;)xh(s,s);xh(s.slice(-e),s.slice(0,e)).forEach(function(r,l){var h=l<e,c=function(e,s){var n=e.cloneNode(!0);return Ch(n,i.classes.clone),n.id=t.root.id+"-clone"+Tc(s+1),n}(r.slide,l);h?Oh(c,s[0].slide):Mh(a.list,c),xh(d,c),o.register(c,l-e+(h?0:n),r.index)})}}(s),e.Layout.resize(!0))}function c(){u(),h()}function u(){Jh(d),gh(d),n.destroy()}function f(){var t=g();s!==t&&(s<t||!t)&&n.emit(Pc)}function g(){var s=i.clones;if(t.is(Wu)){if(Ih(s)){var n=i[l("fixedWidth")]&&e.Layout.slideSize(0);s=n&&fc(Zh(a.track)[l("width")]/n)||i[l("autoWidth")]&&t.length||2*i.perPage}}else s=0;return s}return{mount:h,destroy:u}},Move:function(t,e,i){var s,n=Yc(t),r=n.on,a=n.emit,o=t.state.set,l=e.Layout,d=l.slideSize,h=l.getPadding,c=l.totalSize,u=l.listSize,f=l.sliderSize,g=e.Direction,p=g.resolve,m=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 n=s?i:function(i){if(t.is(Wu)){var s=I(i),n=s>e.Controller.getEnd();(s<0||n)&&(i=A(i,n))}return i}(i);Yh(y,"transform","translate"+p("X")+"("+n+"px)"),i!==n&&a(Vc)}}function A(t,e){var i=t-k(e),s=f();return t-=m(s*(fc(gc(i)/s)||1))*(e?1:-1)}function L(){b(_(),!0),s.cancel()}function I(t){for(var i=e.Slides.get(),s=0,n=1/0,r=0;r<i.length;r++){var a=i[r].index,o=gc(R(a,!0)-t);if(!(o<=n))break;n=o,s=a}return s}function R(e,s){var n=m(c(e-1)-function(t){var e=i.focus;return"center"===e?(u()-d(t,!0))/2:+e*d(t)||0}(e));return s?function(e){i.trimSpace&&t.is(Yu)&&(e=vc(e,0,m(f(!0)-u())));return e}(n):n}function _(){var t=p("left");return Zh(y)[t]-Zh(E)[t]+m(h(!1))}function k(t){return R(t?e.Controller.getEnd():0,!!i.trimSpace)}return{mount:function(){s=e.Transition,r([Ac,Oc,Cc,Pc],T)},move:function(t,e,i,n){var r,l;t!==e&&(r=t>i,l=m(A(_(),r)),r?l>=0:l<=y[p("scrollWidth")]-Zh(E)[p("width")])&&(L(),b(A(_(),t>i),!0)),o(4),a(Ic,e,i,t),s.start(e,function(){o(3),a(Rc,e,i,t),n&&n()})},jump:S,translate:b,shift:A,cancel:L,toIndex:I,toPosition:R,getPosition:_,getLimit:k,exceededLimit:function(t,e){e=Ih(e)?_():e;var i=!0!==t&&m(e)<m(k(!1)),s=!1!==t&&m(e)>m(k(!0));return i||s},reposition:T}},Controller:function(t,e,i){var s,n,r,a,o=Yc(t),l=o.on,d=o.emit,h=e.Move,c=h.getPosition,u=h.getLimit,f=h.toPosition,g=e.Slides,p=g.isEnough,m=g.getLength,v=i.omitEnd,y=t.is(Wu),E=t.is(Yu),T=mh(R,!1),S=mh(R,!0),b=i.start||0,A=b;function L(){n=m(!0),r=i.perMove,a=i.perPage,s=w();var t=vc(b,0,v?s:n-1);t!==b&&(b=t,h.reposition())}function I(){s!==w()&&d(Hc)}function R(t,e){var i=r||(C()?1:a),n=_(b+i*(t?-1:1),b,!(r||C()));return-1===n&&E&&!pc(c(),u(!t),1)?t?0:s:e?n:k(n)}function _(e,o,l){if(p()||C()){var d=function(e){if(E&&"move"===i.trimSpace&&e!==b)for(var s=c();s===f(e,!0)&&mc(e,0,t.length-1,!i.rewind);)e<b?--e:++e;return e}(e);d!==e&&(o=e,e=d,l=!1),e<0||e>s?e=r||!mc(0,e,o,!0)&&!mc(s,o,e,!0)?y?l?e<0?-(n%a||a):n:e:i.rewind?e<0?s:0:-1:D(x(e)):l&&e!==o&&(e=D(x(o)+(e<o?-1:1)))}else e=-1;return e}function k(t){return y?(t+n)%n||0:t}function w(){for(var t=n-(C()||y&&r?1:a);v&&t-- >0;)if(f(n-1,!0)!==f(t,!0)){t++;break}return vc(t,0,n-1)}function D(t){return vc(C()?t:a*t,0,s)}function x(t){return C()?hc(t,s):uc((t>=s?n-1:t)/a)}function P(t){t!==b&&(A=b,b=t)}function C(){return!Ih(i.focus)||i.isNavigation}function M(){return t.state.is([4,5])&&!!i.waitForTransition}return{mount:function(){L(),l([Cc,Pc,Hc],L),l(Oc,I)},go:function(t,e,i){if(!M()){var n=function(t){var e=b;if(Lh(t)){var i=t.match(/([+\-<>])(\d+)?/)||[],n=i[1],r=i[2];"+"===n||"-"===n?e=_(b+ +(""+n+(+r||1)),b):">"===n?e=r?D(+r):T(!0):"<"===n&&(e=S(!0))}else e=y?t:vc(t,0,s);return e}(t),r=k(n);r>-1&&(e||r!==b)&&(P(r),h.move(n,r,A,i))}},scroll:function(t,i,n,r){e.Scroll.scroll(t,i,n,function(){var t=k(h.toIndex(c()));P(v?hc(t,s):t),r&&r()})},getNext:T,getPrev:S,getAdjacent:R,getEnd:w,setIndex:P,getIndex:function(t){return t?A:b},toIndex:D,toPage:x,toDest:function(t){var e=h.toIndex(t);return E?vc(e,0,s):e},hasFocus:C,isBusy:M}},Arrows:function(t,e,i){var s,n,r=Yc(t),a=r.on,o=r.bind,l=r.emit,d=i.classes,h=i.i18n,c=e.Elements,u=e.Controller,f=c.arrows,g=c.track,p=f,m=c.prev,v=c.next,y={};function E(){!function(){var t=i.arrows;!t||m&&v||(p=f||Hh("div",d.arrows),m=A(!0),v=A(!1),s=!0,Mh(p,[m,v]),!f&&Oh(p,g));m&&v&&(Gh(y,{prev:m,next:v}),Wh(p,t?"":"none"),Ch(p,n=Iu+"--"+i.direction),t&&(a([Ac,Rc,Pc,Nc,Hc],L),o(v,"click",mh(b,">")),o(m,"click",mh(b,"<")),L(),Vh([m,v],ru,g.id),l($c,m,v)))}(),a(Cc,T)}function T(){S(),E()}function S(){r.destroy(),nc(p,n),s?(Jh(f?[m,v]:p),m=v=null):Kh([m,v],mu)}function b(t){u.go(t,!0)}function A(t){return tc('<button class="'+d.arrow+" "+(t?d.prev:d.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(m&&v){var e=t.index,i=u.getPrev(),s=u.getNext(),n=i>-1&&e<i?h.last:h.prev,r=s>-1&&e>s?h.first:h.next;m.disabled=i<0,v.disabled=s<0,Vh(m,lu,n),Vh(v,lu,r),l("arrows:updated",m,v,i,s)}}return{arrows:y,mount:E,destroy:S,update:L}},Autoplay:function(t,e,i){var s,n,r=Yc(t),a=r.on,o=r.bind,l=r.emit,d=Wc(i.interval,t.go.bind(t,">"),function(t){var e=c.bar;e&&Yh(e,"width",100*t+"%"),l("autoplay:playing",t)}),h=d.isPaused,c=e.Elements,u=e.Elements,f=u.root,g=u.toggle,p=i.autoplay,m="pause"===p;function v(){h()&&e.Slides.isEnough()&&(d.start(!i.resetProgress),n=s=m=!1,T(),l(Gc))}function y(t){void 0===t&&(t=!0),m=!!t,T(),h()||(d.pause(),l(jc))}function E(){m||(s||n?y(!1):v())}function T(){g&&(Ph(g,Ou,!m),Vh(g,lu,i.i18n[m?"play":"pause"]))}function S(t){var s=e.Slides.getAt(t);d.set(s&&+Xh(s.slide,Qu)||i.interval)}return{mount:function(){p&&(!function(){i.pauseOnHover&&o(f,"mouseenter mouseleave",function(t){s="mouseenter"===t.type,E()});i.pauseOnFocus&&o(f,"focusin focusout",function(t){n="focusin"===t.type,E()});g&&o(g,"click",function(){m?v():y(!0)});a([Ic,Fc,Pc],d.rewind),a(Ic,S)}(),g&&Vh(g,ru,c.track.id),m||v(),T())},destroy:d.cancel,play:v,pause:y,isPaused:h}},Cover:function(t,e,i){var s=Yc(t).on;function n(t){e.Slides.forEach(function(e){var i=Bh(e.container||e.slide,"img");i&&i.src&&r(t,i,e)})}function r(t,e,i){i.style("background",t?'center/cover no-repeat url("'+e.src+'")':"",!0),Wh(e,t?"none":"")}return{mount:function(){i.cover&&(s(qc,mh(r,!0)),s([Ac,Cc,Pc],mh(n,!0)))},destroy:mh(n,!1)}},Scroll:function(t,e,i){var s,n,r=Yc(t),a=r.on,o=r.emit,l=t.state.set,d=e.Move,h=d.getPosition,c=d.getLimit,u=d.exceededLimit,f=d.translate,g=t.is(Yu),p=1;function m(t,i,r,a,c){var f=h();if(E(),r&&(!g||!u())){var m=e.Layout.sliderSize(),T=yc(t)*m*uc(gc(t)/m)||0;t=d.toPosition(e.Controller.toDest(t%m))+T}var S=pc(f,t,1);p=1,i=S?0:i||cc(gc(t-f)/1.5,800),n=a,s=Wc(i,v,mh(y,f,t,c),1),l(5),o(Fc),s.start()}function v(){l(3),n&&n(),o(Nc)}function y(t,e,s,r){var a,o,l=h(),d=(t+(e-t)*(a=r,(o=i.easingFunc)?o(a):1-Math.pow(1-a,4))-l)*p;f(l+d),g&&!s&&u()&&(p*=.6,gc(d)<10&&m(c(u(!0)),600,!1,n,!0))}function E(){s&&s.cancel()}function T(){s&&!s.isPaused()&&(E(),v())}return{mount:function(){a(Ic,E),a([Cc,Pc],T)},destroy:E,scroll:m,cancel:T}},Drag:function(t,e,i){var s,n,r,a,o,l,d,h,c=Yc(t),u=c.on,f=c.emit,g=c.bind,p=c.unbind,m=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,_=!1;function k(){var t=i.drag;$(!t),a="free"===t}function w(t){if(l=!1,!d){var e=B(t);s=t.target,n=i.noDrag,Fh(s,"."+Du+", ."+Ru)||n&&Fh(s,n)||!e&&t.button||(E.isBusy()?ec(t,!0):(h=e?T:window,o=m.is([4,5]),r=null,g(h,Vu,D,Zu),g(h,Hu,x,Zu),v.cancel(),y.cancel(),C(t)))}var s,n}function D(e){if(m.is(6)||(m.set(6),f("drag")),e.cancelable)if(o){v.translate(s+M(e)/(_&&t.is(Yu)?5:1));var n=O(e)>200,r=_!==(_=R());(n||r)&&C(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=Sh(e),n=s&&e.mouse||0,r=(s?e.touch:+e)||10;return gc(M(t))>(B(t)?r:n)}(e),ec(e))}function x(s){m.is(6)&&(m.set(3),f("dragged")),o&&(!function(s){var n=function(e){if(t.is(Wu)||!_){var i=O(e);if(i&&i<200)return M(e)/i}return 0}(s),r=function(t){return I()+yc(t)*hc(gc(t)*(i.flickPower||600),a?1/0:e.Layout.listSize()*(i.flickMaxPages||1))}(n),o=i.rewind&&i.rewindByDrag;S(!1),a?E.scroll(r,0,i.snap):t.is(zu)?E.go(L(yc(n))<0?o?"<":"-":o?">":"+"):t.is(Yu)&&_&&o?E.go(R(!0)?">":"<"):E.go(E.toDest(r),!0);S(!0)}(s),ec(s)),p(h,Vu,D),p(h,Hu,x),o=!1}function P(t){!d&&l&&ec(t,!0)}function C(t){r=n,n=t,s=I()}function M(t,e){return N(t,e)-N(F(t),e)}function O(t){return rc(t)-rc(F(t))}function F(t){return n===t&&r||n}function N(t,e){return(B(t)?t.changedTouches[0]:t)["page"+A(e?"Y":"X")]}function B(t){return"undefined"!=typeof TouchEvent&&t instanceof TouchEvent}function $(t){d=t}return{mount:function(){g(T,Vu,yh,Zu),g(T,Hu,yh,Zu),g(T,Ku,w,Zu),g(T,"click",P,{capture:!0}),g(T,"dragstart",ec),u([Ac,Cc],k)},disable:$,isDragging:function(){return o}}},Keyboard:function(t,e,i){var s,n,r=Yc(t),a=r.on,o=r.bind,l=r.unbind,d=t.root,h=e.Direction.resolve;function c(){var t=i.keyboard;t&&(s="global"===t?window:d,o(s,ef,g))}function u(){l(s,ef)}function f(){var t=n;n=!0,vh(function(){n=t})}function g(e){if(!n){var i=tf(e);i===h(Xc)?t.go("<"):i===h(Qc)&&t.go(">")}}return{mount:function(){c(),a(Cc,u),a(Cc,c),a(Ic,f)},destroy:u,disable:function(t){n=t}}},LazyLoad:function(t,e,i){var s=Yc(t),n=s.on,r=s.off,a=s.bind,o=s.emit,l="sequential"===i.lazyLoad,d=[Rc,Nc],h=[];function c(){gh(h),e.Slides.forEach(function(t){sc(t.slide,rf).forEach(function(e){var s=Xh(e,sf),n=Xh(e,nf);if(s!==e.src||n!==e.srcset){var r=i.classes.spinner,a=e.parentElement,o=Bh(a,"."+r)||Hh("span",r,a);h.push([e,t,o]),e.src||Wh(e,"none")}})}),l?p():(r(d),n(d,u),u())}function u(){(h=h.filter(function(e){var s=i.perPage*((i.preloadPages||1)+1)-1;return!e[1].isWithin(t.index,s)||f(e)})).length||r(d)}function f(t){var e=t[0];Ch(t[1].slide,$u),a(e,"load error",mh(g,t)),Vh(e,"src",Xh(e,sf)),Vh(e,"srcset",Xh(e,nf)),Kh(e,sf),Kh(e,nf)}function g(t,e){var i=t[0],s=t[1];nc(s.slide,$u),"error"!==e.type&&(Jh(t[2]),Wh(i,""),o(qc,i,s),o(Mc)),l&&p()}function p(){h.length&&f(h.shift())}return{mount:function(){i.lazyLoad&&(c(),n(Pc,c))},destroy:mh(gh,h),check:u}},Pagination:function(t,e,i){var s,n,r=Yc(t),a=r.on,o=r.emit,l=r.bind,d=e.Slides,h=e.Elements,c=e.Controller,u=c.hasFocus,f=c.getIndex,g=c.go,p=e.Direction.resolve,m=h.pagination,v=[];function y(){s&&(Jh(m?ph(s.children):s),nc(s,n),gh(v),s=null),r.destroy()}function E(t){g(">"+t,!0)}function T(t,e){var i=v.length,s=tf(e),n=S(),r=-1;s===p(Qc,!1,n)?r=++t%i:s===p(Xc,!1,n)?r=(--t+i)%i:"Home"===s?r=0:"End"===s&&(r=i-1);var a=v[r];a&&(zh(a.button),g(">"+r),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;nc(i,Ou),Kh(i,ou),Vh(i,su,-1)}if(e){var n=e.button;Ch(n,Ou),Vh(n,ou,!0),Vh(n,su,"")}o("pagination:updated",{list:s,items:v},t,e)}return{items:v,mount:function e(){y(),a([Cc,Pc,Hc],e);var r=i.pagination;m&&Wh(m,r?"":"none"),r&&(a([Ic,Fc,Nc],A),function(){var e=t.length,r=i.classes,a=i.i18n,o=i.perPage,f=u()?c.getEnd()+1:fc(e/o);Ch(s=m||Hh("ul",r.pagination,h.track.parentElement),n=wu+"--"+S()),Vh(s,iu,"tablist"),Vh(s,lu,a.select),Vh(s,cu,S()===tu?"vertical":"");for(var g=0;g<f;g++){var p=Hh("li",null,s),y=Hh("button",{class:r.page,type:"button"},p),b=d.getIn(g).map(function(t){return t.slide.id}),A=!u()&&o>1?a.pageX:a.slideX;l(y,"click",mh(E,g)),i.paginationKeyboard&&l(y,"keydown",mh(T,g)),Vh(p,iu,"presentation"),Vh(y,iu,"tab"),Vh(y,ru,b.join(" ")),Vh(y,lu,Ec(A,g+1)),Vh(y,su,-1),v.push({li:p,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,n=i.slideFocus,r=[];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)(_c,h),i(Kc,c),i([Ac,Cc],d),r.push(e),e.emit(Uc,t.splides))}function o(){r.forEach(function(t){t.destroy()}),gh(r)}function l(t,e){var i=Yc(t);i.on(Ic,function(t,i,s){e.go(e.is(Wu)?s:t)}),r.push(i)}function d(){Vh(e.Elements.list,cu,i.direction===tu?"vertical":"")}function h(e){t.go(e.index)}function c(t,e){Dh(af,tf(e))&&(h(t),ec(e))}return{setup:mh(e.Media.set,{slideFocus:Ih(n)?s:n},!0),mount:a,destroy:o,remount:function(){o(),a()}}},Wheel:function(t,e,i){var s=Yc(t).bind,n=0;function r(s){if(s.cancelable){var r=s.deltaY,a=r<0,o=rc(s),l=i.wheelMinThreshold||0,d=i.wheelSleep||0;gc(r)>l&&o-n>d&&(t.go(a?"<":">"),n=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",r,Zu)}}},Live:function(t,e,i){var s=Yc(t).on,n=e.Elements.track,r=i.live&&!i.isNavigation,a=Hh("span",Cu),o=Wc(90,mh(l,!1));function l(t){Vh(n,gu,t),t?(Mh(n,a),o.start()):(Jh(a),o.cancel())}function d(t){r&&Vh(n,fu,t?"off":"polite")}return{mount:function(){r&&(d(!e.Autoplay.isPaused()),Vh(n,pu,!0),a.textContent="…",s(Gc,mh(d,!0)),s(jc,mh(d,!1)),s([Rc,Nc],mh(l,!0)))},disable:d,destroy:function(){Kh(n,[fu,pu,gu]),Jh(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:qu,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 df(t,e,i){var s=e.Slides;function n(){s.forEach(function(t){t.style("transform","translateX(-"+100*t.index+"%)")})}return{mount:function(){Yc(t).on([Ac,Pc],n)},start:function(t,e){s.style("transition","opacity "+i.speed+"ms "+i.easing),vh(e)},cancel:yh}}function hf(t,e,i){var s,n=e.Move,r=e.Controller,a=e.Scroll,o=e.Elements.list,l=mh(Yh,o,"transition");function d(){l(""),a.cancel()}return{mount:function(){Yc(t).bind(o,"transitionend",function(t){t.target===o&&s&&(d(),s())})},start:function(e,o){var d=n.toPosition(e,!0),h=n.getPosition(),c=function(e){var s=i.rewindSpeed;if(t.is(Yu)&&s){var n=r.getIndex(!0),a=r.getEnd();if(0===n&&e>=a||n>=a&&0===e)return s}return i.speed}(e);gc(d-h)>=1&&c>=1?i.useScroll?a.scroll(d,c,!1,o):(l("transform "+c+"ms "+i.easing),n.translate(d,!0),s=o):(n.jump(e),o())},cancel:d}}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 Dh(kh(t),s)}}),this.splides=[],this._o={},this._E={};var n=Lh(e)?ic(document,e):e;dc(n,n+" is invalid."),this.root=n,i=jh({label:Xh(n,lu)||"",labelledby:Xh(n,du)||""},lf,t.defaults,i||{});try{jh(i,JSON.parse(Xh(n,lc)))}catch(t){dc(!1,"Invalid JSON")}this._o=Object.create(jh({},i))}var e=t.prototype;return e.mount=function(t,e){var i=this,s=this.state,n=this.Components;return dc(s.is([1,7]),"Already mounted!"),s.set(1),this._C=n,this._T=e||this._T||(this.is(zu)?df:hf),this._E=t||this._E,Uh(Gh({},of,this._E,{Transition:this._T}),function(t,e){var s=t(i,n,i._o);n[e]=s,s.setup&&s.setup()}),Uh(n,function(t){t.mount&&t.mount()}),this.emit(Ac),Ch(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(ph(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(Pc),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)):(Uh(this._C,function(e){e.destroy&&e.destroy(t)},!0),e.emit(Bc),e.destroy(),t&&gh(this.splides),i.set(7)),this},ch(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=fh,function(){if("undefined"!=typeof document){const t="jaaq-styles-splide.min";if(!document.getElementById(t)){const e=document.createElement("style");e.id=t,e.textContent=".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}",document.head.appendChild(e)}}}();const ff=new WeakMap,gf=[];function pf(t){if(ff.has(t))return ff.get(t);const e=function(t){const e=t.getAttribute("data-api-key"),i=t.getAttribute("data-client-id"),s=t.getAttribute("data-video-id");if(!e||!i||!s)return console.error("JAAQ Player: Missing required attributes (data-api-key, data-client-id, data-video-id)",t),null;const n={apiKey:e,clientId:i,videoId:s},r=t.getAttribute("data-autoplay");null!==r&&(n.autoplay="true"===r);const a=t.getAttribute("data-width");a&&(n.width=a);const o=t.getAttribute("data-height");o&&(n.height=o);const l=t.getAttribute("data-base-url");l&&(n.baseUrl=l);const d=t.getAttribute("data-api-version");d&&(n.apiVersion=d);const h=t.getAttribute("data-class-name");return h&&(n.className=h),n}(t);if(!e)return null;try{const i=new hh(t,e);return ff.set(t,i),gf.push({element:t,player:i}),i}catch(e){return console.error("JAAQ Player: Failed to initialize player",e,t),null}}function mf(t=document){t.querySelectorAll("[data-jaaq-player]").forEach(t=>{pf(t)})}const vf={init:mf,getPlayer:function(t){let e;if("string"==typeof t){if(e=document.querySelector(t),!e)return console.error("JAAQ Player: Element not found for selector",t),null}else e=t;return ff.get(e)||null},destroyAll:function(){gf.forEach(({element:t,player:e})=>{try{e.destroy(),ff.delete(t)}catch(t){console.error("JAAQ Player: Error destroying player",t)}}),gf.length=0}};"undefined"!=typeof window&&"undefined"!=typeof document&&("loading"===document.readyState?document.addEventListener("DOMContentLoaded",()=>{mf()}):mf());class yf 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 ${dh}\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,n=this.getAttribute("api-version")||void 0,r=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"),d=!this.hasAttribute("show-author")||"false"!==this.getAttribute("show-author"),h=!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 hh(this.container,{videoId:t??void 0,apiKey:e??void 0,clientId:i??void 0,client:this.clientInstance||void 0,baseUrl:s,apiVersion:n,autoplay:r,controls:a,showLogo:o,showTitle:l,showAuthor:d,showDescription:h,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(){if("undefined"!=typeof document){const t="jaaq-styles-CollectionPlayer";if(!document.getElementById(t)){const e=document.createElement("style");e.id=t,e.textContent=".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",document.head.appendChild(e)}}}();class Ef 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 ${dh}\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,n=this.getAttribute("api-version")||void 0;if(this.clientInstance||e||i){this.showLoading();try{const r=this.clientInstance||rh.init({apiKey:e,clientId:i,baseUrl:s||nh,apiVersion:n});this.collectionData=await r.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"),n=this.getAttribute("base-url"),r=this.getAttribute("video-settings");let a=null;if(r)try{a=JSON.parse(r)}catch(t){console.warn("[CollectionPlayer] Failed to parse video-settings attribute",t)}this.getVideosFromCollection(this.collectionData).forEach(t=>{const r=document.createElement("li");r.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),n&&o.setAttribute("base-url",n),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))),r.appendChild(o),e.appendChild(r)}),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"),n=s?.getAttribute("video-id");console.log("[CollectionPlayer] Active slide from DOM:",{activeIndex:t,activeVideoId:n,foundActiveSlide:!!i});const r=this.carouselElement.querySelectorAll(".splide__slide:not(.splide__slide--clone)");Array.from(r).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")}}),r.forEach((t,i)=>{const s=t.querySelector("jaaq-video-player");if(!s)return;const n=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:n}),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 Tf="jaaq-video-player",Sf="jaaq-collection-player";function bf(){"undefined"!=typeof window&&"undefined"!=typeof customElements?(customElements.get(Tf)||customElements.define(Tf,yf),customElements.get(Sf)||customElements.define(Sf,Ef)):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",()=>{bf()}):bf()),t.JaaqCollectionPlayer=class{constructor(t,e){if(this.client=null,this.splide=null,this.playerElement=null,this.carouselElement=null,this.collectionData=null,this.autoplayTimeoutId=null,this.listeners=new Map,this.container="string"==typeof t?document.querySelector(t):t,!this.container)throw new Error("Container element not found");if(this.config={autoplay:!1,showArrows:!0,showDots:!0,...e},e.client)this.client=e.client;else{if(!e.apiKey||!e.clientId)throw new Error("Either client property or apiKey and clientId are required");this.client=ah({apiKey:e.apiKey,clientId:e.clientId,baseUrl:e.baseUrl||nh,apiVersion:e.apiVersion})}this.init()}async init(){this.render(),await this.initCarousel()}render(){this.container.innerHTML="",this.playerElement=document.createElement("div"),this.playerElement.className=`jaaq-collection-player ${this.config.className||""}`,this.container.appendChild(this.playerElement)}async initCarousel(){if(!this.playerElement)return;const t=this.config.collectionId;if(t){this.showLoading();try{if(!this.client)throw new Error("Client is not initialized");this.collectionData=await this.client.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.emit("loaded",this.collectionData)}catch(t){this.emitError(t instanceof Error?t:new Error("Failed to load collection"))}}else this.emitError(new Error("collectionId is required"))}showLoading(){this.playerElement&&(this.playerElement.innerHTML='\n <div class="jaaq-collection-loading">\n <div class="jaaq-collection-spinner"></div>\n </div>\n ')}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[]}renderCarousel(){if(!this.playerElement||!this.collectionData)return;this.playerElement.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";this.getVideosFromCollection(this.collectionData).forEach(t=>{const i=document.createElement("li");i.className="splide__slide";const s=document.createElement("jaaq-video-player");if(s.setAttribute("video-id",t.videoId),this.config.apiKey&&s.setAttribute("api-key",this.config.apiKey),this.config.clientId&&s.setAttribute("client-id",this.config.clientId),this.config.baseUrl&&s.setAttribute("base-url",this.config.baseUrl),this.config.apiVersion&&s.setAttribute("api-version",this.config.apiVersion),s.setAttribute("autoplay","false"),s.setAttribute("width","100%"),this.config.videoSettings){const t=this.config.videoSettings;void 0!==t.controls&&s.setAttribute("controls",String(t.controls)),void 0!==t.showLogo&&s.setAttribute("show-logo",String(t.showLogo)),void 0!==t.showTitle&&s.setAttribute("show-title",String(t.showTitle)),void 0!==t.showAuthor&&s.setAttribute("show-author",String(t.showAuthor)),void 0!==t.showDescription&&s.setAttribute("show-description",String(t.showDescription)),void 0!==t.showCaptions&&s.setAttribute("show-captions",String(t.showCaptions)),void 0!==t.startMuted&&s.setAttribute("start-muted",String(t.startMuted)),void 0!==t.width&&s.setAttribute("width",String(t.width)),void 0!==t.height&&s.setAttribute("height",String(t.height))}this.client&&void 0!==s.client&&(s.client=this.client),i.appendChild(s),e.appendChild(i)}),t.appendChild(e),this.carouselElement.appendChild(t),this.playerElement.appendChild(this.carouselElement)}initSplide(){this.carouselElement&&(this.splide=new uf(this.carouselElement,{type:"loop",perPage:3,focus:"center",gap:"0.5rem",perMove:1,autoHeight:!0,updateOnMove:!0,padding:"5rem",breakpoints:{768:{perPage:1},1024:{perPage:2}},arrows:!1!==this.config.showArrows,pagination:!1!==this.config.showDots,autoplay:!1}),this.splide.on("moved",t=>{if(this.handleSlideChange(t),this.collectionData){const e=this.getVideosFromCollection(this.collectionData);this.emit("slidechange",{index:t,video:e[t]})}}),this.splide.mount(),setTimeout(()=>{this.splide&&this.handleSlideChange(this.splide.index)},100))}handleSlideChange(t){if(!this.carouselElement)return;const e=this.config.autoplay;null!==this.autoplayTimeoutId&&(clearTimeout(this.autoplayTimeoutId),this.autoplayTimeoutId=null);this.carouselElement.querySelectorAll(".splide__slide:not(.splide__slide--clone)").forEach(t=>{const i=t.querySelector("jaaq-video-player");if(!i)return;t.classList.contains("is-active")?e&&(this.autoplayTimeoutId=window.setTimeout(()=>{i.play?.()},1e3)):i.pause?.()})}destroyCarousel(){null!==this.autoplayTimeoutId&&(clearTimeout(this.autoplayTimeoutId),this.autoplayTimeoutId=null),this.splide&&(this.splide.destroy(),this.splide=null),this.playerElement&&(this.playerElement.innerHTML=""),this.collectionData=null}emitError(t){this.playerElement&&(this.playerElement.innerHTML=`\n <div class="jaaq-collection-error">\n ${t.message}\n </div>\n `),this.emit("error",t)}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)})}refresh(){this.destroyCarousel(),this.initCarousel()}next(){this.splide?.go("+1")}prev(){this.splide?.go("-1")}go(t){this.splide?.go(t)}destroy(){this.destroyCarousel(),this.listeners.clear(),this.container.innerHTML=""}getCollection(){return this.collectionData}},t.JaaqCollectionPlayerElement=Ef,t.JaaqPlayer=vf,t.JaaqVideoPlayer=hh,t.JaaqVideoPlayerElement=yf,t.isRegistered=function(){return"undefined"!=typeof window&&"undefined"!=typeof customElements&&(!!customElements.get(Tf)&&!!customElements.get(Sf))},t.registerJaaqComponents=bf});
7
+ */var gh="(prefers-reduced-motion: reduce)",ph={CREATED:1,MOUNTED:2,IDLE:3,MOVING:4,SCROLLING:5,DRAGGING:6,DESTROYED:7};function mh(t){t.length=0}function vh(t,e,i){return Array.prototype.slice.call(t,e,i)}function yh(t){return t.bind.apply(t,[null].concat(vh(arguments,1)))}var Eh=setTimeout,Th=function(){};function Sh(t){return requestAnimationFrame(t)}function bh(t,e){return typeof e===t}function Ah(t){return!kh(t)&&bh("object",t)}var Lh=Array.isArray,Ih=yh(bh,"function"),Rh=yh(bh,"string"),_h=yh(bh,"undefined");function kh(t){return null===t}function wh(t){try{return t instanceof(t.ownerDocument.defaultView||window).HTMLElement}catch(t){return!1}}function Dh(t){return Lh(t)?t:[t]}function xh(t,e){Dh(t).forEach(e)}function Ph(t,e){return t.indexOf(e)>-1}function Ch(t,e){return t.push.apply(t,Dh(e)),t}function Mh(t,e,i){t&&xh(e,function(e){e&&t.classList[i?"add":"remove"](e)})}function Oh(t,e){Mh(t,Rh(e)?e.split(" "):e,!0)}function Fh(t,e){xh(e,t.appendChild.bind(t))}function Nh(t,e){xh(t,function(t){var i=(e||t).parentNode;i&&i.insertBefore(t,e)})}function $h(t,e){return wh(t)&&(t.msMatchesSelector||t.matches).call(t,e)}function Bh(t,e){var i=t?vh(t.children):[];return e?i.filter(function(t){return $h(t,e)}):i}function Uh(t,e){return e?Bh(t,e)[0]:t.firstElementChild}var Gh=Object.keys;function jh(t,e,i){return t&&(i?Gh(t).reverse():Gh(t)).forEach(function(i){"__proto__"!==i&&e(t[i],i)}),t}function qh(t){return vh(arguments,1).forEach(function(e){jh(e,function(i,s){t[s]=e[s]})}),t}function Kh(t){return vh(arguments,1).forEach(function(e){jh(e,function(e,i){Lh(e)?t[i]=e.slice():Ah(e)?t[i]=Kh({},Ah(t[i])?t[i]:{},e):t[i]=e})}),t}function Vh(t,e){xh(e||Gh(t),function(e){delete t[e]})}function Hh(t,e){xh(t,function(t){xh(e,function(e){t&&t.removeAttribute(e)})})}function Yh(t,e,i){Ah(e)?jh(e,function(e,i){Yh(t,i,e)}):xh(t,function(t){kh(i)||""===i?Hh(t,e):t.setAttribute(e,String(i))})}function Wh(t,e,i){var s=document.createElement(t);return e&&(Rh(e)?Oh(s,e):Yh(s,e)),i&&Fh(i,s),s}function zh(t,e,i){if(_h(i))return getComputedStyle(t)[e];kh(i)||(t.style[e]=""+i)}function Xh(t,e){zh(t,"display",e)}function Qh(t){t.setActive&&t.setActive()||t.focus({preventScroll:!0})}function Jh(t,e){return t.getAttribute(e)}function Zh(t,e){return t&&t.classList.contains(e)}function tc(t){return t.getBoundingClientRect()}function ec(t){xh(t,function(t){t&&t.parentNode&&t.parentNode.removeChild(t)})}function ic(t){return Uh((new DOMParser).parseFromString(t,"text/html").body)}function sc(t,e){t.preventDefault(),e&&(t.stopPropagation(),t.stopImmediatePropagation())}function nc(t,e){return t&&t.querySelector(e)}function rc(t,e){return e?vh(t.querySelectorAll(e)):[]}function ac(t,e){Mh(t,e,!1)}function oc(t){return t.timeStamp}function lc(t){return Rh(t)?t:t?t+"px":""}var dc="splide",hc="data-"+dc;function cc(t,e){if(!t)throw new Error("["+dc+"] "+(e||""))}var uc=Math.min,fc=Math.max,gc=Math.floor,pc=Math.ceil,mc=Math.abs;function vc(t,e,i){return mc(t-e)<i}function yc(t,e,i,s){var n=uc(e,i),r=fc(e,i);return s?n<t&&t<r:n<=t&&t<=r}function Ec(t,e,i){var s=uc(e,i),n=fc(e,i);return uc(fc(s,t),n)}function Tc(t){return+(t>0)-+(t<0)}function Sc(t,e){return xh(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){xh(t,function(t){t&&xh(e,function(e){e.split(" ").forEach(function(e){var s=e.split(".");i(t,s[0],s[1])})})})}return{bind:function(i,s,n,r){e(i,s,function(e,i,s){var a="addEventListener"in e,o=a?e.removeEventListener.bind(e,i,n,r):e.removeListener.bind(e,n);a?e.addEventListener(i,n,r):e.addListener(n),t.push([e,i,s,n,o])})},unbind:function(i,s,n){e(i,s,function(e,i,s){t=t.filter(function(t){return!!(t[0]!==e||t[1]!==i||t[2]!==s||n&&t[3]!==n)||(t[4](),!1)})})},dispatch:function(t,e,i){var s,n=!0;return"function"==typeof CustomEvent?s=new CustomEvent(e,{bubbles:n,detail:i}):(s=document.createEvent("CustomEvent")).initCustomEvent(e,n,!1,i),t.dispatchEvent(s),s},destroy:function(){t.forEach(function(t){t[4]()}),mh(t)}}}var Ic="mounted",Rc="ready",_c="move",kc="moved",wc="click",Dc="active",xc="inactive",Pc="visible",Cc="hidden",Mc="refresh",Oc="updated",Fc="resize",Nc="resized",$c="scroll",Bc="scrolled",Uc="destroy",Gc="arrows:mounted",jc="navigation:mounted",qc="autoplay:play",Kc="autoplay:pause",Vc="lazyload:loaded",Hc="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),qh(i,{bus:e,on:function(t,s){i.bind(e,Dh(t).join(" "),function(t){s.apply(s,Lh(t.detail)?t.detail:[])})},off:yh(i.unbind,e),emit:function(t){i.dispatch(e,t,vh(arguments,1))}})}function Xc(t,e,i,s){var n,r,a=Date.now,o=0,l=!0,d=0;function h(){if(!l){if(o=t?uc((a()-n)/t,1):1,i&&i(o),o>=1&&(e(),n=a(),s&&++d>=s))return c();r=Sh(h)}}function c(){l=!0}function u(){r&&cancelAnimationFrame(r),o=0,r=0,l=!0}return{start:function(e){e||u(),n=a()-(e?o*t:0),l=!1,r=Sh(h)},rewind:function(){n=a(),o=0,i&&i(o)},pause:c,cancel:u,set:function(e){t=e},isPaused:function(){return l}}}var Qc="Arrow",Jc=Qc+"Left",Zc=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,Zc],ArrowRight:[eu,Jc]};var nu="role",ru="tabindex",au="aria-",ou=au+"controls",lu=au+"current",du=au+"selected",hu=au+"label",cu=au+"labelledby",uu=au+"hidden",fu=au+"orientation",gu=au+"roledescription",pu=au+"live",mu=au+"busy",vu=au+"atomic",yu=[nu,ru,"disabled",ou,lu,hu,cu,uu,fu,gu],Eu=dc+"__",Tu="is-",Su=dc,bu=Eu+"track",Au=Eu+"list",Lu=Eu+"slide",Iu=Lu+"--clone",Ru=Lu+"__container",_u=Eu+"arrows",ku=Eu+"arrow",wu=ku+"--prev",Du=ku+"--next",xu=Eu+"pagination",Pu=xu+"__page",Cu=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",ju=Tu+"focus-in",qu=Tu+"overflow",Ku=[Nu,Uu,$u,Bu,Gu,ju,qu],Vu={slide:Lu,clone:Iu,arrows:_u,arrow:ku,prev:wu,next:Du,pagination:xu,page:Pu,spinner:Eu+"spinner"};var Hu="touchstart mousedown",Yu="touchmove mousemove",Wu="touchend touchcancel mouseup click";var zu="slide",Xu="loop",Qu="fade";function Ju(t,e,i,s){var n,r=zc(t),a=r.on,o=r.emit,l=r.bind,d=t.Components,h=t.root,c=t.options,u=c.isNavigation,f=c.updateOnMove,g=c.i18n,p=c.pagination,m=c.slideFocus,v=d.Direction.resolve,y=Jh(s,"style"),E=Jh(s,hu),T=i>-1,S=Uh(s,"."+Ru);function b(){var n=t.splides.map(function(t){var i=t.splide.Components.Slides.getAt(e);return i?i.slide.id:""}).join(" ");Yh(s,hu,Sc(g.slideX,(T?i:e)+1)),Yh(s,ou,n),Yh(s,nu,m?"button":""),m&&Hh(s,gu)}function A(){n||L()}function L(){if(!n){var i=t.index;(r=I())!==Zh(s,Nu)&&(Mh(s,Nu,r),Yh(s,lu,u&&r||""),o(r?Dc:xc,R)),function(){var e=function(){if(t.is(Qu))return I();var e=tc(d.Elements.track),i=tc(s),n=v("left",!0),r=v("right",!0);return gc(e[n])<=pc(i[n])&&gc(i[r])<=pc(e[r])}(),i=!e&&(!I()||T);t.state.is([4,5])||Yh(s,uu,i||"");Yh(rc(s,c.focusableNodes||""),ru,i?-1:""),m&&Yh(s,ru,i?-1:0);e!==Zh(s,Uu)&&(Mh(s,Uu,e),o(e?Pc:Cc,R));if(!e&&document.activeElement===s){var n=d.Slides.getAt(t.index);n&&Qh(n.slide)}}(),Mh(s,$u,e===i-1),Mh(s,Bu,e===i+1)}var r}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=h.id+"-slide"+bc(e+1),Yh(s,nu,p?"tabpanel":"group"),Yh(s,gu,g.slide),Yh(s,hu,E||Sc(g.slideLabel,[e+1,t.length]))),l(s,"click",yh(o,wc,R)),l(s,"keydown",yh(o,Hc,R)),a([kc,Yc,Bc],L),a(jc,b),f&&a(_c,A)},destroy:function(){n=!0,r.destroy(),ac(s,Ku),Hh(s,yu),Yh(s,"style",y),Yh(s,hu,E||"")},update:L,style:function(t,e,i){zh(i&&S||s,t,e)},isWithin:function(i,s){var n=mc(i-e);return T||!c.rewind&&!t.is(Xu)||(n=uc(n,t.length-n)),n<=s}};return R}var Zu=hc+"-interval";var tf={passive:!1,capture:!0};var ef={Spacebar:" ",Right:Zc,Left:Jc,Up:tu,Down:eu};function sf(t){return t=Rh(t)?t:t.key,ef[t]||t}var nf="keydown";var rf=hc+"-lazy",af=rf+"-srcset",of="["+rf+"], ["+af+"]";var lf=[" ","Enter"];var df=Object.freeze({__proto__:null,Media:function(t,e,i){var s=t.state,n=i.breakpoints||{},r=i.reducedMotion||{},a=Lc(),o=[];function l(t){t&&a.destroy()}function d(t,e){var i=matchMedia(e);a.bind(i,"change",h),o.push([t,i])}function h(){var e=s.is(7),n=i.direction,r=o.reduce(function(t,e){return Kh(t,e[1].matches?e[0]:{})},{});Vh(i),c(r),i.destroy?t.destroy("completely"===i.destroy):e?(l(!0),t.mount()):n!==i.direction&&t.refresh()}function c(e,n,r){Kh(i,e),n&&Kh(Object.getPrototypeOf(i),e),!r&&s.is(1)||t.emit(Oc,i)}return{setup:function(){var t="min"===i.mediaQuery;Gh(n).sort(function(e,i){return t?+e-+i:+i-+e}).forEach(function(e){d(n[e],"("+(t?"min":"max")+"-width:"+e+"px)")}),d(r,gh),h()},destroy:l,reduce:function(t){matchMedia(gh).matches&&(t?Kh(i,r):Vh(i,Gh(r)))},set:c}},Direction:function(t,e,i){return{resolve:function(t,e,s){var n="rtl"!==(s=s||i.direction)||e?s===iu?0:-1:1;return su[t]&&su[t][n]||t.replace(/width|left|right/i,function(t,e){var i=su[t.toLowerCase()][n]||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,n,r,a=zc(t),o=a.on,l=a.bind,d=t.root,h=i.i18n,c={},u=[],f=[],g=[];function p(){s=y("."+bu),n=Uh(s,"."+Au),cc(s&&n,"A track/list element is missing."),Ch(u,Bh(n,"."+Lu+":not(."+Iu+")")),jh({arrows:_u,pagination:xu,prev:wu,next:Du,bar:Cu,toggle:Mu},function(t,e){c[e]=y("."+t)}),qh(c,{root:d,track:s,list:n,slides:u}),function(){var t=d.id||(r=dc,""+r+bc(Ac[r]=(Ac[r]||0)+1)),e=i.role;var r;d.id=t,s.id=s.id||t+"-track",n.id=n.id||t+"-list",!Jh(d,nu)&&"SECTION"!==d.tagName&&e&&Yh(d,nu,e);Yh(d,gu,h.carousel),Yh(n,nu,"presentation")}(),v()}function m(t){var e=yu.concat("style");mh(u),ac(d,f),ac(s,g),Hh([s,n],e),Hh(d,t?e:["style",gu])}function v(){ac(d,f),ac(s,g),f=E(Su),g=E(bu),Oh(d,f),Oh(s,g),Yh(d,hu,i.label),Yh(d,cu,i.labelledby)}function y(t){var e=nc(d,t);return e&&function(t,e){if(Ih(t.closest))return t.closest(e);for(var i=t;i&&1===i.nodeType&&!$h(i,e);)i=i.parentElement;return i}(e,"."+Su)===d?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 qh(c,{setup:p,mount:function(){o(Mc,m),o(Mc,p),o(Oc,v),l(document,Hu+" keydown",function(t){r="keydown"===t.type},{capture:!0}),l(d,"focusin",function(){Mh(d,ju,!!r)})},destroy:m})},Slides:function(t,e,i){var s=zc(t),n=s.on,r=s.emit,a=s.bind,o=e.Elements,l=o.slides,d=o.list,h=[];function c(){l.forEach(function(t,e){f(t,e,-1)})}function u(){p(function(t){t.destroy()}),mh(h)}function f(e,i,s){var n=Ju(t,i,s,e);n.mount(),h.push(n),h.sort(function(t,e){return t.index-e.index})}function g(t){return t?m(function(t){return!t.isClone}):h}function p(t,e){g(e).forEach(t)}function m(t){return h.filter(Ih(t)?t:function(e){return Rh(t)?$h(e.slide,t):Ph(Dh(t),e.index)})}return{mount:function(){c(),n(Mc,u),n(Mc,c)},destroy:u,update:function(){p(function(t){t.update()})},register:f,get:g,getIn:function(t){var s=e.Controller,n=s.toIndex(t),r=s.hasFocus()?1:i.perPage;return m(function(t){return yc(t.index,n,n+r-1)})},getAt:function(t){return m(t)[0]},add:function(t,e){xh(t,function(t){if(Rh(t)&&(t=ic(t)),wh(t)){var s=l[e];s?Nh(t,s):Fh(d,t),Oh(t,i.classes.slide),n=t,o=yh(r,Fc),h=rc(n,"img"),(c=h.length)?h.forEach(function(t){a(t,"load error",function(){--c||o()})}):o()}var n,o,h,c}),r(Mc)},remove:function(t){ec(m(t).map(function(t){return t.slide})),r(Mc)},forEach:p,filter:m,style:function(t,e,i){p(function(s){s.style(t,e,i)})},getLength:function(t){return t?l.length:h.length},isEnough:function(){return h.length>i.perPage}}},Layout:function(t,e,i){var s,n,r,a=zc(t),o=a.on,l=a.bind,d=a.emit,h=e.Slides,c=e.Direction.resolve,u=e.Elements,f=u.root,g=u.track,p=u.list,m=h.getAt,v=h.style;function y(){s=i.direction===iu,zh(f,"maxWidth",lc(i.width)),zh(g,c("paddingLeft"),T(!1)),zh(g,c("paddingRight"),T(!0)),E(!0)}function E(t){var e=tc(f);(t||n.width!==e.width||n.height!==e.height)&&(zh(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),n=e,d(Nc),r!==(r=k())&&(Mh(f,qu,r),d("overflow",r)))}function T(t){var e=i.padding,s=c(t?"right":"left");return e&&lc(e[s]||(Ah(e)?0:e))||"0px"}function S(){return lc(i.height||tc(p).width*i.heightRatio)}function b(){var t=lc(i.gap);return"calc((100%"+(t&&" + "+t)+")/"+(i.perPage||1)+(t&&" - "+t)+")"}function A(){return tc(p)[c("width")]}function L(t,e){var i=m(t||0);return i?tc(i.slide)[c("width")]+(e?0:_()):0}function I(t,e){var i=m(t);if(i){var s=tc(i.slide)[c("right")],n=tc(p)[c("left")];return mc(s-n)+(e?0:_())}return 0}function R(e){return I(t.length-1)-I(0)+L(0,e)}function _(){var t=m(0);return t&&parseFloat(zh(t.slide,c("marginRight")))||0}function k(){return t.is(Qu)||R(!0)>A()}return{mount:function(){var t,e;y(),l(window,"resize load",(t=yh(d,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(zh(g,c("padding"+(t?"Right":"Left"))))||0},isOverflow:k}},Clones:function(t,e,i){var s,n=zc(t),r=n.on,a=e.Elements,o=e.Slides,l=e.Direction.resolve,d=[];function h(){r(Mc,c),r([Oc,Fc],f),(s=g())&&(!function(e){var s=o.get().slice(),n=s.length;if(n){for(;s.length<e;)Ch(s,s);Ch(s.slice(-e),s.slice(0,e)).forEach(function(r,l){var h=l<e,c=function(e,s){var n=e.cloneNode(!0);return Oh(n,i.classes.clone),n.id=t.root.id+"-clone"+bc(s+1),n}(r.slide,l);h?Nh(c,s[0].slide):Fh(a.list,c),Ch(d,c),o.register(c,l-e+(h?0:n),r.index)})}}(s),e.Layout.resize(!0))}function c(){u(),h()}function u(){ec(d),mh(d),n.destroy()}function f(){var t=g();s!==t&&(s<t||!t)&&n.emit(Mc)}function g(){var s=i.clones;if(t.is(Xu)){if(_h(s)){var n=i[l("fixedWidth")]&&e.Layout.slideSize(0);s=n&&pc(tc(a.track)[l("width")]/n)||i[l("autoWidth")]&&t.length||2*i.perPage}}else s=0;return s}return{mount:h,destroy:u}},Move:function(t,e,i){var s,n=zc(t),r=n.on,a=n.emit,o=t.state.set,l=e.Layout,d=l.slideSize,h=l.getPadding,c=l.totalSize,u=l.listSize,f=l.sliderSize,g=e.Direction,p=g.resolve,m=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 n=s?i:function(i){if(t.is(Xu)){var s=I(i),n=s>e.Controller.getEnd();(s<0||n)&&(i=A(i,n))}return i}(i);zh(y,"transform","translate"+p("X")+"("+n+"px)"),i!==n&&a(Yc)}}function A(t,e){var i=t-k(e),s=f();return t-=m(s*(pc(mc(i)/s)||1))*(e?1:-1)}function L(){b(_(),!0),s.cancel()}function I(t){for(var i=e.Slides.get(),s=0,n=1/0,r=0;r<i.length;r++){var a=i[r].index,o=mc(R(a,!0)-t);if(!(o<=n))break;n=o,s=a}return s}function R(e,s){var n=m(c(e-1)-function(t){var e=i.focus;return"center"===e?(u()-d(t,!0))/2:+e*d(t)||0}(e));return s?function(e){i.trimSpace&&t.is(zu)&&(e=Ec(e,0,m(f(!0)-u())));return e}(n):n}function _(){var t=p("left");return tc(y)[t]-tc(E)[t]+m(h(!1))}function k(t){return R(t?e.Controller.getEnd():0,!!i.trimSpace)}return{mount:function(){s=e.Transition,r([Ic,Nc,Oc,Mc],T)},move:function(t,e,i,n){var r,l;t!==e&&(r=t>i,l=m(A(_(),r)),r?l>=0:l<=y[p("scrollWidth")]-tc(E)[p("width")])&&(L(),b(A(_(),t>i),!0)),o(4),a(_c,e,i,t),s.start(e,function(){o(3),a(kc,e,i,t),n&&n()})},jump:S,translate:b,shift:A,cancel:L,toIndex:I,toPosition:R,getPosition:_,getLimit:k,exceededLimit:function(t,e){e=_h(e)?_():e;var i=!0!==t&&m(e)<m(k(!1)),s=!1!==t&&m(e)>m(k(!0));return i||s},reposition:T}},Controller:function(t,e,i){var s,n,r,a,o=zc(t),l=o.on,d=o.emit,h=e.Move,c=h.getPosition,u=h.getLimit,f=h.toPosition,g=e.Slides,p=g.isEnough,m=g.getLength,v=i.omitEnd,y=t.is(Xu),E=t.is(zu),T=yh(R,!1),S=yh(R,!0),b=i.start||0,A=b;function L(){n=m(!0),r=i.perMove,a=i.perPage,s=w();var t=Ec(b,0,v?s:n-1);t!==b&&(b=t,h.reposition())}function I(){s!==w()&&d(Wc)}function R(t,e){var i=r||(C()?1:a),n=_(b+i*(t?-1:1),b,!(r||C()));return-1===n&&E&&!vc(c(),u(!t),1)?t?0:s:e?n:k(n)}function _(e,o,l){if(p()||C()){var d=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);d!==e&&(o=e,e=d,l=!1),e<0||e>s?e=r||!yc(0,e,o,!0)&&!yc(s,o,e,!0)?y?l?e<0?-(n%a||a):n:e:i.rewind?e<0?s:0:-1:D(x(e)):l&&e!==o&&(e=D(x(o)+(e<o?-1:1)))}else e=-1;return e}function k(t){return y?(t+n)%n||0:t}function w(){for(var t=n-(C()||y&&r?1:a);v&&t-- >0;)if(f(n-1,!0)!==f(t,!0)){t++;break}return Ec(t,0,n-1)}function D(t){return Ec(C()?t:a*t,0,s)}function x(t){return C()?uc(t,s):gc((t>=s?n-1:t)/a)}function P(t){t!==b&&(A=b,b=t)}function C(){return!_h(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 n=function(t){var e=b;if(Rh(t)){var i=t.match(/([+\-<>])(\d+)?/)||[],n=i[1],r=i[2];"+"===n||"-"===n?e=_(b+ +(""+n+(+r||1)),b):">"===n?e=r?D(+r):T(!0):"<"===n&&(e=S(!0))}else e=y?t:Ec(t,0,s);return e}(t),r=k(n);r>-1&&(e||r!==b)&&(P(r),h.move(n,r,A,i))}},scroll:function(t,i,n,r){e.Scroll.scroll(t,i,n,function(){var t=k(h.toIndex(c()));P(v?uc(t,s):t),r&&r()})},getNext:T,getPrev:S,getAdjacent:R,getEnd:w,setIndex:P,getIndex:function(t){return t?A:b},toIndex:D,toPage:x,toDest:function(t){var e=h.toIndex(t);return E?Ec(e,0,s):e},hasFocus:C,isBusy:M}},Arrows:function(t,e,i){var s,n,r=zc(t),a=r.on,o=r.bind,l=r.emit,d=i.classes,h=i.i18n,c=e.Elements,u=e.Controller,f=c.arrows,g=c.track,p=f,m=c.prev,v=c.next,y={};function E(){!function(){var t=i.arrows;!t||m&&v||(p=f||Wh("div",d.arrows),m=A(!0),v=A(!1),s=!0,Fh(p,[m,v]),!f&&Nh(p,g));m&&v&&(qh(y,{prev:m,next:v}),Xh(p,t?"":"none"),Oh(p,n=_u+"--"+i.direction),t&&(a([Ic,kc,Mc,Bc,Wc],L),o(v,"click",yh(b,">")),o(m,"click",yh(b,"<")),L(),Yh([m,v],ou,g.id),l(Gc,m,v)))}(),a(Oc,T)}function T(){S(),E()}function S(){r.destroy(),ac(p,n),s?(ec(f?[m,v]:p),m=v=null):Hh([m,v],yu)}function b(t){u.go(t,!0)}function A(t){return ic('<button class="'+d.arrow+" "+(t?d.prev:d.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(m&&v){var e=t.index,i=u.getPrev(),s=u.getNext(),n=i>-1&&e<i?h.last:h.prev,r=s>-1&&e>s?h.first:h.next;m.disabled=i<0,v.disabled=s<0,Yh(m,hu,n),Yh(v,hu,r),l("arrows:updated",m,v,i,s)}}return{arrows:y,mount:E,destroy:S,update:L}},Autoplay:function(t,e,i){var s,n,r=zc(t),a=r.on,o=r.bind,l=r.emit,d=Xc(i.interval,t.go.bind(t,">"),function(t){var e=c.bar;e&&zh(e,"width",100*t+"%"),l("autoplay:playing",t)}),h=d.isPaused,c=e.Elements,u=e.Elements,f=u.root,g=u.toggle,p=i.autoplay,m="pause"===p;function v(){h()&&e.Slides.isEnough()&&(d.start(!i.resetProgress),n=s=m=!1,T(),l(qc))}function y(t){void 0===t&&(t=!0),m=!!t,T(),h()||(d.pause(),l(Kc))}function E(){m||(s||n?y(!1):v())}function T(){g&&(Mh(g,Nu,!m),Yh(g,hu,i.i18n[m?"play":"pause"]))}function S(t){var s=e.Slides.getAt(t);d.set(s&&+Jh(s.slide,Zu)||i.interval)}return{mount:function(){p&&(!function(){i.pauseOnHover&&o(f,"mouseenter mouseleave",function(t){s="mouseenter"===t.type,E()});i.pauseOnFocus&&o(f,"focusin focusout",function(t){n="focusin"===t.type,E()});g&&o(g,"click",function(){m?v():y(!0)});a([_c,$c,Mc],d.rewind),a(_c,S)}(),g&&Yh(g,ou,c.track.id),m||v(),T())},destroy:d.cancel,play:v,pause:y,isPaused:h}},Cover:function(t,e,i){var s=zc(t).on;function n(t){e.Slides.forEach(function(e){var i=Uh(e.container||e.slide,"img");i&&i.src&&r(t,i,e)})}function r(t,e,i){i.style("background",t?'center/cover no-repeat url("'+e.src+'")':"",!0),Xh(e,t?"none":"")}return{mount:function(){i.cover&&(s(Vc,yh(r,!0)),s([Ic,Oc,Mc],yh(n,!0)))},destroy:yh(n,!1)}},Scroll:function(t,e,i){var s,n,r=zc(t),a=r.on,o=r.emit,l=t.state.set,d=e.Move,h=d.getPosition,c=d.getLimit,u=d.exceededLimit,f=d.translate,g=t.is(zu),p=1;function m(t,i,r,a,c){var f=h();if(E(),r&&(!g||!u())){var m=e.Layout.sliderSize(),T=Tc(t)*m*gc(mc(t)/m)||0;t=d.toPosition(e.Controller.toDest(t%m))+T}var S=vc(f,t,1);p=1,i=S?0:i||fc(mc(t-f)/1.5,800),n=a,s=Xc(i,v,yh(y,f,t,c),1),l(5),o($c),s.start()}function v(){l(3),n&&n(),o(Bc)}function y(t,e,s,r){var a,o,l=h(),d=(t+(e-t)*(a=r,(o=i.easingFunc)?o(a):1-Math.pow(1-a,4))-l)*p;f(l+d),g&&!s&&u()&&(p*=.6,mc(d)<10&&m(c(u(!0)),600,!1,n,!0))}function E(){s&&s.cancel()}function T(){s&&!s.isPaused()&&(E(),v())}return{mount:function(){a(_c,E),a([Oc,Mc],T)},destroy:E,scroll:m,cancel:T}},Drag:function(t,e,i){var s,n,r,a,o,l,d,h,c=zc(t),u=c.on,f=c.emit,g=c.bind,p=c.unbind,m=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,_=!1;function k(){var t=i.drag;B(!t),a="free"===t}function w(t){if(l=!1,!d){var e=$(t);s=t.target,n=i.noDrag,$h(s,"."+Pu+", ."+ku)||n&&$h(s,n)||!e&&t.button||(E.isBusy()?sc(t,!0):(h=e?T:window,o=m.is([4,5]),r=null,g(h,Yu,D,tf),g(h,Wu,x,tf),v.cancel(),y.cancel(),C(t)))}var s,n}function D(e){if(m.is(6)||(m.set(6),f("drag")),e.cancelable)if(o){v.translate(s+M(e)/(_&&t.is(zu)?5:1));var n=O(e)>200,r=_!==(_=R());(n||r)&&C(e),l=!0,f("dragging"),sc(e)}else(function(t){return mc(M(t))>mc(M(t,!0))})(e)&&(o=function(t){var e=i.dragMinThreshold,s=Ah(e),n=s&&e.mouse||0,r=(s?e.touch:+e)||10;return mc(M(t))>($(t)?r:n)}(e),sc(e))}function x(s){m.is(6)&&(m.set(3),f("dragged")),o&&(!function(s){var n=function(e){if(t.is(Xu)||!_){var i=O(e);if(i&&i<200)return M(e)/i}return 0}(s),r=function(t){return I()+Tc(t)*uc(mc(t)*(i.flickPower||600),a?1/0:e.Layout.listSize()*(i.flickMaxPages||1))}(n),o=i.rewind&&i.rewindByDrag;S(!1),a?E.scroll(r,0,i.snap):t.is(Qu)?E.go(L(Tc(n))<0?o?"<":"-":o?">":"+"):t.is(zu)&&_&&o?E.go(R(!0)?">":"<"):E.go(E.toDest(r),!0);S(!0)}(s),sc(s)),p(h,Yu,D),p(h,Wu,x),o=!1}function P(t){!d&&l&&sc(t,!0)}function C(t){r=n,n=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 n===t&&r||n}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){d=t}return{mount:function(){g(T,Yu,Th,tf),g(T,Wu,Th,tf),g(T,Hu,w,tf),g(T,"click",P,{capture:!0}),g(T,"dragstart",sc),u([Ic,Oc],k)},disable:B,isDragging:function(){return o}}},Keyboard:function(t,e,i){var s,n,r=zc(t),a=r.on,o=r.bind,l=r.unbind,d=t.root,h=e.Direction.resolve;function c(){var t=i.keyboard;t&&(s="global"===t?window:d,o(s,nf,g))}function u(){l(s,nf)}function f(){var t=n;n=!0,Eh(function(){n=t})}function g(e){if(!n){var i=sf(e);i===h(Jc)?t.go("<"):i===h(Zc)&&t.go(">")}}return{mount:function(){c(),a(Oc,u),a(Oc,c),a(_c,f)},destroy:u,disable:function(t){n=t}}},LazyLoad:function(t,e,i){var s=zc(t),n=s.on,r=s.off,a=s.bind,o=s.emit,l="sequential"===i.lazyLoad,d=[kc,Bc],h=[];function c(){mh(h),e.Slides.forEach(function(t){rc(t.slide,of).forEach(function(e){var s=Jh(e,rf),n=Jh(e,af);if(s!==e.src||n!==e.srcset){var r=i.classes.spinner,a=e.parentElement,o=Uh(a,"."+r)||Wh("span",r,a);h.push([e,t,o]),e.src||Xh(e,"none")}})}),l?p():(r(d),n(d,u),u())}function u(){(h=h.filter(function(e){var s=i.perPage*((i.preloadPages||1)+1)-1;return!e[1].isWithin(t.index,s)||f(e)})).length||r(d)}function f(t){var e=t[0];Oh(t[1].slide,Gu),a(e,"load error",yh(g,t)),Yh(e,"src",Jh(e,rf)),Yh(e,"srcset",Jh(e,af)),Hh(e,rf),Hh(e,af)}function g(t,e){var i=t[0],s=t[1];ac(s.slide,Gu),"error"!==e.type&&(ec(t[2]),Xh(i,""),o(Vc,i,s),o(Fc)),l&&p()}function p(){h.length&&f(h.shift())}return{mount:function(){i.lazyLoad&&(c(),n(Mc,c))},destroy:yh(mh,h),check:u}},Pagination:function(t,e,i){var s,n,r=zc(t),a=r.on,o=r.emit,l=r.bind,d=e.Slides,h=e.Elements,c=e.Controller,u=c.hasFocus,f=c.getIndex,g=c.go,p=e.Direction.resolve,m=h.pagination,v=[];function y(){s&&(ec(m?vh(s.children):s),ac(s,n),mh(v),s=null),r.destroy()}function E(t){g(">"+t,!0)}function T(t,e){var i=v.length,s=sf(e),n=S(),r=-1;s===p(Zc,!1,n)?r=++t%i:s===p(Jc,!1,n)?r=(--t+i)%i:"Home"===s?r=0:"End"===s&&(r=i-1);var a=v[r];a&&(Qh(a.button),g(">"+r),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),Hh(i,du),Yh(i,ru,-1)}if(e){var n=e.button;Oh(n,Nu),Yh(n,du,!0),Yh(n,ru,"")}o("pagination:updated",{list:s,items:v},t,e)}return{items:v,mount:function e(){y(),a([Oc,Mc,Wc],e);var r=i.pagination;m&&Xh(m,r?"":"none"),r&&(a([_c,$c,Bc],A),function(){var e=t.length,r=i.classes,a=i.i18n,o=i.perPage,f=u()?c.getEnd()+1:pc(e/o);Oh(s=m||Wh("ul",r.pagination,h.track.parentElement),n=xu+"--"+S()),Yh(s,nu,"tablist"),Yh(s,hu,a.select),Yh(s,fu,S()===iu?"vertical":"");for(var g=0;g<f;g++){var p=Wh("li",null,s),y=Wh("button",{class:r.page,type:"button"},p),b=d.getIn(g).map(function(t){return t.slide.id}),A=!u()&&o>1?a.pageX:a.slideX;l(y,"click",yh(E,g)),i.paginationKeyboard&&l(y,"keydown",yh(T,g)),Yh(p,nu,"presentation"),Yh(y,nu,"tab"),Yh(y,ou,b.join(" ")),Yh(y,hu,Sc(A,g+1)),Yh(y,ru,-1),v.push({li:p,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,n=i.slideFocus,r=[];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)(wc,h),i(Hc,c),i([Ic,Oc],d),r.push(e),e.emit(jc,t.splides))}function o(){r.forEach(function(t){t.destroy()}),mh(r)}function l(t,e){var i=zc(t);i.on(_c,function(t,i,s){e.go(e.is(Xu)?s:t)}),r.push(i)}function d(){Yh(e.Elements.list,fu,i.direction===iu?"vertical":"")}function h(e){t.go(e.index)}function c(t,e){Ph(lf,sf(e))&&(h(t),sc(e))}return{setup:yh(e.Media.set,{slideFocus:_h(n)?s:n},!0),mount:a,destroy:o,remount:function(){o(),a()}}},Wheel:function(t,e,i){var s=zc(t).bind,n=0;function r(s){if(s.cancelable){var r=s.deltaY,a=r<0,o=oc(s),l=i.wheelMinThreshold||0,d=i.wheelSleep||0;mc(r)>l&&o-n>d&&(t.go(a?"<":">"),n=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",r,tf)}}},Live:function(t,e,i){var s=zc(t).on,n=e.Elements.track,r=i.live&&!i.isNavigation,a=Wh("span",Ou),o=Xc(90,yh(l,!1));function l(t){Yh(n,mu,t),t?(Fh(n,a),o.start()):(ec(a),o.cancel())}function d(t){r&&Yh(n,pu,t?"off":"polite")}return{mount:function(){r&&(d(!e.Autoplay.isPaused()),Yh(n,vu,!0),a.textContent="…",s(qc,yh(d,!0)),s(Kc,yh(d,!1)),s([kc,Bc],yh(l,!0)))},disable:d,destroy:function(){Hh(n,[pu,vu,mu]),ec(a)}}}}),hf={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 cf(t,e,i){var s=e.Slides;function n(){s.forEach(function(t){t.style("transform","translateX(-"+100*t.index+"%)")})}return{mount:function(){zc(t).on([Ic,Mc],n)},start:function(t,e){s.style("transition","opacity "+i.speed+"ms "+i.easing),Eh(e)},cancel:Th}}function uf(t,e,i){var s,n=e.Move,r=e.Controller,a=e.Scroll,o=e.Elements.list,l=yh(zh,o,"transition");function d(){l(""),a.cancel()}return{mount:function(){zc(t).bind(o,"transitionend",function(t){t.target===o&&s&&(d(),s())})},start:function(e,o){var d=n.toPosition(e,!0),h=n.getPosition(),c=function(e){var s=i.rewindSpeed;if(t.is(zu)&&s){var n=r.getIndex(!0),a=r.getEnd();if(0===n&&e>=a||n>=a&&0===e)return s}return i.speed}(e);mc(d-h)>=1&&c>=1?i.useScroll?a.scroll(d,c,!1,o):(l("transform "+c+"ms "+i.easing),n.translate(d,!0),s=o):(n.jump(e),o())},cancel:d}}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 Ph(Dh(t),s)}}),this.splides=[],this._o={},this._E={};var n=Rh(e)?nc(document,e):e;cc(n,n+" is invalid."),this.root=n,i=Kh({label:Jh(n,hu)||"",labelledby:Jh(n,cu)||""},hf,t.defaults,i||{});try{Kh(i,JSON.parse(Jh(n,hc)))}catch(t){cc(!1,"Invalid JSON")}this._o=Object.create(Kh({},i))}var e=t.prototype;return e.mount=function(t,e){var i=this,s=this.state,n=this.Components;return cc(s.is([1,7]),"Already mounted!"),s.set(1),this._C=n,this._T=e||this._T||(this.is(Qu)?cf:uf),this._E=t||this._E,jh(qh({},df,this._E,{Transition:this._T}),function(t,e){var s=t(i,n,i._o);n[e]=s,s.setup&&s.setup()}),jh(n,function(t){t.mount&&t.mount()}),this.emit(Ic),Oh(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(vh(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)):(jh(this._C,function(e){e.destroy&&e.destroy(t)},!0),e.emit(Uc),e.destroy(),t&&mh(this.splides),i.set(7)),this},fh(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=ph,function(){if("undefined"!=typeof document){const t="jaaq-styles-splide.min";if(!document.getElementById(t)){const e=document.createElement("style");e.id=t,e.textContent=".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}",document.head.appendChild(e)}}}();const pf=new WeakMap,mf=[];function vf(t){if(pf.has(t))return pf.get(t);const e=function(t){const e=t.getAttribute("data-api-key"),i=t.getAttribute("data-client-id"),s=t.getAttribute("data-video-id");if(!e||!i||!s)return console.error("JAAQ Player: Missing required attributes (data-api-key, data-client-id, data-video-id)",t),null;const n={apiKey:e,clientId:i,videoId:s},r=t.getAttribute("data-autoplay");null!==r&&(n.autoplay="true"===r);const a=t.getAttribute("data-width");a&&(n.width=a);const o=t.getAttribute("data-height");o&&(n.height=o);const l=t.getAttribute("data-base-url");l&&(n.baseUrl=l);const d=t.getAttribute("data-api-version");d&&(n.apiVersion=d);const h=t.getAttribute("data-class-name");return h&&(n.className=h),n}(t);if(!e)return null;try{const i=new uh(t,e);return pf.set(t,i),mf.push({element:t,player:i}),i}catch(e){return console.error("JAAQ Player: Failed to initialize player",e,t),null}}function yf(t=document){t.querySelectorAll("[data-jaaq-player]").forEach(t=>{vf(t)})}const Ef={init:yf,getPlayer:function(t){let e;if("string"==typeof t){if(e=document.querySelector(t),!e)return console.error("JAAQ Player: Element not found for selector",t),null}else e=t;return pf.get(e)||null},destroyAll:function(){mf.forEach(({element:t,player:e})=>{try{e.destroy(),pf.delete(t)}catch(t){console.error("JAAQ Player: Error destroying player",t)}}),mf.length=0}};"undefined"!=typeof window&&"undefined"!=typeof document&&("loading"===document.readyState?document.addEventListener("DOMContentLoaded",()=>{yf()}):yf());class Tf 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 ${ch}\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,n=this.getAttribute("api-version")||void 0,r=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"),d=!this.hasAttribute("show-author")||"false"!==this.getAttribute("show-author"),h=!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 uh(this.container,{videoId:t??void 0,apiKey:e??void 0,clientId:i??void 0,client:this.clientInstance||void 0,baseUrl:s,apiVersion:n,autoplay:r,controls:a,showLogo:o,showTitle:l,showAuthor:d,showDescription:h,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(){if("undefined"!=typeof document){const t="jaaq-styles-CollectionPlayer";if(!document.getElementById(t)){const e=document.createElement("style");e.id=t,e.textContent=".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",document.head.appendChild(e)}}}();class Sf 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 ${ch}\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,n=this.getAttribute("api-version")||void 0;if(this.clientInstance||e||i){this.showLoading();try{const r=this.clientInstance||oh.init({apiKey:e,clientId:i,baseUrl:s||ah,apiVersion:n});this.collectionData=await r.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"),n=this.getAttribute("base-url"),r=this.getAttribute("video-settings");let a=null;if(r)try{a=JSON.parse(r)}catch(t){console.warn("[CollectionPlayer] Failed to parse video-settings attribute",t)}this.getVideosFromCollection(this.collectionData).forEach(t=>{const r=document.createElement("li");r.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),n&&o.setAttribute("base-url",n),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))),r.appendChild(o),e.appendChild(r)}),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"),n=s?.getAttribute("video-id");console.log("[CollectionPlayer] Active slide from DOM:",{activeIndex:t,activeVideoId:n,foundActiveSlide:!!i});const r=this.carouselElement.querySelectorAll(".splide__slide:not(.splide__slide--clone)");Array.from(r).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")}}),r.forEach((t,i)=>{const s=t.querySelector("jaaq-video-player");if(!s)return;const n=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:n}),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 bf="jaaq-video-player",Af="jaaq-collection-player";function Lf(){"undefined"!=typeof window&&"undefined"!=typeof customElements?(customElements.get(bf)||customElements.define(bf,Tf),customElements.get(Af)||customElements.define(Af,Sf)):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",()=>{Lf()}):Lf()),t.JaaqCollectionPlayer=class{constructor(t,e){if(this.client=null,this.splide=null,this.playerElement=null,this.carouselElement=null,this.collectionData=null,this.autoplayTimeoutId=null,this.listeners=new Map,this.container="string"==typeof t?document.querySelector(t):t,!this.container)throw new Error("Container element not found");if(this.config={autoplay:!1,showArrows:!0,showDots:!0,...e},e.client)this.client=e.client;else{if(!e.apiKey||!e.clientId)throw new Error("Either client property or apiKey and clientId are required");this.client=lh({apiKey:e.apiKey,clientId:e.clientId,baseUrl:e.baseUrl||ah,apiVersion:e.apiVersion})}this.init()}async init(){this.render(),await this.initCarousel()}render(){this.container.innerHTML="",this.playerElement=document.createElement("div"),this.playerElement.className=`jaaq-collection-player ${this.config.className||""}`,this.container.appendChild(this.playerElement)}async initCarousel(){if(!this.playerElement)return;const t=this.config.collectionId;if(t){this.showLoading();try{if(!this.client)throw new Error("Client is not initialized");this.collectionData=await this.client.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.emit("loaded",this.collectionData)}catch(t){this.emitError(t instanceof Error?t:new Error("Failed to load collection"))}}else this.emitError(new Error("collectionId is required"))}showLoading(){this.playerElement&&(this.playerElement.innerHTML='\n <div class="jaaq-collection-loading">\n <div class="jaaq-collection-spinner"></div>\n </div>\n ')}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[]}renderCarousel(){if(!this.playerElement||!this.collectionData)return;this.playerElement.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";this.getVideosFromCollection(this.collectionData).forEach(t=>{const i=document.createElement("li");i.className="splide__slide";const s=document.createElement("jaaq-video-player");if(s.setAttribute("video-id",t.videoId),this.config.apiKey&&s.setAttribute("api-key",this.config.apiKey),this.config.clientId&&s.setAttribute("client-id",this.config.clientId),this.config.baseUrl&&s.setAttribute("base-url",this.config.baseUrl),this.config.apiVersion&&s.setAttribute("api-version",this.config.apiVersion),s.setAttribute("autoplay","false"),s.setAttribute("width","100%"),this.config.videoSettings){const t=this.config.videoSettings;void 0!==t.controls&&s.setAttribute("controls",String(t.controls)),void 0!==t.showLogo&&s.setAttribute("show-logo",String(t.showLogo)),void 0!==t.showTitle&&s.setAttribute("show-title",String(t.showTitle)),void 0!==t.showAuthor&&s.setAttribute("show-author",String(t.showAuthor)),void 0!==t.showDescription&&s.setAttribute("show-description",String(t.showDescription)),void 0!==t.showCaptions&&s.setAttribute("show-captions",String(t.showCaptions)),void 0!==t.startMuted&&s.setAttribute("start-muted",String(t.startMuted)),void 0!==t.width&&s.setAttribute("width",String(t.width)),void 0!==t.height&&s.setAttribute("height",String(t.height))}this.client&&void 0!==s.client&&(s.client=this.client),i.appendChild(s),e.appendChild(i)}),t.appendChild(e),this.carouselElement.appendChild(t),this.playerElement.appendChild(this.carouselElement)}initSplide(){this.carouselElement&&(this.splide=new gf(this.carouselElement,{type:"loop",perPage:3,focus:"center",gap:"0.5rem",perMove:1,autoHeight:!0,updateOnMove:!0,padding:"5rem",breakpoints:{768:{perPage:1},1024:{perPage:2}},arrows:!1!==this.config.showArrows,pagination:!1!==this.config.showDots,autoplay:!1}),this.splide.on("moved",t=>{if(this.handleSlideChange(t),this.collectionData){const e=this.getVideosFromCollection(this.collectionData);this.emit("slidechange",{index:t,video:e[t]})}}),this.splide.mount(),setTimeout(()=>{this.splide&&this.handleSlideChange(this.splide.index)},100))}handleSlideChange(t){if(!this.carouselElement)return;const e=this.config.autoplay;null!==this.autoplayTimeoutId&&(clearTimeout(this.autoplayTimeoutId),this.autoplayTimeoutId=null);this.carouselElement.querySelectorAll(".splide__slide:not(.splide__slide--clone)").forEach(t=>{const i=t.querySelector("jaaq-video-player");if(!i)return;t.classList.contains("is-active")?e&&(this.autoplayTimeoutId=window.setTimeout(()=>{i.play?.()},1e3)):i.pause?.()})}destroyCarousel(){null!==this.autoplayTimeoutId&&(clearTimeout(this.autoplayTimeoutId),this.autoplayTimeoutId=null),this.splide&&(this.splide.destroy(),this.splide=null),this.playerElement&&(this.playerElement.innerHTML=""),this.collectionData=null}emitError(t){this.playerElement&&(this.playerElement.innerHTML=`\n <div class="jaaq-collection-error">\n ${t.message}\n </div>\n `),this.emit("error",t)}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)})}refresh(){this.destroyCarousel(),this.initCarousel()}next(){this.splide?.go("+1")}prev(){this.splide?.go("-1")}go(t){this.splide?.go(t)}destroy(){this.destroyCarousel(),this.listeners.clear(),this.container.innerHTML=""}getCollection(){return this.collectionData}},t.JaaqCollectionPlayerElement=Sf,t.JaaqPlayer=Ef,t.JaaqVideoPlayer=uh,t.JaaqVideoPlayerElement=Tf,t.isRegistered=function(){return"undefined"!=typeof window&&"undefined"!=typeof customElements&&(!!customElements.get(bf)&&!!customElements.get(Af))},t.registerJaaqComponents=Lf});
8
8
  //# sourceMappingURL=jaaq-vanilla-bundled.min.js.map