@vexor-video/player 0.0.0-stage → 0.1.1

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.
@@ -0,0 +1,45 @@
1
+ "use strict";var VexorPlayer=(()=>{var Li=Object.defineProperty;var fc=Object.getOwnPropertyDescriptor;var gc=Object.getOwnPropertyNames;var mc=Object.prototype.hasOwnProperty;var pc=(n,e)=>{for(var t in e)Li(n,t,{get:e[t],enumerable:!0})},yc=(n,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of gc(e))!mc.call(n,i)&&i!==t&&Li(n,i,{get:()=>e[i],enumerable:!(s=fc(e,i))||s.enumerable});return n};var Ec=n=>yc(Li({},"__esModule",{value:!0}),n);var yg={};pc(yg,{createVexorPlayer:()=>pg});var $=Number.isFinite||function(n){return typeof n=="number"&&isFinite(n)},Tc=Number.isSafeInteger||function(n){return typeof n=="number"&&Math.abs(n)<=Sc},Sc=Number.MAX_SAFE_INTEGER||9007199254740991,W=(function(n){return n.NETWORK_ERROR="networkError",n.MEDIA_ERROR="mediaError",n.KEY_SYSTEM_ERROR="keySystemError",n.MUX_ERROR="muxError",n.OTHER_ERROR="otherError",n})({}),R=(function(n){return n.KEY_SYSTEM_NO_KEYS="keySystemNoKeys",n.KEY_SYSTEM_NO_ACCESS="keySystemNoAccess",n.KEY_SYSTEM_NO_SESSION="keySystemNoSession",n.KEY_SYSTEM_NO_CONFIGURED_LICENSE="keySystemNoConfiguredLicense",n.KEY_SYSTEM_LICENSE_REQUEST_FAILED="keySystemLicenseRequestFailed",n.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED="keySystemServerCertificateRequestFailed",n.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED="keySystemServerCertificateUpdateFailed",n.KEY_SYSTEM_SESSION_UPDATE_FAILED="keySystemSessionUpdateFailed",n.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED="keySystemStatusOutputRestricted",n.KEY_SYSTEM_STATUS_INTERNAL_ERROR="keySystemStatusInternalError",n.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR="keySystemDestroyMediaKeysError",n.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR="keySystemDestroyCloseSessionError",n.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR="keySystemDestroyRemoveSessionError",n.MANIFEST_LOAD_ERROR="manifestLoadError",n.MANIFEST_LOAD_TIMEOUT="manifestLoadTimeOut",n.MANIFEST_PARSING_ERROR="manifestParsingError",n.MANIFEST_INCOMPATIBLE_CODECS_ERROR="manifestIncompatibleCodecsError",n.LEVEL_EMPTY_ERROR="levelEmptyError",n.PLAYLIST_UNCHANGED_ERROR="playlistUnchangedError",n.LEVEL_LOAD_ERROR="levelLoadError",n.LEVEL_LOAD_TIMEOUT="levelLoadTimeOut",n.LEVEL_PARSING_ERROR="levelParsingError",n.LEVEL_SWITCH_ERROR="levelSwitchError",n.AUDIO_TRACK_LOAD_ERROR="audioTrackLoadError",n.AUDIO_TRACK_LOAD_TIMEOUT="audioTrackLoadTimeOut",n.SUBTITLE_LOAD_ERROR="subtitleTrackLoadError",n.SUBTITLE_TRACK_LOAD_TIMEOUT="subtitleTrackLoadTimeOut",n.FRAG_LOAD_ERROR="fragLoadError",n.FRAG_LOAD_TIMEOUT="fragLoadTimeOut",n.FRAG_DECRYPT_ERROR="fragDecryptError",n.FRAG_PARSING_ERROR="fragParsingError",n.FRAG_GAP="fragGap",n.REMUX_ALLOC_ERROR="remuxAllocError",n.KEY_LOAD_ERROR="keyLoadError",n.KEY_LOAD_TIMEOUT="keyLoadTimeOut",n.BUFFER_ADD_CODEC_ERROR="bufferAddCodecError",n.BUFFER_INCOMPATIBLE_CODECS_ERROR="bufferIncompatibleCodecsError",n.BUFFER_APPEND_ERROR="bufferAppendError",n.BUFFER_APPENDING_ERROR="bufferAppendingError",n.BUFFER_APPEND_NO_PROGRESS="bufferAppendNoProgress",n.BUFFER_STALLED_ERROR="bufferStalledError",n.BUFFER_FULL_ERROR="bufferFullError",n.BUFFER_SEEK_OVER_HOLE="bufferSeekOverHole",n.BUFFER_NUDGE_ON_STALL="bufferNudgeOnStall",n.ASSET_LIST_LOAD_ERROR="assetListLoadError",n.ASSET_LIST_LOAD_TIMEOUT="assetListLoadTimeout",n.ASSET_LIST_PARSING_ERROR="assetListParsingError",n.INTERSTITIAL_ASSET_ITEM_ERROR="interstitialAssetItemError",n.INTERNAL_EXCEPTION="internalException",n.INTERNAL_ABORTED="aborted",n.ATTACH_MEDIA_ERROR="attachMediaError",n.MEDIA_SOURCE_REQUIRES_RESET="mediaSourceRequiresReset",n.UNKNOWN="unknown",n})({}),p=(function(n){return n.MEDIA_ATTACHING="hlsMediaAttaching",n.MEDIA_ATTACHED="hlsMediaAttached",n.MEDIA_DETACHING="hlsMediaDetaching",n.MEDIA_DETACHED="hlsMediaDetached",n.MEDIA_ENDED="hlsMediaEnded",n.STALL_RESOLVED="hlsStallResolved",n.BUFFER_RESET="hlsBufferReset",n.BUFFER_CODECS="hlsBufferCodecs",n.BUFFER_CREATED="hlsBufferCreated",n.BUFFER_APPENDING="hlsBufferAppending",n.BUFFER_APPENDED="hlsBufferAppended",n.BUFFER_EOS="hlsBufferEos",n.BUFFERED_TO_END="hlsBufferedToEnd",n.BUFFER_FLUSHING="hlsBufferFlushing",n.BUFFER_FLUSHED="hlsBufferFlushed",n.MANIFEST_LOADING="hlsManifestLoading",n.MANIFEST_LOADED="hlsManifestLoaded",n.MANIFEST_PARSED="hlsManifestParsed",n.LEVEL_SWITCHING="hlsLevelSwitching",n.LEVEL_SWITCHED="hlsLevelSwitched",n.LEVEL_LOADING="hlsLevelLoading",n.LEVEL_LOADED="hlsLevelLoaded",n.LEVEL_UPDATED="hlsLevelUpdated",n.LEVEL_PTS_UPDATED="hlsLevelPtsUpdated",n.LEVELS_UPDATED="hlsLevelsUpdated",n.AUDIO_TRACKS_UPDATED="hlsAudioTracksUpdated",n.AUDIO_TRACK_SWITCHING="hlsAudioTrackSwitching",n.AUDIO_TRACK_SWITCHED="hlsAudioTrackSwitched",n.AUDIO_TRACK_LOADING="hlsAudioTrackLoading",n.AUDIO_TRACK_LOADED="hlsAudioTrackLoaded",n.AUDIO_TRACK_UPDATED="hlsAudioTrackUpdated",n.SUBTITLE_TRACKS_UPDATED="hlsSubtitleTracksUpdated",n.SUBTITLE_TRACKS_CLEARED="hlsSubtitleTracksCleared",n.SUBTITLE_TRACK_SWITCH="hlsSubtitleTrackSwitch",n.SUBTITLE_TRACK_LOADING="hlsSubtitleTrackLoading",n.SUBTITLE_TRACK_LOADED="hlsSubtitleTrackLoaded",n.SUBTITLE_TRACK_UPDATED="hlsSubtitleTrackUpdated",n.SUBTITLE_FRAG_PROCESSED="hlsSubtitleFragProcessed",n.CUES_PARSED="hlsCuesParsed",n.NON_NATIVE_TEXT_TRACKS_FOUND="hlsNonNativeTextTracksFound",n.INIT_PTS_FOUND="hlsInitPtsFound",n.FRAG_LOADING="hlsFragLoading",n.FRAG_LOAD_EMERGENCY_ABORTED="hlsFragLoadEmergencyAborted",n.FRAG_LOADED="hlsFragLoaded",n.FRAG_DECRYPTED="hlsFragDecrypted",n.FRAG_PARSING_INIT_SEGMENT="hlsFragParsingInitSegment",n.FRAG_PARSING_USERDATA="hlsFragParsingUserdata",n.FRAG_PARSING_METADATA="hlsFragParsingMetadata",n.FRAG_PARSED="hlsFragParsed",n.FRAG_BUFFERED="hlsFragBuffered",n.FRAG_CHANGED="hlsFragChanged",n.FPS_DROP="hlsFpsDrop",n.FPS_DROP_LEVEL_CAPPING="hlsFpsDropLevelCapping",n.MAX_AUTO_LEVEL_UPDATED="hlsMaxAutoLevelUpdated",n.ERROR="hlsError",n.DESTROYING="hlsDestroying",n.KEY_LOADING="hlsKeyLoading",n.KEY_LOADED="hlsKeyLoaded",n.LIVE_BACK_BUFFER_REACHED="hlsLiveBackBufferReached",n.BACK_BUFFER_REACHED="hlsBackBufferReached",n.STEERING_MANIFEST_LOADED="hlsSteeringManifestLoaded",n.ASSET_LIST_LOADING="hlsAssetListLoading",n.ASSET_LIST_LOADED="hlsAssetListLoaded",n.INTERSTITIALS_UPDATED="hlsInterstitialsUpdated",n.INTERSTITIALS_BUFFERED_TO_BOUNDARY="hlsInterstitialsBufferedToBoundary",n.INTERSTITIAL_ASSET_PLAYER_CREATED="hlsInterstitialAssetPlayerCreated",n.INTERSTITIAL_STARTED="hlsInterstitialStarted",n.INTERSTITIAL_ASSET_STARTED="hlsInterstitialAssetStarted",n.INTERSTITIAL_ASSET_ENDED="hlsInterstitialAssetEnded",n.INTERSTITIAL_ASSET_ERROR="hlsInterstitialAssetError",n.INTERSTITIAL_ENDED="hlsInterstitialEnded",n.INTERSTITIALS_PRIMARY_RESUMED="hlsInterstitialsPrimaryResumed",n.PLAYOUT_LIMIT_REACHED="hlsPlayoutLimitReached",n.EVENT_CUE_ENTER="hlsEventCueEnter",n})({});function vc(n){return n&&n.__esModule&&Object.prototype.hasOwnProperty.call(n,"default")?n.default:n}var Ri={exports:{}},zn;function xc(){return zn||(zn=1,(function(n,e){(function(t){var s=/^(?=((?:[a-zA-Z0-9+\-.]+:)?))\1(?=((?:\/\/[^\/?#]*)?))\2(?=((?:(?:[^?#\/]*\/)*[^;?#\/]*)?))\3((?:;[^?#]*)?)(\?[^#]*)?(#[^]*)?$/,i=/^(?=([^\/?#]*))\1([^]*)$/,r=/(?:\/|^)\.(?=\/)/g,a=/(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g,o={buildAbsoluteURL:function(l,c,h){if(h=h||{},l=l.trim(),c=c.trim(),!c){if(!h.alwaysNormalize)return l;var u=o.parseURL(l);if(!u)throw new Error("Error trying to parse base URL.");return u.path=o.normalizePath(u.path),o.buildURLFromParts(u)}var d=o.parseURL(c);if(!d)throw new Error("Error trying to parse relative URL.");if(d.scheme)return h.alwaysNormalize?(d.path=o.normalizePath(d.path),o.buildURLFromParts(d)):c;var f=o.parseURL(l);if(!f)throw new Error("Error trying to parse base URL.");if(!f.netLoc&&f.path&&f.path[0]!=="/"){var g=i.exec(f.path);f.netLoc=g[1],f.path=g[2]}f.netLoc&&!f.path&&(f.path="/");var m={scheme:f.scheme,netLoc:d.netLoc,path:null,params:d.params,query:d.query,fragment:d.fragment};if(!d.netLoc&&(m.netLoc=f.netLoc,d.path[0]!=="/"))if(!d.path)m.path=f.path,d.params||(m.params=f.params,d.query||(m.query=f.query));else{var y=f.path,E=y.substring(0,y.lastIndexOf("/")+1)+d.path;m.path=o.normalizePath(E)}return m.path===null&&(m.path=h.alwaysNormalize?o.normalizePath(d.path):d.path),o.buildURLFromParts(m)},parseURL:function(l){var c=s.exec(l);return c?{scheme:c[1]||"",netLoc:c[2]||"",path:c[3]||"",params:c[4]||"",query:c[5]||"",fragment:c[6]||""}:null},normalizePath:function(l){for(l=l.split("").reverse().join("").replace(r,"");l.length!==(l=l.replace(a,"")).length;);return l.split("").reverse().join("")},buildURLFromParts:function(l){return l.scheme+l.netLoc+l.path+l.params+l.query+l.fragment}};n.exports=o})()})(Ri)),Ri.exports}var Ln=xc(),ts=class{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}}},se=(function(n){return n.MANIFEST="manifest",n.LEVEL="level",n.AUDIO_TRACK="audioTrack",n.SUBTITLE_TRACK="subtitleTrack",n.MEDIA_FRAGMENT="media-fragment",n.KEY="key",n.STEERING_MANIFEST="steering-manifest",n.SERVER_CERTIFICATE="server-certificate",n.INTERSTITIAL_ASSET_LIST="interstitial-asset-list",n})({}),K=(function(n){return n.MAIN="main",n.AUDIO="audio",n.SUBTITLE="subtitle",n})({}),ue={AUDIO:"audio",VIDEO:"video",AUDIOVIDEO:"audiovideo"},Gs=class{constructor(e){this._byteRange=null,this._url=null,this._stats=null,this._streams=null,this.base=void 0,this.relurl=void 0,typeof e=="string"&&(e={url:e}),this.base=e,Ic(this,"stats")}setByteRange(e,t){let s=e.split("@",2),i;s.length===1?i=t?.byteRangeEndOffset||0:i=parseInt(s[1]),this._byteRange=[i,parseInt(s[0])+i]}get baseurl(){return this.base.url}get byteRange(){return this._byteRange===null?[]:this._byteRange}get byteRangeStartOffset(){return this.byteRange[0]}get byteRangeEndOffset(){return this.byteRange[1]}get elementaryStreams(){return this._streams===null&&(this._streams={[ue.AUDIO]:null,[ue.VIDEO]:null,[ue.AUDIOVIDEO]:null}),this._streams}set elementaryStreams(e){this._streams=e}get hasStats(){return this._stats!==null}get hasStreams(){return this._streams!==null}get stats(){return this._stats===null&&(this._stats=new ts),this._stats}set stats(e){this._stats=e}get url(){return!this._url&&this.relurl&&(this._url=Ln.buildAbsoluteURL(this.baseurl,this.relurl,{alwaysNormalize:!0})),this._url||""}set url(e){this._url=e}clearElementaryStreamInfo(){let{elementaryStreams:e}=this;e[ue.AUDIO]=null,e[ue.VIDEO]=null,e[ue.AUDIOVIDEO]=null,this.url=null}};function pe(n){return n.sn!=="initSegment"}function jt(n,e){return n.sn===e?.sn&&n.level===e.level}function Ji(n,e){return n.sn===e?.sn&&n.level===e.level&&n.cc===e.cc}var Ft=class extends Gs{constructor(e,t){super(t),this._decryptdata=null,this._programDateTime=null,this._ref=null,this._bitrate=void 0,this.rawProgramDateTime=null,this.tagList=[],this.duration=0,this.sn=0,this.levelkeys=void 0,this.type=void 0,this.loader=null,this.keyLoader=null,this.level=-1,this.cc=0,this.startPTS=void 0,this.endPTS=void 0,this.startDTS=void 0,this.endDTS=void 0,this.start=0,this.playlistOffset=0,this.deltaPTS=void 0,this.maxStartPTS=void 0,this.minEndPTS=void 0,this.data=void 0,this.bitrateTest=!1,this.title=null,this.initSegment=null,this.endList=void 0,this.gap=void 0,this.urlId=0,this.type=e}get byteLength(){if(this.hasStats){let e=this.stats.total;if(e)return e}if(this.byteRange.length){let e=this.byteRange[0],t=this.byteRange[1];if($(e)&&$(t))return t-e}return null}get bitrate(){return this.byteLength?this.byteLength*8/this.duration:this._bitrate?this._bitrate:null}set bitrate(e){this._bitrate=e}get decryptdata(){var e;let{levelkeys:t}=this;if(!t||t.NONE)return null;if(t.identity)this._decryptdata||(this._decryptdata=t.identity.getDecryptData(this.sn));else if(!((e=this._decryptdata)!=null&&e.keyId)){let s=Object.keys(t);if(s.length===1){let i=this._decryptdata=t[s[0]]||null;i&&(this._decryptdata=i.getDecryptData(this.sn,t))}}return this._decryptdata}get end(){return this.start+this.duration}get endProgramDateTime(){if(this.programDateTime===null)return null;let e=$(this.duration)?this.duration:0;return this.programDateTime+e*1e3}get encrypted(){var e;if((e=this._decryptdata)!=null&&e.encrypted)return!0;if(this.levelkeys){var t;let s=Object.keys(this.levelkeys),i=s.length;if(i>1||i===1&&(t=this.levelkeys[s[0]])!=null&&t.encrypted)return!0}return!1}get programDateTime(){return this._programDateTime===null&&this.rawProgramDateTime&&(this.programDateTime=Date.parse(this.rawProgramDateTime)),this._programDateTime}set programDateTime(e){if(!$(e)){this._programDateTime=this.rawProgramDateTime=null;return}this._programDateTime=e}get ref(){return pe(this)?(this._ref||(this._ref={base:this.base,start:this.start,duration:this.duration,sn:this.sn,programDateTime:this.programDateTime}),this._ref):null}addStart(e){this.setStart(this.start+e)}setStart(e){this.start=e,this._ref&&(this._ref.start=e)}setDuration(e){this.duration=e,this._ref&&(this._ref.duration=e)}setKeyFormat(e){let t=this.levelkeys;if(t){var s;let i=t[e];i&&!((s=this._decryptdata)!=null&&s.keyId)&&(this._decryptdata=i.getDecryptData(this.sn,t))}}abortRequests(){var e,t;(e=this.loader)==null||e.abort(),(t=this.keyLoader)==null||t.abort()}setElementaryStreamInfo(e,t,s,i,r,a=!1){let{elementaryStreams:o}=this,l=o[e];if(!l){o[e]={startPTS:t,endPTS:s,startDTS:i,endDTS:r,partial:a};return}l.startPTS=Math.min(l.startPTS,t),l.endPTS=Math.max(l.endPTS,s),l.startDTS=Math.min(l.startDTS,i),l.endDTS=Math.max(l.endDTS,r)}},er=class extends Gs{constructor(e,t,s,i,r){super(s),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=e.decimalFloatingPoint("DURATION"),this.gap=e.bool("GAP"),this.independent=e.bool("INDEPENDENT"),this.relurl=e.enumeratedString("URI"),this.fragment=t,this.index=i;let a=e.enumeratedString("BYTERANGE");a&&this.setByteRange(a,r),r&&(this.fragOffset=r.fragOffset+r.duration)}get start(){return this.fragment.start+this.fragOffset}get end(){return this.start+this.duration}get loaded(){let{elementaryStreams:e}=this;return!!(e.audio||e.video||e.audiovideo||this.fragment.type===K.SUBTITLE&&this.stats.loading.end>0)}};function vo(n,e){let t=Object.getPrototypeOf(n);if(t){let s=Object.getOwnPropertyDescriptor(t,e);return s||vo(t,e)}}function Ic(n,e){let t=vo(n,e);t&&(t.enumerable=!0,Object.defineProperty(n,e,t))}function Ac(n,e,t){return(e=bc(e))in n?Object.defineProperty(n,e,{value:t,enumerable:!0,configurable:!0,writable:!0}):n[e]=t,n}function he(){return he=Object.assign?Object.assign.bind():function(n){for(var e=1;e<arguments.length;e++){var t=arguments[e];for(var s in t)({}).hasOwnProperty.call(t,s)&&(n[s]=t[s])}return n},he.apply(null,arguments)}function Xn(n,e){var t=Object.keys(n);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(n);e&&(s=s.filter(function(i){return Object.getOwnPropertyDescriptor(n,i).enumerable})),t.push.apply(t,s)}return t}function Y(n){for(var e=1;e<arguments.length;e++){var t=arguments[e]!=null?arguments[e]:{};e%2?Xn(Object(t),!0).forEach(function(s){Ac(n,s,t[s])}):Object.getOwnPropertyDescriptors?Object.defineProperties(n,Object.getOwnPropertyDescriptors(t)):Xn(Object(t)).forEach(function(s){Object.defineProperty(n,s,Object.getOwnPropertyDescriptor(t,s))})}return n}function vi(n,e){if(n==null)return{};var t,s,i=Lc(n,e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(n);for(s=0;s<r.length;s++)t=r[s],e.indexOf(t)===-1&&{}.propertyIsEnumerable.call(n,t)&&(i[t]=n[t])}return i}function Lc(n,e){if(n==null)return{};var t={};for(var s in n)if({}.hasOwnProperty.call(n,s)){if(e.indexOf(s)!==-1)continue;t[s]=n[s]}return t}function Rc(n,e){if(typeof n!="object"||!n)return n;var t=n[Symbol.toPrimitive];if(t!==void 0){var s=t.call(n,e);if(typeof s!="object")return s;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(n)}function bc(n){var e=Rc(n,"string");return typeof e=="symbol"?e:e+""}function Vs(n){switch(n.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 xo(n){return n.details.startsWith("key")}function Io(n){return xo(n)&&!!n.frag&&!n.frag.decryptdata}function Qn(n,e){let t=Vs(e);return n.default[`${t?"timeout":"error"}Retry`]}function Rn(n,e){let t=n.backoff==="linear"?1:Math.pow(2,e);return Math.min(t*n.retryDelayMs,n.maxRetryDelayMs)}function Zn(n){return Y(Y({},n),{errorRetry:null,timeoutRetry:null})}function ss(n,e,t,s){if(!n)return!1;let i=s?.code,r=e<n.maxNumRetry&&(_c(i)||!!t);return n.shouldRetry?n.shouldRetry(n,e,t,s,r):r}function _c(n){return is(n)||!!n&&(n<400||n>499)}function is(n){return n===0&&navigator.onLine===!1}function Ao(n,e){return e>0&&n.loadError>0&&n.loadErrorTime!==0&&self.performance.now()-n.loadErrorTime>e}var mt=class{constructor(e,t=0,s=0){this.halfLife=void 0,this.alpha_=void 0,this.estimate_=void 0,this.totalWeight_=void 0,this.halfLife=e,this.alpha_=e?Math.exp(Math.log(.5)/e):0,this.estimate_=t,this.totalWeight_=s}sample(e,t){let s=Math.pow(this.alpha_,e);this.estimate_=t*(1-s)+s*this.estimate_,this.totalWeight_+=e}getTotalWeight(){return this.totalWeight_}getEstimate(){if(this.alpha_){let e=1-Math.pow(this.alpha_,this.totalWeight_);if(e)return this.estimate_/e}return this.estimate_}},tr=class{constructor(e,t,s,i=100){this.defaultEstimate_=void 0,this.minWeight_=void 0,this.minDelayMs_=void 0,this.slow_=void 0,this.fast_=void 0,this.defaultTTFB_=void 0,this.ttfb_=void 0,this.defaultEstimate_=s,this.minWeight_=.001,this.minDelayMs_=50,this.slow_=new mt(e),this.fast_=new mt(t),this.defaultTTFB_=i,this.ttfb_=new mt(e)}update(e,t){let{slow_:s,fast_:i,ttfb_:r}=this;s.halfLife!==e&&(this.slow_=new mt(e,s.getEstimate(),s.getTotalWeight())),i.halfLife!==t&&(this.fast_=new mt(t,i.getEstimate(),i.getTotalWeight())),r.halfLife!==e&&(this.ttfb_=new mt(e,r.getEstimate(),r.getTotalWeight()))}sample(e,t){if(t<=0)return;let s=Math.min(this.minDelayMs_,t/1e5),i=8*t,r=Math.max(e,s)/1e3,a=i/r;this.fast_.sample(r,a),this.slow_.sample(r,a)}sampleTTFB(e){let t=e/1e3,s=Math.sqrt(2)*Math.exp(-Math.pow(t,2)/2);this.ttfb_.sample(s,Math.max(e,5))}canEstimate(){return this.fast_.getTotalWeight()>=this.minWeight_}getEstimate(){return this.canEstimate()?Math.min(this.fast_.getEstimate(),this.slow_.getEstimate()):this.defaultEstimate_}getEstimateTTFB(){return this.ttfb_.getTotalWeight()>=this.minWeight_?this.ttfb_.getEstimate():this.defaultTTFB_}get defaultEstimate(){return this.defaultEstimate_}destroy(){}},we=class{constructor(e,t){this.trace=void 0,this.debug=void 0,this.log=void 0,this.warn=void 0,this.info=void 0,this.error=void 0;let s=`[${e}]:`;this.trace=pt,this.debug=t.debug.bind(null,s),this.log=t.log.bind(null,s),this.warn=t.warn.bind(null,s),this.info=t.info.bind(null,s),this.error=t.error.bind(null,s)}},pt=function(){},Dc={trace:pt,debug:pt,log:pt,warn:pt,info:pt,error:pt};function sr(){return he({},Dc)}function Pc(n,e){let t=self.console[n];return t?t.bind(self.console,`${e?"["+e+"] ":""}[${n}] >`):pt}function Jn(n,e,t){return e[n]?e[n].bind(e):Pc(n,t)}var ir=sr();function Cc(n,e,t){let s=sr();if(typeof console=="object"&&n===!0||typeof n=="object"){let i=["debug","log","info","warn","error"];i.forEach(r=>{s[r]=Jn(r,n,t)});try{s.log(`Debug logs enabled for "${e}" in hls.js version 1.7.4`)}catch{return sr()}i.forEach(r=>{ir[r]=Jn(r,n)})}else he(ir,s);return s}var oe=ir;function vt(n=!0){return typeof self>"u"?void 0:(n||!self.MediaSource)&&self.ManagedMediaSource||self.MediaSource||self.WebKitMediaSource}function kc(n){return typeof self<"u"&&n===self.ManagedMediaSource}function Lo(n,e){let t=Object.keys(n),s=Object.keys(e),i=t.length,r=s.length;return!i||!r||i===r&&!t.some(a=>s.indexOf(a)===-1)}function Oc(n){return btoa(String.fromCharCode(...n))}function xi(n){return n instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&n instanceof SharedArrayBuffer}var wc="utf-16",bi="utf-16be",ea="utf-16le",ws="utf-8";function Mc(n,e={}){let t;xi(n)?t=new DataView(n):t=new DataView(n.buffer,n.byteOffset,n.byteLength);let s=0,{encoding:i}=e;if(!i){let c=t.getUint8(0),h=t.getUint8(1);c==239&&h==187&&t.getUint8(2)==191?(i=ws,s=3):c==254&&h==255?(i=bi,s=2):c==255&&h==254?(i=ea,s=2):i=ws}if(typeof TextDecoder<"u")return new TextDecoder(i).decode(t);let{byteLength:r}=t,a=i!==bi,o="",l;for(;s<r;){switch(i){case ws:if(l=t.getUint8(s),l<128)s++;else if(l>=194&&l<=223)if(s+1<r){let c=t.getUint8(s+1);c>=128&&c<=191?(l=(l&31)<<6|c&63,s+=2):s++}else s++;else if(l>=224&&l<=239)if(s+2<=r-1){let c=t.getUint8(s+1),h=t.getUint8(s+2);c>=128&&c<=191&&h>=128&&h<=191?(l=(l&15)<<12|(c&63)<<6|h&63,s+=3):s++}else s++;else if(l>=240&&l<=244)if(s+3<=r-1){let c=t.getUint8(s+1),h=t.getUint8(s+2),u=t.getUint8(s+3);c>=128&&c<=191&&h>=128&&h<=191&&u>=128&&u<=191?(l=(l&7)<<18|(c&63)<<12|(h&63)<<6|u&63,s+=4):s++}else s++;else s++;break;case bi:case wc:case ea:l=t.getUint16(s,a),s+=2;break}o+=String.fromCodePoint(l)}return o}function Fc(n){let e=typeof n=="string"?new URL(n):n;return e.origin+e.pathname.substring(0,e.pathname.lastIndexOf("/")+1)}function Ro(n,e){if(n<0)return-Ro(-n,e);let t=Math.pow(10,e);if(Math.abs(n*t%1-.5)<Number.EPSILON){let s=Math.floor(n*t);return(s%2===0?s:s+1)/t}else return Math.round(n*t)/t}function Nc(n,e){let t;try{t=new URL(n)}catch{return n}let s=new URL(e);if(t.origin!==s.origin)return n;let i=t.pathname.split("/").slice(1),r=s.pathname.split("/").slice(1,-1),a=Math.min(i.length,r.length);for(let o=0;o<a&&i[o]===r[o];o++)i.shift(),r.shift();for(;r.length;)r.shift(),i.unshift("..");return i.join("/")+t.search+t.hash}function bo(){try{return crypto.randomUUID()}catch{try{let e=URL.createObjectURL(new Blob),t=e.toString();return URL.revokeObjectURL(e),t.slice(t.lastIndexOf("/")+1)}catch{let t=new Date().getTime();return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,s=>{let i=(t+Math.random()*16)%16|0;return t=Math.floor(t/16),(s=="x"?i:i&3|8).toString(16)})}}}function bn(n,e){return e+10<=n.length&&n[e]===73&&n[e+1]===68&&n[e+2]===51&&n[e+3]<255&&n[e+4]<255&&n[e+6]<128&&n[e+7]<128&&n[e+8]<128&&n[e+9]<128}function Ii(n,e){let t=0;return t=(n[e]&127)<<21,t|=(n[e+1]&127)<<14,t|=(n[e+2]&127)<<7,t|=n[e+3]&127,t}function Bc(n,e){return bn(n,e)&&Ii(n,e+6)+10<=n.length-e}function _o(n,e){return e+10<=n.length&&n[e]===51&&n[e+1]===68&&n[e+2]===73&&n[e+3]<255&&n[e+4]<255&&n[e+6]<128&&n[e+7]<128&&n[e+8]<128&&n[e+9]<128}function rs(n,e){let t=e,s=0;for(;bn(n,e);){s+=10;let i=Ii(n,e+6);s+=i,_o(n,e+10)&&(s+=10),e+=s}if(s>0)return n.subarray(t,t+s)}function $c(n){return xi(n)?n:n.byteOffset==0&&n.byteLength==n.buffer.byteLength?n.buffer:new Uint8Array(n).buffer}function _i(n,e=0,t=1/0){return Uc(n,e,t,Uint8Array)}function Uc(n,e,t,s){let i=Gc(n),r=1;"BYTES_PER_ELEMENT"in s&&(r=s.BYTES_PER_ELEMENT);let a=Vc(n)?n.byteOffset:0,o=(a+n.byteLength)/r,l=(a+e)/r,c=Math.floor(Math.max(0,Math.min(l,o)));return new s(i,c,Math.floor(Math.min(c+Math.max(t,0),o))-c)}function Gc(n){return xi(n)?n:n.buffer}function Vc(n){return n&&xi(n.buffer)&&n.byteLength!==void 0&&n.byteOffset!==void 0}function He(n,e=!1){let t=e?n.indexOf(0):n.length,s=Mc(new DataView(n.buffer,n.byteOffset,t),{encoding:ws});return e?s:s.replace(/\0/g,"")}function Kc(n){let e={key:n.type,description:"",data:"",mimeType:null,pictureType:null},t=3;if(n.size<2)return;if(n.data[0]!==t){console.log("Ignore frame with unrecognized character encoding");return}let s=n.data.subarray(1).indexOf(0);if(s===-1)return;let i=He(_i(n.data,1,s)),r=n.data[2+s],a=n.data.subarray(3+s).indexOf(0);if(a===-1)return;let o=He(_i(n.data,3+s,a)),l;return i==="-->"?l=He(_i(n.data,4+s+a)):l=$c(n.data.subarray(4+s+a)),e.mimeType=i,e.pictureType=r,e.description=o,e.data=l,e}function Hc(n){if(n.size<2)return;let e=He(n.data,!0),t=new Uint8Array(n.data.subarray(e.length+1));return{key:n.type,info:e,data:t.buffer}}function Yc(n){if(n.size<2)return;if(n.type==="TXXX"){let t=1,{data:s}=n,i=He(s.subarray(t),!0);t+=i.length+1;let r=He(s.subarray(t));return{key:n.type,info:i,data:r}}let e=He(n.data.subarray(1));return{key:n.type,info:"",data:e}}function Wc(n){if(n.type==="WXXX"){if(n.size<2)return;let t=1,s=He(n.data.subarray(t),!0);t+=s.length+1;let i=He(n.data.subarray(t));return{key:n.type,info:s,data:i}}let e=He(n.data);return{key:n.type,info:"",data:e}}function qc(n){return n.type==="PRIV"?Hc(n):n.type[0]==="W"?Wc(n):n.type==="APIC"?Kc(n):Yc(n)}function jc(n){let e=String.fromCharCode(n[0],n[1],n[2],n[3]),t=Ii(n,4),s=10;return{type:e,size:t,data:n.subarray(s,s+t)}}var Ts=10,zc=10;function Do(n){let e=0,t=[];for(;bn(n,e);){let s=Ii(n,e+6);n[e+5]>>6&1&&(e+=Ts),e+=Ts;let i=e+s;for(;e+zc<i;){let r=jc(n.subarray(e)),a=qc(r);a&&t.push(a),e+=r.size+Ts}_o(n,e)&&(e+=Ts)}return t}function Po(n){return n&&n.key==="PRIV"&&n.info==="com.apple.streaming.transportStreamTimestamp"}function Xc(n){if(n.data.byteLength===8){let e=new Uint8Array(n.data),t=e[3]&1,s=(e[4]<<23)+(e[5]<<15)+(e[6]<<7)+e[7];return s/=45,t&&(s+=4772185884e-2),Math.round(s)}}function _n(n){let e=Do(n);for(let t of e)if(Po(t))return Xc(t)}function Ie(n){let e="";for(let t=0;t<n.length;t++){let s=n[t].toString(16);s.length<2&&(s="0"+s),e+=s}return e}function Co(n){return Uint8Array.from(n.replace(/^0x/,"").replace(/([\da-fA-F]{2}) ?/g,"0x$1 ").replace(/ +$/,"").split(" ")).buffer}function Dn(n){return Uint8Array.from(atob(n),e=>e.charCodeAt(0))}function Ze(n){return String.fromCharCode.apply(null,n)}var et=Math.pow(2,32)-1,z={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},ko={video:1,audio:2,id3:3,text:4};function Oo(n,e){let t=n[e]<<8|n[e+1];return t<0?65536+t:t}function V(n,e){let t=n[e]<<24|n[e+1]<<16|n[e+2]<<8|n[e+3];return t<0?4294967296+t:t}function ta(n,e){let t=V(n,e);return t*=Math.pow(2,32),t+=V(n,e+4),t}function Ss(n,e){let t="";for(let s=e;s<n.length;s++)if(t+=String.fromCharCode(n[s]),n[s]===0)return t;return null}function rr(n,e){return n[e]<<24|n[e+1]<<16|n[e+2]<<8|n[e+3]}function Te(n,e,t){n[e]=t>>24,n[e+1]=t>>16&255,n[e+2]=t>>8&255,n[e+3]=t&255}function sa(n,e,t){let s=e.byteOffset-n.byteOffset-8,i=8+t,r=e.byteLength+8-i;r<8||(Te(n,s,i),Te(n,s+i,r),Te(n,s+i+4,z.free))}function nr(n,e){return[n.byteOffset-e-8,n.byteOffset-e+n.byteLength]}function wo(n,e){e.sort((o,l)=>o[0]-l[0]);let t=e.reduce((o,[l,c])=>o+c-l,0),s=new Uint8Array(n.byteLength-t),i=0,r=0;for(let o=0;o<e.length;o++){let[l,c]=e[o];s.set(n.subarray(i,l),r),r+=l-i,i=c}return s.set(n.subarray(i),r),{result:s,dropped:t,droppedBefore:o=>e.reduce((l,[c,h])=>h<=o?l+h-c:l,0)}}function Qc(n){let e=Q(n,["moov"]);if(e.length!==1||Q(n,["moof"]).length)return null;let t=n.byteOffset,s=[],i=[],r=!1,a=Q(e[0],["trak"]);for(let f=0;f<a.length;f++){let g=a[f],m=Q(g,["mdia","hdlr"])[0];if((m?Ze(m.subarray(8,12)):"")==="vide"){r=!0;continue}let E=Q(g,["tkhd"])[0];if(!E)return null;let S=E[0];i.push(V(E,S===0?12:20)),s.push(nr(g,t))}if(!r||!s.length)return null;let o=Q(e[0],["mvex"])[0],l=0;if(o){let f=Q(o,["trex"]);for(let g=0;g<f.length;g++){let m=f[g];i.indexOf(V(m,4))!==-1&&(s.push(nr(m,t)),l+=m.byteLength+8)}}let{result:c,dropped:h,droppedBefore:u}=wo(n,s),d=e[0].byteOffset-t-8;if(Te(c,d,e[0].byteLength+8-h),o&&l){let f=o.byteOffset-t-8;Te(c,f-u(f),o.byteLength+8-l)}return c}function Zc(n,e,t,s,i){if(t<1)return null;let r=Q(n,["moof"]);if(r.length!==1)return null;let a=r[0],o=n.byteOffset,l=[],c=[],h=Q(a,["traf"]),u=!0;for(let m=0;m<h.length;m++){let y=h[m],E=Q(y,["tfhd"])[0];if(!E)return null;V(E,4)===e?(l.push(y),V(E,0)&131072||(u=!1)):c.push(nr(y,o))}if(!l.length||c.length&&!u)return null;if(s!==void 0){let m=t;for(let E=0;E<l.length;E++){let S=l[E],T=0,v=Q(S,["trun"]);for(let A=0;A<v.length;A++){let b=v[A],_=Math.min(m,V(b,4));if(_){Te(n,b.byteOffset-o+4,_);let L=V(b,0)&16777215,P=(L&256?4:0)+(L&512?4:0)+(L&1024?4:0)+(L&2048?4:0);sa(n,b,8+(L&1?4:0)+(L&4?4:0)+_*P)}else Te(n,b.byteOffset-o-4,z.free);m-=_,T+=_}let x=Q(S,["senc"])[0];x&&Te(n,x.byteOffset-o+4,T);let I=Q(S,["saiz"])[0];if(I){let A=I[1]<<16|I[2]<<8|I[3],b=4;A&1&&(b+=8);let _=I[b];b+=1,Te(n,I.byteOffset-o+b,T),sa(n,I,b+4+(_===0?T:0))}}let y=Q(n,["mdat"]);if(y.length===1){let E=y[0].byteOffset-o-8;Te(n,E,s-E)}}let d=n,f=0,g=()=>0;if(c.length){({result:d,dropped:f,droppedBefore:g}=wo(n,c)),Te(d,a.byteOffset-o-8,a.byteLength+8-f);for(let m=0;m<l.length;m++){let y=l[m],E=g(y.byteOffset-o),S=Q(y,["trun"]);for(let T=0;T<S.length;T++){let v=S[T];V(v,0)&1&&Te(d,v.byteOffset-o-E+8,V(v,8)-f)}if(E){let T=Q(y,["saio"]);for(let v=0;v<T.length;v++){let x=T[v],I=x[0]===0?4:8,A=V(x,0)&1?12:4,b=V(x,A);for(A+=4;b--;A+=I){let _=A+I-4;Te(d,x.byteOffset-o-E+_,V(x,_)-E)}}}}}if(i){let{durationOffset:m,value:y}=i;Te(d,m-g(m),y)}return s!==void 0?d.subarray(0,s-f):d}function Jc(n,e){let t=n.byteLength;for(let s=0;s<t;){let i=V(n,s);if(i>8&&V(n,s+4)===z[e])return!0;s=i>1?s+i:t}return!1}function Q(n,e){let t=[];return e.length&&Mo(n,e,0,0,n.byteLength,t),t}function Mo(n,e,t,s,i,r){let a=e[t];if(a?.length!==4)return;let o=a.charCodeAt(0),l=a.charCodeAt(1),c=a.charCodeAt(2),h=a.charCodeAt(3),u=e.length-1;for(let d=s;d<i;){let f=d+8<=i,g=d+4<=i?n[d]*16777216+(n[d+1]<<16|n[d+2]<<8|n[d+3]):V(n,d),m=g>1?d+g:i;if(f&&n[d+4]===o&&n[d+5]===l&&n[d+6]===c&&n[d+7]===h){let y=Math.min(m,i);t===u?r.push(n.subarray(d+8,y)):Mo(n,e,t+1,d+8,y,r)}d=m}}function eh(n){let e=[],t=n[0],s=8,i=V(n,s);s+=4;let r=0,a=0;t===0?(r=V(n,s),a=V(n,s+4),s+=8):(r=ta(n,s),a=ta(n,s+8),s+=16),s+=2;let o=n.length+a,l=Oo(n,s);s+=2;for(let c=0;c<l;c++){let h=s,u=V(n,h);h+=4;let d=u&2147483647;if((u&2147483648)>>>31===1)return oe.warn("SIDX has hierarchical references (not supported)"),null;let g=V(n,h);h+=4,e.push({referenceSize:d,subsegmentDuration:g,info:{duration:g/i,start:o,end:o+d-1}}),o+=d,h+=4,s=h}return{earliestPresentationTime:r,timescale:i,version:t,referencesCount:l,references:e}}function Fo(n){let e=[],t=Q(n,["moov","trak"]);for(let i=0;i<t.length;i++){let r=t[i],a=Q(r,["tkhd"])[0];if(a){let o=a[0],l=V(a,o===0?12:20),c=Q(r,["mdia","mdhd"])[0];if(c){o=c[0];let h=V(c,o===0?12:20),u=Q(r,["mdia","hdlr"])[0];if(u){let d=Ze(u.subarray(8,12)),f={soun:ue.AUDIO,vide:ue.VIDEO}[d],g=Q(r,["mdia","minf","stbl","stsd"])[0],m=th(g);f?(e[l]={timescale:h,type:f,stsd:m},e[f]=Y({timescale:h,id:l},m)):e[l]={timescale:h,type:d,stsd:m}}}}}return Q(n,["moov","mvex","trex"]).forEach(i=>{let r=V(i,4),a=e[r];a&&(a.default={duration:V(i,12),sampleSize:V(i,16),flags:V(i,20)})}),e}function th(n){let e=n.subarray(8),t=e.subarray(86),s=Ze(e.subarray(4,8)),i=s,r,a=s==="enca"||s==="encv";if(a){let c=Q(e,[s])[0].subarray(s==="enca"?28:78);Q(c,["sinf"]).forEach(u=>{let d=Q(u,["schm"])[0];if(d){let f=Ze(d.subarray(4,8));if(f==="cbcs"||f==="cenc"){let g=Q(u,["frma"])[0];g&&(i=Ze(g))}}})}let o=i;switch(i){case"avc1":case"avc2":case"avc3":case"avc4":{let l=Q(t,["avcC"])[0];l&&l.length>3&&(i+="."+xs(l[1])+xs(l[2])+xs(l[3]),r=vs(o==="avc1"?"dva1":"dvav",t));break}case"mp4a":{let l=Q(e,[s])[0],c=Q(l.subarray(28),["esds"])[0];if(c&&c.length>7){let h=4;if(c[h++]!==3)break;h=Di(c,h),h+=2;let u=c[h++];if(u&128&&(h+=2),u&64&&(h+=c[h++]),c[h++]!==4)break;h=Di(c,h);let d=c[h++];if(d===64)i+="."+xs(d);else break;if(h+=12,c[h++]!==5)break;h=Di(c,h);let f=c[h++],g=(f&248)>>3;g===31&&(g+=1+((f&7)<<3)+((c[h]&224)>>5)),i+="."+g}break}case"hvc1":case"hev1":{let l=Q(t,["hvcC"])[0];if(l&&l.length>12){let c=l[1],h=["","A","B","C"][c>>6],u=c&31,d=V(l,2),f=(c&32)>>5?"H":"L",g=l[12],m=l.subarray(6,12);i+="."+h+u,i+="."+sh(d).toString(16).toUpperCase(),i+="."+f+g;let y="";for(let E=m.length;E--;){let S=m[E];(S||y)&&(y="."+S.toString(16).toUpperCase()+y)}i+=y}r=vs(o=="hev1"?"dvhe":"dvh1",t);break}case"dvh1":case"dvhe":case"dvav":case"dva1":case"dav1":{i=vs(i,t)||i;break}case"vp09":{let l=Q(t,["vpcC"])[0];if(l&&l.length>6){let c=l[4],h=l[5],u=l[6]>>4&15;i+="."+tt(c)+"."+tt(h)+"."+tt(u)}break}case"av01":{let l=Q(t,["av1C"])[0];if(l&&l.length>2){let c=l[1]>>>5,h=l[1]&31,u=l[2]>>>7?"H":"M",d=(l[2]&64)>>6,f=(l[2]&32)>>5,g=c===2&&d?f?12:10:d?10:8,m=(l[2]&16)>>4,y=(l[2]&8)>>3,E=(l[2]&4)>>2,S=l[2]&3;i+="."+c+"."+tt(h)+u+"."+tt(g)+"."+m+"."+y+E+S+"."+tt(1)+"."+tt(1)+"."+tt(1)+"."+0,r=vs("dav1",t)}break}}return{codec:i,encrypted:a,supplemental:r}}function vs(n,e){let t=Q(e,["dvvC"]),s=t.length?t[0]:Q(e,["dvcC"])[0];if(s){let i=s[2]>>1&127,r=s[2]<<5&32|s[3]>>3&31;return n+"."+tt(i)+"."+tt(r)}}function sh(n){let e=0;for(let t=0;t<32;t++)e|=(n>>t&1)<<31-t;return e>>>0}function Di(n,e){let t=e+5;for(;n[e++]&128&&e<t;);return e}function xs(n){return("0"+n.toString(16).toUpperCase()).slice(-2)}function tt(n){return(n<10?"0":"")+n}function ih(n,e){if(!n||!e)return;let t=e.keyId;t?.byteLength===16&&e.isCommonEncryption&&No(n,(s,i)=>{let r=s.subarray(8,24);r.some(a=>a!==0)||(oe.log(`[eme] Patching keyId in 'enc${i?"a":"v"}>sinf>>tenc' box: ${Ie(r)} -> ${Ie(t)}`),s.set(t,8))})}function rh(n){let e=[];return No(n,t=>e.push(t.subarray(8,24))),e}function No(n,e){Q(n,["moov","trak"]).forEach(s=>{let i=Q(s,["mdia","minf","stbl","stsd"])[0];if(!i)return;let r=i.subarray(8),a=Q(r,["enca"]),o=a.length>0;o||(a=Q(r,["encv"])),a.forEach(l=>{let c=o?l.subarray(28):l.subarray(78);Q(c,["sinf"]).forEach(u=>{let d=Bo(u);d&&e(d,o)})})})}function Bo(n){let e=Q(n,["schm"])[0];if(e){let t=Ze(e.subarray(4,8));if(t==="cbcs"||t==="cenc"){let s=Q(n,["schi","tenc"])[0];if(s)return s}}}var ia;function nh(n){return typeof TextDecoder>"u"?He(n):(ia||(ia=new TextDecoder("utf-8"))).decode(n).replace(/\0/g,"")}function ah(n){let e=n.byteLength,t=[];for(let s=0;s<e;){let i=s+8<=e,r=s+4<=e?n[s]*16777216+(n[s+1]<<16|n[s+2]<<8|n[s+3]):V(n,s),a=r>1?s+r:e;if(i&&n[s+4]===109&&n[s+5]===111&&n[s+6]===111&&n[s+7]===102){let o=Math.min(a,e);for(let l=s+8;l<o;){let c=l+8<=o,h=l+4<=o?n[l]*16777216+(n[l+1]<<16|n[l+2]<<8|n[l+3]):V(n,l),u=h>1?l+h:o;if(c&&n[l+4]===116&&n[l+5]===114&&n[l+6]===97&&n[l+7]===102){let d=Math.min(u,o),f,g,m=[];for(let y=l+8;y<d;){let E=y+8<=d,S=y+4<=d?n[y]*16777216+(n[y+1]<<16|n[y+2]<<8|n[y+3]):V(n,y),T=S>1?y+S:d;if(E&&n[y+4]===116){let v=Math.min(T,d);n[y+5]===102&&n[y+6]===104&&n[y+7]===100?g||(g=n.subarray(y+8,v)):n[y+5]===102&&n[y+6]===100&&n[y+7]===116?f||(f=n.subarray(y+8,v)):n[y+5]===114&&n[y+6]===117&&n[y+7]===110&&m.push(n.subarray(y+8,v))}y=T}t.push({moofOffset:n.byteOffset+s,tfdt:f,tfhd:g,truns:m})}l=u}}s=a}return t}function oh(n,e,t,s,i=!0){return $o(n,e,s,i)}function lh(n,e,t,s,i=!1){let r=[],a=e.samples,o=$o(a,t,s,i,{isHEVCFlavor:Es(e.codec),samples:r,timeOffset:n,timescale:e.timescale,trackId:e.id});return{samples:r,sampleData:{includeSampleDetails:i,tracks:o}}}function $o(n,e,t,s,i){let r={},a=!1,o=ah(n),l=n.byteLength;for(let u=0;u<o.length;u++){let{moofOffset:d,tfdt:f,tfhd:g,truns:m}=o[u],y=V(g,4),E=e[y];if(!E)continue;let S=r[y]||(r[y]={start:NaN,duration:0,sampleCount:0,trun:[],timescale:E.timescale,type:E.type}),T;if(f){let w=f[0];T=V(f,4),w===1&&(T===et?t.warn("[mp4-demuxer]: Ignoring assumed invalid signed 64-bit track fragment decode time"):(T*=et+1,T+=V(f,8))),$(T)&&(!$(S.start)||T<S.start)&&(S.start=T),i&&$(T)&&(i.timeOffset=T/i.timescale)}let v=i?.trackId===y&&E.type===ue.VIDEO,x=E.default,I=V(g,0)&16777215,A=x?.duration||0,b,_=x?.sampleSize||0,L=8;I&1&&(L+=8),I&2&&(L+=4),I&8&&(A=V(g,L),b=g.byteOffset-n.byteOffset+L,L+=4),I&16&&(_=V(g,L));let P=0,D=(I&1)!==0,M=!D&&(I&131072)!==0;D?(P=V(g,8),P*=Math.pow(2,32),P+=V(g,12)):M&&(P=d);let U=T||0,B=0,k=A;for(let w=0;w<m.length;w++){let O=m[w],F=V(O,4),H=S.sampleCount;S.sampleCount+=F;let N=O[3]&1,G=0,Z=O[3]&4,q=O[2]&1,ie=O[2]&2,j=O[2]&4,ne=O[2]&8,re=8;N&&(G=rr(O,re),re+=4),Z&&(!(O[re+1]&1)&&S.keyFrameIndex===void 0&&(S.keyFrameIndex=H),re+=4);let ae=P+G;if(!s&&O[1]===0&&O[2]===6&&O[3]===1){var c,h;let be=U,Se=ae,ht=re,ee=-1,J=0,te=0,ve=(c=i?.timeOffset)!=null?c:0,ye=A/((h=i?.timescale)!=null?h:1),Ce=i?.isHEVCFlavor===!0,Fe=Ce?2:1;for(let Pe=0;Pe<F;Pe++){let ke=O[re]===0?O[re+1]<<16|O[re+2]<<8|O[re+3]:V(O,re),Ne=ee===-1&&S.keyFrameIndex===void 0&&(O[re+5]&1)===0;re+=8;let ut=ae+ke;if(v){if(ke>0){let Ae=ae;do{let dt=n[Ae]===0?n[Ae+1]<<16|n[Ae+2]<<8|n[Ae+3]:V(n,Ae);Ae+=4;let ft=n[Ae],Ge=Ce?ft>>1&63:ft&31;(Ce?Ge===39||Ge===40:Ge===6)&&ns(n.subarray(Ae,Ae+dt),Fe,ve,i.samples),Ae+=dt}while(Ae<ut)}ve+=ye}ae=ut,Ne&&(ee=Pe,J=ae)}if(ae<=l)te=F;else{let Pe=Se,ke=ht;for(let Ne=0;Ne<F;Ne++){let ut=O[ke]===0?O[ke+1]<<16|O[ke+2]<<8|O[ke+3]:V(O,ke);if(Pe+=ut,Pe>l)break;te=Ne+1,ke+=8}}if(v&&(i.timeOffset=ve),ee!==-1&&J<=l&&S.keyFrameIndex===void 0&&(S.keyFrameIndex=ee,S.keyFrameStart=be+ee*A),te){(!$(S.ptsMin)||be<S.ptsMin)&&(S.ptsMin=be);let Pe=be+te*A;(!$(S.ptsMax)||Pe>S.ptsMax)&&(S.ptsMax=Pe)}let It=A*F;U=be+It,B+=It;continue}let Ee,Me;s&&(Ee=[],Me={sampleOffset:ae,samples:Ee,defaultSampleDurationOffset:b},ae<=l&&S.trun.push(Me));let nt;for(let be=0;be<F;be++){let Se;q?(s&&(Se=O.byteOffset-n.byteOffset+re),k=V(O,re),re+=4):k=A,ie?(nt=V(O,re),re+=4):nt=_;let ht,ee;j&&(ee=O[re+1]&1?1:0,s&&(ht={isNonSync:ee,dependsOn:(O[re]&3)===1?1:2}),re+=4);let J=0;if(ne&&(J=O[0]===0?V(O,re):rr(O,re),re+=4),v){let te=ae,ve=0;for(;ve<nt;){let ye=V(n,te);te+=4,Uo(i.isHEVCFlavor,n[te])&&ns(n.subarray(te,te+ye),i.isHEVCFlavor?2:1,i.timeOffset+J/i.timescale,i.samples),te+=ye,ve+=ye+4}i.timeOffset+=k/i.timescale}if(ae+=nt,ae<=l){Me&&Se!==void 0&&(Me.lastSampleDurationOffset=Se),ee===0&&S.keyFrameIndex===void 0&&(S.keyFrameIndex=be,S.keyFrameStart=U);let te=U+J;(!$(S.ptsMin)||te<S.ptsMin)&&(S.ptsMin=te),(!$(S.ptsMax)||te+k>S.ptsMax)&&(S.ptsMax=te+k),Ee&&(Ee[be]={cts:J,duration:k,flags:ht,size:nt})}U+=k,B+=k}!B&&A&&(B+=A*F)}S.duration+=B,S.duration&&(a=!0)}if(!a){let u=1/0,d=0,f=Q(n,["sidx"]);for(let g=0;g<f.length;g++){let m=eh(f[g]);if(m!=null&&m.references){u=Math.min(u,m.earliestPresentationTime/m.timescale);let y=m.references.reduce((E,S)=>E+S.info.duration||0,0);d=Math.max(d,y+m.earliestPresentationTime/m.timescale)}}d&&$(d)&&Object.keys(r).forEach(g=>{r[g].duration||(r[g].duration=d*r[g].timescale-r[g].start)})}return r}function ch(n){let e={valid:null,remainder:null},t=Q(n,["moof"]);if(t.length<2)return e.remainder=n,e;let s=t[t.length-1];return e.valid=n.slice(0,s.byteOffset-8),e.remainder=n.slice(s.byteOffset-8),e}function We(n,e){let t=new Uint8Array(n.length+e.length);return t.set(n),t.set(e,n.length),t}function hh(n,e){let t=[],s=e.samples,i=e.timescale,r=e.id,a=!1;return Q(s,["moof"]).map(l=>{let c=l.byteOffset-8;Q(l,["traf"]).map(u=>{let d=Q(u,["tfdt"]).map(f=>{let g=f[0],m=V(f,4);return g===1&&(m*=Math.pow(2,32),m+=V(f,8)),m/i})[0];return d!==void 0&&(n=d),Q(u,["tfhd"]).map(f=>{let g=V(f,4),m=V(f,0)&16777215,y=(m&1)!==0,E=0,S=(m&2)!==0,T=(m&8)!==0,v=0,x=(m&16)!==0,I=0,A=(m&32)!==0,b=!y&&(m&131072)!==0,_=8;g===r&&(y?(E=V(f,_),_+=4,E*=Math.pow(2,32),E+=V(f,_),_+=4):b&&(E=c),S&&(_+=4),T&&(v=V(f,_),_+=4),x&&(I=V(f,_),_+=4),A&&(_+=4),e.type==="video"&&(a=Es(e.codec)),Q(u,["trun"]).map(L=>{let P=L[0],D=V(L,0)&16777215,M=(D&1)!==0,U=0,B=(D&4)!==0,k=(D&256)!==0,w=0,O=(D&512)!==0,F=0,H=(D&1024)!==0,N=(D&2048)!==0,G=0,Z=V(L,4),q=8;M&&(U=V(L,q),q+=4),B&&(q+=4);let ie=E+U;for(let j=0;j<Z;j++){if(k?(w=V(L,q),q+=4):w=v,O?(F=V(L,q),q+=4):F=I,H&&(q+=4),N&&(P===0?G=V(L,q):G=rr(L,q),q+=4),e.type===ue.VIDEO){let ne=0;for(;ne<F;){let re=V(s,ie);if(ie+=4,Uo(a,s[ie])){let ae=s.subarray(ie,ie+re);ns(ae,a?2:1,n+G/i,t)}ie+=re,ne+=re+4}}n+=w/i}}))})})}),t}function Es(n){if(!n)return!1;let e=n.substring(0,4);return e==="hvc1"||e==="hev1"||e==="dvh1"||e==="dvhe"}function Uo(n,e){if(n){let t=e>>1&63;return t===39||t===40}else return(e&31)===6}function ns(n,e,t,s){let i=Go(n),r=0;r+=e;let a=0,o=0,l=0;for(;r<i.length;){a=0;do{if(r>=i.length)break;l=i[r++],a+=l}while(l===255);o=0;do{if(r>=i.length)break;l=i[r++],o+=l}while(l===255);let c=i.length-r,h=r;if(o<c)r+=o;else if(o>c){oe.error(`Malformed SEI payload. ${o} is too small, only ${c} bytes left to parse.`);break}if(a===4){if(i[h++]===181){let d=Oo(i,h);if(h+=2,d===49){let f=V(i,h);if(h+=4,f===1195456820){let g=i[h++];if(g===3){let m=i[h++],y=31&m,E=64&m,S=E?2+y*3:0,T=new Uint8Array(S);if(E){T[0]=m;for(let v=1;v<S;v++)T[v]=i[h++]}s.push({type:g,payloadType:a,pts:t,bytes:T})}}}}}else if(a===5&&o>16){let u=[];for(let g=0;g<16;g++){let m=i[h++].toString(16);u.push(m.length==1?"0"+m:m),(g===3||g===5||g===7||g===9)&&u.push("-")}let d=o-16,f=new Uint8Array(d);for(let g=0;g<d;g++)f[g]=i[h++];s.push({payloadType:a,pts:t,uuid:u.join(""),userData:nh(f),userDataBytes:f})}}}function Go(n){let e=n.byteLength,t,s=n.indexOf(3,3);for(;s!==-1;)n[s-1]===0&&n[s-2]===0&&(t||(t=[])).push(s),s=n.indexOf(3,s+1);if(!t)return n;let i=e-t.length,r=new Uint8Array(i),a=0,o=0;for(let l=0;l<i;o++,l++)o===t[a]&&(o++,a++),r[l]=n[o];return r}function uh(n){let e=n[0],t="",s="",i=0,r=0,a,o=0,l=0,c=4;if(e===0){let u=Ss(n,c),d=u!==null?Ss(n,c+u.length):null;u!==null&&d!==null?(t=u,s=d,c+=u.length+d.length,i=V(n,c),c+=4,r=V(n,c),c+=4,o=V(n,c),c+=4,l=V(n,c),c+=4):(oe.warn(`Unterminated ${u===null?"scheme_id_uri":"value"} in parsing emsg box: version 0 box ends inside a string, dropping all of its fields`),c=n.length)}else if(e===1){i=V(n,c),c+=4;let u=V(n,c);c+=4;let d=V(n,c);c+=4,a=2**32*u+d,Tc(a)||(a=Number.MAX_SAFE_INTEGER,oe.warn("Presentation time exceeds safe integer limit and wrapped to max safe integer in parsing emsg box")),o=V(n,c),c+=4,l=V(n,c),c+=4;let f=Ss(n,c),g=f!==null?Ss(n,c+f.length):null;f!==null&&(t=f,c+=f.length),g!==null?(s=g,c+=g.length):(oe.warn(`Unterminated ${f===null?"scheme_id_uri":"value"} in parsing emsg box: version 1 box ends inside a string, dropping its ${f===null?"strings and payload":"value and payload"}`),c=n.length)}let h=n.subarray(c,n.byteLength);return{schemeIdUri:t,value:s,timeScale:i,presentationTime:a,presentationTimeDelta:r,eventDuration:o,id:l,payload:h}}function dh(n,...e){let t=e.length,s=8,i=t;for(;i--;)s+=e[i].byteLength;let r=new Uint8Array(s);for(r[0]=s>>24&255,r[1]=s>>16&255,r[2]=s>>8&255,r[3]=s&255,r.set(n,4),i=0,s=8;i<t;i++)r.set(e[i],s),s+=e[i].byteLength;return r}function fh(n,e,t){if(n.byteLength!==16)throw new RangeError("Invalid system id");let s,i;s=0,i=new Uint8Array;let r;s>0?(r=new Uint8Array(4),e.length>0&&new DataView(r.buffer).setUint32(0,e.length,!1)):r=new Uint8Array;let a=new Uint8Array(4);return t.byteLength>0&&new DataView(a.buffer).setUint32(0,t.byteLength,!1),dh([112,115,115,104],new Uint8Array([s,0,0,0]),n,r,i,a,t)}function Vo(n){let e=[];if(n instanceof ArrayBuffer){let t=n.byteLength,s=0;for(;s+32<t;){let i=new DataView(n,s),r=mh(i);e.push(r),s+=r.size}}return e}function gh(n){let e=[];for(let t=0;t<n.length;){let s=n[t++],i=s&7;if(i===0){for(;n[t++]&128;);continue}if(i!==2){t+=i===1?8:4;continue}let r=0;for(let a=0,o=128;o&128;a+=7)r|=((o=n[t++])&127)<<a;if(s>>3===2)if(r===32){let a=new Uint8Array(16);for(let o=0;o<16;o++)a[o]=parseInt(String.fromCharCode(n[t+o*2],n[t+o*2+1]),16);e.push(a)}else r===16&&e.push(n.subarray(t,t+16));t+=r}return e}function mh(n){let e=n.getUint32(0),t=n.byteOffset,s=n.byteLength;if(s<e)return{offset:t,size:s};if(n.getUint32(4)!==1886614376)return{offset:t,size:e};let r=n.getUint32(8)>>>24;if(r!==0&&r!==1)return{offset:t,size:e};let a=n.buffer,o=Ie(new Uint8Array(a,t+12,16)),l=null,c=null,h=0;if(r===0)h=28;else{let d=n.getUint32(28);if(!d||s<32+d*16)return{offset:t,size:e};l=[];for(let f=0;f<d;f++)l.push(new Uint8Array(a,t+32+f*16,16));h=32+d*16}if(!h)return{offset:t,size:e};let u=n.getUint32(h);return e-32<u?{offset:t,size:e}:(c=new Uint8Array(a,t+h+4,u),r===0&&(l=gh(c)),{version:r,systemId:o,kids:l,data:c,offset:t,size:e})}var Kt=Ko("userAgent"),ph=Ko("vendor"),Pi,Ci,ki;function Ko(n){try{return navigator[n]||""}catch{}return""}function yh(){if(ki===void 0){let n=Kt.match(/Safari\/(\d+)/i);ki=n?parseInt(n[1]):0}return ki}function Xt(){if(Pi===void 0){let n=Kt.match(/Chrome\/(\d+)/i);Pi=n?parseInt(n[1]):0}return Pi}function Eh(){if(Ci===void 0){let n=Kt.match(/Firefox\/(\d+)/i);Ci=n?parseInt(n[1]):0}return Ci}function Ho(){return/\(Windows.+Firefox\//i.test(Kt)}function Th(){return ph.indexOf("Apple")>-1||/iPhone|iPad|iPod/.test(Kt)}function Sh(){return/Android/.test(Kt)}var Ut={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 Pn(n,e){let t=Ut[e];return!!t&&!!t[n.slice(0,4)]}function as(n,e,t=!0){return!n.split(",").some(s=>!Cn(s,e,t))}function Cn(n,e,t=!0){var s;let i=vt(t);return(s=i?.isTypeSupported(os(n,e)))!=null?s:!1}function os(n,e){return`${e}/mp4;codecs=${n}`}function ra(n){if(n){let e=n.substring(0,4);return Ut.video[e]}return 2}function Ks(n){let e=Ho();return n.split(",").reduce((t,s)=>{let r=e&&Es(s)?9:Ut.video[s];return r?(r*2+t)/(t?3:2):(Ut.audio[s]+t)/(t?2:1)},0)}var Oi={};function vh(n,e=!0){if(Oi[n])return Oi[n];let t={flac:["flac","fLaC","FLAC"],opus:["opus","Opus"],"mp4a.40.34":["mp3"]}[n];for(let i=0;i<t.length;i++){var s;if(Cn(t[i],"audio",e))return Oi[n]=t[i],t[i];if(t[i]==="mp3"&&(s=vt(e))!=null&&s.isTypeSupported("audio/mpeg"))return""}return n}var xh=/flac|opus|mp4a\.40\.34/i;function Hs(n,e=!0){return n.replace(xh,t=>vh(t.toLowerCase(),e))}function Ih(n,e){let t=[];if(n){let s=n.split(",");for(let i=0;i<s.length;i++)Pn(s[i],"video")||t.push(s[i])}return e&&t.push(e),t.join(",")}function Ms(n,e){if(n&&(n.length>4||["ac-3","ec-3","alac","fLaC","Opus"].indexOf(n)!==-1)&&(na(n,"audio")||na(n,"video")))return n;if(e){let t=e.split(",");if(t.length>1){if(n){for(let s=t.length;s--;)if(t[s].substring(0,4)===n.substring(0,4))return t[s]}return t[0]}}return e||n}function na(n,e){return Pn(n,e)&&Cn(n,e)}function Ah(n){let e=n.split(",");for(let t=0;t<e.length;t++){let s=e[t].split(".");s.length>2&&s[0]==="avc1"&&(e[t]=`avc1.${parseInt(s[1]).toString(16)}${("000"+parseInt(s[2]).toString(16)).slice(-4)}`)}return e.join(",")}function Lh(n){if(n.startsWith("av01.")){let e=n.split("."),t=["0","111","01","01","01","0"];for(let s=e.length;s>4&&s<10;s++)e[s]=t[s-4];return e.join(".")}return n}function aa(n){let e=vt(n)||{isTypeSupported:()=>!1};return{mpeg:e.isTypeSupported("audio/mpeg"),mp3:e.isTypeSupported('audio/mp4; codecs="mp3"'),ac3:e.isTypeSupported('audio/mp4; codecs="ac-3"')}}function ar(n){return n.replace(/^.+codecs=["']?([^"']+).*$/,"$1")}var Rh={supported:!0,powerEfficient:!0,smooth:!0},bh={supported:!1,smooth:!1,powerEfficient:!1},Yo={supported:!0,configurations:[],decodingInfoResults:[Rh]};function Wo(n,e){return{supported:!1,configurations:e,decodingInfoResults:[bh],error:n}}function _h(n,e,t,s,i,r){let a=n.videoCodec,o=n.audioCodec?n.audioGroups:null,l=r?.audioCodec,c=r?.channels,h=c?parseInt(c):l?1/0:2,u=null;if(o!=null&&o.length)try{o.length===1&&o[0]?u=e.groups[o[0]].channels:u=o.reduce((d,f)=>{if(f){let g=e.groups[f];if(!g)throw new Error(`Audio track group ${f} not found`);Object.keys(g.channels).forEach(m=>{d[m]=(d[m]||0)+g.channels[m]})}return d},{2:0})}catch{return!0}return a!==void 0&&(a.split(",").some(d=>Es(d))||n.width>1920&&n.height>1088||n.height>1920&&n.width>1088||n.frameRate>Math.max(s,30)||n.videoRange!=="SDR"&&n.videoRange!==t||n.bitrate>Math.max(i,8e6))||!!u&&$(h)&&Object.keys(u).some(d=>parseInt(d)>h)}function qo(n,e,t,s={}){let i=n.videoCodec;if(!i&&!n.audioCodec||!t)return Promise.resolve(Yo);let r=[],a=Dh(n),o=a.length,l=Ph(n,e,o>0),c=l.length;for(let h=o||1*c||1;h--;){let u={type:"media-source"};if(o&&(u.video=a[h%o]),c){u.audio=l[h%c];let d=u.audio.bitrate;u.video&&d&&(u.video.bitrate-=d)}r.push(u)}if(i){let h=navigator.userAgent;if(i.split(",").some(u=>Es(u))&&Ho())return Promise.resolve(Wo(new Error(`Overriding Windows Firefox HEVC MediaCapabilities result based on user-agent string: (${h})`),r))}return Promise.all(r.map(h=>{let u=Ch(h);return s[u]||(s[u]=t.decodingInfo(h))})).then(h=>({supported:!h.some(u=>!u.supported),configurations:r,decodingInfoResults:h})).catch(h=>({supported:!1,configurations:r,decodingInfoResults:[],error:h}))}function Dh(n){var e;let t=(e=n.videoCodec)==null?void 0:e.split(","),s=zo(n),i=n.width||640,r=n.height||480,a=n.frameRate||30,o=n.videoRange.toLowerCase();return t?t.map(l=>{let c={contentType:os(Lh(l),"video"),width:i,height:r,bitrate:s,framerate:a};return o!=="sdr"&&(c.transferFunction=o),c}):[]}function Ph(n,e,t){var s;let i=(s=n.audioCodec)==null?void 0:s.split(","),r=zo(n);return i&&n.audioGroups?n.audioGroups.reduce((a,o)=>{var l;let c=o?(l=e.groups[o])==null?void 0:l.tracks:null;return c?c.reduce((h,u)=>{if(u.groupId===o){let d=parseFloat(u.channels||"");i.forEach(f=>{let g={contentType:os(f,"audio"),bitrate:t?jo(f,r):r};d&&(g.channels=""+d),h.push(g)})}return h},a):a},[]):[]}function jo(n,e){if(e<=1)return 1;let t=128e3;return n==="ec-3"?t=768e3:n==="ac-3"&&(t=64e4),Math.min(e/2,t)}function zo(n){return Math.ceil(Math.max(n.bitrate*.9,n.averageBitrate)/1e3)*1e3||1}function Ch(n){let e="",{audio:t,video:s}=n;if(s){let i=ar(s.contentType);e+=`${i}_r${s.height}x${s.width}f${Math.ceil(s.framerate)}${s.transferFunction||"sd"}_${Math.ceil(s.bitrate/1e5)}`}if(t){let i=ar(t.contentType);e+=`${s?"_":""}${i}_c${t.channels}`}return e}function Tt(n,e,t){let s=encodeURIComponent(e),i=`${s}=${encodeURIComponent(t)}`,r=!1,a=[];n.search.substring(1).split("&").forEach(o=>{o===s||o.startsWith(s+"=")?r||(a.push(i),r=!0):o&&a.push(o)}),r||a.push(i),n.search=a.join("&")}var or=["NONE","TYPE-0","TYPE-1",null];function kh(n){return or.indexOf(n)>-1}var Ys=["SDR","PQ","HLG"];function Oh(n){return!!n&&Ys.indexOf(n)>-1}var Fs={No:"",Yes:"YES",v2:"v2"};function oa(n){let{canSkipUntil:e,canSkipDateRanges:t,age:s}=n,i=s<e/2;return e&&i?t?Fs.v2:Fs.Yes:Fs.No}var Ws=class{constructor(e,t,s){this.msn=void 0,this.part=void 0,this.skip=void 0,this.msn=e,this.part=t,this.skip=s}addDirectives(e){let t=new self.URL(e);return this.msn!==void 0&&Tt(t,"_HLS_msn",this.msn.toString()),this.part!==void 0&&Tt(t,"_HLS_part",this.part.toString()),this.skip&&Tt(t,"_HLS_skip",this.skip),t.href}},Pt=class{constructor(e){if(this._attrs=void 0,this.audioCodec=void 0,this.bitrate=void 0,this.codecSet=void 0,this.url=void 0,this.frameRate=void 0,this.height=void 0,this.id=void 0,this.name=void 0,this.supplemental=void 0,this.videoCodec=void 0,this.width=void 0,this.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=[e.url],this._attrs=[e.attrs],this.bitrate=e.bitrate,e.details&&(this.details=e.details),this.id=e.id||0,this.name=e.name,this.width=e.width||0,this.height=e.height||0,this.frameRate=e.attrs.optionalFloat("FRAME-RATE",0),this._avgBitrate=e.attrs.decimalInteger("AVERAGE-BANDWIDTH"),this.audioCodec=e.audioCodec,this.videoCodec=e.videoCodec,"imageCodec"in e&&(this.imageCodec=e.imageCodec),this.codecSet=[e.videoCodec,e.audioCodec].filter(s=>!!s).map(s=>s.substring(0,4)).join(","),"supplemental"in e){var t;this.supplemental=e.supplemental;let s=(t=e.supplemental)==null?void 0:t.videoCodec;s&&s!==e.videoCodec&&(this.codecSet+=`,${s.substring(0,4)}`)}"iframes"in e&&e.iframes?this.iframes=!0:(this.addGroupId("audio",e.attrs.AUDIO),this.addGroupId("text",e.attrs.SUBTITLES))}get maxBitrate(){return Math.max(this.realBitrate,this.bitrate)}get averageBitrate(){return this._avgBitrate||this.realBitrate||this.bitrate}get attrs(){return this._attrs[0]}get codecs(){return this.attrs.CODECS||""}get pathwayId(){return this.attrs["PATHWAY-ID"]||"."}get videoRange(){return this.attrs["VIDEO-RANGE"]||"SDR"}get score(){return this.attrs.optionalFloat("SCORE",0)}get uri(){return this.url[0]||""}hasAudioGroup(e){return la(this._audioGroups,e)}hasSubtitleGroup(e){return la(this._subtitleGroups,e)}get audioGroups(){return this._audioGroups}get subtitleGroups(){return this._subtitleGroups}addGroupId(e,t){if(t){if(e==="audio"){let s=this._audioGroups;s||(s=this._audioGroups=[]),s.indexOf(t)===-1&&s.push(t)}else if(e==="text"){let s=this._subtitleGroups;s||(s=this._subtitleGroups=[]),s.indexOf(t)===-1&&s.push(t)}}}get urlId(){return 0}set urlId(e){}get audioGroupIds(){return this.audioGroups?[this.audioGroupId]:void 0}get textGroupIds(){return this.subtitleGroups?[this.textGroupId]:void 0}get audioGroupId(){var e;return(e=this.audioGroups)==null?void 0:e[0]}get textGroupId(){var e;return(e=this.subtitleGroups)==null?void 0:e[0]}addFallback(){}};function la(n,e){return!e||!n?!1:n.indexOf(e)!==-1}function wh(){if(typeof matchMedia=="function"){let n=matchMedia("(dynamic-range: high)"),e=matchMedia("bad query");if(n.media!==e.media)return n.matches===!0}return!1}function Mh(n,e){let t=!1,s=[];if(n&&(t=n!=="SDR",s=[n]),e){s=e.allowedVideoRanges||Ys.slice(0);let i=s.join("")!=="SDR"&&!e.videoCodec;t=e.preferHDR!==void 0?e.preferHDR:i&&wh(),t||(s=["SDR"])}return{preferHDR:t,allowedVideoRanges:s}}var Fh=n=>{let e=new WeakSet;return(t,s)=>{if(n&&(s=n(t,s)),typeof s=="object"&&s!==null){if(e.has(s))return;e.add(s)}return s}},de=(n,e)=>JSON.stringify(n,Fh(e));function Nh(n,e,t,s,i){let r=Object.keys(n),a=s?.channels,o=s?.audioCodec,l=i?.videoCodec,c=a&&parseInt(a)===2,h=!1,u=!1,d=1/0,f=1/0,g=1/0,m=1/0,y=0,E=[],{preferHDR:S,allowedVideoRanges:T}=Mh(e,i);for(let b=r.length;b--;){let _=n[r[b]];h||(h=_.channels[2]>0),d=Math.min(d,_.minHeight),f=Math.min(f,_.minFramerate),g=Math.min(g,_.minBitrate),T.filter(P=>_.videoRanges[P]>0).length>0&&(u=!0)}d=$(d)?d:0,f=$(f)?f:0;let v=Math.max(1080,d),x=Math.max(30,f);g=$(g)?g:t,t=Math.max(g,t),u||(e=void 0);let I=r.length>1;return{codecSet:r.reduce((b,_)=>{let L=n[_];if(_===b)return b;if(E=u?T.filter(P=>L.videoRanges[P]>0):[],I){if(L.minBitrate>t)return Je(_,`min bitrate of ${L.minBitrate} > current estimate of ${t}`),b;if(!L.hasDefaultAudio)return Je(_,"no renditions with default or auto-select sound found"),b;if(o&&_.indexOf(o.substring(0,4))%5!==0)return Je(_,`audio codec preference "${o}" not found`),b;if(a&&!c){if(!L.channels[a])return Je(_,`no renditions with ${a} channel sound found (channels options: ${Object.keys(L.channels)})`),b}else if((!o||c)&&h&&L.channels[2]===0)return Je(_,"no renditions with stereo sound found"),b;if(L.minHeight>v)return Je(_,`min resolution of ${L.minHeight} > maximum of ${v}`),b;if(L.minFramerate>x)return Je(_,`min framerate of ${L.minFramerate} > maximum of ${x}`),b;if(!E.some(P=>L.videoRanges[P]>0))return Je(_,`no variants with VIDEO-RANGE of ${de(E)} found`),b;if(l&&_.indexOf(l.substring(0,4))%5!==0)return Je(_,`video codec preference "${l}" not found`),b;if(L.maxScore<y)return Je(_,`max score of ${L.maxScore} < selected max of ${y}`),b}return b&&(Ks(_)>=Ks(b)||L.fragmentError>n[b].fragmentError)?b:(m=L.minIndex,y=L.maxScore,_)},void 0),videoRanges:E,preferHDR:S,minFramerate:f,minBitrate:g,minIndex:m}}function Je(n,e){oe.log(`[abr] start candidates with "${n}" ignored because ${e}`)}function Xo(n){return n.reduce((e,t)=>{let s=e.groups[t.groupId];s||(s=e.groups[t.groupId]={tracks:[],channels:{2:0},hasDefault:!1,hasAutoSelect:!1}),s.tracks.push(t);let i=t.channels||"2";return s.channels[i]=(s.channels[i]||0)+1,s.hasDefault=s.hasDefault||t.default,s.hasAutoSelect=s.hasAutoSelect||t.autoselect,s.hasDefault&&(e.hasDefaultAudio=!0),s.hasAutoSelect&&(e.hasAutoSelectAudio=!0),e},{hasDefaultAudio:!1,hasAutoSelectAudio:!1,groups:{}})}function Bh(n,e,t,s){return n.slice(t,s+1).reduce((i,r,a)=>{if(!r.codecSet)return i;let o=r.audioGroups,l=i[r.codecSet];l||(i[r.codecSet]=l={minBitrate:1/0,minHeight:1/0,minFramerate:1/0,minIndex:a,maxScore:0,videoRanges:{SDR:0},channels:{2:0},hasDefaultAudio:!o,fragmentError:0}),l.minBitrate=Math.min(l.minBitrate,r.bitrate);let c=Math.min(r.height,r.width);return l.minHeight=Math.min(l.minHeight,c),l.minFramerate=Math.min(l.minFramerate,r.frameRate),l.minIndex=Math.min(l.minIndex,a),l.maxScore=Math.max(l.maxScore,r.score),l.fragmentError+=r.fragmentError,l.videoRanges[r.videoRange]=(l.videoRanges[r.videoRange]||0)+1,o&&o.forEach(h=>{if(!h)return;let u=e.groups[h];u&&(l.hasDefaultAudio=l.hasDefaultAudio||e.hasDefaultAudio?u.hasDefault:u.hasAutoSelect||!e.hasDefaultAudio&&!e.hasAutoSelectAudio,Object.keys(u.channels).forEach(d=>{l.channels[d]=(l.channels[d]||0)+u.channels[d]}))}),i},{})}function ca(n){if(!n)return n;let{lang:e,assocLang:t,characteristics:s,channels:i,audioCodec:r}=n;return{lang:e,assocLang:t,characteristics:s,channels:i,audioCodec:r}}function it(n,e,t){if("attrs"in n){let s=e.indexOf(n);if(s!==-1)return s}for(let s=0;s<e.length;s++){let i=e[s];if(_t(n,i,t))return s}return-1}function _t(n,e,t){let{groupId:s,name:i,lang:r,assocLang:a,default:o}=n,l=n.forced;return(s===void 0||e.groupId===s)&&(i===void 0||e.name===i)&&(r===void 0||$h(r,e.lang))&&(a===void 0||e.assocLang===a)&&(o===void 0||e.default===o)&&(l===void 0||e.forced===l)&&(!("characteristics"in n)||Uh(n.characteristics||"",e.characteristics))&&(t===void 0||t(n,e))}function $h(n,e="--"){return n.length===e.length?n===e:n.startsWith(e)||e.startsWith(n)}function Uh(n,e=""){let t=n.split(","),s=e.split(",");return t.length===s.length&&!t.some(i=>s.indexOf(i)===-1)}function bt(n,e){let{audioCodec:t,channels:s}=n;return(t===void 0||(e.audioCodec||"").substring(0,4)===t.substring(0,4))&&(s===void 0||s===(e.channels||"2"))}function Gh(n,e,t,s,i){let r=e[s],o=e.reduce((d,f,g)=>{let m=f.uri;return(d[m]||(d[m]=[])).push(g),d},{})[r.uri];o.length>1&&(s=Math.max.apply(Math,o));let l=r.videoRange,c=r.frameRate,h=r.codecSet.substring(0,4),u=ha(e,s,d=>{if(d.videoRange!==l||d.frameRate!==c||d.codecSet.substring(0,4)!==h)return!1;let f=d.audioGroups,g=t.filter(m=>ls(m.groupId,f));return it(n,g,i)>-1});return u>-1?u:ha(e,s,d=>{let f=d.audioGroups,g=t.filter(m=>ls(m.groupId,f));return it(n,g,i)>-1})}function ha(n,e,t){for(let s=e;s>-1;s--)if(t(n[s]))return s;for(let s=e+1;s<n.length;s++)if(t(n[s]))return s;return-1}function qs(n,e){var t;return!!n&&n!==((t=e.loadLevelObj)==null?void 0:t.uri)}function ls(n,e){return e?e.indexOf(n)!==-1:!0}function Qo(n,e){if(e||n){let t=he({},e);return n&&(n.videoCodec&&(t.videoCodec=n.videoCodec),n.videoRange&&(t.allowedVideoRanges=[n.videoRange])),t}}var lr=class extends we{constructor(e){super("abr",e.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 s;let{fragCurrent:i,partCurrent:r,hls:a}=this;if(!a)return;let{autoLevelEnabled:o,media:l}=a;if(!i||!l)return;let c=performance.now(),h=r?r.stats:i.stats,u=r?r.duration:i.duration,d=c-h.loading.start,f=a.minAutoLevel,g=i.level,m=this._nextAutoLevel;if(h.aborted||h.loaded&&h.loaded===h.total||g<=f){this.clearTimer(),this._nextAutoLevel=-1;return}if(!o)return;let y=m>-1&&m!==g,E=!!t||y;if(!E&&(l.paused||!l.playbackRate||!l.readyState))return;let S=a.mainForwardBufferInfo;if(!E&&S===null)return;let T=this.bwEstimator.getEstimateTTFB(),v=Math.abs(l.playbackRate);if(d<=Math.max(T,1e3*(u/(v*2))))return;let x=S?S.len/v:0,I=h.loading.first?h.loading.first-h.loading.start:-1,A=h.loaded&&I>-1,b=this.getBwEstimate(),_=a.levels,L=_[g],P=Math.max(h.loaded,Math.round(u*(i.bitrate||L.averageBitrate)/8)),D=A?d-I:d;D<1&&A&&(D=Math.min(d,h.loaded*8/b));let M=A?h.loaded*1e3/D:0,U=T/1e3,B=M?(P-h.loaded)/M:P*8/b+U;if(B<=x)return;let k=M?M*8:b,w=((s=t?.details||a.latestLevelDetails)==null?void 0:s.live)===!0,O=a.config.abrBandWidthUpFactor,F=Number.POSITIVE_INFINITY,H;for(H=g-1;H>f;H--){let q=_[H].maxBitrate,ie=!_[H].details||w;if(F=this.getTimeToLoadFrag(U,k,u*q,ie),F<Math.min(x,u+U))break}if(F>=B||F>u*10)return;A?this.bwEstimator.sample(d-Math.min(T,I),h.loaded):this.bwEstimator.sampleTTFB(d);let N=_[H].maxBitrate;this.getBwEstimate()*O>N&&(this.firstAutoFloor=Math.min(H,a.firstLevel),this.resetEstimator(N));let G=this.findBestLevel(N,f,H,0,x,1,1);G>-1&&(H=G),this.warn(`Fragment ${i.sn}${r?" part "+r.index:""} of level ${g} is loading too slowly;
2
+ Fragment duration: ${i.duration.toFixed(3)}
3
+ Time to underbuffer: ${x.toFixed(3)} s
4
+ Estimated load time for current fragment: ${B.toFixed(3)} s
5
+ Estimated load time for down switch fragment: ${F.toFixed(3)} s
6
+ TTFB estimate: ${I|0} ms
7
+ Current BW estimate: ${$(b)?b|0:"Unknown"} bps
8
+ New BW estimate: ${this.getBwEstimate()|0} bps
9
+ Switching to level ${H} @ ${N|0} bps`),a.nextLoadLevel=a.nextAutoLevel=H,this.clearTimer();let Z=()=>{this.clearTimer();let q=this.hls;if(this.fragCurrent===i&&q.loadLevel===H&&H>0){let ie=this.getStarvationDelay();if(this.warn(`Aborting inflight request ${H>0?"and switching down":""}
10
+ Fragment duration: ${i.duration.toFixed(3)} s
11
+ Time to underbuffer: ${ie.toFixed(3)} s`),i.abortRequests(),this.fragCurrent=this.partCurrent=null,H>f){let j=this.findBestLevel(q.levels[f].bitrate,f,H,0,ie,1,1);j===-1&&(j=f),q.nextLoadLevel=q.nextAutoLevel=j,this.firstAutoFloor=Math.min(j,q.firstLevel),this.resetEstimator(q.levels[j].bitrate)}}};y||B>F*2?Z():this.timer=self.setInterval(Z,F*1e3),a.trigger(p.FRAG_LOAD_EMERGENCY_ABORTED,{frag:i,part:r,stats:h})},this.hls=e,this.bwEstimator=this.initEstimator(),this.registerListeners()}resetEstimator(e){this.hls&&(e&&(this.log(`setting initial bwe to ${e}`),this.hls.config.abrEwmaDefaultEstimate=e),this.firstSelection=-1,this.bwEstimator=this.initEstimator())}initEstimator(){let e=this.hls.config;return new tr(e.abrEwmaSlowVoD,e.abrEwmaFastVoD,e.abrEwmaDefaultEstimate)}registerListeners(){let e=this.hls;e.on(p.MANIFEST_LOADING,this.onManifestLoading,this),e.on(p.FRAG_LOADING,this.onFragLoading,this),e.on(p.FRAG_LOADED,this.onFragLoaded,this),e.on(p.FRAG_BUFFERED,this.onFragBuffered,this),e.on(p.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(p.LEVEL_LOADED,this.onLevelLoaded,this),e.on(p.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(p.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.on(p.ERROR,this.onError,this)}unregisterListeners(){let{hls:e}=this;e&&(e.off(p.MANIFEST_LOADING,this.onManifestLoading,this),e.off(p.FRAG_LOADING,this.onFragLoading,this),e.off(p.FRAG_LOADED,this.onFragLoaded,this),e.off(p.FRAG_BUFFERED,this.onFragBuffered,this),e.off(p.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(p.LEVEL_LOADED,this.onLevelLoaded,this),e.off(p.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(p.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.off(p.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(e,t){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(e,t){let s=t.frag;if(!this.ignoreFragment(s)){if(!s.bitrateTest){var i;this.fragCurrent=s,this.partCurrent=(i=t.part)!=null?i:null}this.clearTimer(),this.timer=self.setInterval(this._abandonRulesCheck,100)}}onLevelSwitching(e,t){this.clearTimer()}onError(e,t){if(!t.fatal)switch(t.details){case R.BUFFER_ADD_CODEC_ERROR:case R.BUFFER_APPEND_ERROR:this.lastLoadedFragLevel=-1,this.firstSelection=-1;break;case R.FRAG_LOAD_TIMEOUT:{let s=t.frag,{fragCurrent:i,partCurrent:r}=this;if(s&&Ji(s,i)){let a=performance.now(),o=r?r.stats:s.stats,l=a-o.loading.start,c=o.loading.first?o.loading.first-o.loading.start:-1;if(o.loaded&&c>-1){let u=this.bwEstimator.getEstimateTTFB();this.bwEstimator.sample(l-Math.min(u,c),o.loaded)}else this.bwEstimator.sampleTTFB(l)}break}}}getTimeToLoadFrag(e,t,s,i){let r=e+s/t,a=i?e+this.lastLevelLoadSec:0;return r+a}onLevelLoaded(e,t){let s=this.hls.config,{loading:i}=t.stats,r=i.end-i.first;$(r)&&(this.lastLevelLoadSec=r/1e3),t.details.live?this.bwEstimator.update(s.abrEwmaSlowLive,s.abrEwmaFastLive):this.bwEstimator.update(s.abrEwmaSlowVoD,s.abrEwmaFastVoD),this.timer>-1&&this._abandonRulesCheck(t.levelInfo)}onFragLoaded(e,t){var s;let{frag:i,part:r}=t,a=r?r.stats:i.stats;if(i.type===K.MAIN&&this.bwEstimator.sampleTTFB(a.loading.first-a.loading.start),!this.ignoreFragment(i)){if(this.clearTimer(),i.level===this._nextAutoLevel&&(this._nextAutoLevel=-1),this.firstSelection=-1,(s=this.hls)!=null&&s.config.abrMaxWithRealBitrate){let o=r?r.duration:i.duration,l=this.hls.levels[i.level],c=(l.loaded?l.loaded.bytes:0)+a.loaded,h=(l.loaded?l.loaded.duration:0)+o;l.loaded={bytes:c,duration:h},l.realBitrate=Math.round(8*c/h)}if(i.bitrateTest){let o={stats:a,frag:i,part:r,id:i.type};this.onFragBuffered(p.FRAG_BUFFERED,o),i.bitrateTest=!1}else this.lastLoadedFragLevel=i.level}}onFragBuffered(e,t){let{frag:s,part:i}=t,r=i!=null&&i.stats.loaded?i.stats:s.stats;if(r.aborted||this.ignoreFragment(s))return;let o=((s.bitrate||0)>=1e5?r.parsing.end:r.loading.end)-r.loading.start-Math.min(r.loading.first-r.loading.start,this.bwEstimator.getEstimateTTFB());this.bwEstimator.sample(o,r.loaded),r.bwEstimate=this.getBwEstimate(),s.bitrateTest?this.bitrateTestDelay=o/1e3:(this.bitrateTestDelay=0,this.firstAutoFloor>-1&&this.bwEstimator.canEstimate()&&(this.firstAutoFloor=-1))}ignoreFragment(e){return e.type!==K.MAIN||e.sn==="initSegment"}clearTimer(){this.timer>-1&&(self.clearInterval(this.timer),this.timer=-1)}get firstAutoLevel(){let{hls:e}=this;if(!e)return 0;let{maxAutoLevel:t,minAutoLevel:s}=e,i=this.getBwEstimate(),r=this.getStarvationDelay(),a=e.config.maxStarvationDelay,o=this.findBestLevel(i,s,t,r/2,a,1,1);if(o>-1)return o;let l=e.firstLevel,c=this.firstAutoFloor===-1?1/0:this.firstAutoFloor,h=Math.min(Math.max(l,s),t,c);return this.warn(`Could not find best starting auto level. Defaulting to first in playlist ${l} clamped to ${h}`),h}get forcedAutoLevel(){return this.nextAutoLevelKey?-1:this._nextAutoLevel}get nextAutoLevel(){if(!this.hls)return-1;let e=this.forcedAutoLevel,s=this.bwEstimator.canEstimate(),i=this.lastLoadedFragLevel>-1;if(e!==-1&&(!s||!i||this.nextAutoLevelKey===this.getAutoLevelKey()))return e;let r=s&&i?this.getNextABRAutoLevel():this.firstAutoLevel;if(e!==-1){let a=this.hls.levels;if(a.length>Math.max(e,r)&&a[e].loadError<=a[r].loadError)return e}return this._nextAutoLevel=r,this.nextAutoLevelKey=this.getAutoLevelKey(),r}getAutoLevelKey(){return`${this.getBwEstimate()}_${this.getStarvationDelay().toFixed(2)}`}getNextABRAutoLevel(){let{fragCurrent:e,partCurrent:t,hls:s}=this;if(!s)return-1;if(s.levels.length<=1)return s.loadLevel;let{maxAutoLevel:i,config:r,minAutoLevel:a}=s,o=t?t.duration:e?e.duration:0,l=this.getBwEstimate(),c=this.getStarvationDelay(),h=r.abrBandWidthFactor,u=r.abrBandWidthUpFactor;if(c){let y=this.findBestLevel(l,a,i,c,0,h,u);if(y>=0)return this.rebufferNotice=-1,y}let d=o?Math.min(o,r.maxStarvationDelay):r.maxStarvationDelay;if(!c){let y=this.bitrateTestDelay;y&&(d=(o?Math.min(o,r.maxLoadingDelay):r.maxLoadingDelay)-y,this.info(`bitrate test took ${Math.round(1e3*y)}ms, set first fragment max fetchDuration to ${Math.round(1e3*d)} ms`),h=u=1)}let f=this.findBestLevel(l,a,i,c,d,h,u);if(this.rebufferNotice!==f&&(this.rebufferNotice=f,this.info(`${c?"rebuffering expected":"buffer is empty"}, optimal quality level ${f}`)),f>-1)return f;let g=s.levels[a],m=s.loadLevelObj;return m&&g?.bitrate<m.bitrate?a:s.loadLevel}getStarvationDelay(){let e=this.hls,t=e?.media;if(!t)return 1/0;let s=t&&t.playbackRate!==0?Math.abs(t.playbackRate):1,i=e.mainForwardBufferInfo;return(i?i.len:0)/s}getBwEstimate(){return this.bwEstimator.getEstimate()}findBestLevel(e,t,s,i,r,a,o){let{hls:l,lastLoadedFragLevel:c,fragCurrent:h,partCurrent:u}=this;if(!l)return-1;let d=i+r,f=c===-1?l.firstLevel:c,{levels:g,allAudioTracks:m,loadLevel:y,latestLevelDetails:E,config:S}=l;if(g.length===1)return 0;let T=g[f],v=!!(E!=null&&E.live),x=y===-1||c===-1,I,A="SDR",b=T?.frameRate||0,{audioPreference:_,videoPreference:L}=S,P=this.audioTracksByGroup||(this.audioTracksByGroup=Xo(m)),D=-1;if(x){if(this.firstSelection!==-1)return this.firstSelection;let w=this.codecTiers||(this.codecTiers=Bh(g,P,t,s)),O=Nh(w,A,e,_,L),{codecSet:F,videoRanges:H,minFramerate:N,minBitrate:G,minIndex:Z,preferHDR:q}=O;D=Z,I=F,A=q?H[H.length-1]:H[0],b=N,e=Math.max(e,G),this.log(`picked start tier ${de(O)}`)}else I=T?.codecSet,A=T?.videoRange;let M=u?u.duration:h?h.duration:0,U=this.bwEstimator.getEstimateTTFB()/1e3,B=[];for(let w=s;w>=t;w--){var k;let O=g[w],F=w>f;if(!O)continue;if(S.useMediaCapabilities&&!O.supportedResult&&!O.supportedPromise){let j=navigator.mediaCapabilities;typeof j?.decodingInfo=="function"&&_h(O,P,A,b,e,_)?(O.supportedPromise=qo(O,P,j,this.supportedCache),O.supportedPromise.then(ne=>{if(!this.hls)return;O.supportedResult=ne;let re=this.hls.levels,ae=re.indexOf(O);ne.error?this.warn(`MediaCapabilities decodingInfo error: "${ne.error}" for level ${ae} ${de(ne)}`):ne.supported?ne.decodingInfoResults.some(Ee=>Ee.smooth===!1||Ee.powerEfficient===!1)&&this.log(`MediaCapabilities decodingInfo for level ${ae} not smooth or powerEfficient: ${de(ne)}`):(this.warn(`Unsupported MediaCapabilities decodingInfo result for level ${ae} ${de(ne)}`),ae>-1&&re.length>1&&(this.log(`Removing unsupported level ${ae}`),this.hls.removeLevel(ae),this.hls.loadLevel===-1&&(this.hls.nextLoadLevel=0)))}).catch(ne=>{this.warn(`Error handling MediaCapabilities decodingInfo: ${ne}`)})):O.supportedResult=Yo}if((I&&O.codecSet!==I||A&&O.videoRange!==A||F&&b>O.frameRate||!F&&b>0&&b<O.frameRate||(k=O.supportedResult)!=null&&(k=k.decodingInfoResults)!=null&&k.some(j=>j.smooth===!1))&&(!x||w!==D)){B.push(w);continue}let H=O.details,N=(u?H?.partTarget:H?.averagetargetduration)||M||1,G;F?G=o*e:G=a*e;let Z=M&&i>=M*2&&r===0?O.averageBitrate:O.maxBitrate,q=this.getTimeToLoadFrag(U,G,Z*N,!H||H.live);if(G>=Z&&(w===c||O.loadError===0&&O.fragmentError===0||Ao(O,S.errorPenaltyExpireMs))&&(q<=U||!$(q)||v&&!this.bitrateTestDelay||q<d)){let j=this.forcedAutoLevel;return w!==y&&(j===-1||j!==y)&&(B.length&&this.trace(`Skipped level(s) ${B.join(",")} of ${s} max with CODECS and VIDEO-RANGE:"${g[B[0]].codecs}" ${g[B[0]].videoRange}; not compatible with "${I}" ${A}`),this.info(`switch candidate:${f}->${w} adjustedbw(${Math.round(G)})-bitrate=${Math.round(G-Z)} ttfb:${U.toFixed(1)} avgDuration:${N.toFixed(1)} maxFetchDuration:${d.toFixed(1)} fetchDuration:${q.toFixed(1)} firstSelection:${x} codecSet:${O.codecSet} videoRange:${O.videoRange} hls.loadLevel:${y}`)),x&&(this.firstSelection=w),w}}return-1}set nextAutoLevel(e){let t=this.deriveNextAutoLevel(e);this._nextAutoLevel!==t&&(this.nextAutoLevelKey="",this._nextAutoLevel=t)}deriveNextAutoLevel(e){if(!this.hls)return-1;let{maxAutoLevel:t,minAutoLevel:s}=this.hls;return Math.min(Math.max(e,s),t)}},cr=class{constructor(e){this.tracks=void 0,this.queues={video:[],audio:[],audiovideo:[]},this.tracks=e}destroy(){this.tracks=this.queues=null}append(e,t,s){if(this.queues===null||this.tracks===null)return;let i=this.queues[t];i.push(e),i.length===1&&!s&&this.executeNext(t)}appendBlocker(e){return new Promise(t=>{let s={label:"async-blocker",execute:t,onStart:()=>{},onComplete:()=>{},onError:()=>{}};this.append(s,e)})}prependBlocker(e){return new Promise(t=>{if(this.queues){let s={label:"async-blocker-prepend",execute:t,onStart:()=>{},onComplete:()=>{},onError:()=>{}};this.queues[e].unshift(s)}})}removeBlockers(){this.queues!==null&&[this.queues.video,this.queues.audio,this.queues.audiovideo].forEach(e=>{var t;let s=(t=e[0])==null?void 0:t.label;s==="async-blocker"||s==="async-blocker-prepend"?(e[0].execute(),e.splice(0,1)):s==="block-audio"&&e.splice(0,1)})}insertNext(e,t){this.queues!==null&&this.queues[t].splice(1,0,...e)}unblockAudio(){var e;this.queues!==null&&((e=this.current("audio"))==null?void 0:e.label)==="block-audio"&&this.shiftAndExecuteNext("audio")}audioBlocking(){return this.queues===null?!1:this.queues.audio.some(e=>e.label==="block-audio")}executeNext(e){if(this.queues===null||this.tracks===null)return;let t=this.queues[e];if(t.length){let i=t[0];try{i.execute()}catch(r){var s;if(i.onError(r),this.queues===null||this.tracks===null)return;let a=(s=this.tracks[e])==null?void 0:s.buffer;a!=null&&a.updating||this.shiftAndExecuteNext(e)}}}shiftAndExecuteNext(e){this.queues!==null&&(this.queues[e].shift(),this.executeNext(e))}current(e){var t;return((t=this.queues)==null?void 0:t[e][0])||null}toString(){let{queues:e,tracks:t}=this;return e===null||t===null?"<destroyed>":`
12
+ ${this.list("video")}
13
+ ${this.list("audio")}
14
+ ${this.list("audiovideo")}}`}list(e){var t,s;return(t=this.queues)!=null&&t[e]||(s=this.tracks)!=null&&s[e]?`${e}: (${this.listSbInfo(e)}) ${this.listOps(e)}`:""}listSbInfo(e){var t;let s=(t=this.tracks)==null?void 0:t[e],i=s?.buffer;return i?`SourceBuffer${i.updating?" updating":""}${s.ended?" ended":""}${s.ending?" ending":""}`:"none"}listOps(e){var t;return((t=this.queues)==null?void 0:t[e].map(s=>s.label).join(", "))||""}},Zo={search:function(n,e){let t=0,s=n.length-1,i=null,r=null;for(;t<=s;){i=(t+s)/2|0,r=n[i];let a=e(r);if(a>0)t=i+1;else if(a<0)s=i-1;else return r}return null}};function Vh(n,e,t){if(e===null||!Array.isArray(n)||!n.length||!$(e))return null;let s=n[0].programDateTime;if(e<(s||0))return null;let i=n[n.length-1].endProgramDateTime;if(e>=(i||0))return null;for(let r=0;r<n.length;++r){let a=n[r];if(Hh(e,t,a))return a}return null}function Gt(n,e,t=0,s=0,i=.005){let r=null;if(n){r=e[1+n.sn-e[0].sn]||null;let o=n.endDTS-t;o>0&&o<15e-7&&(t+=15e-7),r&&n.level!==r.level&&r.end<=n.end&&(r=e[2+n.sn-e[0].sn]||null)}else t===0&&e[0].start===0&&(r=e[0]);if(r&&((!n||n.level===r.level)&&ua(t,s,r)===0||Kh(r,n,Math.min(i,s))))return r;let a=Zo.search(e,ua.bind(null,t,s));return a&&(a!==n||!r)?a:r}function Kh(n,e,t){if(e?.start===0&&e.level<n.level&&(e.endPTS||0)>0){let s=e.tagList.reduce((i,r)=>(r[0]==="INF"&&(i+=parseFloat(r[1])),i),t);return n.start<=s}return!1}function ua(n=0,e=0,t){if(t.start<=n&&t.start+t.duration>n)return 0;let s=Math.min(e,t.duration+(t.deltaPTS?t.deltaPTS:0));return t.start+t.duration-s<=n?1:t.start-s>n&&t.start?-1:0}function Hh(n,e,t){let s=Math.min(e,t.duration+(t.deltaPTS?t.deltaPTS:0))*1e3;return(t.endProgramDateTime||0)-s>n}function Jo(n,e,t){if(n&&n.startCC<=e&&n.endCC>=e){let s=n.fragments,{fragmentHint:i}=n;i&&(s=s.concat(i));let r;return Zo.search(s,a=>a.cc<e?1:a.cc>e?-1:(r=a,a.end<=t?1:a.start>t?-1:0)),r||null}return null}function el(n,e){return e===n.endSN&&n.fragmentHint?n.fragmentHint:n.fragments[1+e-n.startSN]||null}var Re={DoNothing:0,SendEndCallback:1,SendAlternateToPenaltyBox:2,RemoveAlternatePermanently:3,InsertDiscontinuity:4,RetryRequest:5},Le={None:0,MoveAllAlternatesMatchingHost:1,MoveAllAlternatesMatchingHDCP:2,MoveAllAlternatesMatchingKey:4,SwitchToSDR:8,ResetMediaSource:16},hr=class extends we{constructor(e){super("error-controller",e.logger),this.hls=void 0,this.playlistError=0,this.hls=e,this.registerListeners()}registerListeners(){let e=this.hls;e.on(p.ERROR,this.onError,this),e.on(p.MANIFEST_LOADING,this.onManifestLoading,this),e.on(p.LEVEL_UPDATED,this.onLevelUpdated,this)}unregisterListeners(){let e=this.hls;e&&(e.off(p.ERROR,this.onError,this),e.off(p.ERROR,this.onErrorOut,this),e.off(p.MANIFEST_LOADING,this.onManifestLoading,this),e.off(p.LEVEL_UPDATED,this.onLevelUpdated,this))}destroy(){this.unregisterListeners(),this.hls=null}startLoad(e){}stopLoad(){this.playlistError=0}getVariantLevelIndex(e){return e?.type===K.MAIN?e.level:this.getVariantIndex()}getVariantIndex(){var e;let t=this.hls,s=t.currentLevel;return(e=t.loadLevelObj)!=null&&e.details||s===-1?t.loadLevel:s}variantHasKey(e,t){if(e){var s;if((s=e.details)!=null&&s.hasKey(t))return!0;let i=e.audioGroups;if(i)return this.hls.allAudioTracks.filter(a=>i.indexOf(a.groupId)>=0).some(a=>{var o;return(o=a.details)==null?void 0:o.hasKey(t)})}return!1}onManifestLoading(){this.playlistError=0}onLevelUpdated(){this.playlistError=0}onError(e,t){var s;if(t.fatal)return;let i=this.hls,r=t.context;switch(t.details){case R.FRAG_LOAD_ERROR:case R.FRAG_LOAD_TIMEOUT:case R.KEY_LOAD_ERROR:case R.KEY_LOAD_TIMEOUT:t.errorAction=this.getFragRetryOrSwitchAction(t);return;case R.FRAG_PARSING_ERROR:if((s=t.frag)!=null&&s.gap){t.errorAction=Qt();return}case R.FRAG_GAP:case R.FRAG_DECRYPT_ERROR:{t.errorAction=this.getFragRetryOrSwitchAction(t),t.errorAction.action=Re.SendAlternateToPenaltyBox;return}case R.PLAYLIST_UNCHANGED_ERROR:case R.LEVEL_EMPTY_ERROR:case R.LEVEL_PARSING_ERROR:{var a;let o=t.parent===K.MAIN?t.level:i.loadLevel;t.details===R.LEVEL_EMPTY_ERROR&&((a=t.context)!=null&&(a=a.levelDetails)!=null&&a.live)?t.errorAction=this.getPlaylistRetryOrSwitchAction(t,o):(t.levelRetry=!1,t.errorAction=this.getLevelSwitchAction(t,o))}return;case R.LEVEL_LOAD_ERROR:case R.LEVEL_LOAD_TIMEOUT:typeof r?.level=="number"&&(t.errorAction=this.getPlaylistRetryOrSwitchAction(t,r.level));return;case R.AUDIO_TRACK_LOAD_ERROR:case R.AUDIO_TRACK_LOAD_TIMEOUT:case R.SUBTITLE_LOAD_ERROR:case R.SUBTITLE_TRACK_LOAD_TIMEOUT:if(r){let o=i.loadLevelObj;if(o&&(r.type===se.AUDIO_TRACK&&o.hasAudioGroup(r.groupId)||r.type===se.SUBTITLE_TRACK&&o.hasSubtitleGroup(r.groupId))){t.errorAction=this.getPlaylistRetryOrSwitchAction(t,i.loadLevel),t.errorAction.action=Re.SendAlternateToPenaltyBox,t.errorAction.flags=Le.MoveAllAlternatesMatchingHost;return}}return;case R.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:t.errorAction={action:Re.SendAlternateToPenaltyBox,flags:Le.MoveAllAlternatesMatchingHDCP};return;case R.KEY_SYSTEM_SESSION_UPDATE_FAILED:case R.KEY_SYSTEM_STATUS_INTERNAL_ERROR:case R.KEY_SYSTEM_NO_SESSION:t.errorAction={action:Re.SendAlternateToPenaltyBox,flags:Le.MoveAllAlternatesMatchingKey};return;case R.BUFFER_ADD_CODEC_ERROR:case R.REMUX_ALLOC_ERROR:case R.BUFFER_APPEND_ERROR:t.errorAction||(t.errorAction=this.getLevelSwitchAction(t,t.level));return;case R.MEDIA_SOURCE_REQUIRES_RESET:t.errorAction||(t.errorAction=this.getLevelSwitchAction(t,t.level)),t.errorAction.flags|=Le.ResetMediaSource|Le.SwitchToSDR;return;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:t.errorAction=Qt();return}t.type===W.KEY_SYSTEM_ERROR&&(t.levelRetry=!1,t.errorAction=Qt())}getPlaylistRetryOrSwitchAction(e,t){let s=this.hls,i=Qn(s.config.playlistLoadPolicy,e),r=this.playlistError++;if(ss(i,r,Vs(e),e.response))return{action:Re.RetryRequest,flags:Le.None,retryConfig:i,retryCount:r};let o=this.getLevelSwitchAction(e,t);return i&&(o.retryConfig=i,o.retryCount=r),o}getFragRetryOrSwitchAction(e){let t=this.hls,s=this.getVariantLevelIndex(e.frag),i=t.levels[s],{fragLoadPolicy:r,keyLoadPolicy:a}=t.config,o=Qn(xo(e)?a:r,e),l=t.levels.reduce((h,u)=>h+u.fragmentError,0);if(i&&(e.details!==R.FRAG_GAP&&i.fragmentError++,!Io(e)&&ss(o,l,Vs(e),e.response)))return{action:Re.RetryRequest,flags:Le.None,retryConfig:o,retryCount:l};let c=this.getLevelSwitchAction(e,s);return o&&(c.retryConfig=o,c.retryCount=l),c}getLevelSwitchAction(e,t){let s=this.hls;t==null&&(t=s.loadLevel);let i=this.hls.levels[t];if(i){var r,a;let c=e.details;i.loadError++,i.loadErrorTime=self.performance.now(),c===R.BUFFER_APPEND_ERROR&&i.fragmentError++;let h=-1,{levels:u,loadLevel:d,minAutoLevel:f,maxAutoLevel:g}=s;!s.autoLevelEnabled&&!s.config.preserveManualLevelOnError&&(s.loadLevel=-1);let m=(r=e.frag)==null?void 0:r.type,E=(m===K.AUDIO&&c===R.FRAG_PARSING_ERROR||e.sourceBufferName==="audio"&&da(e))&&u.some(({audioCodec:I})=>i.audioCodec!==I),T=e.sourceBufferName==="video"&&da(e)&&u.some(({codecSet:I,audioCodec:A})=>i.codecSet!==I&&i.audioCodec===A),{type:v,groupId:x}=(a=e.context)!=null?a:{};for(let I=u.length;I--;){let A=(I+d)%u.length;if(A!==d&&A>=f&&A<=g&&(u[A].loadError===0||Ao(u[A],s.config.errorPenaltyExpireMs))){var o,l;let b=u[A];if(c===R.FRAG_GAP&&m===K.MAIN&&e.frag){let _=u[A].details;if(_){let L=Gt(e.frag,_.fragments,e.frag.start);if(L!=null&&L.gap)continue}}else{if(v===se.AUDIO_TRACK&&b.hasAudioGroup(x)||v===se.SUBTITLE_TRACK&&b.hasSubtitleGroup(x))continue;if(m===K.AUDIO&&(o=i.audioGroups)!=null&&o.some(_=>b.hasAudioGroup(_))||m===K.SUBTITLE&&(l=i.subtitleGroups)!=null&&l.some(_=>b.hasSubtitleGroup(_))||E&&i.audioCodec===b.audioCodec||T&&i.codecSet===b.codecSet||!E&&i.audioCodec!==b.audioCodec)continue}h=A;break}}if(h>-1&&s.loadLevel!==h)return e.levelRetry=!0,this.playlistError=0,{action:Re.SendAlternateToPenaltyBox,flags:Le.None,nextAutoLevel:h}}return{action:Re.SendAlternateToPenaltyBox,flags:Le.MoveAllAlternatesMatchingHost}}onErrorOut(e,t){var s,i;switch((s=t.errorAction)==null?void 0:s.action){case Re.DoNothing:break;case Re.SendAlternateToPenaltyBox:this.sendAlternateToPenaltyBox(t),!t.errorAction.resolved&&t.details!==R.FRAG_GAP&&t.details!==R.PLAYLIST_UNCHANGED_ERROR&&!tl(t)&&(t.fatal=!0);break;case Re.RetryRequest:break}if((((i=t.errorAction)==null?void 0:i.flags)||0)&Le.ResetMediaSource&&this.hls.recoverMediaError(),t.fatal){this.hls.stopLoad();return}}sendAlternateToPenaltyBox(e){let t=this.hls,s=e.errorAction;if(!s)return;let i=s.nextAutoLevel;if(s.flags===Le.None)this.switchLevel(e,i);else if(s.flags&Le.SwitchToSDR){let o=this.hls.levels,l=o.length;for(let c=l;c--;)o[c].videoRange!=="SDR"?(o[c].fragmentError++,o[c].loadError++):i===void 0&&(i=c)}else if(s.flags&Le.MoveAllAlternatesMatchingHDCP){let o=this.getVariantLevelIndex(e.frag),l=t.levels[o],c=l?.attrs["HDCP-LEVEL"];s.hdcpLevel=c;let h=c==="NONE";c&&!h?(t.maxHdcpLevel=or[or.indexOf(c)-1],s.resolved=!0,this.warn(`Restricting playback to HDCP-LEVEL of "${t.maxHdcpLevel}" or lower`)):(h&&this.warn("HDCP policy resticted output with HDCP-LEVEL=NONE"),s.flags|=Le.MoveAllAlternatesMatchingKey)}if(s.flags&Le.MoveAllAlternatesMatchingKey){let o=e.decryptdata;if(o){let l=this.hls.levels,c=l.length;for(let u=c;u--;)if(this.variantHasKey(l[u],o)){var r,a;this.log(`Banned key found in level ${u} (${l[u].bitrate}bps) or audio group "${(r=l[u].audioGroups)==null?void 0:r.join(",")}" (${(a=e.frag)==null?void 0:a.type} fragment) ${Ie(o.keyId||[])}`),l[u].fragmentError++,l[u].loadError++,this.log(`Removing level ${u} with key error (${e.error})`),this.hls.removeLevel(u)}let h=e.frag;if(this.hls.levels.length<c)s.resolved=!0;else if(h&&h.type!==K.MAIN){let u=h.decryptdata;u&&!o.matches(u)&&(s.resolved=!0)}}}s.resolved||this.switchLevel(e,i)}switchLevel(e,t){if(t!==void 0&&e.errorAction&&(this.warn(`switching to level ${t} after ${e.details}`),this.hls.nextAutoLevel=t,e.errorAction.resolved=!0,this.hls.nextLoadLevel=this.hls.nextAutoLevel,e.details===R.BUFFER_ADD_CODEC_ERROR&&e.mimeType&&e.sourceBufferName!=="audiovideo")){let s=ar(e.mimeType),i=this.hls.levels;for(let r=i.length;r--;)i[r][`${e.sourceBufferName}Codec`]===s&&(this.log(`Removing level ${r} for ${e.details} ("${s}" not supported)`),this.hls.removeLevel(r))}}};function da(n){let e=n.details;return e===R.BUFFER_ADD_CODEC_ERROR||e===R.MEDIA_SOURCE_REQUIRES_RESET||e===R.BUFFER_APPEND_ERROR&&!tl(n)}function tl(n){return n.details===R.BUFFER_APPEND_ERROR&&(n.error.name==="QuotaExceededError"||n.error.name==="InvalidStateError")}function Qt(n){let e={action:Re.DoNothing,flags:Le.None};return n&&(e.resolved=!0),e}var sl=10,ur=class{constructor(e){this.PTSKnown=!1,this.alignedSliding=!1,this.averagetargetduration=void 0,this.endCC=0,this.endSN=0,this.fragments=void 0,this.fragmentHint=void 0,this.partList=null,this.dateRanges=void 0,this.dateRangeTagCount=0,this.live=!0,this.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=e}reloaded(e){if(!e){this.advanced=!0,this.updated=!0;return}let t=this.lastPartSn-e.lastPartSn,s=this.lastPartIndex-e.lastPartIndex;this.updated=this.endSN!==e.endSN||!!s||!!t||!this.live,this.advanced=this.endSN>e.endSN||t>0||t===0&&s>0,this.updated||this.advanced?this.misses=0:this.misses=e.misses+1}hasKey(e){return this.encryptedFragments.some(t=>{let s=t.decryptdata;return s||(t.setKeyFormat(e.keyFormat),s=t.decryptdata),!!s&&e.matches(s)})}get hasProgramDateTime(){return this.fragments.length?$(this.fragments[this.fragments.length-1].programDateTime):!1}get levelTargetDuration(){return this.averagetargetduration||this.targetduration||sl}get drift(){let e=this.driftEndTime-this.driftStartTime;return e>0?(this.driftEnd-this.driftStart)*1e3/e:1}get edge(){return this.partEnd||this.fragmentEnd}get partEnd(){var e;return(e=this.partList)!=null&&e.length?this.partList[this.partList.length-1].end:this.fragmentEnd}get fragmentEnd(){return this.fragments.length?this.fragments[this.fragments.length-1].end:0}get fragmentStart(){return this.fragments.length?this.fragments[0].start:0}get age(){return this.advancedDateTime?Math.max(Date.now()-this.advancedDateTime,0)/1e3:0}get lastPartIndex(){var e;return(e=this.partList)!=null&&e.length?this.partList[this.partList.length-1].index:-1}get maxPartIndex(){let e=this.partList;if(e){let t=this.lastPartIndex;if(t!==-1){for(let s=e.length;s--;)if(e[s].index>t)return e[s].index;return t}}return 0}get lastPartSn(){var e;return(e=this.partList)!=null&&e.length?this.partList[this.partList.length-1].fragment.sn:this.endSN}get expired(){if(this.live&&this.advancedDateTime!==void 0&&this.misses<3){let e=this.partEnd-this.fragmentStart;return this.age>Math.max(e,this.totalduration)+this.levelTargetDuration}return!1}get partsExpired(){return this.live&&this.partTarget&&this.advancedDateTime!==void 0&&this.misses<3?this.age>(this.partHoldBack||this.partTarget*3)*1.5:!1}},fa={length:0,start:()=>0,end:()=>0},X=class n{static isBuffered(e,t){if(e){let s=n.getBuffered(e);for(let i=s.length;i--;)if(t>=s.start(i)&&t<=s.end(i))return!0}return!1}static bufferedRanges(e){if(e){let t=n.getBuffered(e);return n.timeRangesToArray(t)}return[]}static timeRangesToArray(e){let t=[];for(let s=0;s<e.length;s++)t.push({start:e.start(s),end:e.end(s)});return t}static bufferInfo(e,t,s){if(e){let i=n.bufferedRanges(e);if(i.length)return n.bufferedInfo(i,t,s)}return{len:0,start:t,end:t,bufferedIndex:-1}}static bufferedInfo(e,t,s){t=Math.max(0,t),e.length>1&&e.sort((h,u)=>h.start-u.start||u.end-h.end);let i=-1,r=[];if(s)for(let h=0;h<e.length;h++){t>=e[h].start&&t<=e[h].end&&(i=h);let u=r.length;if(u){let d=r[u-1].end;e[h].start-d<s?e[h].end>d&&(r[u-1].end=e[h].end):r.push(e[h])}else r.push(e[h])}else r=e;let a=0,o,l=t,c=t;for(let h=0;h<r.length;h++){let u=r[h].start,d=r[h].end;if(i===-1&&t>=u&&t<=d&&(i=h),t+s>=u&&t<d)l=u,c=d,a=c-t;else if(t+s<u){o=u;break}}return{len:a,start:l||0,end:c||0,nextStart:o,buffered:e,bufferedIndex:i}}static getBuffered(e){try{return e.buffered||fa}catch(t){return oe.log("failed to get media.buffered",t),fa}}};function ce(n,e,t){le(n,e,t),n.addEventListener(e,t)}function le(n,e,t){n.removeEventListener(e,t)}function js(n){let e="",t=n.length;for(let s=0;s<t;s++)e+=`[${n.start(s).toFixed(3)}-${n.end(s).toFixed(3)}]`;return e}var ga=/(avc[1234]|hvc1|hev1|dvh[1e]|vp09|av01)(?:\.[^.,]+)+/,il="HlsJsTrackRemovedError",rl="HlsJsSourceBufferError",Yh=.25,Wh=.001,dr=class extends Error{constructor(e){super(e),this.name=il}},fr=class extends we{constructor(e,t){super("buffer-controller",e.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=s=>{var i;this.hls&&((i=this.mediaSource)==null?void 0:i.readyState)==="open"&&(!this.media||this.media.seeking||this.hls.pauseBuffering())},this._onStartStreaming=s=>{this.hls&&this.hls.resumeBuffering()},this._onMediaSourceOpen=s=>{let{media:i,mediaSource:r}=this;s&&this.log("Media source opened"),!(!i||!r)&&(le(r,"sourceopen",this._onMediaSourceOpen),le(i,"emptied",this._onMediaEmptied),this.updateDuration(),this.hls.trigger(p.MEDIA_ATTACHED,{media:i,mediaSource:r}),this.mediaSource!==null&&this.checkPendingTracks())},this._onMediaSourceClose=()=>{if(this.log("Media source closed"),this.media){if(this.isMediaSourceReplaced()){let{currentSrc:l}=this.media,c=l&&l!==this._objectUrl?l:this.mediaSrc;this.warn(`MediaSource closed after media element switched to another source (${this._objectUrl} > ${c}) - detaching media`),this.hls.detachMedia();return}let s=this.media.error,{appendError:i,appendErrors:r}=this,a=!1;!i&&s&&(a=Math.max(++r.audio,++r.video,++r.audiovideo)>=this.hls.config.appendErrorMaxRetry);let o=new Error(`MediaSource closed while media attached${pa(a,s)}`);this.warn(o),this.hls.trigger(p.ERROR,he({fatal:a},i,{type:W.MEDIA_ERROR,details:R.MEDIA_SOURCE_REQUIRES_RESET,error:o}))}},this._onMediaSourceEnded=()=>{this.log("Media source ended")},this._onMediaEmptied=()=>{let{mediaSrc:s,_objectUrl:i}=this;s!==i&&this.error(`Media element src was set while attaching MediaSource (${i} > ${s})`)},this._onMediaError=()=>{let{media:s}=this;if(s){var i,r;this.log(`Media error (code: ${(i=s.error)==null?void 0:i.code}): ${(r=s.error)==null?void 0:r.message}`)}},this.hls=e,this.fragmentTracker=t,this.appendSource=kc(vt(e.config.preferManagedMediaSource)),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(){let{hls:e}=this;e.on(p.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(p.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(p.MANIFEST_LOADING,this.onManifestLoading,this),e.on(p.MANIFEST_PARSED,this.onManifestParsed,this),e.on(p.BUFFER_RESET,this.onBufferReset,this),e.on(p.BUFFER_APPENDING,this.onBufferAppending,this),e.on(p.BUFFER_CODECS,this.onBufferCodecs,this),e.on(p.BUFFER_EOS,this.onBufferEos,this),e.on(p.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(p.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(p.FRAG_PARSED,this.onFragParsed,this),e.on(p.FRAG_CHANGED,this.onFragChanged,this),e.on(p.ERROR,this.onError,this)}unregisterListeners(){let{hls:e}=this;e.off(p.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(p.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(p.MANIFEST_LOADING,this.onManifestLoading,this),e.off(p.MANIFEST_PARSED,this.onManifestParsed,this),e.off(p.BUFFER_RESET,this.onBufferReset,this),e.off(p.BUFFER_APPENDING,this.onBufferAppending,this),e.off(p.BUFFER_CODECS,this.onBufferCodecs,this),e.off(p.BUFFER_EOS,this.onBufferEos,this),e.off(p.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(p.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(p.FRAG_PARSED,this.onFragParsed,this),e.off(p.FRAG_CHANGED,this.onFragChanged,this),e.off(p.ERROR,this.onError,this)}transferMedia(){let{media:e,mediaSource:t}=this;if(!e)return null;let s={};if(this.operationQueue){let r=this.isUpdating();r||this.operationQueue.removeBlockers();let a=this.isQueued();(r||a)&&this.warn(`Transfering MediaSource with${a?" operations in queue":""}${r?" updating SourceBuffer(s)":""} ${this.operationQueue}`),this.operationQueue.destroy()}let i=this.transferData;return i&&!this.sourceBufferCount&&i.mediaSource===t?he(s,i.tracks):this.sourceBuffers.forEach(r=>{let[a]=r;a&&(s[a]=he({},this.tracks[a]),this.removeBuffer(a)),r[0]=r[1]=null}),{media:e,mediaSource:t,tracks:s}}initTracks(){let e={};this.resetAppendProgress(),this.sourceBuffers=[[null,null],[null,null]],this.tracks=e,this.resetQueue(),this.lastMpegAudioChunk=null,this.lastVideoAppendEnd=0}onManifestLoading(){this.bufferCodecEventsTotal=0,this.details=null,this.resetAppendErrors(),this.resetAppendProgress()}onManifestParsed(e,t){var s;let i=2;(t.audio&&!t.video||!t.altAudio)&&(i=1),this.bufferCodecEventsTotal=i,this.log(`${i} bufferCodec event(s) expected.`),(s=this.transferData)!=null&&s.mediaSource&&this.sourceBufferCount&&i&&this.bufferCreated()}onMediaAttaching(e,t){let s=this.media=t.media;this.transferData=this.overrides=void 0;let i=vt(this.appendSource);if(i){let a=!!t.mediaSource;(a||t.overrides)&&(this.transferData=t,this.overrides=t.overrides);let o=this.mediaSource=t.mediaSource||new i;if(this.assignMediaSource(o),a)this._objectUrl=s.src,this.attachTransferred();else{var r;let l=this._objectUrl=self.URL.createObjectURL(o),c=this.hls.config,h=c.emeEnabled&&s.mediaKeys?(r=c.emeController)==null?void 0:r.CDMCleanupPromise:null;h?h.then(()=>{this.hls&&this.setSource(s,o,l)}).catch(()=>{}):this.setSource(s,o,l)}ce(s,"emptied",this._onMediaEmptied),ce(s,"error",this._onMediaError),this.appendSource&&ce(s,"seeking",this._onStartStreaming)}}setSource(e,t,s){if(this.appendSource)try{e.removeAttribute("src");let i=self.ManagedMediaSource;e.disableRemotePlayback=e.disableRemotePlayback||i&&t instanceof i,ma(e),qh(e,s),e.load()}catch{e.src=s}else e.src=s}assignMediaSource(e){var t,s;this.log(`${((t=this.transferData)==null?void 0:t.mediaSource)===e?"transferred":"created"} media source: ${(s=e.constructor)==null?void 0:s.name}`),ce(e,"sourceopen",this._onMediaSourceOpen),ce(e,"sourceended",this._onMediaSourceEnded),ce(e,"sourceclose",this._onMediaSourceClose),this.appendSource&&(ce(e,"startstreaming",this._onStartStreaming),ce(e,"endstreaming",this._onEndStreaming))}attachTransferred(){let e=this.media,t=this.transferData;if(!t||!e)return;let s=this.tracks,i=t.tracks,r=i?Object.keys(i):null,a=r?r.length:0,o=()=>{Promise.resolve().then(()=>{this.media&&this.mediaSourceOpenOrEnded&&this._onMediaSourceOpen()})};if(i&&r&&a){if(!this.tracksReady){this.hls.config.startFragPrefetch=!0,this.log("attachTransferred: waiting for SourceBuffer track info");return}if(this.log(`attachTransferred: (bufferCodecEventsTotal ${this.bufferCodecEventsTotal})
15
+ required tracks: ${de(s,(l,c)=>l==="initSegment"?void 0:c)};
16
+ transfer tracks: ${de(i,(l,c)=>l==="initSegment"?void 0:c)}}`),!Lo(i,s)){t.mediaSource=null,t.tracks=void 0;let l=e.currentTime,c=this.details,h=Math.max(l,c?.fragments[0].start||0);if(h-l>1){this.log(`attachTransferred: waiting for playback to reach new tracks start time ${l} -> ${h}`);return}this.warn(`attachTransferred: resetting MediaSource for incompatible tracks ("${Object.keys(i)}"->"${Object.keys(s)}") start time: ${h} currentTime: ${l}`),this.onMediaDetaching(p.MEDIA_DETACHING,{}),this.onMediaAttaching(p.MEDIA_ATTACHING,t),e.currentTime=h;return}this.transferData=void 0,r.forEach(l=>{let c=l,h=i[c];if(h){let u=h.buffer;if(u){let d=this.fragmentTracker,f=h.id;if(d.hasFragments(f)||d.hasParts(f)){let y=X.getBuffered(u);d.detectEvictedFragments(c,y,f,null,null,!0)}let g=wi(c),m=[c,u];this.sourceBuffers[g]=m,u.updating&&this.operationQueue&&this.operationQueue.prependBlocker(c),this.trackSourceBuffer(c,h)}}}),o(),this.bufferCreated()}else this.log("attachTransferred: MediaSource w/o SourceBuffers"),o()}get mediaSourceOpenOrEnded(){var e;let t=(e=this.mediaSource)==null?void 0:e.readyState;return t==="open"||t==="ended"}onMediaDetaching(e,t){let s=!!t.transferMedia;this.transferData=this.overrides=void 0;let{media:i,mediaSource:r,_objectUrl:a}=this;if(r){if(this.log(`media source ${s?"transferring":"detaching"}`),s)this.sourceBuffers.forEach(([o])=>{o&&this.removeBuffer(o)}),this.resetQueue();else{if(this.mediaSourceOpenOrEnded){let o=r.readyState==="open";try{let l=r.sourceBuffers;for(let c=l.length;c--;)o&&l[c].abort(),r.removeSourceBuffer(l[c]);o&&r.endOfStream()}catch(l){this.warn(`onMediaDetaching: ${l.message} while calling endOfStream`)}}this.sourceBufferCount&&this.onBufferReset()}le(r,"sourceopen",this._onMediaSourceOpen),le(r,"sourceended",this._onMediaSourceEnded),le(r,"sourceclose",this._onMediaSourceClose),this.appendSource&&(le(r,"startstreaming",this._onStartStreaming),le(r,"endstreaming",this._onEndStreaming)),this.mediaSource=null,this._objectUrl=null}i&&(le(i,"emptied",this._onMediaEmptied),le(i,"error",this._onMediaError),le(i,"seeking",this._onStartStreaming),s||(a&&self.URL.revokeObjectURL(a),this.mediaSrc===a&&!this.isMediaSourceReplaced(a)?(i.removeAttribute("src"),this.appendSource&&ma(i),i.load()):this.warn("media|source.src was changed by a third party - skip cleanup")),this.media=null)}onBufferReset(){this.sourceBuffers.forEach(([e])=>{e&&this.resetBuffer(e)}),this.initTracks()}resetBuffer(e){var t;let s=(t=this.tracks[e])==null?void 0:t.buffer;if(this.removeBuffer(e),s)try{var i;(i=this.mediaSource)!=null&&i.sourceBuffers.length&&this.mediaSource.removeSourceBuffer(s)}catch(r){this.warn(`onBufferReset ${e}`,r)}delete this.tracks[e]}removeBuffer(e){this.removeBufferListeners(e),this.sourceBuffers[wi(e)]=[null,null];let t=this.tracks[e];t&&(this.clearBufferAppendTimeoutId(t),t.buffer=void 0)}resetQueue(){this.operationQueue&&this.operationQueue.destroy(),this.operationQueue=new cr(this.tracks)}onBufferCodecs(e,t){var s;let i=this.tracks,r=Object.keys(t);this.log(`BUFFER_CODECS: "${r}" (current SB count ${this.sourceBufferCount})`);let a="audiovideo"in t&&(i.audio||i.video)||i.audiovideo&&("audio"in t||"video"in t),o=!a&&this.sourceBufferCount&&this.media&&r.some(l=>!i[l]);if(a||o){this.warn(`Unsupported transition between "${Object.keys(i)}" and "${r}" SourceBuffers`);return}r.forEach(l=>{var c,h;let u=t[l],{id:d,codec:f,levelCodec:g,container:m,metadata:y,supplemental:E}=u,S=i[l],T=(c=this.transferData)==null||(c=c.tracks)==null?void 0:c[l],v=T!=null&&T.buffer?T:S,x=v?.pendingCodec||v?.codec,I=v?.levelCodec;S||(S=i[l]={buffer:void 0,listeners:[],codec:f,supplemental:E,container:m,levelCodec:g,metadata:y,id:d});let A=Ms(x,I),b=A?.replace(ga,"$1"),_=Ms(f,g),L=(h=_)==null?void 0:h.replace(ga,"$1");_&&A&&b!==L&&(l.slice(0,5)==="audio"&&(_=Hs(_,this.appendSource)),this.log(`switching codec ${x} to ${_}`),_!==(S.pendingCodec||S.codec)&&(S.pendingCodec=_),S.container=m,this.appendChangeType(l,m,_))}),(this.tracksReady||this.sourceBufferCount)&&(t.tracks=this.sourceBufferTracks),!this.sourceBufferCount&&(this.bufferCodecEventsTotal>1&&!this.tracks.video&&!t.video&&((s=t.audio)==null?void 0:s.id)==="main"&&(this.log("Main audio-only"),this.bufferCodecEventsTotal=1),this.mediaSourceOpenOrEnded&&this.checkPendingTracks())}get sourceBufferTracks(){return Object.keys(this.tracks).reduce((e,t)=>{let s=this.tracks[t];return e[t]={id:s.id,container:s.container,codec:s.codec,levelCodec:s.levelCodec},e},{})}appendChangeType(e,t,s){let i=`${t};codecs=${s}`,r={label:`change-type=${i}`,execute:()=>{let a=this.tracks[e];if(a){let o=a.buffer;o!=null&&o.changeType&&(this.log(`changing ${e} sourceBuffer type to ${i}`),o.changeType(i),a.codec=s,a.container=t)}this.shiftAndExecuteNext(e)},onStart:()=>{},onComplete:()=>{},onError:a=>{this.warn(`Failed to change ${e} SourceBuffer type`,a)}};this.append(r,e,this.isPending(this.tracks[e]))}blockAudio(e){var t;let s=e.start,i=s+e.duration*.05;if(((t=this.fragmentTracker.getAppendedFrag(s,K.MAIN))==null?void 0:t.gap)===!0)return;let a={label:"block-audio",execute:()=>{var o,l;(this.lastVideoAppendEnd>i||X.isBuffered((o=this.tracks.video)==null?void 0:o.buffer,i)||((l=this.fragmentTracker.getAppendedFrag(i,K.MAIN))==null?void 0:l.gap)===!0)&&this.unblockAudio()},onStart:()=>{},onComplete:()=>{},onError:o=>{this.warn("Error executing block-audio operation",o)}};this.append(a,"audio",!0)}unblockAudio(){this.operationQueue&&this.operationQueue.unblockAudio()}onBufferAppending(e,t){let{tracks:s}=this,{data:i,type:r,parent:a,frag:o,part:l,chunkMeta:c,offset:h}=t,u=c.buffering[r],d=pe(o)&&!l&&!o.gap&&!c.partial&&!c.iframe,f=null,g=!1,{sn:m,cc:y}=o,E=self.performance.now();u.start=E;let S=o.stats.buffering,T=l?l.stats.buffering:null;S.start===0&&(S.start=E),T?.start===0&&(T.start=E);let v=s.audio,x=!1;r==="audio"&&v?.container==="audio/mpeg"&&(x=!this.lastMpegAudioChunk||c.id===1||this.lastMpegAudioChunk.sn!==c.sn,this.lastMpegAudioChunk=c);let I=s.video,A=I?.buffer;if(A&&m!=="initSegment"&&h!==void 0){let L=v?.buffer,P=l||o;if(r==="audio"&&a!=="main"&&!(I.ending||I.ended)&&L&&X.getBuffered(L).length){let M=P.start+P.duration*.05,U=X.getBuffered(A),B=this.currentOp("video");!U.length&&!B?this.blockAudio(P):!X.isBuffered(A,M)&&this.lastVideoAppendEnd<M&&this.blockAudio(P)}else if(r==="video"){let D=P.end,M=this.lastVideoAppendEnd-D;this.lastVideoAppendEnd=D,M<0||M>P.duration?this.unblockAudio():this.isAudioBlocked()&&this.executeNext("audio")}}let b=(l||o).start,_={label:`append-${r}`,execute:()=>{var L;u.executeStart=self.performance.now();let P=(L=this.tracks[r])==null?void 0:L.buffer;P&&(d&&(f=X.timeRangesToArray(X.getBuffered(P)),g=Ea(Mi(f,o),o)),x?this.updateTimestampOffset(P,b,.1,r,m,y):h!==void 0&&$(h)&&this.updateTimestampOffset(P,h,1e-6,r,m,y)),this.appendExecutor(i,r)},onStart:()=>{},onComplete:()=>{this.clearBufferAppendTimeoutId(this.tracks[r]);let L=self.performance.now();u.executeEnd=u.end=L,S.first===0&&(S.first=L),T?.first===0&&(T.first=L);let P={};if(this.sourceBuffers.forEach(([D,M])=>{D&&(P[D]=X.getBuffered(M))}),d){let D=this.getFragmentAppendProgress(o),M=P[r];if(M&&f){let U=X.timeRangesToArray(M),B=Mi(U,o);D.progressed||(D.progressed=B-Mi(f,o)>Wh);let k=g&&Ea(B,o);D.fullyBuffered[r]=(D.fullyBuffered[r]===void 0||D.fullyBuffered[r])&&k}}this.hls.trigger(p.BUFFER_APPENDED,{type:r,frag:o,part:l,chunkMeta:c,parent:a,timeRanges:P})},onError:L=>{var P;this.clearBufferAppendTimeoutId(this.tracks[r]);let D=L.code===DOMException.QUOTA_EXCEEDED_ERR||L.name=="QuotaExceededError"||"quota"in L;if(D&&!this._quotaEvictionPending[r]){let k=this.getBackBufferEvictionTarget(r,i.byteLength,o.type);if(k>0){this._quotaEvictionPending[r]=!0,this.log(`QuotaExceededError on "${r}" append sn: ${m} - evicting back buffer to ${k.toFixed(3)}s and retrying`);let w=this.getFlushOp(r,0,k),O=this.getClearEvictionPendingOp(r);this.insertNext([w,_,O],r);return}this.warn(`QuotaExceededError on "${r}" sn: ${m} - no back buffer available to evict`)}d&&(this.getFragmentAppendProgress(o).errored=!0);let M={type:W.MEDIA_ERROR,parent:a,details:R.BUFFER_APPEND_ERROR,sourceBufferName:r,frag:o,part:l,chunkMeta:c,error:L,err:L,fatal:!1},U=(P=this.media)==null?void 0:P.error;if(L.name===il&&this.sourceBufferCount===0&&(!this.media||this.pendingTrackCount===0))M.errorAction=Qt(!0);else{var B;D&&(M.details=R.BUFFER_FULL_ERROR);let k=++this.appendErrors[r],w=this.hls.config.appendErrorMaxRetry;this.warn(`Failed ${k}/${w+1} times to append segment in "${r}" sourceBuffer with error: ${L.message}`),k>=w&&(M.fatal=!D);let O=(B=this.mediaSource)==null?void 0:B.readyState;(O==="ended"||O==="closed"||U)&&!this.isMediaSourceReplaced()&&(this.warn(`MediaSource readyState "${O}" during SourceBuffer${pa(M.fatal,U)}`),M.details=R.MEDIA_SOURCE_REQUIRES_RESET)}this.appendError=M,this.hls.trigger(p.ERROR,M),D&&this.hls&&this.trimBuffers(o.start,1)}};this.log(`queuing "${r}" append sn: ${m}${l?" p: "+l.index:""} of ${a} playlist ${o.level} cc: ${y} offset: ${h} bytes: ${i.byteLength}`),this.append(_,r,this.isPending(this.tracks[r]))}getClearEvictionPendingOp(e){return{label:"clear",execute:()=>{this._quotaEvictionPending[e]=!1,this.shiftAndExecuteNext(e)},onStart:()=>{},onComplete:()=>{},onError:()=>{}}}getFlushOp(e,t,s){return this.log(`queuing "${e}" remove ${t}-${s}`),{label:"remove",execute:()=>{this.removeExecutor(e,t,s)},onStart:()=>{},onComplete:()=>{var i;let r=(i=this.tracks[e])==null?void 0:i.buffer;this.log(`Remove request ${t}-${s} from ${e} Source Buffer complete > buffer: ${r?js(X.getBuffered(r)):"(detached)"}`),this.hls.trigger(p.BUFFER_FLUSHED,{type:e,start:t,end:s})},onError:i=>{this.warn(`Failed to remove ${t}-${s} from "${e}" SourceBuffer`,i),this.hls.trigger(p.BUFFER_FLUSHED,{type:e,start:0,end:0,error:i})}}}onBufferFlushing(e,t){let{type:s,startOffset:i,endOffset:r}=t;(!s||s==="audio")&&this.unblockAudio(),s?this.append(this.getFlushOp(s,i,r),s):this.sourceBuffers.forEach(([a])=>{a&&this.append(this.getFlushOp(a,i,r),a)})}onFragParsed(e,t){let{frag:s,part:i,chunkMeta:r}=t,a=[],o=i?i.elementaryStreams:s.elementaryStreams;o[ue.AUDIOVIDEO]?a.push("audiovideo"):(o[ue.AUDIO]&&a.push("audio"),o[ue.VIDEO]&&a.push("video"));let l=()=>{let c=self.performance.now();s.stats.buffering.end=c,i&&(i.stats.buffering.end=c);let h=i?i.stats:s.stats;this.checkAppendProgress(s,i,r,a),this.hls&&(this.hls.trigger(p.FRAG_BUFFERED,{frag:s,part:i,stats:h,id:s.type,chunkMeta:r}),!i&&s.gap&&h.retry&&this.log(`Nothing buffered for ${s.type} level: ${s.level} sn: ${s.sn} retries ${h.retry}`))};a.length===0&&this.log(`Fragments must have at least one ElementaryStreamType set. ${s.type} ${s.level} ${i?`part: ${i.index} of `:""}sn: ${s.sn}`),this.blockBuffers(l,a).catch(c=>{this.warn(`Fragment buffered callback ${c.message}`),this.stepOperationQueue(this.sourceBufferTypes)})}onFragChanged(e,t){var s,i;let r=(s=this.hls)==null?void 0:s.config;if(!r)return;let{backBufferLength:a,frontBufferFlushThreshold:o}=r;this.trimBuffers(o,a,t.frag,t.previousFrag);let l=t.frag.elementaryStreams,{appendErrors:c}=this,h=(i=this.appendError)==null?void 0:i.sourceBufferName;Object.keys(l).forEach(u=>{l[u]&&(c[u]=0,u===h&&(this.appendError=void 0),u==="audio"||u==="video"?(c.audiovideo=0,h==="audiovideo"&&(this.appendError=void 0)):(c.audio=0,c.video=0,h!=="audiovideo"&&(this.appendError=void 0)))})}get bufferedToEnd(){return this.sourceBufferCount>0&&!this.sourceBuffers.some(([e])=>{if(e){let t=this.tracks[e];if(t)return!t.ended||t.ending}return!1})}onBufferEos(e,t){var s;this.sourceBuffers.forEach(([r])=>{if(r){let a=this.tracks[r];(!t.type||t.type===r)&&(a.ending=!0,a.ended||(a.ended=!0,this.log(`${r} buffer reached EOS`)))}});let i=((s=this.overrides)==null?void 0:s.endOfStream)!==!1;this.allTracksEnding?(this.unblockAudio(),i?(this.log("Queueing EOS"),this.blockUntilOpen(()=>{if(this.tracksEnded(),!this.allTracksEnding){this.log("EOS cancelled");return}let{mediaSource:r}=this;if(r?.readyState!=="open"){r&&this.log(`Could not call mediaSource.endOfStream(). mediaSource.readyState: ${r.readyState}`);return}this.log("Calling mediaSource.endOfStream()"),r.endOfStream(),this.hls.trigger(p.BUFFERED_TO_END,void 0)})):(this.tracksEnded(),this.hls.trigger(p.BUFFERED_TO_END,void 0))):t.type==="video"&&this.unblockAudio()}get allTracksEnding(){return this.sourceBufferCount>0&&!this.sourceBuffers.some(([e])=>{var t;return e&&!((t=this.tracks[e])!=null&&t.ended)})}tracksEnded(){this.sourceBuffers.forEach(([e])=>{if(e!==null){let t=this.tracks[e];t&&(t.ending=!1)}})}onLevelUpdated(e,{details:t}){t.fragments.length&&(this.details=t,this.updateDuration())}updateDuration(){this.blockUntilOpen(()=>{let e=this.getDurationAndRange();e&&this.updateMediaSource(e)})}onError(e,t){if(t.details===R.BUFFER_APPEND_ERROR&&t.frag){var s;let i=(s=t.errorAction)==null?void 0:s.nextAutoLevel;$(i)&&i!==t.frag.level&&this.resetAppendErrors()}}getBackBufferEvictionTarget(e,t,s){let{media:i}=this;return i?this.fragmentTracker.getBackBufferEvictionEnd(i.currentTime,s,t):0}getFragmentAppendProgress(e){var t;let s=ya(e),i=this.fragmentAppendProgress[s];return((t=i)==null?void 0:t.stats)!==e.stats&&(i={stats:e.stats,progressed:!1,errored:!1,fullyBuffered:Object.create(null)},this.fragmentAppendProgress[s]=i),i}checkAppendProgress(e,t,s,i){if(t||!pe(e)||e.gap||s.iframe||s.partial)return;let r=ya(e),a=this.fragmentAppendProgress[r];delete this.fragmentAppendProgress[r];let o=e.stats.buffering;if(o.start&&!o.first)return;let l=a?.stats===e.stats?a:void 0;if(l!=null&&l.errored)return;let c=i.length>0&&i.every(f=>l?.fullyBuffered[f]===!0);if(l!=null&&l.progressed||c){delete this.appendsWithoutProgress[r];return}if(!l&&i.length===0)return;let h=(this.appendsWithoutProgress[r]||0)+1,u=this.hls;h>=u.config.appendErrorMaxRetry?delete this.appendsWithoutProgress[r]:this.appendsWithoutProgress[r]=h,this.warn(`Fragment ${e.sn} of ${e.type} playlist ${e.level} appended ${h} time${h>1?"s":""} without buffered range growth`),u.trigger(p.ERROR,{type:W.MEDIA_ERROR,details:R.BUFFER_APPEND_NO_PROGRESS,fatal:!1,frag:e,chunkMeta:s,parent:e.type,appendsWithoutProgress:h,error:new Error(`Fragment append did not increase buffered coverage (${h})`)})}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(e,t,s,i){let{hls:r,details:a,media:o}=this;if(!o||a===null||!this.sourceBufferCount)return;let l=r.config,c=o.currentTime,h=a.levelTargetDuration;t=a.live&&l.liveBackBufferLength!==null?l.liveBackBufferLength:t;let u=-1/0;if($(t)&&t>=0){let d=Math.max(t,h);u=Math.floor(c/h)*h-d}if(s){let d=this.getLoopBackBufferFlushEnd(s,i??null);d>0&&(u=Math.max(u,d))}if(u>0&&this.flushBackBuffer(c,h,u),$(e)&&e>0){let d=Math.max(l.maxBufferLength,e),f=Math.max(d,h),g=Math.floor(c/h)*h+f;this.flushFrontBuffer(c,h,g)}}getLoopBackBufferFlushEnd(e,t){var s;let{media:i}=this;if(((s=this.hls)==null?void 0:s.config.loopBackBufferFlush)===!1||!(i!=null&&i.loop)||!t||e.level<=t.level)return 0;let{video:r,audiovideo:a}=e.elementaryStreams;if(r!=null&&r.partial||a!=null&&a.partial)return 0;let o=this.getEarliestElementaryStreamStart(e)-Yh;return o<=0?0:(this.log(`Flushing lower quality back buffer for loop: level ${e.level}, range [0-${o.toFixed(3)}]`),o)}getEarliestElementaryStreamStart(e){let{audio:t,video:s,audiovideo:i}=e.elementaryStreams,r=e.start;return i?r=Math.min(r,i.startDTS):(t&&(r=Math.min(r,t.startDTS)),s&&(r=Math.min(r,s.startDTS))),r}flushBackBuffer(e,t,s){this.sourceBuffers.forEach(([i,r])=>{if(r){let c=X.getBuffered(r);if(c.length>0&&s>c.start(0)){var a,o,l;this.hls.trigger(p.BACK_BUFFER_REACHED,{bufferEnd:s});let h=this.tracks[i];if((a=this.details)!=null&&a.live)this.hls.trigger(p.LIVE_BACK_BUFFER_REACHED,{bufferEnd:s});else if(h!=null&&h.ended&&!((o=this.media)!=null&&o.loop&&((l=this.hls)==null?void 0:l.config.loopBackBufferFlush)!==!1)){this.log(`Cannot flush ${i} back buffer while SourceBuffer is in ended state`);return}this.hls.trigger(p.BUFFER_FLUSHING,{startOffset:0,endOffset:s,type:i})}}})}flushFrontBuffer(e,t,s){this.sourceBuffers.forEach(([i,r])=>{if(r){let a=X.getBuffered(r),o=a.length;if(o<2)return;let l=a.start(o-1),c=a.end(o-1);if(s>l||e>=l&&e<=c)return;this.hls.trigger(p.BUFFER_FLUSHING,{startOffset:l,endOffset:1/0,type:i})}})}getDurationAndRange(){var e;let{details:t,mediaSource:s}=this;if(!t||!this.media||s?.readyState!=="open")return null;let i=t.edge;if(t.live&&this.hls.config.liveDurationInfinity){if(t.fragments.length&&s.setLiveSeekableRange){let c=Math.max(0,t.fragmentStart),h=Math.max(c,i);return{duration:1/0,start:c,end:h}}return{duration:1/0}}let r=(e=this.overrides)==null?void 0:e.duration;if(r)return $(r)?{duration:r}:null;let a=this.media.duration,o=$(s.duration)?s.duration:0;return i>o&&i>a||!$(a)?{duration:i}:null}updateMediaSource({duration:e,start:t,end:s}){let i=this.mediaSource;!i||!this.media||i.readyState!=="open"||(i.duration!==e&&($(e)&&this.log(`Updating MediaSource duration to ${e.toFixed(3)}`),i.duration=e),t!==void 0&&s!==void 0&&(this.log(`MediaSource duration is set to ${i.duration}. Setting seekable range to ${t}-${s}.`),i.setLiveSeekableRange(t,s)))}get tracksReady(){let e=this.pendingTrackCount;return e>0&&(e>=this.bufferCodecEventsTotal||this.isPending(this.tracks.audiovideo))}checkPendingTracks(){let{bufferCodecEventsTotal:e,pendingTrackCount:t,tracks:s}=this;if(this.log(`checkPendingTracks (pending: ${t} codec events expected: ${e}) ${de(s)}`),this.tracksReady){var i;let r=(i=this.transferData)==null?void 0:i.tracks;r&&Object.keys(r).length?this.attachTransferred():this.createSourceBuffers()}}bufferCreated(){if(this.sourceBufferCount){let e={};this.sourceBuffers.forEach(([t,s])=>{if(t){let i=this.tracks[t];e[t]={buffer:s,container:i.container,codec:i.codec,supplemental:i.supplemental,levelCodec:i.levelCodec,id:i.id,metadata:i.metadata}}}),this.hls.trigger(p.BUFFER_CREATED,{tracks:e}),this.log(`SourceBuffers created. Running queue: ${this.operationQueue}`),this.sourceBuffers.forEach(([t])=>{this.executeNext(t)})}else{let e=new Error("could not create source buffer for media codec(s)");this.hls.trigger(p.ERROR,{type:W.MEDIA_ERROR,details:R.BUFFER_INCOMPATIBLE_CODECS_ERROR,fatal:!0,error:e,reason:e.message})}}createSourceBuffers(){let{tracks:e,sourceBuffers:t,mediaSource:s}=this;if(!s)throw new Error("createSourceBuffers called when mediaSource was null");for(let r in e){let a=r,o=e[a];if(this.isPending(o)){let l=this.getTrackCodec(o,a),c=`${o.container};codecs=${l}`;o.codec=l,this.log(`creating sourceBuffer(${c})${this.currentOp(a)?" Queued":""} ${de(o)}`);try{let h=s.addSourceBuffer(c),u=wi(a),d=[a,h];t[u]=d,o.buffer=h}catch(h){var i;this.error(`error while trying to add sourceBuffer: ${h.message}`),this.shiftAndExecuteNext(a),(i=this.operationQueue)==null||i.removeBlockers(),delete this.tracks[a],this.hls.trigger(p.ERROR,{type:W.MEDIA_ERROR,details:R.BUFFER_ADD_CODEC_ERROR,fatal:!1,error:h,sourceBufferName:a,mimeType:c,parent:o.id});return}this.trackSourceBuffer(a,o)}}this.bufferCreated()}clearBufferAppendTimeoutId(e){e&&(self.clearTimeout(e.bufferAppendTimeoutId),e.bufferAppendTimeoutId=void 0)}getTrackCodec(e,t){let s=e.supplemental,i=e.codec;s&&(t==="video"||t==="audiovideo")&&as(s,"video")&&(i=Ih(i,s));let r=Ms(i,e.levelCodec);return r?t.slice(0,5)==="audio"?Hs(r,this.appendSource):r:""}trackSourceBuffer(e,t){let s=t.buffer;if(!s)return;let i=this.getTrackCodec(t,e);this.tracks[e]={buffer:s,codec:i,container:t.container,levelCodec:t.levelCodec,supplemental:t.supplemental,metadata:t.metadata,id:t.id,listeners:[]},this.removeBufferListeners(e),this.addBufferListener(e,"updatestart",this.onSBUpdateStart),this.addBufferListener(e,"updateend",this.onSBUpdateEnd),this.addBufferListener(e,"error",this.onSBUpdateError),this.appendSource&&this.addBufferListener(e,"bufferedchange",(r,a)=>{let o=a.removedRanges;o!=null&&o.length&&(this.log(`${r} buffer removed ${js(o)}`),this.hls.trigger(p.BUFFER_FLUSHED,{type:r,start:o.start(0),end:o.end(o.length-1)}))})}get mediaSrc(){var e;let t=this.media;return t?(t.src?t:((e=t.querySelector)==null?void 0:e.call(t,"source"))||t).src:void 0}isMediaSourceReplaced(e=this._objectUrl){var t;if(!e)return!1;let s=(t=this.media)==null?void 0:t.currentSrc,i=this.mediaSrc;return!!s&&s!==e||!!i&&i!==e}onSBUpdateStart(e){let t=this.currentOp(e);t&&t.onStart()}onSBUpdateEnd(e){var t,s;if(((t=this.mediaSource)==null?void 0:t.readyState)==="closed"){this.resetBuffer(e);return}let i=this.currentOp(e);if(!i)return;if(i.onComplete(),(s=this.tracks[e])==null||(s=s.buffer)==null?void 0:s.updating){this.log(`${e} SourceBuffer updating on "updateend"`),this.blockUntilOpen(()=>{this.shiftAndExecuteNext(e)});return}this.shiftAndExecuteNext(e)}onSBUpdateError(e,t){var s;let i=(s=this.mediaSource)==null?void 0:s.readyState,r=new Error(`${e} SourceBuffer error. MediaSource readyState: ${i}`);r.name=rl,this.error(`${r.message}`,t),this.hls.trigger(p.ERROR,{type:W.MEDIA_ERROR,details:R.BUFFER_APPENDING_ERROR,sourceBufferName:e,error:r,fatal:!1});let a=this.currentOp(e);a&&a.onError(r)}updateTimestampOffset(e,t,s,i,r,a){let o=t-e.timestampOffset;Math.abs(o)>=s&&(this.log(`Updating ${i} SourceBuffer timestampOffset to ${t} (sn: ${r} cc: ${a})`),e.timestampOffset=t)}removeExecutor(e,t,s){let{media:i,mediaSource:r}=this,a=this.tracks[e],o=a?.buffer;if(!i||!r||!o)throw new Error(`Attempting to remove from the ${e} SourceBuffer, but it does not exist`);let l=$(i.duration)?i.duration:1/0,c=$(r.duration)?r.duration:1/0,h=Math.max(0,t);if(h>=c){var u;(u=this.currentOp(e))==null||u.onComplete(),this.shiftAndExecuteNext(e);return}let d=Math.min(s,l,c);if(d>h&&(!a.ending||a.ended))a.ended=!1,this.log(`Removing [${h},${d}] from the ${e} SourceBuffer`),o.remove(h,d);else throw new Error(`Cannot remove ${d<=h?`invalid range (${h} >= ${d}) `:""}from the ${e} SourceBuffer${a.ending?" while track ending":""}`)}appendExecutor(e,t){let s=this.tracks[t],i=s?.buffer;if(!i)throw new dr(`Attempting to append to the ${t} SourceBuffer, but it does not exist`);if(s.ending=!1,s.ended=!1,this.hls.config.appendTimeout!==1/0){let r=this.calculateAppendTimeoutTime(i);s.bufferAppendTimeoutId=self.setTimeout(()=>this.appendTimeoutHandler(t,i,r),r)}i.appendBuffer(e)}appendTimeoutHandler(e,t,s){this.log(`Received timeout after ${s}ms for append on ${e} source buffer. Aborting and triggering error.`);try{t.abort()}catch{this.log(`Failed to abort append on ${e} source buffer after timeout.`)}let i=this.currentOp(e);i&&i.onError(new Error(`${e}-append-timeout`))}calculateAppendTimeoutTime(e){let t=sl;this.details&&(t=this.details.levelTargetDuration);let s=2*t*1e3;if(this.media===null)return s;let i=X.bufferInfo(e,this.media.currentTime,0);return i.len?(s=Math.max(i.len*1e3,s),Math.max(this.hls.config.appendTimeout,s)):s}blockUntilOpen(e){if(this.isUpdating()||this.isQueued())this.blockBuffers(e).catch(t=>{this.warn(`SourceBuffer blocked callback ${t}`),this.stepOperationQueue(this.sourceBufferTypes)});else try{e()}catch(t){this.warn(`Callback run without blocking ${this.operationQueue} ${t}`)}}isUpdating(){return this.sourceBuffers.some(([e,t])=>e&&t.updating)}isQueued(){return this.sourceBuffers.some(([e])=>e&&!!this.currentOp(e))}isPending(e){return!!e&&!e.buffer}isAudioBlocked(){var e;return((e=this.currentOp("audio"))==null?void 0:e.label)==="block-audio"}isAudioBlocking(){return this.operationQueue?this.operationQueue.audioBlocking():!1}blockBuffers(e,t=this.sourceBufferTypes){if(!t.length)return this.log("Blocking operation requested, but no SourceBuffers exist"),Promise.resolve().then(e);let{operationQueue:s}=this,r=t.length===2&&this.isAudioBlocking()?[this.appendBlocker("video")]:t.map(a=>this.appendBlocker(a));return Promise.all(r).then(a=>{s===this.operationQueue&&(e(),this.stepOperationQueue(this.sourceBufferTypes))})}stepOperationQueue(e){e.forEach(t=>{var s;let i=(s=this.tracks[t])==null?void 0:s.buffer;!i||i.updating||t==="audio"&&this.isAudioBlocked()||this.shiftAndExecuteNext(t)})}append(e,t,s){this.operationQueue&&this.operationQueue.append(e,t,s)}insertNext(e,t){this.operationQueue&&this.operationQueue.insertNext(e,t)}appendBlocker(e){if(this.operationQueue)return this.operationQueue.appendBlocker(e)}currentOp(e){return this.operationQueue?this.operationQueue.current(e):null}executeNext(e){e&&this.operationQueue&&this.operationQueue.executeNext(e)}shiftAndExecuteNext(e){this.operationQueue&&this.operationQueue.shiftAndExecuteNext(e)}get pendingTrackCount(){return Object.keys(this.tracks).reduce((e,t)=>e+(this.isPending(this.tracks[t])?1:0),0)}get sourceBufferCount(){return this.sourceBuffers.reduce((e,[t])=>e+(t?1:0),0)}get sourceBufferTypes(){return this.sourceBuffers.map(([e])=>e).filter(e=>!!e)}addBufferListener(e,t,s){let i=this.tracks[e];if(!i)return;let r=i.buffer;if(!r)return;let a=s.bind(this,e);i.listeners.push({event:t,listener:a}),ce(r,t,a)}removeBufferListeners(e){let t=this.tracks[e];if(!t)return;let s=t.buffer;s&&(t.listeners.forEach(i=>{le(s,i.event,i.listener)}),t.listeners.length=0)}};function ma(n){let e=n.querySelectorAll("source");[].slice.call(e).forEach(t=>{n.removeChild(t)})}function qh(n,e){let t=self.document.createElement("source");t.type="video/mp4",t.src=e,n.appendChild(t)}function wi(n){return n==="audio"?1:0}function pa(n,e){return`${n?"":" - triggering recovery"}${e?" with HTMLMediaElement Error: "+e.message:""}`}function ya(n){return`${n.type}_${n.sn}_${n.level}`}function Mi(n,e){let{start:t,end:s}=e,i=0;for(let r=0;r<n.length;r++){let a=n[r];if(a.start>=s)break;let o=Math.max(t,a.start),l=Math.min(s,a.end);l>o&&(i+=l-o)}return i}function Ea(n,e){return e.duration-n<=.05}var fe={NOT_LOADED:"NOT_LOADED",APPENDING:"APPENDING",PARTIAL:"PARTIAL",OK:"OK"},gr=class{constructor(e){this.activePartLists=Object.create(null),this.endListFragments=Object.create(null),this.fragments=Object.create(null),this.timeRanges=Object.create(null),this.bufferPadding=.2,this.hls=void 0,this.hasGaps=!1,this.hls=e,this._registerListeners()}_registerListeners(){let{hls:e}=this;e&&(e.on(p.MANIFEST_LOADING,this.onManifestLoading,this),e.on(p.BUFFER_APPENDED,this.onBufferAppended,this),e.on(p.FRAG_BUFFERED,this.onFragBuffered,this),e.on(p.FRAG_LOADED,this.onFragLoaded,this))}_unregisterListeners(){let{hls:e}=this;e&&(e.off(p.MANIFEST_LOADING,this.onManifestLoading,this),e.off(p.BUFFER_APPENDED,this.onBufferAppended,this),e.off(p.FRAG_BUFFERED,this.onFragBuffered,this),e.off(p.FRAG_LOADED,this.onFragLoaded,this))}destroy(){this._unregisterListeners(),this.hls=this.fragments=this.activePartLists=this.endListFragments=this.timeRanges=null}getAppendedFrag(e,t){let s=this.activePartLists[t];if(s)for(let i=s.length;i--;){let r=s[i];if(!r)break;if(r.start<=e&&e<=r.end&&r.loaded)return r}return this.getBufferedFrag(e,t)}getBufferedFrag(e,t){return this.getFragAtPos(e,t,!0)}getFragAtPos(e,t,s){let{fragments:i}=this,r=Object.keys(i);for(let a=r.length;a--;){let o=i[r[a]];if(o?.body.type===t&&(!s||o.buffered)){let l=o.body;if(l.start<=e&&e<=l.end)return l}}return null}detectEvictedFragments(e,t,s,i,r,a){this.timeRanges&&(this.timeRanges[e]=t);let o=r?.fragment.sn||-1;Object.keys(this.fragments).forEach(l=>{let c=this.fragments[l];if(!c||!this.hls)return;let h=c.body;if(o>=h.sn)return;if(!c.buffered&&(!c.loaded||a)){h.type===s&&this.removeFragment(h);return}let u=c.range[e];if(u){if(u.time.length===0){this.removeFragment(h);return}if(u.time.some(d=>{let f=!this.isTimeBuffered(d.startPTS,d.endPTS,t);return f&&this.removeFragment(h),f}),i&&i!==h&&Xt()){let d=i.endPTS,f=h.startPTS;if(d&&f&&c.range.video){let g=f-d;g<0&&g>-.1&&(this.removeFragment(h),this.hls.trigger(p.BUFFER_FLUSHING,{startOffset:d+.004,endOffset:1/0,type:"video"}))}}}})}detectPartialFragments(e){let t=this.timeRanges,{frag:s,part:i,id:r}=e;if(!t||!pe(s))return;let a=kt(s),o=this.fragments[a];if(!o||o.buffered&&s.gap)return;let l=!s.relurl;Object.keys(t).forEach(h=>{let u=s.elementaryStreams[h];if(!u)return;let d=t[h],f=l||u.partial===!0;o.range[h]=this.getBufferedTimes(s,i,f,d),this.detectEvictedFragments(h,d,r,s,i)}),o.loaded=null;let c=Object.keys(o.range);if(c.length){if(this.bufferedEnd(o,s),Is(o)||this.removeParts(s.sn-1,s.type),!i){let h=Math.min(.004,s.duration);c.some(u=>{var d;let f=(d=o.range[u])==null?void 0:d.time,g=f.length===0||f.length===1&&f[0].endPTS-f[0].startPTS<h;return g&&this.addAsGap(s),g})}}else this.removeFragment(s)}addAsGap(e){e.gap=!0,this.removeFragment(e),this.fragBuffered(e,!0)}bufferedEnd(e,t){e.buffered=!0,(e.body.endList=t.endList||e.body.endList)&&!t.gap&&(this.endListFragments[e.body.type]=e)}removeParts(e,t){let s=this.activePartLists[t];s&&(this.activePartLists[t]=Ta(s,i=>i.fragment.sn>=e))}fragBuffered(e,t){let s=kt(e),i=this.fragments[s];return!i&&t&&(i=this.fragments[s]={body:e,appendedPTS:null,loaded:null,buffered:!1,range:Object.create(null)},e.gap&&(this.hasGaps=!0)),i&&(i.loaded=null,this.bufferedEnd(i,e)),i}getBufferedTimes(e,t,s,i){let r={time:[],partial:s},a=e.start,o=e.end,l=e.minEndPTS||o,c=e.maxStartPTS||a;for(let h=0;h<i.length;h++){let u=i.start(h)-this.bufferPadding,d=i.end(h)+this.bufferPadding;if(c>=u&&l<=d){r.time.push({startPTS:Math.max(a,i.start(h)),endPTS:Math.min(o,i.end(h))});break}else if(a<d&&o>u){let f=Math.max(a,i.start(h)),g=Math.min(o,i.end(h));g>f&&(r.partial=!0,r.time.push({startPTS:f,endPTS:g}))}else if(o<=u)break}return r}getPartialFragment(e){let t=null,s,i,r,a=0,{bufferPadding:o,fragments:l}=this;return Object.keys(l).forEach(c=>{let h=l[c];h&&Is(h)&&(i=h.body.start-o,r=h.body.end+o,e>=i&&e<=r&&(s=Math.min(e-i,r-e),a<=s&&(t=h.body,a=s)))}),t}isEndListAppended(e){let t=this.endListFragments[e];return t!==void 0&&(t.buffered||Is(t))}getState(e){let t=kt(e),s=this.fragments[t];return s?s.buffered?Is(s)?fe.PARTIAL:fe.OK:fe.APPENDING:fe.NOT_LOADED}isTimeBuffered(e,t,s){let i,r;for(let a=0;a<s.length;a++){if(i=s.start(a)-this.bufferPadding,r=s.end(a)+this.bufferPadding,e>=i&&t<=r)return!0;if(t<=i)return!1}return!1}onManifestLoading(){this.removeAllFragments()}onFragLoaded(e,t){if(!pe(t.frag)||t.frag.bitrateTest)return;let s=t.frag,i=t.part?null:t,r=kt(s);this.fragments[r]={body:s,appendedPTS:null,loaded:i,buffered:!1,range:Object.create(null)}}onBufferAppended(e,t){let{frag:s,part:i,timeRanges:r}=t;if(!pe(s))return;let a=s.type;if(i){let o=this.activePartLists[a];o||(this.activePartLists[a]=o=[]),o.push(i)}this.timeRanges=r}onFragBuffered(e,t){this.detectPartialFragments(t)}hasFragment(e){let t=kt(e);return!!this.fragments[t]}hasFragments(e){let{fragments:t}=this,s=Object.keys(t);if(!e)return s.length>0;for(let i=s.length;i--;){let r=t[s[i]];if(r?.body.type===e)return!0}return!1}hasParts(e){var t;return!!((t=this.activePartLists[e])!=null&&t.length)}getBackBufferEvictionEnd(e,t,s){let{fragments:i}=this,r=0,a=0,o=Object.keys(i);for(let l=0;l<o.length;l++){let c=i[o[l]];if(!c||!c.buffered||c.body.type!==t)continue;let h=c.body;if(h.gap)return 0;let u=h.hasStats&&h.stats.loaded||h.byteLength||h.bitrate&&h.bitrate*8*h.duration;if(h.end<=e&&u&&(r+=u,a=Math.max(a,h.end),r>=s))return a}return a>0?a:0}removeFragmentsInRange(e,t,s,i,r){i&&!this.hasGaps||Object.keys(this.fragments).forEach(a=>{let o=this.fragments[a];if(!o)return;let l=o.body;l.type!==s||i&&!l.gap||l.start<t&&l.end>e&&(o.buffered||r)&&this.removeFragment(l)})}removeFragment(e){let t=kt(e);e.clearElementaryStreamInfo();let s=this.activePartLists[e.type];if(s){let i=e.sn;this.activePartLists[e.type]=Ta(s,r=>r.fragment.sn!==i)}delete this.fragments[t],e.endList&&delete this.endListFragments[e.type]}gapFragments(){return this.hasGaps?Object.keys(this.fragments).map(e=>{var t;return(t=this.fragments[e])==null?void 0:t.body}).filter(e=>!!(e!=null&&e.gap)):[]}removeAllFragments(){var e;this.fragments=Object.create(null),this.endListFragments=Object.create(null),this.activePartLists=Object.create(null),this.hasGaps=!1;let t=(e=this.hls)==null||(e=e.latestLevelDetails)==null?void 0:e.partList;t&&t.forEach(s=>s.clearElementaryStreamInfo())}};function Is(n){var e,t,s,i;return n.buffered&&!!(n.body.gap||(e=n.range.video)!=null&&e.partial||(t=n.range.audio)!=null&&t.partial||(s=n.range.audiovideo)!=null&&s.partial||(i=n.range.subs)!=null&&i.partial)}function kt(n){return`${n.type}_${n.level}_${n.sn}`}function Ta(n,e){return n.filter(t=>{let s=e(t);return s||t.clearElementaryStreamInfo(),s})}var xt={cbc:0,ctr:1},mr=class{constructor(e,t,s){this.subtle=void 0,this.aesIV=void 0,this.aesMode=void 0,this.subtle=e,this.aesIV=t,this.aesMode=s}decrypt(e,t){switch(this.aesMode){case xt.cbc:return this.subtle.decrypt({name:"AES-CBC",iv:this.aesIV},t,e);case xt.ctr:return this.subtle.decrypt({name:"AES-CTR",counter:this.aesIV,length:64},t,e);default:throw new Error(`[AESCrypto] invalid aes mode ${this.aesMode}`)}}};function jh(n){let e=n.byteLength,t=e&&new DataView(n.buffer).getUint8(e-1);return t?n.slice(0,e-t):n}var pr=class{constructor(){this.rcon=[0,1,2,4,8,16,32,64,128,27,54],this.subMix=[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)],this.invSubMix=[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)],this.sBox=new Uint32Array(256),this.invSBox=new Uint32Array(256),this.key=new Uint32Array(0),this.ksRows=0,this.keySize=0,this.keySchedule=void 0,this.invKeySchedule=void 0,this.initTable()}uint8ArrayToUint32Array_(e){let t=new DataView(e),s=new Uint32Array(4);for(let i=0;i<4;i++)s[i]=t.getUint32(i*4);return s}initTable(){let e=this.sBox,t=this.invSBox,s=this.subMix,i=s[0],r=s[1],a=s[2],o=s[3],l=this.invSubMix,c=l[0],h=l[1],u=l[2],d=l[3],f=new Uint32Array(256),g=0,m=0,y=0;for(y=0;y<256;y++)y<128?f[y]=y<<1:f[y]=y<<1^283;for(y=0;y<256;y++){let E=m^m<<1^m<<2^m<<3^m<<4;E=E>>>8^E&255^99,e[g]=E,t[E]=g;let S=f[g],T=f[S],v=f[T],x=f[E]*257^E*16843008;i[g]=x<<24|x>>>8,r[g]=x<<16|x>>>16,a[g]=x<<8|x>>>24,o[g]=x,x=v*16843009^T*65537^S*257^g*16843008,c[E]=x<<24|x>>>8,h[E]=x<<16|x>>>16,u[E]=x<<8|x>>>24,d[E]=x,g?(g=S^f[f[f[v^S]]],m^=f[f[m]]):g=m=1}}expandKey(e){let t=this.uint8ArrayToUint32Array_(e),s=!0,i=0;for(;i<t.length&&s;)s=t[i]===this.key[i],i++;if(s)return;this.key=t;let r=this.keySize=t.length;if(r!==4&&r!==6&&r!==8)throw new Error("Invalid aes key size="+r);let a=this.ksRows=(r+6+1)*4,o,l,c=this.keySchedule=new Uint32Array(a),h=this.invKeySchedule=new Uint32Array(a),u=this.sBox,d=this.rcon,f=this.invSubMix,g=f[0],m=f[1],y=f[2],E=f[3],S,T;for(o=0;o<a;o++){if(o<r){S=c[o]=t[o];continue}T=S,o%r===0?(T=T<<8|T>>>24,T=u[T>>>24]<<24|u[T>>>16&255]<<16|u[T>>>8&255]<<8|u[T&255],T^=d[o/r|0]<<24):r>6&&o%r===4&&(T=u[T>>>24]<<24|u[T>>>16&255]<<16|u[T>>>8&255]<<8|u[T&255]),c[o]=S=(c[o-r]^T)>>>0}for(l=0;l<a;l++)o=a-l,l&3?T=c[o]:T=c[o-4],l<4||o<=4?h[l]=T:h[l]=g[u[T>>>24]]^m[u[T>>>16&255]]^y[u[T>>>8&255]]^E[u[T&255]],h[l]=h[l]>>>0}networkToHostOrderSwap(e){return e<<24|(e&65280)<<8|(e&16711680)>>8|e>>>24}decrypt(e,t,s){let i=this.keySize+6,r=this.invKeySchedule,a=this.invSBox,o=this.invSubMix,l=o[0],c=o[1],h=o[2],u=o[3],d=this.uint8ArrayToUint32Array_(s),f=d[0],g=d[1],m=d[2],y=d[3],E=new Int32Array(e),S=new Int32Array(E.length),T,v,x,I,A,b,_,L,P,D,M,U,B,k,w=this.networkToHostOrderSwap;for(;t<E.length;){for(P=w(E[t]),D=w(E[t+1]),M=w(E[t+2]),U=w(E[t+3]),A=P^r[0],b=U^r[1],_=M^r[2],L=D^r[3],B=4,k=1;k<i;k++)T=l[A>>>24]^c[b>>16&255]^h[_>>8&255]^u[L&255]^r[B],v=l[b>>>24]^c[_>>16&255]^h[L>>8&255]^u[A&255]^r[B+1],x=l[_>>>24]^c[L>>16&255]^h[A>>8&255]^u[b&255]^r[B+2],I=l[L>>>24]^c[A>>16&255]^h[b>>8&255]^u[_&255]^r[B+3],A=T,b=v,_=x,L=I,B=B+4;T=a[A>>>24]<<24^a[b>>16&255]<<16^a[_>>8&255]<<8^a[L&255]^r[B],v=a[b>>>24]<<24^a[_>>16&255]<<16^a[L>>8&255]<<8^a[A&255]^r[B+1],x=a[_>>>24]<<24^a[L>>16&255]<<16^a[A>>8&255]<<8^a[b&255]^r[B+2],I=a[L>>>24]<<24^a[A>>16&255]<<16^a[b>>8&255]<<8^a[_&255]^r[B+3],S[t]=w(T^f),S[t+1]=w(I^g),S[t+2]=w(x^m),S[t+3]=w(v^y),f=P,g=D,m=M,y=U,t=t+4}return S.buffer}},yr=class{constructor(e,t,s){this.subtle=void 0,this.key=void 0,this.aesMode=void 0,this.subtle=e,this.key=t,this.aesMode=s}expandKey(){let e=zh(this.aesMode);return this.subtle.importKey("raw",this.key,{name:e},!1,["encrypt","decrypt"])}};function zh(n){switch(n){case xt.cbc:return"AES-CBC";case xt.ctr:return"AES-CTR";default:throw new Error(`[FastAESKey] invalid aes mode ${n}`)}}var Xh=16,cs=class{constructor(e,t){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=e.enableSoftwareAES,t!==!0)try{let s=self.crypto;s&&(this.subtle=s.subtle||s.webkitSubtle)}catch{}this.useSoftware=!this.subtle}destroy(){this.subtle=null,this.softwareDecrypter=null,this.key=null,this.fastAesKey=null,this.remainderData=null,this.currentIV=null,this.currentResult=null}isSync(){return this.useSoftware}flush(){let{currentResult:e,remainderData:t}=this;if(!e||t)return this.reset(),null;let s=new Uint8Array(e);this.reset();let i=this.decryptRange;return i?i.start===0&&i.end>=s.length?s:s.slice(i.start,i.end):jh(s)}reset(){this.currentResult=null,this.currentIV=null,this.remainderData=null,this.softwareDecrypter&&(this.softwareDecrypter=null)}decrypt(e,t,s,i,r){return this.decryptRange=r,this.useSoftware||r?new Promise((a,o)=>{let l=ArrayBuffer.isView(e)?e:new Uint8Array(e);this.softwareDecrypt(l,t,s,i);let c=this.flush();c?a(c.buffer):o(new Error("[softwareDecrypt] Failed to decrypt data"))}):this.webCryptoDecrypt(new Uint8Array(e),t,s,i)}softwareDecrypt(e,t,s,i){let{currentIV:r,currentResult:a,remainderData:o}=this;if(i!==xt.cbc||t.byteLength!==16)return oe.warn("SoftwareDecrypt: can only handle AES-128-CBC"),null;this.logOnce("JS AES decrypt"),o&&(e=We(o,e),this.remainderData=null);let l=this.getValidChunk(e);if(!l.length)return null;r&&(s=r);let c=this.softwareDecrypter;c||(c=this.softwareDecrypter=new pr),c.expandKey(t);let h=a;return this.currentResult=c.decrypt(l.buffer,0,s),this.currentIV=l.slice(-16).buffer,h||null}webCryptoDecrypt(e,t,s,i){if(this.key!==t||!this.fastAesKey){if(!this.subtle)return Promise.resolve(this.onWebCryptoError(e,t,s,i));this.key=t,this.fastAesKey=new yr(this.subtle,t,i)}return this.fastAesKey.expandKey().then(r=>this.subtle?(this.logOnce("WebCrypto AES decrypt"),new mr(this.subtle,new Uint8Array(s),i).decrypt(e.buffer,r)):Promise.reject(new Error("web crypto not initialized"))).catch(r=>(oe.warn(`[decrypter]: WebCrypto Error, disable WebCrypto API, ${r.name}: ${r.message}`),this.onWebCryptoError(e,t,s,i)))}onWebCryptoError(e,t,s,i){let r=this.enableSoftwareAES;if(r){this.useSoftware=!0,this.logEnabled=!0,this.softwareDecrypt(e,t,s,i);let a=this.flush();if(a)return a.buffer}throw new Error("WebCrypto"+(r?" and softwareDecrypt":"")+": failed to decrypt data")}getValidChunk(e){let t=e,s=e.length-e.length%Xh;return s!==e.length&&(t=e.slice(0,s),this.remainderData=e.slice(s)),t}logOnce(e){this.logEnabled&&(oe.log(`[decrypter]: ${e}`),this.logEnabled=!1)}},Sa=Math.pow(2,17),zs=class{constructor(e){this.config=void 0,this.loader=null,this.partLoadTimeout=-1,this.config=e}destroy(){this.loader&&(this.loader.destroy(),this.loader=null)}abort(){this.loader&&this.loader.abort()}load(e,t,s,i){let r=e.url;if(!r)return Promise.reject(new Ye({type:W.NETWORK_ERROR,details:R.FRAG_LOAD_ERROR,fatal:!1,frag:e,error:new Error(`Fragment does not have a ${r?"part list":"url"}`),networkDetails:null}));this.abort();let a=this.config,o=a.fLoader,l=a.loader;return new Promise((c,h)=>{if(this.loader&&this.loader.destroy(),e.gap)if(e.tagList.some(y=>y[0]==="GAP")){h(xa(e));return}else e.gap=!1;let u=this.loader=o?new o(a):new l(a),d=va(e,null,t);e.loader=u;let f=Zn(a.fragLoadPolicy.default),g={loadPolicy:f,timeout:f.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:e.sn==="initSegment"?1/0:Sa};u.stats.retry=e.stats.retry,e.stats=u.stats;let m={onSuccess:(y,E,S,T)=>{this.resetLoader(e,u);let v=y.data;S.resetIV&&e.decryptdata&&(e.decryptdata.iv=new Uint8Array(v.slice(0,16)),v=v.slice(16)),c({frag:e,part:null,payload:v,networkDetails:T})},onError:(y,E,S,T)=>{this.resetLoader(e,u),h(new Ye({type:W.NETWORK_ERROR,details:R.FRAG_LOAD_ERROR,fatal:!1,frag:e,response:Y({url:r,data:void 0},y),error:new Error(`HTTP Error ${y.code} ${y.text}`),networkDetails:S,stats:T}))},onAbort:(y,E,S)=>{this.resetLoader(e,u),h(new Ye({type:W.NETWORK_ERROR,details:R.INTERNAL_ABORTED,fatal:!1,frag:e,error:new Error("Aborted"),networkDetails:S,stats:y}))},onTimeout:(y,E,S)=>{this.resetLoader(e,u),h(new Ye({type:W.NETWORK_ERROR,details:R.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,error:new Error(`Timeout after ${g.timeout}ms`),networkDetails:S,stats:y}))}};if(s){let y=this.gateProgress(s,i);m.onProgress=(E,S,T,v)=>y({frag:e,part:null,payload:T,networkDetails:v})}u.load(d,g,m)})}gateProgress(e,t){let s=e;if(t){let i=[],r=!1;t.then(()=>{r=!0,i.forEach(a=>e(a)),i.length=0}).catch(()=>{}),s=a=>{r?e(a):i.push(a)}}return s}loadPart(e,t,s){this.abort();let i=this.config,r=i.fLoader,a=i.loader;return new Promise((o,l)=>{if(this.loader&&this.loader.destroy(),e.gap||t.gap){l(xa(e,t));return}let c=this.loader=r?new r(i):new a(i),h=va(e,t);e.loader=c;let u=Zn(i.fragLoadPolicy.default),d={loadPolicy:u,timeout:u.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:Sa};t.stats=c.stats,c.load(h,d,{onSuccess:(f,g,m,y)=>{this.resetLoader(e,c),this.updateStatsFromPart(e,t);let E={frag:e,part:t,payload:f.data,networkDetails:y};s(E),o(E)},onError:(f,g,m,y)=>{this.resetLoader(e,c),l(new Ye({type:W.NETWORK_ERROR,details:R.FRAG_LOAD_ERROR,fatal:!1,frag:e,part:t,response:Y({url:h.url,data:void 0},f),error:new Error(`HTTP Error ${f.code} ${f.text}`),networkDetails:m,stats:y}))},onAbort:(f,g,m)=>{e.stats.aborted=t.stats.aborted,this.resetLoader(e,c),l(new Ye({type:W.NETWORK_ERROR,details:R.INTERNAL_ABORTED,fatal:!1,frag:e,part:t,error:new Error("Aborted"),networkDetails:m,stats:f}))},onTimeout:(f,g,m)=>{this.resetLoader(e,c),l(new Ye({type:W.NETWORK_ERROR,details:R.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,part:t,error:new Error(`Timeout after ${d.timeout}ms`),networkDetails:m,stats:f}))}})})}updateStatsFromPart(e,t){let s=e.stats,i=t.stats,r=i.total;if(s.loaded+=i.loaded,r){let l=Math.round(e.duration/t.duration),c=Math.min(Math.round(s.loaded/r),l),u=(l-c)*Math.round(s.loaded/c);s.total=s.loaded+u}else s.total=Math.max(s.loaded,s.total);let a=s.loading,o=i.loading;a.start?a.first+=o.first-o.start:(a.start=o.start,a.first=o.first),a.end=o.end}resetLoader(e,t){e.loader=null,e.url=null,this.loader===t&&(self.clearTimeout(this.partLoadTimeout),this.loader=null),t.destroy()}};function va(n,e=null,t){let s=e||n,i={type:se.MEDIA_FRAGMENT,frag:n,part:e,responseType:"arraybuffer",url:s.url,headers:{},rangeStart:0,rangeEnd:0},r=Xs(n,e,t);return r.resetIV&&(i.resetIV=!0),r.byteRange&&(i.rangeStart=r.byteRange.start,i.rangeEnd=r.byteRange.end),i}function Xs(n,e=null,t){let s={},i=e||n,r=i.byteRangeStartOffset,a=i.byteRangeEndOffset;if($(r)&&$(a)){var o;if((n.sn==="initSegment"||t)&&Qh((o=n.decryptdata)==null?void 0:o.method)){let l=Math.floor(r/16)*16,c=Math.ceil(a/16)*16;s.decryptRange={start:r-l,end:a-l},l>=16&&(s.resetIV=!0,l=l-16),s.byteRange={start:l,end:c}}else s.byteRange={start:r,end:a}}return s}function xa(n,e){let t=new Error(`GAP ${n.gap?"tag":"attribute"} found`),s={type:W.MEDIA_ERROR,details:R.FRAG_GAP,fatal:!1,frag:n,error:t,networkDetails:null};return e&&(s.part=e),(e||n).stats.aborted=!0,new Ye(s)}function Qh(n){return n==="AES-128"||n==="AES-256"}var Ye=class extends Error{constructor(e){super(e.error.message),this.data=void 0,this.data=e}},Qs=class extends we{constructor(e,t){super(e,t),this._boundTick=void 0,this._tickTimer=null,this._tickInterval=null,this._tickCallCount=0,this._boundTick=this.tick.bind(this)}destroy(){this.onHandlerDestroying(),this.onHandlerDestroyed()}onHandlerDestroying(){this.clearNextTick(),this.clearInterval()}onHandlerDestroyed(){}hasInterval(){return!!this._tickInterval}hasNextTick(){return!!this._tickTimer}setInterval(e){return this._tickInterval?!1:(this._tickCallCount=0,this._tickInterval=self.setInterval(this._boundTick,e),!0)}clearInterval(){return this._tickInterval?(self.clearInterval(this._tickInterval),this._tickInterval=null,!0):!1}clearNextTick(){return this._tickTimer?(self.clearTimeout(this._tickTimer),this._tickTimer=null,!0):!1}tick(){this._tickCallCount++,this._tickCallCount===1?(this.doTick(),this._tickCallCount>1&&this.tickImmediate(),this._tickCallCount=0):(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(){}},hs=class{constructor(e,t,s,i=0,r=-1,a=!1,o,l,c){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=As(),this.buffering={audio:As(),video:As(),audiovideo:As()},this.level=e,this.sn=t,this.id=s,this.size=i,this.part=r,this.partial=a,this.duration=o||0,this.decryptRange=c,this.iframe=l||!1}};function As(){return{start:0,executeStart:0,executeEnd:0,end:0}}var Er=/\{\$([a-zA-Z0-9-_]+)\}/g;function Ia(n){return Er.lastIndex=0,Er.test(n)}function kn(n,e){if(n.variableList!==null||n.hasVariableRefs){let t=n.variableList;return e.replace(Er,s=>{let i=s.substring(2,s.length-1),r=t?.[i];return r===void 0?(n.playlistParsingError||(n.playlistParsingError=new Error(`Missing preceding EXT-X-DEFINE tag for Variable Reference: "${i}"`)),s):r})}return e}function Aa(n,e,t){let s=n.variableList;s||(n.variableList=s={});let i,r;if("QUERYPARAM"in e){i=e.QUERYPARAM;try{let a=new self.URL(t).searchParams;if(a.has(i))r=a.get(i);else throw new Error(`"${i}" does not match any query parameter in URI: "${t}"`)}catch(a){n.playlistParsingError||(n.playlistParsingError=new Error(`EXT-X-DEFINE QUERYPARAM: ${a.message}`))}}else i=e.NAME,r=e.VALUE;i in s?n.playlistParsingError||(n.playlistParsingError=new Error(`EXT-X-DEFINE duplicate Variable Name declarations: "${i}"`)):s[i]=r||""}function Zh(n,e,t){let s=e.IMPORT;if(t&&s in t){let i=n.variableList;i||(n.variableList=i={}),i[s]=t[s]}else n.playlistParsingError||(n.playlistParsingError=new Error(`EXT-X-DEFINE IMPORT attribute not found in Multivariant Playlist: "${s}"`))}var Jh=/^(\d+)x(\d+)$/,La=/(.+?)=(".*?"|.*?)(?:,|$)/g,me=class n{constructor(e,t){typeof e=="string"&&(e=n.parseAttrList(e,t)),he(this,e)}get clientAttrs(){return Object.keys(this).filter(e=>e.substring(0,2)==="X-")}decimalInteger(e){let t=parseInt(this[e],10);return t>Number.MAX_SAFE_INTEGER?1/0:t}hexadecimalInteger(e){if(this[e]){let t=(this[e]||"0x").slice(2);t=(t.length&1?"0":"")+t;let s=new Uint8Array(t.length/2);for(let i=0;i<t.length/2;i++)s[i]=parseInt(t.slice(i*2,i*2+2),16);return s}return null}hexadecimalIntegerAsNumber(e){let t=parseInt(this[e],16);return t>Number.MAX_SAFE_INTEGER?1/0:t}decimalFloatingPoint(e){return parseFloat(this[e])}optionalFloat(e,t){let s=this[e];return s?parseFloat(s):t}enumeratedString(e){return this[e]}enumeratedStringList(e,t){let s=this[e];return(s?s.split(/[ ,]+/):[]).reduce((i,r)=>(i[r.toLowerCase()]=!0,i),t)}bool(e){return this[e]==="YES"}decimalResolution(e){let t=Jh.exec(this[e]);if(t!==null)return{width:parseInt(t[1],10),height:parseInt(t[2],10)}}static parseAttrList(e,t){let s,i={};for(La.lastIndex=0;(s=La.exec(e))!==null;){let a=s[1].trim(),o=s[2],l=o.indexOf('"')===0&&o.lastIndexOf('"')===o.length-1,c=!1;if(l)o=o.slice(1,-1);else switch(a){case"IV":case"SCTE35-CMD":case"SCTE35-IN":case"SCTE35-OUT":c=!0}if(t&&(l||c))o=kn(t,o);else if(!c&&!l)switch(a){case"CLOSED-CAPTIONS":if(o==="NONE")break;case"ALLOWED-CPC":case"CLASS":case"ASSOC-LANGUAGE":case"AUDIO":case"BYTERANGE":case"CHANNELS":case"CHARACTERISTICS":case"CODECS":case"DATA-ID":case"END-DATE":case"GROUP-ID":case"ID":case"IMPORT":case"INSTREAM-ID":case"KEYFORMAT":case"KEYFORMATVERSIONS":case"LANGUAGE":case"NAME":case"PATHWAY-ID":case"QUERYPARAM":case"RECENTLY-REMOVED-DATERANGES":case"SERVER-URI":case"STABLE-RENDITION-ID":case"STABLE-VARIANT-ID":case"START-DATE":case"SUBTITLES":case"SUPPLEMENTAL-CODECS":case"URI":case"VALUE":case"VIDEO":case"X-ASSET-LIST":case"X-ASSET-URI":oe.warn(`${e}: attribute ${a} is missing quotes`)}i[a]=o}return i}},eu="com.apple.hls.interstitial";function tu(n){return n!=="ID"&&n!=="CLASS"&&n!=="CUE"&&n!=="START-DATE"&&n!=="DURATION"&&n!=="END-DATE"&&n!=="END-ON-NEXT"}function su(n){return n==="SCTE35-OUT"||n==="SCTE35-IN"||n==="SCTE35-CMD"}var Zs=class{constructor(e,t,s=0){var i;if(this.attr=void 0,this.tagAnchor=void 0,this.tagOrder=void 0,this._startDate=void 0,this._endDate=void 0,this._dateAtEnd=void 0,this._cue=void 0,this._badValueForSameId=void 0,this.tagAnchor=t?.tagAnchor||null,this.tagOrder=(i=t?.tagOrder)!=null?i:s,t){let r=t.attr;for(let a in r)if(Object.prototype.hasOwnProperty.call(e,a)&&e[a]!==r[a]){oe.warn(`DATERANGE tag attribute: "${a}" does not match for tags with ID: "${e.ID}"`),this._badValueForSameId=a;break}e=he(new me({}),r,e)}if(this.attr=e,t?(this._startDate=t._startDate,this._cue=t._cue,this._endDate=t._endDate,this._dateAtEnd=t._dateAtEnd):this._startDate=new Date(e["START-DATE"]),"END-DATE"in e){let r=t?.endDate||new Date(e["END-DATE"]);$(r.getTime())&&(this._endDate=r)}}get id(){return this.attr.ID}get class(){return this.attr.CLASS}get cue(){let e=this._cue;return e===void 0?this._cue=this.attr.enumeratedStringList(this.attr.CUE?"CUE":"X-CUE",{pre:!1,post:!1,once:!1}):e}get startTime(){let{tagAnchor:e}=this;return e===null||e.programDateTime===null?(oe.warn(`Expected tagAnchor Fragment with PDT set for DateRange "${this.id}": ${e}`),NaN):e.start+(this.startDate.getTime()-e.programDateTime)/1e3}get startDate(){return this._startDate}get endDate(){let e=this._endDate||this._dateAtEnd;if(e)return e;let t=this.duration;return t!==null?this._dateAtEnd=new Date(this._startDate.getTime()+t*1e3):null}get duration(){if("DURATION"in this.attr){let e=this.attr.decimalFloatingPoint("DURATION");if($(e))return e}else if(this._endDate)return(this._endDate.getTime()-this._startDate.getTime())/1e3;return null}get plannedDuration(){return"PLANNED-DURATION"in this.attr?this.attr.decimalFloatingPoint("PLANNED-DURATION"):null}get endOnNext(){return this.attr.bool("END-ON-NEXT")}get isInterstitial(){return this.class===eu}get isValid(){return!!this.id&&!this._badValueForSameId&&$(this.startDate.getTime())&&(this.duration===null||this.duration>=0)&&(!this.endOnNext||!!this.class)&&(!this.attr.CUE||!this.cue.pre&&!this.cue.post||this.cue.pre!==this.cue.post)&&(!this.isInterstitial||"X-ASSET-URI"in this.attr||"X-ASSET-LIST"in this.attr)}get invalidReason(){return this.id?this._badValueForSameId?`Date range ${this._badValueForSameId} mismatch`:$(this.startDate.getTime())?this.isInterstitial&&!("X-ASSET-URI"in this.attr||"X-ASSET-LIST"in this.attr)?"Interstitial Date range missing X-ASSET-(LIST|URI)":this.isValid?null:"Unknown (check DURATION(|END|NEXT), CLASS, and CUE)":"Date range invalid start date":"Missing ID"}};function Js(n,e){return n.length===e.length?!n.some((t,s)=>t!==e[s]):!1}function Ra(n,e){return!n&&!e?!0:!n||!e?!1:Js(n,e)}function Bt(n){return n==="AES-128"||n==="AES-256"||n==="AES-256-CTR"}function On(n){switch(n){case"AES-128":case"AES-256":return xt.cbc;case"AES-256-CTR":return xt.ctr;default:throw new Error(`invalid full segment method ${n}`)}}function Tr(n){return Uint8Array.from(unescape(encodeURIComponent(n)),e=>e.charCodeAt(0))}function iu(n){let e=Tr(n).subarray(0,16),t=new Uint8Array(16);return t.set(e,16-e.length),t}function nl(n){let e=function(s,i,r){let a=s[i];s[i]=s[r],s[r]=a};e(n,0,3),e(n,1,2),e(n,4,5),e(n,6,7)}function al(n){let e=n.split(":"),t=null;if(e[0]==="data"&&e.length===2){let s=e[1].split(";"),i=s[s.length-1].split(",");if(i.length===2){let r=i[0]==="base64",a=i[1];r?(s.splice(-1,1),t=Dn(a)):t=iu(a)}}return t}var ei=typeof self<"u"?self:void 0,ge={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.fps",PLAYREADY:"com.microsoft.playready",WIDEVINE:"com.widevine.alpha"},De={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.streamingkeydelivery",PLAYREADY:"com.microsoft.playready",WIDEVINE:"urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed"};function Ls(n){switch(n){case De.FAIRPLAY:return ge.FAIRPLAY;case De.PLAYREADY:return ge.PLAYREADY;case De.WIDEVINE:return ge.WIDEVINE;case De.CLEARKEY:return ge.CLEARKEY}}var ol={WIDEVINE:"edef8ba979d64acea3c827dcd51d21ed"};function Fi(n){switch(n){case ge.FAIRPLAY:return De.FAIRPLAY;case ge.PLAYREADY:return De.PLAYREADY;case ge.WIDEVINE:return De.WIDEVINE;case ge.CLEARKEY:return De.CLEARKEY}}function Ht(n){let{drmSystems:e,widevineLicenseUrl:t}=n,s=e?[ge.FAIRPLAY,ge.WIDEVINE,ge.PLAYREADY,ge.CLEARKEY].filter(i=>!!e[i]):[];return!s[ge.WIDEVINE]&&t&&s.push(ge.WIDEVINE),s}var ll=(function(n){return ei!=null&&(n=ei.navigator)!=null&&n.requestMediaKeySystemAccess?self.navigator.requestMediaKeySystemAccess.bind(self.navigator):null})();function ru(n,e,t,s){let i;switch(n){case ge.FAIRPLAY:i=["cenc","sinf"];break;case ge.WIDEVINE:case ge.PLAYREADY:i=["cenc"];break;case ge.CLEARKEY:i=["cenc","keyids"];break;default:throw new Error(`Unknown key-system: ${n}`)}return nu(i,e,t,s)}function nu(n,e,t,s){return[{initDataTypes:n,persistentState:s.persistentState||"optional",distinctiveIdentifier:s.distinctiveIdentifier||"optional",sessionTypes:s.sessionTypes||[s.sessionType||"temporary"],audioCapabilities:e.map(r=>({contentType:`audio/mp4; codecs=${r}`,robustness:s.audioRobustness||"",encryptionScheme:s.audioEncryptionScheme||null})),videoCapabilities:t.map(r=>({contentType:`video/mp4; codecs=${r}`,robustness:s.videoRobustness||"",encryptionScheme:s.videoEncryptionScheme||null}))}]}function au(n){var e;return!!n&&(n.sessionType==="persistent-license"||!!((e=n.sessionTypes)!=null&&e.some(t=>t==="persistent-license")))}function wn(n){let e=new Uint16Array(n.buffer,n.byteOffset,n.byteLength/2),t=Ze(e),s=t.substring(t.indexOf("<"),t.length),a=new DOMParser().parseFromString(s,"text/xml").getElementsByTagName("KID")[0];if(a){let o=a.childNodes[0]?a.childNodes[0].nodeValue:a.getAttribute("VALUE");if(o){let l=Dn(o).subarray(0,16);return nl(l),l}}return null}var Ot={},Ct=class n{static clearKeyUriToKeyIdMap(){Ot={}}static setKeyIdForUri(e,t){Ot[e]=t}static addKeyIdForUri(e){let t=Object.keys(Ot).length%Number.MAX_SAFE_INTEGER,s=new Uint8Array(16);return new DataView(s.buffer,12,4).setUint32(0,t),Ot[e]=s,s}constructor(e,t,s,i=[1],r=null,a){this.uri=void 0,this.method=void 0,this.keyFormat=void 0,this.keyFormatVersions=void 0,this.encrypted=void 0,this.isCommonEncryption=void 0,this.iv=null,this.key=null,this.keyId=null,this.pssh=null,this.scheme=void 0,this.method=e,this.uri=t,this.keyFormat=s,this.keyFormatVersions=i,this.iv=r,this.encrypted=e?e!=="NONE":!1,this.isCommonEncryption=this.encrypted&&!Bt(e),a!=null&&a.startsWith("0x")&&(this.keyId=new Uint8Array(Co(a)))}matches(e){return e.uri===this.uri&&e.method===this.method&&e.encrypted===this.encrypted&&e.keyFormat===this.keyFormat&&Js(e.keyFormatVersions,this.keyFormatVersions)&&Ra(e.iv,this.iv)&&Ra(e.keyId,this.keyId)}isSupported(){if(this.method){if(Bt(this.method)||this.method==="NONE")return!0;if(this.keyFormat==="identity")return this.method==="SAMPLE-AES";switch(this.keyFormat){case De.FAIRPLAY:case De.WIDEVINE:case De.PLAYREADY:case De.CLEARKEY:return["SAMPLE-AES","SAMPLE-AES-CENC","SAMPLE-AES-CTR"].indexOf(this.method)!==-1}}return!1}getDecryptData(e,t){var s;if(!this.encrypted||!this.uri)return null;if(Bt(this.method)){let a=this.iv;return a||(typeof e!="number"&&(oe.warn(`missing IV for initialization segment with method="${this.method}" - compliance issue`),e=0),a=lu(e)),new n(this.method,this.uri,"identity",this.keyFormatVersions,a)}if(this.keyId){let a=Ot[this.uri];if(a&&!Js(this.keyId,a)&&n.setKeyIdForUri(this.uri,this.keyId),this.pssh)return this}let i=al(this.uri);if(i)switch(this.keyFormat){case De.WIDEVINE:if(this.pssh=i,!this.keyId){let a=Vo(i.buffer).filter(o=>o.systemId===ol.WIDEVINE);if(a.length){var r;let o=a[0];this.keyId=(r=o.kids)!=null&&r.length?o.kids[0]:null}}this.keyId||(this.keyId=ba(t));break;case De.PLAYREADY:{let a=new Uint8Array([154,4,240,121,152,64,66,134,171,146,230,91,224,136,95,149]);this.pssh=fh(a,null,i),this.keyId=wn(i);break}default:{let a=i.subarray(0,16);if(a.length!==16){let o=new Uint8Array(16);o.set(a,16-a.length),a=o}this.keyId=a;break}}if(((s=this.keyId)==null?void 0:s.byteLength)!==16){let a;a=ou(t),a||(a=ba(t),a||(a=Ot[this.uri])),a&&(this.keyId=a,n.setKeyIdForUri(this.uri,a))}return this}};function ou(n){let e=n?.[De.WIDEVINE];return e?e.keyId:null}function ba(n){let e=n?.[De.PLAYREADY];if(e){let t=al(e.uri);if(t)return wn(t)}return null}function lu(n){let e=new Uint8Array(16);for(let t=12;t<16;t++)e[t]=n>>8*(15-t)&255;return e}var _a=/#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,Da=/#EXT-X-MEDIA:(.*)/g,cu=/^#EXT(?:INF|-X-TARGETDURATION):/m,Ni=new RegExp([/#EXTINF:\s*(\d+(?:\.\d*)?|\.\d+)?(?:,(.*)\s+)?/.source,/(?!#) *(\S[^\r\n]*)/.source,/#.*/.source].join("|"),"g"),hu=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("|")),Et=class n{static findGroup(e,t){for(let s=0;s<e.length;s++){let i=e[s];if(i.id===t)return i}}static resolve(e,t){return Ln.buildAbsoluteURL(t,e,{alwaysNormalize:!0})}static isMediaPlaylist(e){return cu.test(e)}static parseMasterPlaylist(e,t){let s=Ia(e),i={contentSteering:null,levels:[],iframeVariants:[],playlistParsingError:null,sessionData:null,sessionKeys:null,startTimeOffset:null,variableList:null,hasVariableRefs:s},r=[];if(_a.lastIndex=0,!e.startsWith("#EXTM3U"))return i.playlistParsingError=new Error("no EXTM3U delimiter"),i;let a;for(;(a=_a.exec(e))!=null;)if(a[1]){let l=new me(a[1],i),c=Pa(l,a[2],t,i,r);c&&i.levels.push(c)}else if(a[3]){let l=a[3],c=a[4];switch(l){case"I-FRAME-STREAM-INF":{let h=new me(c,i),u=Pa(h,h.URI,t,i,r,!0);u&&i.iframeVariants.push(u)}break;case"SESSION-DATA":{let h=new me(c,i),u=h["DATA-ID"];u&&(i.sessionData===null&&(i.sessionData={}),i.sessionData[u]=h);break}case"SESSION-KEY":{let h=Ca(c,t,i);h.encrypted&&h.isSupported()?(i.sessionKeys===null&&(i.sessionKeys=[]),i.sessionKeys.push(h)):oe.warn(`[Keys] Ignoring invalid EXT-X-SESSION-KEY tag: "${c}"`);break}case"DEFINE":{{let h=new me(c,i);Aa(i,h,t)}break}case"CONTENT-STEERING":{let h=new me(c,i);i.contentSteering={uri:n.resolve(h["SERVER-URI"],t),pathwayId:h["PATHWAY-ID"]||"."};break}case"START":{i.startTimeOffset=ka(c);break}}}let o=r.length>0&&r.length<i.levels.length;return i.levels=o?r:i.levels,i.levels.length===0&&(i.playlistParsingError=new Error("no levels found in manifest")),i}static parseMasterPlaylistMedia(e,t,s){let i,r={},a=s.levels,o={AUDIO:a.map(c=>({id:c.attrs.AUDIO,audioCodec:c.audioCodec})),SUBTITLES:a.map(c=>({id:c.attrs.SUBTITLES,textCodec:c.textCodec})),"CLOSED-CAPTIONS":[]},l=0;for(Da.lastIndex=0;(i=Da.exec(e))!==null;){let c=new me(i[1],s),h=c.TYPE;if(h){let u=o[h],d=r[h]||[];r[h]=d;let f=c.LANGUAGE,g=c["ASSOC-LANGUAGE"],m=c.CHANNELS,y=c.CHARACTERISTICS,E=c["INSTREAM-ID"],S={attrs:c,bitrate:0,id:l++,groupId:c["GROUP-ID"]||"",name:c.NAME||f||"",type:h,default:c.bool("DEFAULT"),autoselect:c.bool("AUTOSELECT"),forced:c.bool("FORCED"),lang:f,url:c.URI?n.resolve(c.URI,t):""};if(g&&(S.assocLang=g),m&&(S.channels=m),y&&(S.characteristics=y),E&&(S.instreamId=E),u!=null&&u.length){let T=n.findGroup(u,S.groupId)||u[0];wa(S,T,"audioCodec"),wa(S,T,"textCodec")}d.push(S)}}return r}static parseLevelPlaylist(e,t,s,i,r,a){var o;let l={url:t},c=new ur(t),h=c.fragments,u=[],d=null,f=0,g=0,m=0,y=0,E=0,S=null,T=new Ft(i,l),v,x,I,A=-1,b=!1,_=null,L;if(Ni.lastIndex=0,c.m3u8=e,c.hasVariableRefs=Ia(e),((o=Ni.exec(e))==null?void 0:o[0])!=="#EXTM3U")return c.playlistParsingError=new Error("Missing format identifier #EXTM3U"),c;for(;(v=Ni.exec(e))!==null;){b&&(b=!1,T=new Ft(i,l),T.playlistOffset=m,T.setStart(m),T.sn=f,T.cc=y,E&&(T.bitrate=E),T.level=s,d&&(T.initSegment=d,d.rawProgramDateTime&&(T.rawProgramDateTime=d.rawProgramDateTime,d.rawProgramDateTime=null),_&&(T.setByteRange(_),_=null)));let B=v[1];if(B){T.duration=parseFloat(B);let k=(" "+v[2]).slice(1);T.title=k||null,T.tagList.push(k?["INF",B,k]:["INF",B])}else if(v[3]){if($(T.duration)){var P;T.playlistOffset=m,T.setStart(m),I&&Fa(T,I,c),T.sn=f,T.level=s,T.cc=y;let k=(" "+v[3]).slice(1);T.relurl=kn(c,k),Sr(T,S,u),S=T,m+=T.duration,f++,g=0;let w=T.byteRange;if(w.length===2&&(T.bitrate=(w[1]-w[0])*8/T.duration|0),c.iframesOnly&&w[0]&&((P=d)==null?void 0:P.cc)!==y){let O=new Ft(i,l);O.relurl=T.relurl,O.setByteRange(`${Math.min(w[0],1316)}@0`),O.level=s,O.sn="initSegment",I&&(O.levelkeys=I,I.identity&&(O._decryptdata=I.identity.getDecryptData(0))),d=O,T.initSegment=d}h.push(T),b=!0}}else{if(v=v[0].match(hu),!v){oe.warn("No matches on slow regex match for level playlist!");continue}for(x=1;x<v.length&&v[x]===void 0;x++);let k=(" "+v[x]).slice(1),w=(" "+v[x+1]).slice(1),O=v[x+2]?(" "+v[x+2]).slice(1):null;switch(k){case"BYTERANGE":S?T.setByteRange(w,S):T.setByteRange(w);break;case"PROGRAM-DATE-TIME":T.rawProgramDateTime=w,T.tagList.push(["PROGRAM-DATE-TIME",w]),A===-1&&(A=h.length);break;case"PLAYLIST-TYPE":c.type&&at(c,k,v),c.type=w.toUpperCase();break;case"MEDIA-SEQUENCE":c.startSN!==0?at(c,k,v):S!==null&&fu(c,k,v),c.startSN=parseInt(w),f=c.startSN+c.skippedSegments;break;case"SKIP":{c.skippedSegments&&at(c,k,v);let F=new me(w,c),H=F.decimalInteger("SKIPPED-SEGMENTS");if($(H)){c.skippedSegments+=H;for(let G=H;G--;)h.push(null);f+=H}let N=F.enumeratedString("RECENTLY-REMOVED-DATERANGES");N&&(c.recentlyRemovedDateranges=(c.recentlyRemovedDateranges||[]).concat(N.split(" ")));break}case"TARGETDURATION":c.targetduration!==0&&at(c,k,v),c.targetduration=Math.max(parseInt(w),1);break;case"VERSION":c.version!==null&&at(c,k,v),c.version=parseInt(w);break;case"INDEPENDENT-SEGMENTS":break;case"I-FRAMES-ONLY":c.iframesOnly=!0;break;case"ENDLIST":c.live||at(c,k,v),c.live=!1;break;case"#":(w||O)&&T.tagList.push(O?[w,O]:[w]);break;case"DISCONTINUITY":y++,T.tagList.push(["DIS"]);break;case"GAP":T.gap=!0,T.tagList.push([k]);break;case"BITRATE":T.tagList.push([k,w]),E=parseInt(w)*1e3,$(E)?T.bitrate=E:E=0;break;case"DATERANGE":{let F=new me(w,c),H=new Zs(F,c.dateRanges[F.ID],c.dateRangeTagCount);c.dateRangeTagCount++,H.isValid||c.skippedSegments?c.dateRanges[H.id]=H:oe.log(`Ignoring invalid DATERANGE tag: ${H.invalidReason}: ${w}`),T.tagList.push(["EXT-X-DATERANGE",w]);break}case"DEFINE":{{let F=new me(w,c);"IMPORT"in F?Zh(c,F,a):Aa(c,F,t)}break}case"DISCONTINUITY-SEQUENCE":c.startCC!==0&&at(c,k,v),c.startCC=y=parseInt(w),h.forEach(F=>F&&(F.cc=y));break;case"KEY":{let F=Ca(w,t,c);if(F.isSupported()){if(F.method==="NONE"){I=void 0;break}I||(I={});let H=I[F.keyFormat];H!=null&&H.matches(F)||(H&&(I=he({},I)),I[F.keyFormat]=F)}else oe.warn(`[Keys] Ignoring unsupported EXT-X-KEY tag: "${w}"`);break}case"START":c.startTimeOffset=ka(w);break;case"MAP":{let F=new me(w,c);if(T.duration){let H=new Ft(i,l);Ma(H,F,s,I),d=H,T.initSegment=d,d.rawProgramDateTime&&!T.rawProgramDateTime&&(T.rawProgramDateTime=d.rawProgramDateTime)}else{let H=T.byteRangeEndOffset;if(H){let N=T.byteRangeStartOffset;_=`${H-N}@${N}`}else _=null;Ma(T,F,s,I),d=T,b=!0}d.cc=y;break}case"SERVER-CONTROL":{L&&at(c,k,v),L=new me(w),c.canBlockReload=L.bool("CAN-BLOCK-RELOAD"),c.canSkipUntil=L.optionalFloat("CAN-SKIP-UNTIL",0),c.canSkipDateRanges=c.canSkipUntil>0&&L.bool("CAN-SKIP-DATERANGES"),c.partHoldBack=L.optionalFloat("PART-HOLD-BACK",0),c.holdBack=L.optionalFloat("HOLD-BACK",0);break}case"PART-INF":{c.partTarget&&at(c,k,v);let F=new me(w);c.partTarget=F.decimalFloatingPoint("PART-TARGET");break}case"PART":{let F=c.partList;F||(F=c.partList=[]);let H=g>0?F[F.length-1]:void 0,N=g++,G=new me(w,c),Z=new er(G,T,l,N,H);F.push(Z),T.duration+=Z.duration;break}case"PRELOAD-HINT":{let F=new me(w,c);c.preloadHint=F;break}case"RENDITION-REPORT":{let F=new me(w,c);c.renditionReports=c.renditionReports||[],c.renditionReports.push(F);break}default:oe.warn(`line parsed but not handled: ${v}`);break}}}S&&!S.relurl?(h.pop(),m-=S.duration,c.partList&&(c.fragmentHint=S)):c.partList&&(Sr(T,S,u),T.cc=y,c.fragmentHint=T,I&&Fa(T,I,c)),c.targetduration||(c.playlistParsingError=new Error("Missing Target Duration"));let D=h.length,M=h[0],U=h[D-1];if(m+=c.skippedSegments*c.targetduration,m>0&&D&&U){c.averagetargetduration=m/D;let B=U.sn;c.endSN=B!=="initSegment"?B:0,c.live||(U.endList=!0),A>0&&(du(h,A,A>D-1?T:null),M&&u.unshift(M))}return c.fragmentHint&&(m+=c.fragmentHint.duration),c.totalduration=m,u.length&&c.dateRangeTagCount&&M&&cl(u,c),c.endCC=y,c}};function Pa(n,e,t,s,i,r){var a;if(e===void 0)return null;let o=kn(s,e),l={attrs:n,bitrate:n.decimalInteger("BANDWIDTH")||n.decimalInteger("AVERAGE-BANDWIDTH"),name:n.NAME,url:Et.resolve(o,t)},c=n.decimalResolution("RESOLUTION");c&&(l.width=c.width,l.height=c.height),Oa(n.CODECS,l);let h=n["SUPPLEMENTAL-CODECS"];return h&&(l.supplemental={},Oa(h,l.supplemental)),(a=l.unknownCodecs)!=null&&a.length||i.push(l),r&&(l.iframes=!0),l}function cl(n,e){let t=n.length;if(!t)if(e.hasProgramDateTime){let o=e.fragments[e.fragments.length-1];n.push(o),t++}else return;let s=n[t-1],i=e.live?1/0:e.totalduration,r=Object.keys(e.dateRanges);for(let o=r.length;o--;){let l=e.dateRanges[r[o]],c=l.startDate.getTime();l.tagAnchor=s.ref;for(let h=t;h--;){var a;if(((a=n[h])==null?void 0:a.sn)<e.startSN)break;let u=uu(e,c,n,h,i);if(u){l.tagAnchor=u.ref;break}}}}function uu(n,e,t,s,i){let r=t[s];if(r){let o=r.programDateTime;if(e>=o||s===0){var a;let l=(((a=t[s+1])==null?void 0:a.start)||i)-r.start;if(e<=o+l*1e3){let c=r.sn-n.startSN,h=n.fragments;if(c>=0&&c<h.length){if(h.length>t.length){let u=t[s+1]||h[h.length-1],d=Math.min(u.sn-n.startSN,h.length-1);for(let f=d;f>c;f--){let g=h[f].programDateTime;if(e>=g&&e<g+h[f].duration*1e3)return h[f]}}return h[c]}}}}return null}function Ca(n,e,t){var s,i;let r=new me(n,t),a=(s=r.METHOD)!=null?s:"",o=r.URI,l=r.hexadecimalInteger("IV"),c=r.KEYFORMATVERSIONS,h=(i=r.KEYFORMAT)!=null?i:"identity";o&&r.IV&&!l&&oe.error(`Invalid IV: ${r.IV}`);let u=o?Et.resolve(o,e):"",d=(c||"1").split("/").map(Number).filter(Number.isFinite);return new Ct(a,u,h,d,l,r.KEYID)}function ka(n){let t=new me(n).decimalFloatingPoint("TIME-OFFSET");return $(t)?t:null}function Oa(n,e){let t=(n||"").split(/[ ,]+/).filter(s=>s);["video","audio","text","image"].forEach(s=>{let i=t.filter(r=>Pn(r,s));i.length&&(e[`${s}Codec`]=i.map(r=>r.split("/")[0]).join(","),t=t.filter(r=>i.indexOf(r)===-1))}),e.unknownCodecs=t}function wa(n,e,t){let s=e[t];s&&(n[t]=s)}function du(n,e,t){if(t||(t=n[e]),!!t)for(let s=e;s--;){let i=n[s];if(!i)return;i.programDateTime=t.programDateTime-i.duration*1e3,t=i}}function Sr(n,e,t){n.rawProgramDateTime?t.push(n):e!=null&&e.programDateTime&&(n.programDateTime=e.endProgramDateTime)}function Ma(n,e,t,s){n.relurl=e.URI,e.BYTERANGE&&n.setByteRange(e.BYTERANGE),n.level=t,n.sn="initSegment",s&&(n.levelkeys=s),n.initSegment=null}function Fa(n,e,t){n.levelkeys=e;let{encryptedFragments:s}=t;(!s.length||s[s.length-1].levelkeys!==e)&&Object.keys(e).some(i=>e[i].isCommonEncryption)&&s.push(n)}function at(n,e,t){n.playlistParsingError=new Error(`#EXT-X-${e} must not appear more than once (${t[0]})`)}function fu(n,e,t){n.playlistParsingError=new Error(`#EXT-X-${e} must appear before the first Media Segment (${t[0]})`)}function Bi(n,e){let t=e.startPTS;if($(t)){let s=0,i;e.sn>n.sn?(s=t-n.start,i=n):(s=n.start-t,i=e),i.duration!==s&&i.setDuration(s)}else e.sn>n.sn?n.cc===e.cc&&n.minEndPTS?e.setStart(n.start+(n.minEndPTS-n.start)):e.setStart(n.start+n.duration):e.setStart(Math.max(n.start-e.duration,0))}function hl(n,e,t,s,i,r,a,o){s-t<=0&&(o.warn("Fragment should have a positive duration",e),s=t+e.duration,r=i+e.duration);let c=t,h=s,u=e.startPTS,d=e.endPTS;if($(u)){let g=Math.abs(u-t);n&&g>n.totalduration?o.warn(`media timestamps and playlist times differ by ${g}s for level ${e.level} ${n.url}`):$(e.deltaPTS)?e.deltaPTS=Math.max(g,e.deltaPTS):e.deltaPTS=g,c=Math.max(t,u),t=Math.min(t,u),i=e.startDTS!==void 0?Math.min(i,e.startDTS):i,h=Math.min(s,d),s=Math.max(s,d),r=e.endDTS!==void 0?Math.max(r,e.endDTS):r}let f=t-e.start;return e.start!==0&&e.setStart(t),e.setDuration(s-e.start),e.startPTS=t,e.maxStartPTS=c,e.startDTS=i,e.endPTS=s,e.minEndPTS=h,e.endDTS=r,ul(n,e,f)}function ul(n,e,t){var s;let i=e.sn;if(!n||i<n.startSN||i>(((s=n.fragmentHint)==null?void 0:s.sn)||n.endSN))return 0;let r,a=i-n.startSN,o=n.fragments;for(o[a]=e,r=a;r>0;r--)Bi(o[r],o[r-1]);for(r=a;r<o.length-1;r++)Bi(o[r],o[r+1]);return n.fragmentHint&&Bi(o[o.length-1],n.fragmentHint),n.PTSKnown=n.alignedSliding=!0,t}function gu(n,e,t){if(n===e)return;let s=null,i=n.fragments;for(let h=i.length-1;h>=0;h--){let u=i[h].initSegment;if(u){s=u;break}}n.fragmentHint&&delete n.fragmentHint.endPTS;let r;yu(n,e,(h,u,d,f)=>{if(u.cc!==h.cc&&(h.cc>u.cc||e.skippedSegments)){let g=h.cc-u.cc;for(let m=d;m<f.length;m++)f[m].cc+=g;e.endCC=f[f.length-1].cc}$(h.startPTS)&&$(h.endPTS)&&(u.setStart(u.startPTS=h.startPTS),u.startDTS=h.startDTS,u.maxStartPTS=h.maxStartPTS,u.endPTS=h.endPTS,u.endDTS=h.endDTS,u.minEndPTS=h.minEndPTS,u.setDuration(h.endPTS-h.startPTS),u.duration&&(r=u),e.PTSKnown=e.alignedSliding=!0),h.hasStreams&&(u.elementaryStreams=h.elementaryStreams),u.loader=h.loader,u.gap=h.gap||u.gap,h.hasStats&&(u.stats=h.stats),h.initSegment&&(u.initSegment=h.initSegment,s=h.initSegment)});let a=e.fragments,o=e.fragmentHint?a.concat(e.fragmentHint):a;if(s&&o.forEach(h=>{var u;h&&(!h.initSegment||h.initSegment.relurl===((u=s)==null?void 0:u.relurl))&&(h.initSegment=s)}),e.skippedSegments){if(e.deltaUpdateFailed=a.some(h=>!h),e.deltaUpdateFailed){t.warn("[level-helper] Previous playlist missing segments skipped in delta playlist");for(let h=e.skippedSegments;h--;)a.shift();e.startSN=a[0].sn}else{e.canSkipDateRanges&&(e.dateRanges=mu(n.dateRanges,e,t));let h=n.fragments.filter(u=>u.rawProgramDateTime);if(n.hasProgramDateTime&&!e.hasProgramDateTime)for(let u=1;u<o.length;u++)o[u].programDateTime===null&&Sr(o[u],o[u-1],h);cl(h,e)}e.endCC=a[a.length-1].cc}else if(e.startSN>n.endSN&&a[0].cc<n.endCC){let h=n.endCC-a[0].cc;o.forEach(u=>{u.cc+=h}),e.endCC+=h}if(!e.startCC){var l;let h=Ns(n,e.startSN-1);e.startCC=(l=h?.cc)!=null?l:a[0].cc}if(pu(n.partList,e.partList,(h,u)=>{u.elementaryStreams=h.elementaryStreams,u.stats=h.stats,u.gap=h.gap||u.gap}),r){let h=e.iframesOnly&&r.type===K.MAIN;hl(e,r,r.startPTS,r.endPTS,r.startDTS,r.endDTS,h,t)}else dl(n,e);a.length&&(e.totalduration=e.edge-a[0].start),e.driftStartTime=n.driftStartTime,e.driftStart=n.driftStart;let c=e.advancedDateTime;if(e.advanced&&c){let h=e.edge;e.driftStart||(e.driftStartTime=c,e.driftStart=h),e.driftEndTime=c,e.driftEnd=h}else e.driftEndTime=n.driftEndTime,e.driftEnd=n.driftEnd,e.advancedDateTime=n.advancedDateTime;e.requestScheduled===-1&&(e.requestScheduled=n.requestScheduled)}function mu(n,e,t){let{dateRanges:s,recentlyRemovedDateranges:i}=e,r=he({},n);i&&i.forEach(l=>{delete r[l]});let o=Object.keys(r).length;return o?(Object.keys(s).forEach(l=>{let c=r[l],h=new Zs(s[l].attr,c);h.isValid?(r[l]=h,c||(h.tagOrder+=o)):t.warn(`Ignoring invalid Playlist Delta Update DATERANGE tag: "${de(s[l].attr)}"`)}),r):s}function pu(n,e,t){if(n&&e){let s=0;for(let i=0,r=n.length;i<r;i++){let a=n[i],o=e[i+s];a&&o&&a.index===o.index&&a.fragment.sn===o.fragment.sn?t(a,o):s--}}}function yu(n,e,t){var s;let i=e.skippedSegments,r=Math.max(n.startSN,e.startSN)-e.startSN,a=(n.fragmentHint?1:0)+(i?e.endSN:Math.min(n.endSN,e.endSN))-e.startSN,o=e.startSN-n.startSN,l=e.fragmentHint?e.fragments.concat(e.fragmentHint):e.fragments,c=(s=n.fragmentHint)!=null&&s.duration?n.fragments.concat(n.fragmentHint):n.fragments;for(let h=r;h<=a;h++){let u=c[o+h],d=l[h];if(i&&!d&&u&&(d=e.fragments[h]=u),u&&d){t(u,d,h,l);let f=u.relurl,g=d.relurl;if(f&&Tu(f,g)){e.playlistParsingError=Na(`media sequence mismatch ${d.sn}:`,n,e,u,d);return}else if(u.cc!==d.cc){e.playlistParsingError=Na(`discontinuity sequence mismatch (${u.cc}!=${d.cc})`,n,e,u,d);return}}}}function Na(n,e,t,s,i){return new Error(`${n} ${i.url}
17
+ Playlist starting @${e.startSN}
18
+ ${e.m3u8}
19
+
20
+ Playlist starting @${t.startSN}
21
+ ${t.m3u8}`)}function dl(n,e,t=!0,s){let i=e.startSN+e.skippedSegments-n.startSN,r=n.fragments,a=i>=0,o=0;if(a&&i<r.length)o=r[i].start,s?.log(`Aligning playlists based on SN ${e.startSN} (diff: ${o})`);else if(a&&e.startSN===n.endSN+1)o=n.fragmentEnd,s?.log(`Aligning playlists based on first/last SN ${e.startSN} (diff: ${o})`);else if(a&&t)o=n.fragmentStart+i*e.levelTargetDuration;else if(!e.skippedSegments&&e.fragmentStart===0)o=n.fragmentStart,s?.log(`Aligning playlists based on first SN ${e.startSN} (diff: ${o})`);else return o;return Eu(e,o),o}function Eu(n,e){if(e){let t=n.fragments;for(let s=n.skippedSegments;s<t.length;s++)t[s].addStart(e);n.fragmentHint&&n.fragmentHint.addStart(e)}}function fl(n,e=1/0){let t=1e3*n.targetduration;if(n.updated){let s=n.fragments;if(s.length&&t*4>e){let r=s[s.length-1].duration*1e3;r>0&&r<t&&(t=r)}}else t/=2;return Math.round(t)}function Ns(n,e,t){var s;if(!n)return null;let i=n.fragments[e-n.startSN];return i||(i=n.fragmentHint,((s=i)==null?void 0:s.sn)===e)?i:t&&e<n.startSN&&t.sn===e?t:null}function Ba(n,e,t){return n?gl(n.partList,e,t):null}function gl(n,e,t){if(n)for(let s=n.length;s--;){let i=n[s];if(i.index===t&&i.fragment.sn===e)return i}return null}function ml(n){n.forEach((e,t)=>{var s;(s=e.details)==null||s.fragments.forEach(i=>{i.level=t,i.initSegment&&(i.initSegment.level=t)})})}function Tu(n,e){return n!==e&&e?$a(n)!==$a(e):!1}function $a(n){return n.replace(/\?[^?]*$/,"")}function Zt(n,e){for(let s=0,i=n.length;s<i;s++){var t;if(((t=n[s])==null?void 0:t.cc)===e)return n[s]}return null}function Su(n,e){return!!(n&&e.startCC<n.endCC&&e.endCC>n.startCC)}function Ua(n,e){let t=n.start+e;n.setStart(t)}function pl(n,e){let t=e.fragments;for(let s=0,i=t.length;s<i;s++)Ua(t[s],n);e.fragmentHint&&Ua(e.fragmentHint,n),e.alignedSliding=!0}function ti(n,e,t){n&&(vu(e,n,t),e.alignedSliding||xu(e,n,t),!e.alignedSliding&&!e.skippedSegments&&dl(n,e,!1,t))}function vu(n,e,t){if(!Su(e,n))return;let s=Math.min(e.endCC,n.endCC),i=Zt(e.fragments,s),r=Zt(n.fragments,s);if(!i||!r)return;let a=i.start-r.start;t.log(`Aligning playlists using dicontinuity sequence ${s} (diff: ${a})`),pl(a,n)}function xu(n,e,t){if(!n.hasProgramDateTime||!e.hasProgramDateTime)return;let s=n.fragments,i=e.fragments;if(!s.length||!i.length)return;let r,a,o=Math.min(e.endCC,n.endCC);e.startCC<o&&n.startCC<o&&(r=Zt(i,o),a=Zt(s,o)),(!r||!a)&&(r=i[Math.floor(i.length/2)]||i.filter(d=>!!d)[0],a=Zt(s,r.cc)||s[Math.floor(s.length/2)]);let l=r.programDateTime,c=a.programDateTime;if(!l||!c)return;let h=(c-l)/1e3;if(Math.abs(h)>Math.max(60,n.totalduration)){t.log(`Cannot align playlists using PDT without overlap (${Math.abs(h)} > ${n.totalduration})`);return}let u=h-(a.start-r.start);t.log(`Aligning playlists using PDT (diff: ${u})`),pl(u,n)}var C={STOPPED:"STOPPED",IDLE:"IDLE",KEY_LOADING:"KEY_LOADING",FRAG_LOADING:"FRAG_LOADING",FRAG_LOADING_WAITING_RETRY:"FRAG_LOADING_WAITING_RETRY",WAITING_TRACK:"WAITING_TRACK",PARSING:"PARSING",PARSED:"PARSED",ENDED:"ENDED",ERROR:"ERROR",WAITING_INIT_PTS:"WAITING_INIT_PTS",WAITING_LEVEL:"WAITING_LEVEL"},us=class extends Qs{constructor(e,t,s,i,r){super(i,e.logger),this.hls=void 0,this.fragPrevious=null,this.fragCurrent=null,this.fragPlaying=null,this.fragmentTracker=void 0,this.transmuxer=null,this._state=C.STOPPED,this.playlistType=void 0,this.media=null,this.mediaBuffer=null,this.config=void 0,this.bitrateTest=!1,this.lastCurrentTime=0,this.nextLoadPosition=0,this.startPosition=-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=()=>{let{config:a,fragCurrent:o,media:l,mediaBuffer:c,state:h}=this,u=l?l.currentTime:0,d=X.bufferInfo(c||l,u,a.maxBufferHole),f=d.len;if(this.log(`Media seeking to ${u}, state: ${h}, ${f?"in":"out of"} buffer`),this.state===C.ENDED)this.resetLoadingState();else if(o){let y=a.maxFragLookUpTolerance,E=o.start-y,S=o.start+o.duration+y;if(!f||S<d.start||E>d.end){let T=u<E,v=u>S;(T||v)&&(o.loader&&(v||!this.isFragmentNearlyDownloaded(o))?(this.log(`Cancelling fragment load for seek (sn: ${o.sn}) - ${T?"backward":"forward"} seek`),o.abortRequests(),this.resetLoadingState()):this.fragPrevious=null)}}if(l){var g;(g=this.hls)!=null&&g.hasEnoughToStart&&!f&&u!==this.startPosition&&this.fragmentTracker.removeFragmentsInRange(u,1/0,this.playlistType,!0);let y=this.lastCurrentTime;if(u>y&&(this.lastCurrentTime=u),!this.loadingParts){let E=Math.max(d.end,u),S=this.shouldLoadParts(this.getLevelDetails(),E);S&&(this.log(`LL-Part loading ON after seeking to ${u} with buffer @${E}`),this.loadingParts=S)}}let m=!X.isBuffered(l,u);(!this.hls.hasEnoughToStart||m)&&(this.log(`Setting ${m?"startPosition":"nextLoadPosition"} to ${u} for seek without enough to start`),this.nextLoadPosition=u,m?this.startPosition=u:this.lastCurrentTime=u),f<1&&this.state===C.IDLE&&this.tickImmediate()},this.onMediaEnded=()=>{this.log("setting startPosition to 0 because media ended"),this.startPosition=this.nextLoadPosition=this.lastCurrentTime=0},this.playlistType=r,this.hls=e,this.fragmentLoader=new zs(e.config),this.initFragmentLoader=new zs(e.config),this.keyLoader=s,this.fragmentTracker=t,this.config=e.config,this.decrypter=new cs(e.config)}registerListeners(){let{hls:e}=this;e.on(p.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(p.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(p.MANIFEST_LOADING,this.onManifestLoading,this),e.on(p.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(p.ERROR,this.onError,this)}unregisterListeners(){let{hls:e}=this;e.off(p.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(p.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(p.MANIFEST_LOADING,this.onManifestLoading,this),e.off(p.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(p.ERROR,this.onError,this)}doTick(){}onTickEnd(){let{media:e}=this;e!=null&&e.readyState&&e.seeking===!1&&(this.lastCurrentTime=e.currentTime)}startLoad(e){}stopLoad(){if(this.state===C.STOPPED)return;this.fragmentLoader.abort(),this.initFragmentLoader.abort(),this.keyLoader.abort(this.playlistType);let e=this.fragCurrent;e!=null&&e.loader&&(e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.resetTransmuxer(),this.fragCurrent=null,this.fragPrevious=null,this.clearInterval(),this.clearNextTick(),this.state=C.STOPPED}get startPositionValue(){let{nextLoadPosition:e,startPosition:t}=this;if(t===-1&&e){let s=this.getLevelDetails();return s!=null&&s.live?(this.hls.liveSyncPosition||s.fragmentStart)+this.timelineOffset:e}return t}get bufferingEnabled(){return this.buffering}get backtrackFragment(){}set backtrackFragment(e){}get couldBacktrack(){return!1}set couldBacktrack(e){}pauseBuffering(){this.buffering=!1}resumeBuffering(){this.buffering=!0}get inFlightFrag(){return{frag:this.fragCurrent,state:this.state}}_streamEnded(e,t){if(t.live||!this.media)return!1;let s=e.end||0,i=this.config.timelineOffset||0;if(s<=i)return!1;let r=e.buffered;this.config.maxBufferHole&&r&&r.length>1&&(e=X.bufferedInfo(r,e.start,0));let a=e.nextStart;if(a&&a>i&&a<t.edge||this.media.currentTime<e.start)return!1;let l=t.partList;if(l!=null&&l.length){let h=l[l.length-1];return X.isBuffered(this.media,h.start+h.duration/2)}let c=t.fragments[t.fragments.length-1];return this.fragmentTracker.isEndListAppended(c.type)}getLevelDetails(){if(this.levels&&this.levelLastLoaded!==null)return this.levelLastLoaded.details}get timelineOffset(){let e=this.config.timelineOffset;if(e){var t;return((t=this.getLevelDetails())==null?void 0:t.appliedTimelineOffset)||e}return 0}onMediaAttached(e,t){let s=this.media=this.mediaBuffer=t.media;ce(s,"seeking",this.onMediaSeeking),ce(s,"ended",this.onMediaEnded);let i=this.config;this.levels&&i.autoStartLoad&&this.state===C.STOPPED&&this.startLoad(i.startPosition)}onMediaDetaching(e,t){this.fragPlaying=null;let s=!!t.transferMedia,i=this.media;if(i===null)return;if(i.ended&&(this.log("MSE detaching and video ended, reset startPosition"),this.startPosition=this.lastCurrentTime=0),le(i,"seeking",this.onMediaSeeking),le(i,"ended",this.onMediaEnded),this.media=this.mediaBuffer=null,this.loopSn=void 0,s){this.resetLoadingState(),this.resetTransmuxer();return}this.loadingParts=!1;let{fragmentTracker:r}=this,a=r.gapFragments();r.removeAllFragments(),a.forEach(o=>r.addAsGap(o)),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(e,t){}onManifestLoaded(e,t){this.startTimeOffset=t.startTimeOffset}onHandlerDestroying(){this.stopLoad(),this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null),super.onHandlerDestroying(),this.hls=this.onMediaSeeking=this.onMediaEnded=null}onHandlerDestroyed(){this.state=C.STOPPED,this.fragmentLoader&&this.fragmentLoader.destroy(),this.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(e,t,s){this.startFragRequested=!0,this._loadFragForPlayback(e,t,s)}_loadFragForPlayback(e,t,s){let i=r=>{let a=r.frag;if(this.fragContextChanged(a)){this.warn(`${a.type} sn: ${a.sn}${r.part?" part: "+r.part.index:""} of ${this.fragInfo(a,!1,r.part)} was dropped during download.`),this.fragmentTracker.removeFragment(a);return}let o=++a.stats.chunkCount;this.log(`load progress ${a.type} sn: ${a.sn}${r.part?" part: "+r.part.index:""} of ${this.fragInfo(a,!1,r.part)} chunk: ${o}`),this._handleFragmentLoadProgress(r)};this._doFragLoad(e,t,s,i).then(r=>{if(!r)return;let a=this.state,o=r.frag;if(this.fragContextChanged(o)){(a===C.FRAG_LOADING||!this.fragCurrent&&a===C.PARSING)&&(this.fragmentTracker.removeFragment(o),this.state=C.IDLE);return}"payload"in r&&(this.log(`Loaded ${o.type} sn: ${o.sn} of ${this.playlistLabel()} ${o.level} (bytes ${o.stats.loaded})`),this.hls.trigger(p.FRAG_LOADED,r)),this._handleFragmentLoadComplete(r)}).catch(r=>{this.state===C.STOPPED||this.state===C.ERROR||(this.log(`Frag error ${e.type} sn:${e.sn} cc:${e.cc}: ${r?.message||r}`),this.resetFragmentLoading(e))})}clearTrackerIfNeeded(e){var t;let{fragmentTracker:s}=this;if(s.getState(e)===fe.APPENDING){let r=e.type,a=this.getFwdBufferInfo(this.mediaBuffer,r),o=Math.max(e.duration,a?a.len:this.config.maxBufferLength),l=this.backtrackFragment;((l?e.sn-l.sn:0)===1||this.reduceMaxBufferLength(o,e.duration))&&s.removeFragment(e)}else((t=this.mediaBuffer)==null?void 0:t.buffered.length)===0?s.removeAllFragments():s.hasParts(e.type)&&(s.detectPartialFragments({frag:e,part:null,stats:e.stats,id:e.type}),s.getState(e)===fe.PARTIAL&&s.removeFragment(e))}checkLiveUpdate(e){if(e.updated&&!e.live){let t=this.fragmentTracker,s=e.fragments[e.fragments.length-1];if(s.endList&&!t.isEndListAppended(this.playlistType)){let i=t.getPartialFragment(s.end);i&&(t.removeFragment(i),t.fragBuffered(s,!0))}t.detectPartialFragments({frag:s,part:null,stats:s.stats,id:s.type})}e.fragments[0]||(e.deltaUpdateFailed=!0)}waitForLive(e){let t=e.details;return t?.live&&t.type!=="EVENT"&&t.advancedDateTime!==void 0&&(t.expired||this.loadingParts&&t.partsExpired||t.misses<3&&t.partEnd<=this.getLoadPosition())}flushMainBuffer(e,t,s=null){if(!(e-t))return;let i={startOffset:e,endOffset:t,type:s};this.hls.trigger(p.BUFFER_FLUSHING,i)}_loadInitSegment(e){let{hls:t}=this;return this.initFragmentLoader.abort(),t.trigger(p.FRAG_LOADING,{frag:e,targetBufferTime:0}),this.initFragmentLoader.load(e).then(s=>{var i;let r=s.frag;if(!this.levels||!Ji(r,(i=this.fragCurrent)==null?void 0:i.initSegment))throw new Ye({type:W.NETWORK_ERROR,details:R.INTERNAL_ABORTED,error:new Error("init load aborted"),fatal:!1,frag:r,networkDetails:null});return s}).then(s=>{let{frag:i,payload:r}=s,a=i.decryptdata;if(r&&r.byteLength>0&&a!=null&&a.key&&a.iv&&Bt(a.method)){let o=self.performance.now(),{decryptRange:l}=Xs(i,null,this.iframesOnly);return this.decrypter.decrypt(new Uint8Array(r),a.key.buffer,a.iv.buffer,On(a.method),l).catch(c=>{throw t.trigger(p.ERROR,{type:W.MEDIA_ERROR,details:R.FRAG_DECRYPT_ERROR,fatal:!1,error:c,reason:c.message,frag:i}),this.fragmentLoader.abort(),c}).then(c=>{let h=self.performance.now();return t.trigger(p.FRAG_DECRYPTED,{frag:i,part:null,payload:c,stats:{tstart:o,tdecrypt:h}}),s.payload=c,this.completeInitSegmentLoad(s)})}return this.completeInitSegmentLoad(s)})}completeInitSegmentLoad(e){let t=e.frag.stats;e.frag.data=new Uint8Array(e.payload),t.parsing.start=t.buffering.start=self.performance.now(),t.parsing.end=t.buffering.end=self.performance.now()}loadInitSegmentIfNeeded(e){let{initSegment:t}=e;if(!this.bitrateTest&&pe(e)&&t&&!t.data){var s;return(t.encrypted&&!((s=t.decryptdata)!=null&&s.key)?this.keyLoader.load(t).then(()=>this._loadInitSegment(t)):this._loadInitSegment(t)).catch(r=>{throw this.state===C.STOPPED||this.state===C.ERROR||("data"in r&&(this.fragmentLoader.abort(),this.handleFragLoadError(r,e)),this.resetFragmentLoading(e)),r})}}unhandledEncryptionError(e,t){var s,i;let r=e.tracks;if(r&&!t.encrypted&&((s=r.audio)!=null&&s.encrypted||(i=r.video)!=null&&i.encrypted)&&(!this.config.emeEnabled||!this.keyLoader.emeController)){let a=this.media,o=new Error(`Encrypted track with no key in ${this.fragInfo(t)} (media ${a?"attached mediaKeys: "+a.mediaKeys:"detached"})`);return this.warn(o.message),!a||a.mediaKeys?!1:(this.hls.trigger(p.ERROR,{type:W.KEY_SYSTEM_ERROR,details:R.KEY_SYSTEM_NO_KEYS,fatal:!1,error:o,frag:t}),this.resetTransmuxer(),!0)}return!1}fragContextChanged(e){let{fragCurrent:t}=this;return!e||!Ji(e,t)}fragBufferedComplete(e,t){let s=this.mediaBuffer?this.mediaBuffer:this.media;if(this.log(`Buffered ${e.type} sn: ${e.sn}${t?" part: "+t.index:""} of ${this.fragInfo(e,!1,t)} > buffer:${s?js(X.getBuffered(s)):"(detached)"})`),pe(e)){var i;if(e.type!==K.SUBTITLE){let a=e.elementaryStreams;if(!Object.keys(a).some(o=>!!a[o])){this.state=C.IDLE;return}}let r=(i=this.levels)==null?void 0:i[e.level];r!=null&&r.fragmentError&&(t||this.fragmentTracker.getState(e)!==fe.PARTIAL)&&(this.log(`Resetting level fragment error count of ${r.fragmentError} on frag buffered`),r.fragmentError=0,e.stats.retry=0)}this.state=C.IDLE}_handleFragmentLoadComplete(e){let{transmuxer:t}=this;if(!t)return;let s=e.frag,{part:i,partsLoaded:r}=e,a=!r||r.length===0||r.some(c=>!c),{decryptRange:o}=Xs(s,i),l=new hs(s.level,s.sn,s.stats.chunkCount+1,0,i?i.index:-1,!a,s.duration,this.iframesOnly,o);this.log(`load complete ${s.type} sn: ${s.sn}${i?" part: "+i.index:""} of ${this.fragInfo(s,!1,i)}`),t.flush(l)}_handleFragmentLoadProgress(e){}loadKeyFor(e,t,s){var i;let r=null;return e.encrypted&&!((i=e.decryptdata)!=null&&i.key)?(this.log(`Loading key for ${e.sn} of [${t.startSN}-${t.endSN}], ${this.playlistLabel()} ${e.level}`),this.state=C.KEY_LOADING,r=this.keyLoader.load(e,s).then(a=>{if(!this.fragContextChanged(a.frag))return this.hls.trigger(p.KEY_LOADED,a),this.state===C.KEY_LOADING&&(this.state=C.IDLE),a}),this.hls.trigger(p.KEY_LOADING,{frag:e})):e.encrypted||(r=this.keyLoader.loadClear(e,t.encryptedFragments,this.startFragRequested),r&&this.log(`[eme] blocking frag sn: ${e.sn} load until media-keys acquired`)),r}_doFragLoad(e,t,s=null,i){this.fragCurrent=e;let r=t.details;if(!this.levels||!r)throw new Error(`frag load aborted, missing level${r?"":" detail"}s`);let a=this.fragPrevious;if(!jt(e,a)){let f=this.shouldLoadParts(t.details,e.end);f!==this.loadingParts&&(this.log(`LL-Part loading ${f?"ON":"OFF"} loading sn ${a?.sn}->${e.sn}`),this.loadingParts=f)}if(s=Math.max(e.start,s||0),this.loadingParts){let f=r.partList;if(f&&i){s>r.fragmentEnd&&r.fragmentHint&&(e=r.fragmentHint);let g=this.getNextPart(f,e,s);if(g>-1){let m=f[g];if(e=this.fragCurrent=m.fragment,!jt(e,a)&&!this.shouldLoadParts(t.details,e.end))return this.log(`LL-Part loading OFF @${this.playhead} next part: ${this.fragInfo(e,!1,m)}`),this.loadingParts=!1,Promise.resolve(null);if(!this.filterReplacedPrimary(m,t.details))return Promise.resolve(null);let y=this.loadKeyFor(e,r);if(this.fragContextChanged(e))return Promise.resolve(null);this.log(`Loading ${e.type} sn: ${e.sn} part: ${m.index} (${g}/${f.length-1}) of ${this.fragInfo(e,!1,m)} cc: ${e.cc} [${r.startSN}-${r.endSN}], target: ${s}${m.byteRange.length?` range:${m.byteRange.join("-")}`:""}`),this.nextLoadPosition=m.start+m.duration,this.state=C.FRAG_LOADING;let E,S=this.loadInitSegmentIfNeeded(e);if(y||S){let T=!!y;E=Promise.all([y,S]).then(([v])=>T&&(!v||this.fragContextChanged(v.frag))?null:this.doFragPartsLoad(e,m,t,i)).catch(v=>this.handleFragLoadError(v,e))}else E=this.doFragPartsLoad(e,m,t,i).catch(T=>this.handleFragLoadError(T,e));return this.hls.trigger(p.FRAG_LOADING,{frag:e,part:m,targetBufferTime:s}),this.fragCurrent===null?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING parts")):E}else if(!e.url||this.loadedEndOfParts(f,s))return Promise.resolve(null)}}if(this.loadingParts){var o;this.log(`LL-Part loading OFF after next part miss @${s} Check buffer at sn: ${e.sn} loaded parts: ${(o=r.partList)==null?void 0:o.filter(f=>f.loaded).map(f=>`[${f.start}-${f.end}]`)}`),this.loadingParts=!1}else if(!e.url)return Promise.resolve(null);if(!this.filterReplacedPrimary(e,t.details))return Promise.resolve(null);let l=this.loadInitSegmentIfNeeded(e),c=this.loadKeyFor(e,r,l);if(this.fragContextChanged(e)){var h;return this.log(`Context changed in KEY_LOADING sn: ${e.sn} ${e.relurl} > ${(h=this.fragCurrent)==null?void 0:h.relurl}`),l?.catch(()=>null),c?.catch(()=>null),Promise.resolve(null)}this.log(`Loading ${e.type} sn: ${e.sn} of ${this.fragInfo(e,!1)} cc: ${e.cc} ${"["+r.startSN+"-"+r.endSN+"]"}, target: ${s}${e.byteRange.length?` range:${e.byteRange.join("-")}`:""}`),$(e.sn)&&!this.bitrateTest&&(this.nextLoadPosition=e.start+e.duration),this.state=C.FRAG_LOADING;let u=this.config.progressive&&e.type!==K.SUBTITLE,d;return u&&c?d=c.then(f=>!f||this.fragContextChanged(f.frag)?null:this.fragmentLoader.load(e,this.iframesOnly,i,l)).catch(f=>this.handleFragLoadError(f,e)):d=Promise.all([this.fragmentLoader.load(e,this.iframesOnly,u?i:void 0,u?l:void 0),c,l]).then(([f])=>(!u&&i&&i(f),f)).catch(f=>this.handleFragLoadError(f,e)),this.hls.trigger(p.FRAG_LOADING,{frag:e,targetBufferTime:s}),this.fragCurrent===null?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING")):Promise.all([d,l]).then(([f])=>f)}doFragPartsLoad(e,t,s,i){return new Promise((r,a)=>{var o;let l=[],c=(o=s.details)==null?void 0:o.partList,h=u=>{this.fragmentLoader.loadPart(e,u,i).then(d=>{l[u.index]=d;let f=d.part;this.hls.trigger(p.FRAG_LOADED,d);let g=Ba(s.details,e.sn,u.index+1)||gl(c,e.sn,u.index+1);if(g)h(g);else return r({frag:e,part:f,partsLoaded:l})}).catch(a)};h(t)})}handleFragLoadError(e,t){if("data"in e){let s=e.data;s.details===R.INTERNAL_ABORTED?this.handleFragLoadAborted(t,s.part):s.type===W.KEY_SYSTEM_ERROR&&!s.fatal&&(t.abortRequests(),this.resetStartWhenNotLoaded(),this.resetFragmentLoading(t)),s.frag!==t?(s.frag&&this.warn(`${s.details} error cascading from ${this.fragInfo(s.frag,!1,s.part)} to ${this.fragInfo(t,!1)}`),this.hls.trigger(p.ERROR,Y(Y({},s),{},{frag:t}))):this.hls.trigger(p.ERROR,s)}else this.hls.trigger(p.ERROR,{type:W.OTHER_ERROR,details:R.INTERNAL_EXCEPTION,err:e,error:e,fatal:!0});return null}_handleTransmuxerFlush(e){let t=this.getCurrentContext(e);if(!t||this.state!==C.PARSING){!this.fragCurrent&&this.state!==C.STOPPED&&this.state!==C.ERROR&&(this.state=C.IDLE);return}let{frag:s,part:i,level:r}=t,a=self.performance.now();s.stats.parsing.end=a,i&&(i.stats.parsing.end=a);let o=this.getLevelDetails(),c=o&&s.sn>o.endSN||this.shouldLoadParts(o,s.end);c!==this.loadingParts&&(this.log(`LL-Part loading ${c?"ON":"OFF"} after parsing segment ending @${s.end}`),this.loadingParts=c),this.updateLevelTiming(s,i,r,e)}shouldLoadParts(e,t){if(this.config.lowLatencyMode){if(!e)return this.loadingParts;if(e.partList&&!this.iframesOnly){var s;let i=e.partList[0],r=i.end+(((s=e.fragmentHint)==null?void 0:s.duration)||0);if(t>=r&&this.playhead>i.start-i.fragment.duration)return!0}}return!1}getCurrentContext(e){let{levels:t,fragCurrent:s}=this,{level:i,sn:r,part:a}=e;if(!(t!=null&&t[i]))return this.warn(`Levels object was unset while buffering fragment ${r} of ${this.playlistLabel()} ${i}. The current chunk will not be buffered.`),null;let o=t[i],l=o.details,c=a>-1?Ba(l,r,a):null,h=c?c.fragment:Ns(l,r,s);return h?(s&&s!==h&&(h.stats=s.stats),{frag:h,part:c,level:o}):null}bufferFragmentData(e,t,s,i,r){if(this.state!==C.PARSING)return;pe(t)&&!this.fragContextChanged(t)&&(this.fragPrevious=t);let{data1:a,data2:o}=e,l=a;if(o&&(l=We(a,o)),!l.length)return;let c=this.initPTS[t.cc],h=c?-c.baseTime/c.timescale:void 0,u={type:e.type,frag:t,part:s,chunkMeta:i,offset:h,parent:t.type,data:l};if(this.hls.trigger(p.BUFFER_APPENDING,u),e.dropped&&e.independent&&!s){if(r)return;this.flushBufferGap(t)}}flushBufferGap(e){let t=this.media;if(!t)return;if(!X.isBuffered(t,t.currentTime)){this.flushMainBuffer(0,e.start);return}let s=t.currentTime,i=X.bufferInfo(t,s,0),r=e.duration,a=Math.min(this.config.maxFragLookUpTolerance*2,r*.25),o=Math.max(Math.min(e.start-a,i.end-a),s+a);e.start-o>a&&this.flushMainBuffer(o,e.start)}getFwdBufferInfo(e,t){var s;let i=this.playhead,a=this.lastCurrentTime>i||(s=this.media)!=null&&s.paused?0:this.config.maxBufferHole;return this.getFwdBufferInfoAtPos(e,i,t,a)}getFwdBufferInfoAtPos(e,t,s,i){let r=X.bufferInfo(e,t,i);if(r.len===0&&r.nextStart!==void 0){let a=this.fragmentTracker.getBufferedFrag(t,s);if(a&&(r.nextStart<=a.end||a.gap)){let o=Math.max(Math.min(r.nextStart,a.end)-t,i);return X.bufferInfo(e,t,o)}}return r}getMaxBufferLength(e){let{config:t}=this,s;return e?s=Math.max(8*t.maxBufferSize/e,t.maxBufferLength):s=t.maxBufferLength,Math.min(s,t.maxMaxBufferLength)}exceedsMaxBuffer(e,t,s){let i=e.nextStart;if(i&&s.start>i){let r=e.buffered;if(r){let a=e.len,o=e.bufferedIndex;for(let l=r.length-1;l>o;l--)r[l].start<s.start&&(a+=r[l].end-r[l].start);return a>=t}}return!1}reduceMaxBufferLength(e,t){let s=this.config,i=Math.max(Math.min(e-t,s.maxBufferLength),t/2),r=Math.max(e-t*3,s.maxMaxBufferLength/2,i);return r>=i?(s.maxMaxBufferLength=r,this.warn(`Reduce max buffer length to ${r}s`),!0):!1}getAppendedFrag(e){let t=this.fragmentTracker?this.fragmentTracker.getAppendedFrag(e,this.playlistType):null;return t&&"fragment"in t?t.fragment:t}getNextFragment(e,t){let s=t.fragments,i=s.length;if(!i)return null;let{config:r}=this,a=t.fragmentStart,o=r.lowLatencyMode&&!!t.partList,l=null;if(t.live){let u=r.initialLiveManifestSize;if(i<u)return this.warn(`Not enough fragments to start playback (have: ${i}, need: ${u})`),null;if(!this.startFragRequested&&o&&!this.loadingParts&&(this.log("LL-Part loading ON for initial live fragment"),this.loadingParts=!0),!t.PTSKnown&&!this.startFragRequested&&this.startPosition===-1||e<a){var c;l=this.getInitialLiveFragment(t);let d=this.config.startPosition,f=this.hls.startPosition,g=this.hls.liveSyncPosition,m=((c=l)==null?void 0:c.start)||0,y,E;if(f!==-1&&f>=a?(y=f,E=f===d?"config":"next load start"):g?(y=g,E="live edge"):(y=e,E="buffer pos"),y<m&&(y=m,E="live frag start"),y<a&&(y=a,E="playlist start"),this.startPosition!=y||this.nextLoadPosition!=y){let T=t.live&&!this.filterReplacedPrimary(l,t)?-1:y;this.log(`Setting startPosition to ${T} next load ${y} ${f===-1?"":`(from ${d}) `}based on ${E}. live edge: ${g} live frag start: ${m} playlist start: ${a} buffer pos: ${e}`),this.startPosition=T,this.nextLoadPosition=y}}}else e<=a&&(l=s[0]);if(!l){let u=this.loadingParts?t.partEnd:t.fragmentEnd;l=this.getFragmentAtPosition(e,u,t)}let h=this.filterReplacedPrimary(l,t);return!h&&l&&(h=el(t,l.sn),h&&(this.nextLoadPosition=h.start)),h}isLoopLoading(e,t){if(this.nextLoadPosition<=t)return!1;let s=this.fragmentTracker.getState(e);return!!(s===fe.OK||s===fe.PARTIAL&&(e.gap||e.stats.retry>1))}getNextFragmentLoopLoading(e,t,s,i,r){let a=null;if(e.gap&&(a=this.getNextFragment(this.nextLoadPosition,t),a&&!a.gap&&s.nextStart)){let o=this.getFwdBufferInfoAtPos(this.mediaBuffer?this.mediaBuffer:this.media,s.nextStart,i,0);if(o!==null&&s.len+o.len>=r){let l=a.sn;return this.loopSn!==l&&(this.log(`buffer full after gaps in "${i}" playlist starting at sn: ${l}`),this.loopSn=l),null}}return this.loopSn=void 0,a}get primaryPrefetch(){if(si(this.config)){var e;if((e=this.hls.interstitialsManager)==null||(e=e.playingItem)==null?void 0:e.event)return!0}return!1}filterReplacedPrimary(e,t){if(!e)return e;if(si(this.config)&&("type"in e?e:e.fragment).type!==K.SUBTITLE){let s=this.hls.interstitialsManager,i=s?.bufferingItem;if(i){let r=i.event;if(r){if(!r.appendInPlace&&(Math.abs(e.start-i.start)>1||i.start===0))return null}else if(e.end<=i.start&&t?.live===!1||e.start>=i.end&&i.nextEvent&&(i.nextEvent.appendInPlace&&!i.nextEvent.hasPlayed||e.start-i.end>1))return null}if(yl(e,s?.playerQueue,this.playhead))return null}return e}getNextPart(e,t,s){let i=-1,r=!1,a=!0;for(let l=0,c=e.length;l<c;l++){let h=e[l];if(a=a&&!h.independent,i>-1&&s<h.start)break;let u=h.loaded||h.gap;u?i=-1:(r||(h.independent||a)&&h.fragment===t)&&(i=l),r=u&&!h.gap}let o=e[i];return o&&o.fragment!==t&&this.log(`Need buffer at ${s} but next unloaded part starts at ${o.start} (sn: ${t.sn} -> ${o.fragment.sn})`),i}loadedEndOfParts(e,t){let s;for(let i=e.length;i--;){if(s=e[i],!s.loaded)return!1;if(t>s.start)return!0}return!1}getInitialLiveFragment(e){let t=e.fragments,s=this.fragPrevious,i=null;if(s){if(e.hasProgramDateTime&&(i=Vh(t,s.endProgramDateTime,this.config.maxFragLookUpTolerance),i&&this.log(`Live playlist, switching playlist, load frag with same PDT: ${s.programDateTime}`)),!i){let r=s.sn+1;if(r>=e.startSN&&r<=e.endSN){let a=t[r-e.startSN];s.cc===a.cc&&(i=a,this.log(`Live playlist, switching playlist, load frag with next SN: ${i.sn}`))}i||(i=Jo(e,s.cc,s.end),i&&this.log(`Live playlist, switching playlist, load frag with same CC: ${i.sn}`))}}else{let r=this.hls.liveSyncPosition;r!==null&&(i=this.getFragmentAtPosition(r,this.bitrateTest?e.fragmentEnd:e.edge,e))}return i}getFragmentAtPosition(e,t,s){let{config:i}=this,{fragPrevious:r}=this,{fragments:a,endSN:o}=s,{fragmentHint:l}=s,{maxFragLookUpTolerance:c}=i,h=s.partList,u=!!(this.loadingParts&&h!=null&&h.length&&l);u&&!this.bitrateTest&&h[h.length-1].fragment.sn===l.sn&&(a=a.concat(l),o=l.sn),r&&this.fragmentTracker.getState(r)===fe.NOT_LOADED&&(r=null);let d;if(e<t){var f;let m=e<this.lastCurrentTime||e>t-c||(f=this.media)!=null&&f.paused||this.loadingParts||!this.startFragRequested?0:c;d=Gt(r,a,e,m)}else d=a[a.length-1];if(d){let g=d.sn,m=g-s.startSN,y=this.fragmentTracker.getState(d);if((y===fe.OK||y===fe.PARTIAL&&d.gap)&&(r=d),jt(d,r)&&(!u||h[0].fragment.sn>g||!s.live||!h.some(E=>E.fragment.sn===g&&!E.loaded&&!E.gap))){let E=a[m+1];d.sn<o&&this.fragmentTracker.getState(E)!==fe.OK?d=E:d=null}}return d}alignPlaylists(e,t,s){let i=e.fragments.length;if(!i)return this.warn("No fragments in live playlist"),0;let r=e.fragmentStart,a=!t,o=e.alignedSliding&&$(r);if(a||!o&&!r){ti(s,e,this);let l=e.fragmentStart;return this.log(`Live playlist sliding: ${l} start-sn: ${t?t.startSN:"na"}->${e.startSN} fragments: ${i}`),l}return r}waitForCdnTuneIn(e){return e.live&&e.canBlockReload&&e.partTarget&&e.tuneInGoal>Math.max(e.partHoldBack,e.partTarget*3)}setStartPosition(e,t){let s=this.startPosition;s<t&&(s=-1);let i=this.timelineOffset;if(s===-1){let r=this.startTimeOffset!==null,a=r?this.startTimeOffset:e.startTimeOffset;if(a!==null&&$(a))s=t+a,a<0&&(s+=e.edge),s=Math.min(Math.max(t,s),t+e.totalduration),this.log(`Setting startPosition to ${s} for start time offset ${a} found in ${r?"multivariant":"media"} playlist`),this.startPosition=s;else if(e.live){let o=this.hls.liveSyncPosition;s=o||t,this.log(`Setting startPosition to -1 to start at ${o?"live edge":"playlist start"} ${s}`),this.startPosition=-1}else this.log("setting startPosition to 0 by default"),this.startPosition=s=0;this.lastCurrentTime=s+i}this.nextLoadPosition=s+i}getLoadPosition(){var e;let{media:t}=this,s=0;return(e=this.hls)!=null&&e.hasEnoughToStart&&t&&!this.iframesOnly?s=t.currentTime:this.nextLoadPosition>=0&&(s=this.nextLoadPosition),s}get playhead(){var e;if((e=this.hls)!=null&&e.hasEnoughToStart){var t;let s=(t=this.media)==null?void 0:t.currentTime;return $(s)?s:this.lastCurrentTime}return this.getLoadPosition()}get iframesOnly(){var e;if(this.playlistType!==K.MAIN)return!1;let t=this.getLevelDetails();return t?t.iframesOnly:(e=this.levelLastLoaded)==null?void 0:e.iframes}handleFragLoadAborted(e,t){this.transmuxer&&e.type===this.playlistType&&pe(e)&&e.stats.aborted&&(this.log(`Fragment ${e.sn}${t?" part "+t.index:""} of ${this.playlistLabel()} ${e.level} was aborted`),this.resetFragmentLoading(e))}resetFragmentLoading(e){this.state!==C.STOPPED&&(!this.fragCurrent||!this.fragContextChanged(e)&&this.state!==C.FRAG_LOADING_WAITING_RETRY)&&(this.state=C.IDLE)}onFragmentOrKeyLoadError(e,t){if(t.chunkMeta&&!t.frag){let S=this.getCurrentContext(t.chunkMeta);S&&(t.frag=S.frag)}let{frag:s,part:i}=t;if(!s||!this.levels||s.type!==e)return;if(this.fragContextChanged(s)){var r;this.warn(`Frag load error must match current frag to retry ${s.relurl} > ${(r=this.fragCurrent)==null?void 0:r.relurl}`);return}let a=t.details===R.FRAG_GAP;a&&this.fragmentTracker.addAsGap(s);let o=t.errorAction;if(!o){this.state=C.ERROR;return}let{action:l,flags:c,retryCount:h=0,retryConfig:u}=o,d=!!u,f=d&&l===Re.RetryRequest,g=d&&!o.resolved&&c&Le.MoveAllAlternatesMatchingHost,m=this.hls.latestLevelDetails,y=m?.live;if(!f&&g&&pe(s)&&y&&s.sn<m.endSN&&!Io(t))this.resetFragmentErrors(e),i?i.gap=!0:this.treatAsGap(s),o.resolved=!0;else if((f||g)&&h<u.maxNumRetry){var E;let S=is((E=t.response)==null?void 0:E.code),T=Rn(u,h);if(this.resetStartWhenNotLoaded(),this.retryDate=self.performance.now()+T,this.state=C.FRAG_LOADING_WAITING_RETRY,o.resolved=!0,S){this.log("Waiting for connection (offline)"),this.retryDate=1/0,t.reason="offline";return}this.warn(`Fragment ${s.sn} of ${e} ${s.level} errored with ${t.details}, retrying loading ${h+1}/${u.maxNumRetry} in ${T}ms`)}else if(u)if(this.resetFragmentErrors(e),h<u.maxNumRetry)!a&&l!==Re.RemoveAlternatePermanently&&(o.resolved=!0);else{this.warn(`${t.details} reached or exceeded max retry (${h})`);return}else l===Re.SendAlternateToPenaltyBox?this.state=C.WAITING_LEVEL:this.state=C.ERROR;this.tickImmediate()}onSourceBufferError(e,t){var s,i;let{frag:r,part:a,sourceBufferName:o}=t,l=r&&((s=this.levels)==null||(s=s[r.level])==null?void 0:s.details);if(t.error.name!==rl||r?.type!==e||!pe(r)||!(l!=null&&l.live))return;let c=a?a.index===0?a:null:r,h=c&&o?(i=c.elementaryStreams[o])==null?void 0:i.startPTS:void 0;if(this.markSourceBufferErrorGap(Ns(l,r.sn)||r),h===void 0)return;let u=Ns(l,r.sn-1);u&&this.fragmentTracker.getState(u)!==fe.NOT_LOADED&&!X.isBuffered(this.mediaBuffer||this.media,h-this.config.maxBufferHole)&&this.markSourceBufferErrorGap(u)}markSourceBufferErrorGap(e){this.warn(`Marking fragment ${e.sn} of ${this.playlistLabel()} ${e.level} as a gap after a SourceBuffer error`),this.fragmentTracker.addAsGap(e)}checkRetryDate(){let e=self.performance.now(),t=this.retryDate,s=t===1/0;(!t||e>=t||s&&!is(0))&&(s&&this.log("Connection restored (online)"),this.resetStartWhenNotLoaded(),this.state=C.IDLE)}reduceLengthAndFlushBuffer(e){if(this.state===C.PARSING||this.state===C.PARSED){let t=e.frag,s=e.parent,i=this.getFwdBufferInfo(this.mediaBuffer,s),r=i&&i.len>.5;r&&this.reduceMaxBufferLength(i.len,t?.duration||10);let a=!r;return a?this.warn(`Buffer full error while media.currentTime (${this.playhead}) is not buffered, flush ${s} buffer`):i.nextStart&&t&&i.nextStart>t.start&&this.flushMainBuffer(i.nextStart,Number.POSITIVE_INFINITY,s===K.AUDIO?s:void 0),t&&(this.fragmentTracker.removeFragment(t),this.nextLoadPosition=t.start),this.resetLoadingState(),a}return!1}resetFragmentErrors(e){e===K.AUDIO&&(this.fragCurrent=null),this.hls.hasEnoughToStart||(this.startFragRequested=!1),this.state!==C.STOPPED&&(this.state=C.IDLE)}afterBufferFlushed(e,t){if(!e)return;let s=X.getBuffered(e);this.fragmentTracker.detectEvictedFragments(t,s,this.playlistType),this.state===C.ENDED&&this.resetLoadingState()}resetLoadingState(){this.log("Reset loading state"),this.fragCurrent=null,this.fragPrevious=null,this.state!==C.STOPPED&&(this.state=C.IDLE)}resetStartWhenNotLoaded(){if(!this.hls.hasEnoughToStart){this.startFragRequested=!1;let e=this.getLevelDetails();e!=null&&e.live?(this.log("resetting startPosition for live start"),this.startPosition=-1,this.setStartPosition(e,e.fragmentStart),this.resetLoadingState()):this.nextLoadPosition=this.startPosition}}resetWhenMissingContext(e){this.log(`Loading context changed while buffering sn ${e.sn} of ${this.playlistLabel()} ${e.level===-1?"<removed>":e.level}. This chunk will not be buffered.`),this.removeUnbufferedFrags(),this.resetStartWhenNotLoaded(),this.resetLoadingState()}removeUnbufferedFrags(e=0){this.fragmentTracker.removeFragmentsInRange(e,1/0,this.playlistType,!1,!0)}updateLevelTiming(e,t,s,i){let r=s.details;if(!r){this.warn("level.details undefined");return}if(this.log(`update level timing ${e.type} sn: ${e.sn}${t?" part: "+t.index:""} of ${this.fragInfo(e,!1,t)}`),!Object.keys(e.elementaryStreams).reduce((u,d)=>{let f=e.elementaryStreams[d];if(f){let g=f.endPTS-f.startPTS;if(g<=0)return this.warn(`Could not parse fragment ${e.sn} ${d} duration reliably (${g})`),u||!1;let m=0;return i.partial?t&&i.part===0&&(m=t.start-f.startPTS,e.startPTS=e.maxStartPTS=f.startPTS,e.startDTS=f.startDTS,e.start!==0&&e.setStart(f.startPTS),ul(r,e,m)):m=hl(r,e,f.startPTS,f.endPTS,f.startDTS,f.endDTS,this.iframesOnly,this),this.hls.trigger(p.LEVEL_PTS_UPDATED,{details:r,level:s,drift:m,type:d,frag:e,part:t,start:f.startPTS,end:f.endPTS}),!0}return u},!1)){var o,l,c,h;let u=((o=this.transmuxer)==null?void 0:o.error)===null,d=((l=this.transmuxer)==null?void 0:l.error)!=null,f=((c=(h=this.levels)==null?void 0:h.length)!=null?c:0)>1;if((s.fragmentError===0||u&&(s.fragmentError<2||e.endList)||d&&f)&&this.treatAsGap(e,s),u){let g=new Error(`Found no media in ${this.playlistLabel()} ${e.level} ${t?`part: ${t.index} of `:""}sn: ${e.sn} at playlist time: ${e.start}. Resetting transmuxer to fallback to playlist timing`);if(this.warn(g.message),this.hls.trigger(p.ERROR,{type:W.MEDIA_ERROR,details:R.FRAG_PARSING_ERROR,fatal:!1,error:g,frag:e,reason:`Found no media in msn ${e.sn} of ${this.playlistLabel()} "${s.url}"`}),!this.hls)return;this.resetTransmuxer()}}this.state=C.PARSED,this.log(`Parsed ${e.type} sn: ${e.sn}${t?" part: "+t.index:""} of ${this.fragInfo(e,!1,t)}`),this.hls.trigger(p.FRAG_PARSED,{frag:e,part:t,chunkMeta:i})}playlistLabel(){return`${this.playlistType} playlist`}fragInfo(e,t=!0,s){var i,r;return`${e.type} playlist ${e.level} (${s?"part":"frag"}:[${(i=t&&!s?e.startPTS:(s||e).start)!=null?i:NaN}-${(r=t&&!s?e.endPTS:(s||e).end)!=null?r:NaN}]${s&&e.type==="main"?"INDEPENDENT="+(s.independent?"YES":"NO"):""})`}treatAsGap(e,t){t&&t.fragmentError++,this.fragmentTracker.addAsGap(e)}resetTransmuxer(){var e;(e=this.transmuxer)==null||e.reset()}isFragmentNearlyDownloaded(e){var t;let s=(t=e.loader)==null?void 0:t.stats;if(!s||s.total<=0)return!1;let i=s.loading.first>0,a=(s.total-s.loaded)*8/(this.hls.bandwidthEstimate||this.hls.config.abrEwmaDefaultEstimate);return i&&a<=.15}recoverWorkerError(e){e.event==="demuxerWorker"&&(this.fragmentTracker.removeAllFragments(),this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null),this.resetStartWhenNotLoaded(),this.resetLoadingState())}set state(e){let t=this._state;t!==e&&(this._state=e,this.log(`${t}->${e}`))}get state(){return this._state}calculateOptimalSwitchPoint(e,t){let s=0,{hls:i,media:r,config:a,levels:o,playlistType:l}=this,c=this.getLevelDetails();if(r&&!r.paused&&o){var h;let f=l===K.AUDIO?jo(e.audioCodec,128e3):e.maxBitrate,g=1+i.ttfbEstimate/1e3,m=i.bandwidthEstimate*a.abrBandWidthUpFactor,y=c&&(this.loadingParts?c.partTarget:c.averagetargetduration)||((h=this.fragCurrent)==null?void 0:h.duration)||6;s=g+f*y/m,e.details||(s+=g)}let u=this.playhead,d=!(c!=null&&c.live)||t.end-u>s*1.5;return{fetchdelay:s,okToFlushForwardBuffer:d}}scheduleTrackSwitch(e,t,s){let{media:i,playlistType:r}=this;if(!i||!e)return;let a=s?this.getBufferedFrag(this.playhead+t):null;if(a){let l=this.followingBufferedFrag(a);if(l){var o;this.abortCurrentFrag();let c=l.maxStartPTS?l.maxStartPTS:l.start,h=l.duration,u=Math.max(a.end,c+Math.min(Math.max(h-this.config.maxFragLookUpTolerance,h*(this.couldBacktrack?.5:.125)),h*(this.couldBacktrack?.75:.25)));if((((o=this.getLevelDetails())==null?void 0:o.fragmentStart)||0)>u)return;let f=r===K.MAIN?null:"audio";this.flushMainBuffer(u,Number.POSITIVE_INFINITY,f),this.cleanupBackBuffer()}}}cleanupBackBuffer(){let{media:e,playlistType:t}=this;if(!e)return;let s=this.getAppendedFrag(this.playhead);if(s&&s.start>1){let i=t===K.AUDIO;this.flushMainBuffer(0,s.start-(i?0:1),i?"audio":null)}}getBufferedFrag(e){return this.fragmentTracker.getBufferedFrag(e,this.playlistType)}followingBufferedFrag(e){return e?this.getBufferedFrag(e.end+.5):null}abortCurrentFrag(){var e;let t=this.fragCurrent;switch(this.fragCurrent=null,t&&(t.abortRequests(),this.fragmentTracker.removeFragment(t)),this.state){case C.KEY_LOADING:case C.FRAG_LOADING:case C.FRAG_LOADING_WAITING_RETRY:case C.PARSING:case C.PARSED:this.state=C.IDLE;break}this.nextLoadPosition=(e=this.hls)!=null&&e.hasEnoughToStart?this.playhead:this.lastCurrentTime}checkFragPlaying(){let e=this.media,t=null;if(e&&e.readyState>1&&e.seeking===!1){let s=e.currentTime;if(X.isBuffered(e,s)?t=this.getAppendedFrag(s):X.isBuffered(e,s+.1)&&(t=this.getAppendedFrag(s+.1)),t&&(this.backtrackFragment=void 0,!jt(t,this.fragPlaying)))return this.fragPlaying=t,!0}return!1}getBufferOutput(){return null}nextLevelSwitch(){let{levels:e,media:t,hls:s,config:i,playlistType:r}=this;if(t!=null&&t.readyState&&e&&s&&i){let a=this.getBufferOutput(),o=this.getFwdBufferInfo(a,r);if(!o)return;let l=r===K.AUDIO?s.nextAudioTrack:s.nextLoadLevel,c=e[l],{fetchdelay:h,okToFlushForwardBuffer:u}=this.calculateOptimalSwitchPoint(c,o);this.scheduleTrackSwitch(o,h,u)}this.tickImmediate()}};function yl(n,e,t){if(e)for(let s=e.length;s--;){let i=e[s].interstitial,r=i.startTime,a=Math.min(r+i.duration,i.resumeTime);if(i.appendInPlace&&(n.start>=r&&n.end<=a||t>n.start&&n.end>r&&n.start<a))return!0}return!1}function si(n){return!!n.interstitialsController&&n.enableInterstitialPlayback!==!1}var ii=class{constructor(){this.chunks=[],this.dataLength=0}push(e){this.chunks.push(e),this.dataLength+=e.length}flush(){let{chunks:e,dataLength:t}=this,s;if(e.length)e.length===1?s=e[0]:s=Iu(e,t);else return new Uint8Array(0);return this.reset(),s}reset(){this.chunks.length=0,this.dataLength=0}};function Iu(n,e){let t=new Uint8Array(e),s=0;for(let i=0;i<n.length;i++){let r=n[i];t.set(r,s),s+=r.length}return t}var $i={exports:{}},Ga;function Au(){return Ga||(Ga=1,(function(n){var e=Object.prototype.hasOwnProperty,t="~";function s(){}Object.create&&(s.prototype=Object.create(null),new s().__proto__||(t=!1));function i(l,c,h){this.fn=l,this.context=c,this.once=h||!1}function r(l,c,h,u,d){if(typeof h!="function")throw new TypeError("The listener must be a function");var f=new i(h,u||l,d),g=t?t+c:c;return l._events[g]?l._events[g].fn?l._events[g]=[l._events[g],f]:l._events[g].push(f):(l._events[g]=f,l._eventsCount++),l}function a(l,c){--l._eventsCount===0?l._events=new s:delete l._events[c]}function o(){this._events=new s,this._eventsCount=0}o.prototype.eventNames=function(){var c=[],h,u;if(this._eventsCount===0)return c;for(u in h=this._events)e.call(h,u)&&c.push(t?u.slice(1):u);return Object.getOwnPropertySymbols?c.concat(Object.getOwnPropertySymbols(h)):c},o.prototype.listeners=function(c){var h=t?t+c:c,u=this._events[h];if(!u)return[];if(u.fn)return[u.fn];for(var d=0,f=u.length,g=new Array(f);d<f;d++)g[d]=u[d].fn;return g},o.prototype.listenerCount=function(c){var h=t?t+c:c,u=this._events[h];return u?u.fn?1:u.length:0},o.prototype.emit=function(c,h,u,d,f,g){var m=t?t+c:c;if(!this._events[m])return!1;var y=this._events[m],E=arguments.length,S,T;if(y.fn){switch(y.once&&this.removeListener(c,y.fn,void 0,!0),E){case 1:return y.fn.call(y.context),!0;case 2:return y.fn.call(y.context,h),!0;case 3:return y.fn.call(y.context,h,u),!0;case 4:return y.fn.call(y.context,h,u,d),!0;case 5:return y.fn.call(y.context,h,u,d,f),!0;case 6:return y.fn.call(y.context,h,u,d,f,g),!0}for(T=1,S=new Array(E-1);T<E;T++)S[T-1]=arguments[T];y.fn.apply(y.context,S)}else{var v=y.length,x;for(T=0;T<v;T++)switch(y[T].once&&this.removeListener(c,y[T].fn,void 0,!0),E){case 1:y[T].fn.call(y[T].context);break;case 2:y[T].fn.call(y[T].context,h);break;case 3:y[T].fn.call(y[T].context,h,u);break;case 4:y[T].fn.call(y[T].context,h,u,d);break;default:if(!S)for(x=1,S=new Array(E-1);x<E;x++)S[x-1]=arguments[x];y[T].fn.apply(y[T].context,S)}}return!0},o.prototype.on=function(c,h,u){return r(this,c,h,u,!1)},o.prototype.once=function(c,h,u){return r(this,c,h,u,!0)},o.prototype.removeListener=function(c,h,u,d){var f=t?t+c:c;if(!this._events[f])return this;if(!h)return a(this,f),this;var g=this._events[f];if(g.fn)g.fn===h&&(!d||g.once)&&(!u||g.context===u)&&a(this,f);else{for(var m=0,y=[],E=g.length;m<E;m++)(g[m].fn!==h||d&&!g[m].once||u&&g[m].context!==u)&&y.push(g[m]);y.length?this._events[f]=y.length===1?y[0]:y:a(this,f)}return this},o.prototype.removeAllListeners=function(c){var h;return c?(h=t?t+c:c,this._events[h]&&a(this,h)):(this._events=new s,this._eventsCount=0),this},o.prototype.off=o.prototype.removeListener,o.prototype.addListener=o.prototype.on,o.prefixed=t,o.EventEmitter=o,n.exports=o})($i)),$i.exports}var Lu=Au(),Mn=vc(Lu),ds="1.7.4",Vt={};function Ru(){return typeof __HLS_WORKER_BUNDLE__=="function"}function bu(){let n=Vt[ds];if(n)return n.clientCount++,n;let e=new self.Blob([`var exports={};var module={exports:exports};function define(f){f()};define.amd=true;(${__HLS_WORKER_BUNDLE__.toString()})(true);`],{type:"text/javascript"}),t=self.URL.createObjectURL(e),i={worker:new self.Worker(t),objectURL:t,clientCount:1};return Vt[ds]=i,i}function _u(n){let e=Vt[n];if(e)return e.clientCount++,e;let t=new self.URL(n,self.location.href).href,i={worker:new self.Worker(t),scriptURL:t,clientCount:1};return Vt[n]=i,i}function Du(n){let e=Vt[n||ds];if(e&&e.clientCount--===1){let{worker:s,objectURL:i}=e;delete Vt[n||ds],i&&self.URL.revokeObjectURL(i),s.terminate()}}function Pu(n,e,t,s){let i=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],r=e[t+2],a=r>>2&15;if(a>12){let y=new Error(`invalid ADTS sampling index:${a}`);n.emit(p.ERROR,p.ERROR,{type:W.MEDIA_ERROR,details:R.FRAG_PARSING_ERROR,fatal:!0,error:y,reason:y.message});return}let o=(r>>6&3)+1,l=e[t+3]>>6&3|(r&1)<<2,c=i[a],h=a;(o===5||o===29)&&(h-=3);let u,d=(h&14)>>1,f=(h&1)<<7|l<<3,g=0;if(o===1&&a>=6){g=5;let y=a-3;u=[g<<3|d,f|(y&14)>>1,(y&1)<<7|8,0]}else u=[o<<3|d,f];let m="mp4a.40."+(g||o);return oe.log(`manifest codec:${s}, parsed codec:${m}, channels:${l}, rate:${c} (ADTS object type:${o} sampling index:${a} esds config:[${u.join(",")}])`),{config:u,samplerate:c,channelCount:l,codec:m,parsedCodec:m,manifestCodec:s}}function El(n,e){return n[e]===255&&(n[e+1]&246)===240}function Tl(n,e){return n[e+1]&1?7:9}function Fn(n,e){return(n[e+3]&3)<<11|n[e+4]<<3|(n[e+5]&224)>>>5}function Cu(n,e){return e+5<n.length}function ri(n,e){return e+1<n.length&&El(n,e)}function ku(n,e){return Cu(n,e)&&El(n,e)&&Fn(n,e)<=n.length-e}function Ou(n,e){if(ri(n,e)){let t=Tl(n,e);if(e+t>=n.length)return!1;let s=Fn(n,e);if(s<=t)return!1;let i=e+s;return i===n.length||ri(n,i)}return!1}function Sl(n,e,t,s,i){if(!n.samplerate){let r=Pu(e,t,s,i);if(!r)return;he(n,r)}}function vl(n){return 1024*9e4/n}function wu(n,e){let t=Tl(n,e);if(e+t<=n.length){let s=Fn(n,e)-t;if(s>0)return{headerLength:t,frameLength:s}}}function xl(n,e,t,s,i){let r=vl(n.samplerate),a=s+i*r,o=wu(e,t),l;if(o){let{frameLength:u,headerLength:d}=o,f=d+u,g=Math.max(0,t+f-e.length);g?(l=new Uint8Array(f-d),l.set(e.subarray(t+d,e.length),0)):l=e.subarray(t+d,t+f);let m={unit:l,pts:a};return g||n.samples.push(m),{sample:m,length:f,missing:g}}let c=e.length-t;return l=new Uint8Array(c),l.set(e.subarray(t,e.length),0),{sample:{unit:l,pts:a},length:c,missing:-1}}var Oe=(function(n){return n.audioId3="org.id3",n.dateRange="com.apple.quicktime.HLS",n.emsg="https://aomedia.org/emsg/ID3",n.misbklv="urn:misb:KLV:bin:1910.1",n})({});function st(n="",e=9e4){return{type:n,id:-1,pid:-1,inputTimeScale:e,sequenceNumber:-1,samples:[],dropped:0}}var fs=class{constructor(){this._audioTrack=void 0,this._id3Track=void 0,this.frameIndex=0,this.cachedData=null,this.basePTS=null,this.initPTS=null,this.lastPTS=null}resetInitSegment(e,t,s,i){this._id3Track={type:"id3",id:3,pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0}}resetTimeStamp(e){this.initPTS=e,this.resetContiguity()}resetContiguity(){this.basePTS=null,this.lastPTS=null,this.frameIndex=0}canParse(e,t){return!1}appendFrame(e,t,s){}demux(e,t){this.cachedData&&(e=We(this.cachedData,e),this.cachedData=null);let s=rs(e,0),i=s?s.length:0,r,a=this._audioTrack,o=this._id3Track,l=s?_n(s):void 0,c=e.length;for((this.basePTS===null||this.frameIndex===0&&$(l))&&(this.basePTS=Mu(l,t,this.initPTS),this.lastPTS=this.basePTS),this.lastPTS===null&&(this.lastPTS=this.basePTS),s&&s.length>0&&o.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:s,type:Oe.audioId3,duration:Number.POSITIVE_INFINITY});i<c;){if(this.canParse(e,i)){let h=this.appendFrame(a,e,i);h?(this.frameIndex++,this.lastPTS=h.sample.pts,i+=h.length,r=i):i=c}else Bc(e,i)?(s=rs(e,i),o.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:s,type:Oe.audioId3,duration:Number.POSITIVE_INFINITY}),i+=s.length,r=i):i++;if(i===c&&r!==c){let h=e.slice(r);this.cachedData?this.cachedData=We(this.cachedData,h):this.cachedData=h}}return{audioTrack:a,videoTrack:st(),id3Track:o,textTrack:st()}}demuxSampleAes(e,t,s){return Promise.reject(new Error(`[${this}] This demuxer does not support Sample-AES decryption`))}flush(e){let t=this.cachedData;return t&&(this.cachedData=null,this.demux(t,0)),{audioTrack:this._audioTrack,videoTrack:st(),id3Track:this._id3Track,textTrack:st()}}destroy(){this.cachedData=null,this._audioTrack=this._id3Track=void 0}},Mu=(n,e,t)=>{if($(n))return n*90;let s=t?t.baseTime*9e4/t.timescale:0;return e*9e4+s},Fu=[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],Nu=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],Bu=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],$u=[0,1,1,4];function Il(n,e,t,s,i){if(t+24>e.length)return;let r=Al(e,t);if(r&&t+r.frameLength<=e.length){let a=r.samplesPerFrame*9e4/r.sampleRate,o=s+i*a,l={unit:e.subarray(t,t+r.frameLength),pts:o,dts:o};return n.config=[],n.channelCount=r.channelCount,n.samplerate=r.sampleRate,n.samples.push(l),{sample:l,length:r.frameLength,missing:0}}}function Al(n,e){let t=n[e+1]>>3&3,s=n[e+1]>>1&3,i=n[e+2]>>4&15,r=n[e+2]>>2&3;if(t!==1&&i!==0&&i!==15&&r!==3){let a=n[e+2]>>1&1,o=n[e+3]>>6,l=t===3?3-s:s===3?3:4,c=Fu[l*14+i-1]*1e3,u=Nu[(t===3?0:t===2?1:2)*3+r],d=o===3?1:2,f=Bu[t][s],g=$u[s],m=f*8*g,y=Math.floor(f*c/u+a)*g,E=Xt();return E&&E<=87&&s===2&&c>=224e3&&o===0&&(n[e+3]=n[e+3]|128),{sampleRate:u,channelCount:d,frameLength:y,samplesPerFrame:m}}}function Nn(n,e){return n[e]===255&&(n[e+1]&224)===224&&(n[e+1]&6)!==0}function Ll(n,e){return e+1<n.length&&Nn(n,e)}function Uu(n,e){return Nn(n,e)&&4<=n.length-e}function Rl(n,e){if(e+1<n.length&&Nn(n,e)){let s=Al(n,e),i=4;s!=null&&s.frameLength&&(i=s.frameLength);let r=e+i;return r===n.length||Ll(n,r)}return!1}var ni=class{constructor(e,t,s){this.keyData=void 0,this.decrypter=void 0,this.keyData=s,this.decrypter=new cs(t,!0)}decryptBuffer(e){return this.decrypter.decrypt(e,this.keyData.key.buffer,this.keyData.iv.buffer,xt.cbc,{start:0,end:e.byteLength})}decryptAacSample(e,t,s){let i=e[t].unit;if(i.length<=16)return;let r=i.subarray(16,i.length-i.length%16),a=r.buffer.slice(r.byteOffset,r.byteOffset+r.length);this.decryptBuffer(a).then(o=>{let l=new Uint8Array(o);i.set(l,16),this.decrypter.isSync()||this.decryptAacSamples(e,t+1,s)}).catch(s)}decryptAacSamples(e,t,s){for(;;t++){if(t>=e.length){s();return}if(!(e[t].unit.length<32)&&(this.decryptAacSample(e,t,s),!this.decrypter.isSync()))return}}getAvcEncryptedData(e){let t=Math.floor((e.length-48)/160)*16+16,s=new Int8Array(t),i=0;for(let r=32;r<e.length-16;r+=160,i+=16)s.set(e.subarray(r,r+16),i);return s}getAvcDecryptedUnit(e,t){let s=new Uint8Array(t),i=0;for(let r=32;r<e.length-16;r+=160,i+=16)e.set(s.subarray(i,i+16),r);return e}decryptAvcSample(e,t,s,i,r){let a=Go(r.data),o=this.getAvcEncryptedData(a);this.decryptBuffer(o.buffer).then(l=>{r.data=this.getAvcDecryptedUnit(a,l),this.decrypter.isSync()||this.decryptAvcSamples(e,t,s+1,i)}).catch(i)}decryptAvcSamples(e,t,s,i){if(e instanceof Uint8Array)throw new Error("Cannot decrypt samples of type Uint8Array");for(;;t++,s=0){if(t>=e.length){i();return}let r=e[t].units;for(;!(s>=r.length);s++){let a=r[s];if(!(a.data.length<=48||a.type!==1&&a.type!==5)&&(this.decryptAvcSample(e,t,s,i,a),!this.decrypter.isSync()))return}}}},vr=class extends fs{constructor(e,t){super(),this.observer=void 0,this.config=void 0,this.sampleAes=null,this.observer=e,this.config=t}resetInitSegment(e,t,s,i){super.resetInitSegment(e,t,s,i),this._audioTrack={container:"audio/adts",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"aac",samples:[],manifestCodec:t,duration:i,inputTimeScale:9e4,dropped:0}}static probe(e,t){if(!e)return!1;let s=rs(e,0),i=s?.length||0;if(Rl(e,i))return!1;for(let r=e.length;i<r;i++)if(Ou(e,i))return t.log("ADTS sync word found !"),!0;return!1}canParse(e,t){return ku(e,t)}appendFrame(e,t,s){Sl(e,this.observer,t,s,e.manifestCodec);let i=xl(e,t,s,this.basePTS,this.frameIndex);if(i?.missing===0)return i}demuxSampleAes(e,t,s){let i=this.demux(e,s),r=this.sampleAes=new ni(this.observer,this.config,t);return new Promise(a=>{r.decryptAacSamples(i.audioTrack.samples,0,()=>{a(i)})})}},bl=(n,e)=>{let t=0,s=5;e+=s;let i=new Uint32Array(1),r=new Uint32Array(1),a=new Uint8Array(1);for(;s>0;){a[0]=n[e];let o=Math.min(s,8),l=8-o;r[0]=4278190080>>>24+l<<l,i[0]=(a[0]&r[0])>>l,t=t?t<<o|i[0]:i[0],e+=1,s-=o}return t},xr=class extends fs{constructor(e){super(),this.observer=void 0,this.observer=e}resetInitSegment(e,t,s,i){super.resetInitSegment(e,t,s,i),this._audioTrack={container:"audio/ac-3",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"ac3",samples:[],manifestCodec:t,duration:i,inputTimeScale:9e4,dropped:0}}canParse(e,t){return t+64<e.length}appendFrame(e,t,s){let i=_l(e,t,s,this.basePTS,this.frameIndex);if(i!==-1)return{sample:e.samples[e.samples.length-1],length:i,missing:0}}static probe(e){if(!e)return!1;let t=rs(e,0);if(!t)return!1;let s=t.length;if(e[s]===11&&e[s+1]===119&&_n(t)!==void 0){if(bl(e,s)<16)return!0;throw new Error("Containerless ec-3 is not supported")}return!1}};function _l(n,e,t,s,i){if(t+8>e.length||e[t]!==11||e[t+1]!==119)return-1;let r=e[t+4]>>6;if(r>=3)return-1;let o=[48e3,44100,32e3][r],l=e[t+4]&63,h=[64,69,96,64,70,96,80,87,120,80,88,120,96,104,144,96,105,144,112,121,168,112,122,168,128,139,192,128,140,192,160,174,240,160,175,240,192,208,288,192,209,288,224,243,336,224,244,336,256,278,384,256,279,384,320,348,480,320,349,480,384,417,576,384,418,576,448,487,672,448,488,672,512,557,768,512,558,768,640,696,960,640,697,960,768,835,1152,768,836,1152,896,975,1344,896,976,1344,1024,1114,1536,1024,1115,1536,1152,1253,1728,1152,1254,1728,1280,1393,1920,1280,1394,1920][l*3+r]*2;if(t+h>e.length)return-1;let u=e[t+6]>>5,d=0;u===2?d+=2:(u&1&&u!==1&&(d+=2),u&4&&(d+=2));let f=(e[t+6]<<8|e[t+7])>>12-d&1,m=[2,1,2,3,3,4,4,5][u]+f,y=e[t+5]>>3,E=e[t+5]&7,S=new Uint8Array([r<<6|y<<1|E>>2,(E&3)<<6|u<<3|f<<2|l>>4,l<<4&224]),T=1536/o*9e4,v=s+i*T,x=e.subarray(t,t+h);return n.config=S,n.channelCount=m,n.samplerate=o,n.samples.push({unit:x,pts:v}),h}var Ir=class extends fs{resetInitSegment(e,t,s,i){super.resetInitSegment(e,t,s,i),this._audioTrack={container:"audio/mpeg",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"mp3",samples:[],manifestCodec:t,duration:i,inputTimeScale:9e4,dropped:0}}static probe(e){if(!e)return!1;let t=rs(e,0),s=t?.length||0;if(t&&e[s]===11&&e[s+1]===119&&_n(t)!==void 0&&bl(e,s)<=16)return!1;for(let i=e.length;s<i;s++)if(Rl(e,s))return oe.log("MPEG Audio sync word found !"),!0;return!1}canParse(e,t){return Uu(e,t)}appendFrame(e,t,s){if(this.basePTS!==null)return Il(e,t,s,this.basePTS,this.frameIndex)}},Gu=/\/emsg[-/]ID3/i,Ar=class{constructor(e,t,s,i=oe){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=t,this.logger=i}resetTimeStamp(){}resetInitSegment(e,t,s,i){let r=this.videoTrack=st("video",1),a=this.audioTrack=st("audio",1),o=this.txtTrack=st("text",1);if(this.id3Track=st("id3",1),this.initData=void 0,this.timeOffset=0,!(e!=null&&e.byteLength))return;let l=this.initData=Fo(e);if(l.video){let{id:c,timescale:h,codec:u,supplemental:d}=l.video;r.id=c,r.timescale=o.timescale=h,r.codec=u,r.supplemental=d}if(l.audio){let{id:c,timescale:h,codec:u}=l.audio;a.id=c,a.timescale=h,a.codec=u}o.id=ko.text,r.sampleDuration=0,r.duration=a.duration=i}resetContiguity(){this.remainderData=null}static probe(e){return Jc(e,"moof")}demux(e,t,s){this.timeOffset=t;let i=e,r=this.videoTrack,a=this.txtTrack;if(this.config.progressive){this.remainderData&&(i=We(this.remainderData,e));let c=ch(i);this.remainderData=c.remainder,r.samples=c.valid||new Uint8Array}else r.samples=i;let o=this.extractID3Track(r,t),l=this.parseFragment(r,a,t,s);return{videoTrack:r,audioTrack:this.audioTrack,id3Track:o,textTrack:this.txtTrack,initData:this.initData,sampleData:l}}flush(e,t){let s=this.timeOffset,i=this.videoTrack,r=this.txtTrack;i.samples=this.remainderData||new Uint8Array,this.remainderData=null;let a=this.extractID3Track(i,this.timeOffset),o=this.parseFragment(i,r,s,t);return{videoTrack:i,audioTrack:st(),id3Track:a,textTrack:st(),initData:this.initData,sampleData:o}}parseFragment(e,t,s,i){let r=this.initData;if(r&&i){let{samples:a,sampleData:o}=lh(s,e,r,this.logger,i.iframe);return t.samples=a,o}t.samples=hh(s,e)}extractID3Track(e,t){let s=this.id3Track;if(e.samples.length){let i=Q(e.samples,["emsg"]);i&&i.forEach(r=>{let a=uh(r);if(Gu.test(a.schemeIdUri)){let o=Va(a,t),l=a.eventDuration===4294967295?Number.POSITIVE_INFINITY:a.eventDuration/a.timeScale;l<=.001&&(l=Number.POSITIVE_INFINITY);let c=a.payload;s.samples.push({data:c,len:c.byteLength,dts:o,pts:o,type:Oe.emsg,duration:l})}else if(this.config.enableEmsgKLVMetadata){let o=this.config.emsgKLVSchemaUri||Oe.misbklv;if(a.schemeIdUri.startsWith(o)){let l=Va(a,t);s.samples.push({data:a.payload,len:a.payload.byteLength,dts:l,pts:l,type:Oe.misbklv,duration:Number.POSITIVE_INFINITY})}}})}return s}demuxSampleAes(e,t,s){return Promise.reject(new Error("The MP4 demuxer does not support SAMPLE-AES decryption"))}destroy(){this.config=null,this.remainderData=null,this.videoTrack=this.audioTrack=this.id3Track=this.txtTrack=void 0,this.initData=void 0}};function Va(n,e){return $(n.presentationTime)?n.presentationTime/n.timeScale:e+n.presentationTimeDelta/n.timeScale}var Vu=1,Ku=2,Hu=3,Yt=-1,ai=class{constructor(){this.VideoSample=null}createVideoSample(e,t,s){return{key:e,frame:!1,pts:t,dts:s,units:[],length:0}}getLastNalUnit(e){var t;let s=this.VideoSample,i;if((!s||s.units.length===0)&&(s=e[e.length-1]),(t=s)!=null&&t.units){let r=s.units;i=r[r.length-1]}return i}pushAccessUnit(e,t){if(e.units.length&&e.frame){if(e.pts===void 0){let s=t.samples,i=s.length;if(i){let r=s[i-1];e.pts=r.pts,e.dts=r.dts}else{t.dropped++;return}}t.samples.push(e)}}parseNALu(e,t,s){let i=t.byteLength;if(i===0)return[];let r=e.naluState||0,a=r===Yt?0:r,o=[],l=0,c=0,h=-1,u=0;for(r===Yt&&(h=0,u=this.getNALuType(t,0),c=1);c<i;){let d=t.indexOf(Vu,c);if(d===-1)break;c=d+1;let f=d;for(;f>0&&t[f-1]===0;)f--;let g=d-f+(f===0?a:0);if(g<Ku)continue;let m=Math.min(g,Hu),y=Math.min(d-f,m),E=m-y;if(f=d-y,h>=0)o.push({data:t.subarray(h,f),type:u});else{let S=this.getLastNalUnit(e.samples);S&&(f>0?S.data=We(S.data,t.subarray(0,f)):E>0&&(S.data=S.data.subarray(0,S.data.byteLength-E)),S.state=0)}if(c<i)h=c,u=this.getNALuType(t,c);else{l=Yt,h=-1;break}}if(l!==Yt){let d=i;for(;d>0&&t[d-1]===0;)d--;l=i-d+(d===0?a:0)}if(h>=0)o.push({data:t.subarray(h),type:u,state:l});else if(o.length===0&&l!==Yt){let d=this.getLastNalUnit(e.samples);d&&(d.data=We(d.data,t),d.state=l)}return e.naluState=l,o}},Dt=class{constructor(e){this.data=void 0,this.bytesAvailable=void 0,this.word=void 0,this.bitsAvailable=void 0,this.data=e,this.bytesAvailable=e.byteLength,this.word=0,this.bitsAvailable=0}loadWord(){let e=this.data,t=this.bytesAvailable,s=e.byteLength-t,i=new Uint8Array(4),r=Math.min(4,t);if(r===0)throw new Error("no bytes available");i.set(e.subarray(s,s+r)),this.word=new DataView(i.buffer).getUint32(0),this.bitsAvailable=r*8,this.bytesAvailable-=r}skipBits(e){let t;e=Math.min(e,this.bytesAvailable*8+this.bitsAvailable),this.bitsAvailable>e?(this.word<<=e,this.bitsAvailable-=e):(e-=this.bitsAvailable,t=e>>3,e-=t<<3,this.bytesAvailable-=t,this.loadWord(),this.word<<=e,this.bitsAvailable-=e)}readBits(e){let t=Math.min(this.bitsAvailable,e),s=this.word>>>32-t;if(e>32&&oe.error("Cannot read more than 32 bits at a time"),this.bitsAvailable-=t,this.bitsAvailable>0)this.word<<=t;else if(this.bytesAvailable>0)this.loadWord();else throw new Error("no bits available");return t=e-t,t>0&&this.bitsAvailable?s<<t|this.readBits(t):s}skipLZ(){let e;for(e=0;e<this.bitsAvailable;++e)if((this.word&2147483648>>>e)!==0)return this.word<<=e,this.bitsAvailable-=e,e;return this.loadWord(),e+this.skipLZ()}skipUEG(){this.skipBits(1+this.skipLZ())}skipEG(){this.skipBits(1+this.skipLZ())}readUEG(){let e=this.skipLZ();return this.readBits(e+1)-1}readEG(){let e=this.readUEG();return 1&e?1+e>>>1:-1*(e>>>1)}readBoolean(){return this.readBits(1)===1}readUByte(){return this.readBits(8)}},Lr=class extends ai{parsePES(e,t,s,i,r){let a=r.iframe,o=this.parseNALu(e,s.data,i),l=this.VideoSample,c,h=!1;s.data=null,l&&o.length&&!e.audFound&&(this.pushAccessUnit(l,e),l=this.VideoSample=this.createVideoSample(!1,s.pts,s.dts)),o.forEach(u=>{var d,f;switch(u.type){case 1:{if(a)break;let E=!1;c=!0;let S=u.data;if(h&&S.length>4){let T=this.readSliceType(S);(T===2||T===4||T===7||T===9)&&(E=!0)}if(E){var g;(g=l)!=null&&g.frame&&!l.key&&(this.pushAccessUnit(l,e),l=this.VideoSample=null)}l||(l=this.VideoSample=this.createVideoSample(!0,s.pts,s.dts)),l.frame=!0,l.key=E;break}case 5:c=!0,(d=l)!=null&&d.frame&&!l.key&&(this.pushAccessUnit(l,e),l=this.VideoSample=null),l||(l=this.VideoSample=this.createVideoSample(!0,s.pts,s.dts)),l.key=!0,l.frame=!0;break;case 6:{if(a)break;c=!0,ns(u.data,1,s.pts,t.samples);break}case 7:{var m,y;c=!0,h=!0;let E=u.data,S=this.readSPS(E);if(!e.sps||e.width!==S.width||e.height!==S.height||((m=e.pixelRatio)==null?void 0:m[0])!==S.pixelRatio[0]||((y=e.pixelRatio)==null?void 0:y[1])!==S.pixelRatio[1]){e.width=S.width,e.height=S.height,e.pixelRatio=S.pixelRatio,e.sps=[E];let T=E.subarray(1,4),v="avc1.";for(let x=0;x<3;x++){let I=T[x].toString(16);I.length<2&&(I="0"+I),v+=I}e.codec=v}break}case 8:c=!0,e.pps=[u.data];break;case 9:c=!0,e.audFound=!0,(f=l)!=null&&f.frame&&(this.pushAccessUnit(l,e),l=null),l||(l=this.VideoSample=this.createVideoSample(!1,s.pts,s.dts));break;case 12:c=!0;break;default:c=!1;break}l&&c&&l.units.push(u)}),i&&l&&(this.pushAccessUnit(l,e),this.VideoSample=null)}getNALuType(e,t){return e[t]&31}readSliceType(e){let t=new Dt(e);return t.readUByte(),t.readUEG(),t.readUEG()}skipScalingList(e,t){let s=8,i=8,r;for(let a=0;a<e;a++)i!==0&&(r=t.readEG(),i=(s+r+256)%256),s=i===0?s:i}readSPS(e){let t=new Dt(e),s=0,i=0,r=0,a=0,o,l,c,h=t.readUByte.bind(t),u=t.readBits.bind(t),d=t.readUEG.bind(t),f=t.readBoolean.bind(t),g=t.skipBits.bind(t),m=t.skipEG.bind(t),y=t.skipUEG.bind(t),E=this.skipScalingList.bind(this);h();let S=h();if(u(5),g(3),h(),y(),S===100||S===110||S===122||S===244||S===44||S===83||S===86||S===118||S===128){let b=d();if(b===3&&g(1),y(),y(),g(1),f())for(l=b!==3?8:12,c=0;c<l;c++)f()&&(c<6?E(16,t):E(64,t))}y();let T=d();if(T===0)d();else if(T===1)for(g(1),m(),m(),o=d(),c=0;c<o;c++)m();y(),g(1);let v=d(),x=d(),I=u(1);I===0&&g(1),g(1),f()&&(s=d(),i=d(),r=d(),a=d());let A=[1,1];if(f()&&f())switch(h()){case 1:A=[1,1];break;case 2:A=[12,11];break;case 3:A=[10,11];break;case 4:A=[16,11];break;case 5:A=[40,33];break;case 6:A=[24,11];break;case 7:A=[20,11];break;case 8:A=[32,11];break;case 9:A=[80,33];break;case 10:A=[18,11];break;case 11:A=[15,11];break;case 12:A=[64,33];break;case 13:A=[160,99];break;case 14:A=[4,3];break;case 15:A=[3,2];break;case 16:A=[2,1];break;case 255:{A=[h()<<8|h(),h()<<8|h()];break}}return{width:Math.ceil((v+1)*16-s*2-i*2),height:(2-I)*(x+1)*16-(I?2:4)*(r+a),pixelRatio:A}}},Rr=class extends ai{constructor(...e){super(...e),this.initVPS=null}parsePES(e,t,s,i){let r=this.parseNALu(e,s.data,i),a=this.VideoSample,o,l=!1;s.data=null;let c=h=>(a=this.VideoSample=this.createVideoSample(h,s.pts,s.dts),a);r.forEach((h,u)=>{var d,f;if(this.startsNewAccessUnit(a,e,h,u)){this.pushAccessUnit(a,e);let m=h.type>=16&&h.type<=23;a=c(m),l=!1}switch(h.type){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:case 8:case 9:a||(a=c(!1)),a.frame=!0,o=!0;break;case 16:case 17:case 18:case 21:case 22:case 23:if(o=!0,l){var g;(g=a)!=null&&g.frame&&!a.key&&(this.pushAccessUnit(a,e),a=this.VideoSample=null)}a||(a=c(!0)),a.key=!0,a.frame=!0;break;case 19:case 20:o=!0,(d=a)!=null&&d.frame&&!a.key&&(this.pushAccessUnit(a,e),a=this.VideoSample=null),a||(a=c(!0)),a.key=!0,a.frame=!0;break;case 39:o=!0,ns(h.data,2,s.pts,t.samples);break;case 32:o=!0,e.vps||(typeof e.params!="object"&&(e.params={}),e.params=he(e.params,this.readVPS(h.data)),this.initVPS=h.data),e.vps=[h.data];break;case 33:if(o=!0,l=!0,e.vps!==void 0&&e.vps[0]!==this.initVPS&&e.sps!==void 0&&!this.matchSPS(e.sps[0],h.data)&&(this.initVPS=e.vps[0],e.sps=e.pps=void 0),!e.sps){let m=this.readSPS(h.data);e.width=m.width,e.height=m.height,e.pixelRatio=m.pixelRatio,e.codec=m.codecString,e.sps=[],typeof e.params!="object"&&(e.params={});for(let y in m.params)e.params[y]=m.params[y]}this.pushParameterSet(e.sps,h.data,e.vps),a||(a=c(!1));break;case 34:if(o=!0,typeof e.params=="object"){if(!e.pps){e.pps=[];let m=this.readPPS(h.data);for(let y in m)e.params[y]=m[y]}this.pushParameterSet(e.pps,h.data,e.vps)}break;case 35:o=!0,e.audFound=!0,(f=a)!=null&&f.frame&&(this.pushAccessUnit(a,e),a=null),a||(a=c(!1));break;default:o=!1;break}a&&o&&a.units.push(h)}),i&&a&&(this.pushAccessUnit(a,e),this.VideoSample=null)}pushParameterSet(e,t,s){(s&&s[0]===this.initVPS||!s&&!e.length)&&e.push(t)}startsNewAccessUnit(e,t,s,i){if(!e)return!1;if(!t.audFound&&i===0)return!0;if(!e.frame)return!1;let{type:r,data:a}=s;return r>=32&&r<=35||r===39||r>=41&&r<=44||r>=48&&r<=55?!0:r<=31&&a.length>2&&(a[2]&128)!==0}getNALuType(e,t){return(e[t]&126)>>>1}ebsp2rbsp(e){let t=new Uint8Array(e.byteLength),s=0;for(let i=0;i<e.byteLength;i++)i>=2&&e[i]===3&&e[i-1]===0&&e[i-2]===0||(t[s]=e[i],s++);return new Uint8Array(t.buffer,0,s)}pushAccessUnit(e,t){super.pushAccessUnit(e,t),this.initVPS&&(this.initVPS=null)}readVPS(e){let t=new Dt(e);t.readUByte(),t.readUByte(),t.readBits(4),t.skipBits(2),t.readBits(6);let s=t.readBits(3),i=t.readBoolean();return{numTemporalLayers:s+1,temporalIdNested:i}}readSPS(e){let t=new Dt(this.ebsp2rbsp(e));t.readUByte(),t.readUByte(),t.readBits(4);let s=t.readBits(3);t.readBoolean();let i=t.readBits(2),r=t.readBoolean(),a=t.readBits(5),o=t.readUByte(),l=t.readUByte(),c=t.readUByte(),h=t.readUByte(),u=t.readUByte(),d=t.readUByte(),f=t.readUByte(),g=t.readUByte(),m=t.readUByte(),y=t.readUByte(),E=t.readUByte(),S=[],T=[];for(let ee=0;ee<s;ee++)S.push(t.readBoolean()),T.push(t.readBoolean());if(s>0)for(let ee=s;ee<8;ee++)t.readBits(2);for(let ee=0;ee<s;ee++)S[ee]&&(t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte()),T[ee]&&t.readUByte();t.readUEG();let v=t.readUEG();v==3&&t.skipBits(1);let x=t.readUEG(),I=t.readUEG(),A=t.readBoolean(),b=0,_=0,L=0,P=0;A&&(b+=t.readUEG(),_+=t.readUEG(),L+=t.readUEG(),P+=t.readUEG());let D=t.readUEG(),M=t.readUEG(),U=t.readUEG(),B=t.readBoolean();for(let ee=B?0:s;ee<=s;ee++)t.skipUEG(),t.skipUEG(),t.skipUEG();if(t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG(),t.readBoolean()&&t.readBoolean())for(let J=0;J<4;J++)for(let te=0;te<(J===3?2:6);te++)if(!t.readBoolean())t.readUEG();else{let ye=Math.min(64,1<<4+(J<<1));J>1&&t.readEG();for(let Ce=0;Ce<ye;Ce++)t.readEG()}t.readBoolean(),t.readBoolean(),t.readBoolean()&&(t.readUByte(),t.skipUEG(),t.skipUEG(),t.readBoolean());let O=t.readUEG(),F=0;for(let ee=0;ee<O;ee++){let J=!1;if(ee!==0&&(J=t.readBoolean()),J){ee===O&&t.readUEG(),t.readBoolean(),t.readUEG();let te=0;for(let ve=0;ve<=F;ve++){let ye=t.readBoolean(),Ce=!1;ye||(Ce=t.readBoolean()),(ye||Ce)&&te++}F=te}else{let te=t.readUEG(),ve=t.readUEG();F=te+ve;for(let ye=0;ye<te;ye++)t.readUEG(),t.readBoolean();for(let ye=0;ye<ve;ye++)t.readUEG(),t.readBoolean()}}if(t.readBoolean()){let ee=t.readUEG();for(let J=0;J<ee;J++){for(let te=0;te<U+4;te++)t.readBits(1);t.readBits(1)}}let N=0,G=1,Z=1,q=!0,ie=1,j=0;t.readBoolean(),t.readBoolean();let ne=!1;if(t.readBoolean()){if(t.readBoolean()){let Fe=t.readUByte(),It=[1,12,10,16,40,24,20,32,80,18,15,64,160,4,3,2],Pe=[1,11,11,11,33,11,11,11,33,11,11,33,99,3,2,1];Fe>0&&Fe<16?(G=It[Fe-1],Z=Pe[Fe-1]):Fe===255&&(G=t.readBits(16),Z=t.readBits(16))}if(t.readBoolean()&&t.readBoolean(),t.readBoolean()&&(t.readBits(3),t.readBoolean(),t.readBoolean()&&(t.readUByte(),t.readUByte(),t.readUByte())),t.readBoolean()&&(t.readUEG(),t.readUEG()),t.readBoolean(),t.readBoolean(),t.readBoolean(),ne=t.readBoolean(),ne&&(t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG()),t.readBoolean()&&(ie=t.readBits(32),j=t.readBits(32),t.readBoolean()&&t.readUEG(),t.readBoolean())){let Pe=t.readBoolean(),ke=t.readBoolean(),Ne=!1;(Pe||ke)&&(Ne=t.readBoolean(),Ne&&(t.readUByte(),t.readBits(5),t.readBoolean(),t.readBits(5)),t.readBits(4),t.readBits(4),Ne&&t.readBits(4),t.readBits(5),t.readBits(5),t.readBits(5));for(let ut=0;ut<=s;ut++){q=t.readBoolean();let Ae=q||t.readBoolean(),dt=!1;Ae?t.readEG():dt=t.readBoolean();let ft=dt?1:t.readUEG()+1;if(Pe)for(let Ge=0;Ge<ft;Ge++)t.readUEG(),t.readUEG(),Ne&&(t.readUEG(),t.readUEG()),t.skipBits(1);if(ke)for(let Ge=0;Ge<ft;Ge++)t.readUEG(),t.readUEG(),Ne&&(t.readUEG(),t.readUEG()),t.skipBits(1)}}t.readBoolean()&&(t.readBoolean(),t.readBoolean(),t.readBoolean(),N=t.readUEG())}let ae=x,Ee=I;if(A){let ee=1,J=1;v===1?ee=J=2:v==2&&(ee=2),ae=x-ee*_-ee*b,Ee=I-J*P-J*L}let Me=i?["A","B","C"][i]:"",nt=o<<24|l<<16|c<<8|h,be=0;for(let ee=0;ee<32;ee++)be=(be|(nt>>ee&1)<<31-ee)>>>0;let Se=be.toString(16);return a===1&&Se==="2"&&(Se="6"),{codecString:`hvc1.${Me}${a}.${Se}.${r?"H":"L"}${E}.B0`,params:{general_tier_flag:r,general_profile_idc:a,general_profile_space:i,general_profile_compatibility_flags:[o,l,c,h],general_constraint_indicator_flags:[u,d,f,g,m,y],general_level_idc:E,bit_depth:D+8,bit_depth_luma_minus8:D,bit_depth_chroma_minus8:M,min_spatial_segmentation_idc:N,chroma_format_idc:v,frame_rate:{fixed:q,fps:j/ie}},width:ae,height:Ee,pixelRatio:[G,Z]}}readPPS(e){let t=new Dt(this.ebsp2rbsp(e));t.readUByte(),t.readUByte(),t.skipUEG(),t.skipUEG(),t.skipBits(2),t.skipBits(3),t.skipBits(2),t.skipUEG(),t.skipUEG(),t.skipEG(),t.skipBits(2),t.readBoolean()&&t.skipUEG(),t.skipEG(),t.skipEG(),t.skipBits(4);let i=t.readBoolean(),r=t.readBoolean(),a=1;return r&&i?a=0:r?a=3:i&&(a=2),{parallelismType:a}}matchSPS(e,t){return Ze(e).substring(3)===Ze(t).substring(3)}},xe=188,oi=class n{constructor(e,t,s,i){this.logger=void 0,this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.sampleAes=null,this.pmtParsed=!1,this.audioCodec=void 0,this.videoCodec=void 0,this._pmtId=-1,this._videoTrack=void 0,this._audioTrack=void 0,this._id3Track=void 0,this._txtTrack=void 0,this._klvPid=-1,this.aacOverFlow=null,this.remainderData=null,this.videoParser=void 0,this.videoIntegrityChecker=null,this.observer=e,this.config=t,this.typeSupported=s,this.logger=i,this.videoParser=null}static probe(e,t){let s=n.syncOffset(e);return s>0&&t.warn(`MPEG2-TS detected but first sync word found @ offset ${s}`),s!==-1}static syncOffset(e){let t=e.length,s=Math.min(xe*5,t-xe)+1,i=0;for(;i<s;){let r=!1,a=-1,o=0;for(let l=i;l<t;l+=xe)if(e[l]===71&&(t-l===xe||e[l+xe]===71)){if(o++,a===-1&&(a=l,a!==0&&(s=Math.min(a+xe*99,e.length-xe)+1)),r||(r=li(e,l)===0),r&&o>1&&(a===0&&o>2||l+xe>s))return a}else{if(o)return-1;break}i++}return-1}static createTrack(e,t){return{container:e==="video"||e==="audio"?"video/mp2t":void 0,type:e,id:ko[e],pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0,duration:e==="audio"?t:void 0}}resetInitSegment(e,t,s,i,r,a){this.pmtParsed=!1,this._pmtId=-1,this._videoTrack=n.createTrack("video"),this._videoTrack.duration=i,this.videoIntegrityChecker=this.config.handleMpegTsVideoIntegrityErrors==="skip"?new _r(this.logger):null,this._audioTrack=n.createTrack("audio",i),this._id3Track=n.createTrack("id3"),this._txtTrack=n.createTrack("text"),this._audioTrack.segmentCodec="aac",this.videoParser=null,this.aacOverFlow=null,this.remainderData=null,this.audioCodec=t,this.videoCodec=s,e&&this.demux(e,0,a,r?.method==="SAMPLE-AES")}resetTimeStamp(){}resetContiguity(){let{_audioTrack:e,_videoTrack:t,_id3Track:s}=this;e&&(e.pesData=null),t&&(t.pesData=null),s&&(s.pesData=null),this.videoParser=null,this.aacOverFlow=null,this.remainderData=null}demux(e,t,s,i=!1,r=!1){i||(this.sampleAes=null);let a,o=this._videoTrack,l=this.videoIntegrityChecker,c=this._audioTrack,h=this._id3Track,u=this._txtTrack,d=s.iframe,f=o.pid,g=o.pesData,m=c.pid,y=h.pid,E=this._klvPid,S=c.pesData,T=h.pesData,v=null,x=null,I=this.pmtParsed,A=this._pmtId,b=e.length;if(this.remainderData&&(e=We(this.remainderData,e),b=e.length,this.remainderData=null),b<xe&&!r)return this.remainderData=e,{audioTrack:c,videoTrack:o,id3Track:h,textTrack:u};let _=Math.max(0,n.syncOffset(e));b-=(b-_)%xe,b<e.byteLength&&!r&&(this.remainderData=new Uint8Array(e.buffer,b,e.buffer.byteLength-b));let L=0;for(let D=_;D<b;D+=xe)if(e[D]===71){let M=!!(e[D+1]&64),U=li(e,D),B=(e[D+3]&48)>>4,k;if(B>1){if(k=D+5+e[D+4],k===D+xe)continue}else k=D+4;switch(U){case f:M&&(g&&!(l!=null&&l.isCorrupted)&&(a=At(g,this.logger))&&(this.readyVideoParser(o.segmentCodec),this.videoParser!==null&&this.videoParser.parsePES(o,u,a,!1,s)),g={data:[],size:0},l?.reset(f)),l?.handlePacket(e.subarray(D)),g&&(g.data.push(e.subarray(k,D+xe)),g.size+=D+xe-k);break;case m:if(d)break;if(M){if(S&&(a=At(S,this.logger)))switch(c.segmentCodec){case"aac":this.parseAACPES(c,a,s);break;case"mp3":this.parseMPEGPES(c,a);break;case"ac3":this.parseAC3PES(c,a);break}S={data:[],size:0}}S&&(S.data.push(e.subarray(k,D+xe)),S.size+=D+xe-k);break;case y:if(d)break;M&&(T&&(a=At(T,this.logger))&&this.parseID3PES(h,a),T={data:[],size:0}),T&&(T.data.push(e.subarray(k,D+xe)),T.size+=D+xe-k);break;case E:if(d)break;M&&(v&&(a=At(v,this.logger))&&this.parseKlvPES(h,a),v={data:[],size:0}),v&&(v.data.push(e.subarray(k,D+xe)),v.size+=D+xe-k);break;case 0:M&&(k+=e[k]+1),A=this._pmtId=Yu(e,k);break;case A:{M&&(k+=e[k]+1);let w=Wu(e,k,this.typeSupported,i,this.observer,this.logger,this.config,s);f=w.videoPid,f>0&&(o.pid=f,o.segmentCodec=w.segmentVideoCodec),m=w.audioPid,m>0&&(c.pid=m,c.segmentCodec=w.segmentAudioCodec),y=w.id3Pid,y>0&&(h.pid=y),E=w.klvPid,E>0&&(this._klvPid=E),x!==null&&!I&&(this.logger.warn(`MPEG-TS PMT found at ${D} after unknown PID '${x}'. Backtracking to sync byte @${_} to parse all TS packets.`),x=null,D=_-188),I=this.pmtParsed=!0;break}case 17:case 8191:break;default:x=U;break}}else L++;L>0&&br(this.observer,new Error(`Found ${L} TS packet/s that do not start with 0x47`),s,void 0,this.logger),o.pesData=g,c.pesData=S,h.pesData=T;let P={audioTrack:c,videoTrack:o,id3Track:h,textTrack:u};return r&&this.extractRemainingSamples(P,s),P}flush(e,t){let{remainderData:s}=this;this.remainderData=null;let i;return s?i=this.demux(s,0,t,!1,!0):i={videoTrack:this._videoTrack,audioTrack:this._audioTrack,id3Track:this._id3Track,textTrack:this._txtTrack},this.extractRemainingSamples(i,t),this.sampleAes?this.decrypt(i,this.sampleAes):i}extractRemainingSamples(e,t){let{audioTrack:s,videoTrack:i,id3Track:r,textTrack:a}=e,o=i.pesData,l=s.pesData,c=r.pesData,h=this.videoIntegrityChecker,u;if(o&&!(h!=null&&h.isCorrupted)&&(u=At(o,this.logger))?(this.readyVideoParser(i.segmentCodec),this.videoParser!==null&&(this.videoParser.parsePES(i,a,u,!0,t),i.pesData=null)):i.pesData=o,l&&(u=At(l,this.logger))){switch(s.segmentCodec){case"aac":this.parseAACPES(s,u,t);break;case"mp3":this.parseMPEGPES(s,u);break;case"ac3":this.parseAC3PES(s,u);break}s.pesData=null}else l!=null&&l.size&&this.logger.log("last AAC PES packet truncated,might overlap between fragments"),s.pesData=l;c&&(u=At(c,this.logger))?(this.parseID3PES(r,u),r.pesData=null):r.pesData=c}demuxSampleAes(e,t,s,i){let r=this.demux(e,s,i,!0,!this.config.progressive),a=this.sampleAes=new ni(this.observer,this.config,t);return this.decrypt(r,a)}readyVideoParser(e){this.videoParser===null&&(e==="avc"?this.videoParser=new Lr:e==="hevc"&&(this.videoParser=new Rr))}decrypt(e,t){return new Promise(s=>{let{audioTrack:i,videoTrack:r}=e;i.samples&&i.segmentCodec==="aac"?t.decryptAacSamples(i.samples,0,()=>{r.samples?t.decryptAvcSamples(r.samples,0,0,()=>{s(e)}):s(e)}):r.samples&&t.decryptAvcSamples(r.samples,0,0,()=>{s(e)})})}destroy(){this.observer&&this.observer.removeAllListeners(),this.config=this.logger=this.observer=null,this.aacOverFlow=this.videoParser=this.remainderData=this.sampleAes=null,this._videoTrack=this._audioTrack=this._id3Track=this._txtTrack=void 0,this.videoIntegrityChecker=null}parseAACPES(e,t,s){let i=0,r=this.aacOverFlow,a=t.data;if(r){this.aacOverFlow=null;let d=r.missing,f=r.sample.unit.byteLength;if(d===-1)a=We(r.sample.unit,a);else{let g=f-d;r.sample.unit.set(a.subarray(0,d),g),e.samples.push(r.sample),i=r.missing}}let o,l;for(o=i,l=a.length;o<l-1&&!ri(a,o);o++);if(o!==i){let d,f=o<l-1;if(f?d=`AAC PES did not start with ADTS header,offset:${o}`:d="No ADTS header found in AAC PES",br(this.observer,new Error(d),s,f,this.logger),!f)return}Sl(e,this.observer,a,o,this.audioCodec);let c;if(t.pts!==void 0)c=t.pts;else if(r){let d=vl(e.samplerate);c=r.sample.pts+d}else{this.logger.warn("[tsdemuxer]: AAC PES unknown PTS");return}let h=0,u;for(;o<l;)if(u=xl(e,a,o,c,h),o+=u.length,u.missing){this.aacOverFlow=u;break}else for(h++;o<l-1&&!ri(a,o);o++);}parseMPEGPES(e,t){let s=t.data,i=s.length,r=0,a=0,o=t.pts;if(o===void 0){this.logger.warn("[tsdemuxer]: MPEG PES unknown PTS");return}for(;a<i;)if(Ll(s,a)){let l=Il(e,s,a,o,r);if(l)a+=l.length,r++;else break}else a++}parseAC3PES(e,t){{let s=t.data,i=t.pts;if(i===void 0){this.logger.warn("[tsdemuxer]: AC3 PES unknown PTS");return}let r=s.length,a=0,o=0,l;for(;o<r&&(l=_l(e,s,o,i,a++))>0;)o+=l}}parseID3PES(e,t){if(t.pts===void 0){this.logger.warn("[tsdemuxer]: ID3 PES unknown PTS");return}let s=he({},t,{type:this._videoTrack?Oe.emsg:Oe.audioId3,duration:Number.POSITIVE_INFINITY});e.samples.push(s)}parseKlvPES(e,t){var s;let i=(s=t.pts)!=null?s:t.dts;if(i===void 0){this.logger.warn("[tsdemuxer]: KLV PES unknown PTS and DTS");return}let r=t.data;if(r.length<16){this.logger.warn("[tsdemuxer]: KLV PES payload too short");return}let a=0;for(;a<r.length;){var o;if(a+16>r.length)break;let l=a;if(a+=16,a>=r.length)break;let c=r[a];a+=1;let h=0;if(c&128){let g=c&127;if(g===0||g>4||a+g>r.length){this.logger.warn("[tsdemuxer]: Invalid KLV length encoding");break}for(let m=0;m<g;m++)h=h<<8|r[a+m];a+=g}else h=c;if(a+h>r.length){this.logger.warn("[tsdemuxer]: KLV value extends beyond PES payload");break}let u=a+h,d=r.subarray(l,u),f={data:d,len:d.byteLength,pts:i,dts:(o=t.dts)!=null?o:i,type:Oe.misbklv,duration:Number.POSITIVE_INFINITY};e.samples.push(f),a=u}}};function li(n,e){return((n[e+1]&31)<<8)+n[e+2]}function Yu(n,e){return(n[e+10]&31)<<8|n[e+11]}function Wu(n,e,t,s,i,r,a,o){let l={audioPid:-1,videoPid:-1,id3Pid:-1,klvPid:-1,segmentVideoCodec:"avc",segmentAudioCodec:"aac"},c=(n[e+1]&15)<<8|n[e+2],h=e+3+c-4,u=(n[e+10]&15)<<8|n[e+11];for(e+=12+u;e<h;){let d=li(n,e),f=(n[e+3]&15)<<8|n[e+4];switch(n[e]){case 207:if(!s){Ui("ADTS AAC",r);break}case 15:l.audioPid===-1&&(l.audioPid=d);break;case 21:l.id3Pid===-1&&(l.id3Pid=d);break;case 219:if(!s){Ui("H.264",r);break}case 27:l.videoPid===-1&&(l.videoPid=d);break;case 3:case 4:!t.mpeg&&!t.mp3?r.log("MPEG audio found, not supported in this browser"):l.audioPid===-1&&(l.audioPid=d,l.segmentAudioCodec="mp3");break;case 193:if(!s){Ui("AC-3",r);break}case 129:t.ac3?l.audioPid===-1&&(l.audioPid=d,l.segmentAudioCodec="ac3"):r.log("AC-3 audio found, not supported in this browser");break;case 6:if(f>0){let g=e+5,m=f;for(;m>2;){switch(n[g]){case 106:l.audioPid===-1&&(t.ac3!==!0?r.log("AC-3 audio found, not supported in this browser for now"):(l.audioPid=d,l.segmentAudioCodec="ac3"));break;case 5:l.klvPid===-1&&a.enableEmsgKLVMetadata&&(l.klvPid=d,r.log(`KLV metadata PID found: ${d}`));break}let E=n[g+1]+2;g+=E,m-=E}}break;case 194:case 135:return br(i,new Error("Unsupported EC-3 in M2TS found"),o,void 0,r),l;case 36:l.videoPid===-1&&(l.videoPid=d,l.segmentVideoCodec="hevc",r.log("HEVC in M2TS found"));break}e+=f+5}return l}function br(n,e,t,s,i){i.warn(`parsing error: ${e.message}`),n.emit(p.ERROR,p.ERROR,{type:W.MEDIA_ERROR,details:R.FRAG_PARSING_ERROR,fatal:!1,levelRetry:s,chunkMeta:t,error:e,reason:e.message})}function Ui(n,e){e.log(`${n} with AES-128-CBC encryption found in unencrypted stream`)}function At(n,e){let t=0,s,i,r,a,o,l=n.data;if(!n||n.size===0)return null;for(;l[0].length<19&&l.length>1;)l[0]=We(l[0],l[1]),l.splice(1,1);if(s=l[0],(s[0]<<16)+(s[1]<<8)+s[2]===1){if(i=(s[4]<<8)+s[5],i&&i>n.size-6)return null;let h=s[7];h&192&&(a=(s[9]&14)*536870912+(s[10]&255)*4194304+(s[11]&254)*16384+(s[12]&255)*128+(s[13]&254)/2,h&64?(o=(s[14]&14)*536870912+(s[15]&255)*4194304+(s[16]&254)*16384+(s[17]&255)*128+(s[18]&254)/2,a-o>60*9e4&&(e.warn(`${Math.round((a-o)/9e4)}s delta between PTS and DTS, align them`),a=o)):o=a),r=s[8];let u=r+9;if(n.size<=u)return null;n.size-=u;let d=new Uint8Array(n.size);for(let f=0,g=l.length;f<g;f++){s=l[f];let m=s.byteLength;if(u)if(u>m){u-=m;continue}else s=s.subarray(u),m-=u,u=0;d.set(s,t),t+=m}return i&&(i-=r+3),{data:d,pts:a,dts:o,len:i}}return null}var _r=class{constructor(e){this.logger=void 0,this.pid=0,this.lastContinuityCounter=-1,this.integrityState="ok",this.logger=e}get isCorrupted(){return this.integrityState!=="ok"}reset(e){this.pid=e,this.lastContinuityCounter=-1,this.integrityState="ok"}handlePacket(e){if(e.byteLength<4)return;let t=li(e,0);if(t!==this.pid){this.logger.debug(`Packet PID mismatch, expected ${this.pid} got ${t}`);return}let s=(e[3]&48)>>4;if(s===0)return;let i=e[3]&15,r=this.lastContinuityCounter;this.lastContinuityCounter=i;let a=(s&1)!=0;if((s&2)!=0&&e[4]!=0&&(e[5]&128)!=0||r<0)return;let c=a?r+1&15:r;if(i!==c){this.logger.warn(`MPEG-TS Continuity Counter check failed for PID='${t}', CC=${i}, Expected-CC=${c} Last-CC=${r}`),this.integrityState="cc-failed";return}if((e[1]&128)!==0){this.logger.warn(`MPEG-TS Packet had TEI flag set for PID='${t}'`),this.integrityState="tei-bit";return}}},Dr=class{static getSilentFrame(e,t){switch(e){case"mp4a.40.2":if(t===1)return new Uint8Array([0,200,0,128,35,128]);if(t===2)return new Uint8Array([33,0,73,144,2,25,0,35,128]);if(t===3)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,142]);if(t===4)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,128,44,128,8,2,56]);if(t===5)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,56]);if(t===6)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,0,178,0,32,8,224]);break;default:if(t===1)return new Uint8Array([1,64,34,128,163,78,230,128,186,8,0,0,0,28,6,241,193,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);if(t===2)return new Uint8Array([1,64,34,128,163,94,230,128,186,8,0,0,0,0,149,0,6,241,161,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);if(t===3)return new Uint8Array([1,64,34,128,163,94,230,128,186,8,0,0,0,0,149,0,6,241,161,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);break}}},ci,qu={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])},Gi=new Uint8Array([0,0,0,0,0,0,0,0]),ju=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),zu=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0]),Xu=new Uint8Array([0,0,0,0,0,0,0,0]),Wt=new Uint8Array([0,0,0,0,0,0,0,1]),Ka=new Uint8Array([105,115,111,109]),Qu=new Uint8Array([97,118,99,49]),Zu=new Uint8Array([0,0,0,1]),lt=class n{static box(e,...t){let s=8,i=t.length,r=i;for(;i--;)s+=t[i].byteLength;let a=new Uint8Array(s);for(Te(a,0,s),Te(a,4,e),i=0,s=8;i<r;i++)a.set(t[i],s),s+=t[i].byteLength;return a}static hdlr(e){return n.box(z.hdlr,qu[e])}static mdat(e){return n.box(z.mdat,e)}static mdhd(e,t){t*=e;let s=Math.floor(t/(et+1)),i=Math.floor(t%(et+1));return n.box(z.mdhd,new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,e>>24&255,e>>16&255,e>>8&255,e&255,s>>24,s>>16&255,s>>8&255,s&255,i>>24,i>>16&255,i>>8&255,i&255,85,196,0,0]))}static mdia(e){return n.box(z.mdia,n.mdhd(e.timescale||0,e.duration||0),n.hdlr(e.type),n.minf(e))}static mfhd(e){return n.box(z.mfhd,new Uint8Array([0,0,0,0,e>>24,e>>16&255,e>>8&255,e&255]))}static minf(e){return e.type==="audio"?n.box(z.minf,n.box(z.smhd,Xu),n.DINF,n.stbl(e)):n.box(z.minf,n.box(z.vmhd,zu),n.DINF,n.stbl(e))}static moof(e,t,s){return n.box(z.moof,n.mfhd(e),n.traf(s,t))}static moov(e){let t=e.length,s=[];for(;t--;)s[t]=n.trak(e[t]);return n.box.apply(null,[z.moov,n.mvhd(e[0].timescale||0,e[0].duration||0)].concat(s).concat(n.mvex(e)))}static mvex(e){let t=e.length,s=[];for(;t--;)s[t]=n.trex(e[t]);return n.box.apply(null,[z.mvex,...s])}static mvhd(e,t){t*=e;let s=Math.floor(t/(et+1)),i=Math.floor(t%(et+1)),r=new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,e>>24&255,e>>16&255,e>>8&255,e&255,s>>24,s>>16&255,s>>8&255,s&255,i>>24,i>>16&255,i>>8&255,i&255,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,255,255,255,255]);return n.box(z.mvhd,r)}static sdtp(e){let t=e.samples||[],s=new Uint8Array(4+t.length),i,r;for(i=0;i<t.length;i++)r=t[i].flags,s[i+4]=r.dependsOn<<4|r.isDependedOn<<2|r.hasRedundancy;return n.box(z.sdtp,s)}static stbl(e){return n.box(z.stbl,n.stsd(e),n.box(z.stts,Gi),n.box(z.stsc,Gi),n.box(z.stsz,ju),n.box(z.stco,Gi))}static avc1(e){let t=[],s=[],i,r,a;for(i=0;i<e.sps.length;i++)r=e.sps[i],a=r.byteLength,t.push(a>>>8&255),t.push(a&255),t=t.concat(Array.prototype.slice.call(r));for(i=0;i<e.pps.length;i++)r=e.pps[i],a=r.byteLength,s.push(a>>>8&255),s.push(a&255),s=s.concat(Array.prototype.slice.call(r));let o=n.box(z.avcC,new Uint8Array([1,t[3],t[4],t[5],255,224|e.sps.length].concat(t).concat([e.pps.length]).concat(s))),l=e.width,c=e.height,h=e.pixelRatio[0],u=e.pixelRatio[1];return n.box(z.avc1,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,l>>8&255,l&255,c>>8&255,c&255,0,72,0,0,0,72,0,0,0,0,0,0,0,1,18,100,97,105,108,121,109,111,116,105,111,110,47,104,108,115,46,106,115,0,0,0,0,0,0,0,0,0,0,0,0,0,0,24,17,17]),o,n.box(z.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),n.box(z.pasp,new Uint8Array([h>>24,h>>16&255,h>>8&255,h&255,u>>24,u>>16&255,u>>8&255,u&255])))}static esds(e){let t=e.config,s=t.length;return new Uint8Array([0,0,0,0,3,23+s,0,1,0,4,15+s,64,21,0,0,0,0,0,0,0,0,0,0,0,5,s,...t,6,1,2])}static audioStsd(e){let t=e.samplerate||0;return new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,e.channelCount||0,0,16,0,0,0,0,t>>8&255,t&255,0,0])}static mp4a(e){return n.box(z.mp4a,n.audioStsd(e),n.box(z.esds,n.esds(e)))}static mp3(e){return n.box(z[".mp3"],n.audioStsd(e))}static ac3(e){return n.box(z["ac-3"],n.audioStsd(e),n.box(z.dac3,e.config))}static stsd(e){let{segmentCodec:t}=e;if(e.type==="audio"){if(t==="aac")return n.box(z.stsd,Wt,n.mp4a(e));if(t==="ac3"&&e.config)return n.box(z.stsd,Wt,n.ac3(e));if(t==="mp3"&&e.codec==="mp3")return n.box(z.stsd,Wt,n.mp3(e))}else if(e.pps&&e.sps){if(t==="avc")return n.box(z.stsd,Wt,n.avc1(e));if(t==="hevc"&&e.vps)return n.box(z.stsd,Wt,n.hvc1(e))}else throw new Error("video track missing pps or sps");throw new Error(`unsupported ${e.type} segment codec (${t}/${e.codec})`)}static tkhd(e){let t=e.id,s=(e.duration||0)*(e.timescale||0),i=e.width||0,r=e.height||0,a=Math.floor(s/(et+1)),o=Math.floor(s%(et+1));return n.box(z.tkhd,new Uint8Array([1,0,0,7,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,t>>24&255,t>>16&255,t>>8&255,t&255,0,0,0,0,a>>24,a>>16&255,a>>8&255,a&255,o>>24,o>>16&255,o>>8&255,o&255,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,i>>8&255,i&255,0,0,r>>8&255,r&255,0,0]))}static traf(e,t){let s=n.sdtp(e),i=e.id,r=Math.floor(t/(et+1)),a=Math.floor(t%(et+1));return n.box(z.traf,n.box(z.tfhd,new Uint8Array([0,0,0,0,i>>24,i>>16&255,i>>8&255,i&255])),n.box(z.tfdt,new Uint8Array([1,0,0,0,r>>24,r>>16&255,r>>8&255,r&255,a>>24,a>>16&255,a>>8&255,a&255])),n.trun(e,s.length+16+20+8+16+8+8),s)}static trak(e){return e.duration=e.duration||4294967295,n.box(z.trak,n.tkhd(e),n.mdia(e))}static trex(e){let t=e.id;return n.box(z.trex,new Uint8Array([0,0,0,0,t>>24,t>>16&255,t>>8&255,t&255,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,1]))}static trun(e,t){let s=e.samples||[],i=s.length,r=12+16*i,a=new Uint8Array(r),o,l,c,h,u,d;for(t+=8+r,a.set([e.type==="video"?1:0,0,15,1,i>>>24&255,i>>>16&255,i>>>8&255,i&255,t>>>24&255,t>>>16&255,t>>>8&255,t&255],0),o=0;o<i;o++)l=s[o],c=l.duration,h=l.size,u=l.flags,d=l.cts,a.set([c>>>24&255,c>>>16&255,c>>>8&255,c&255,h>>>24&255,h>>>16&255,h>>>8&255,h&255,u.isLeading<<2|u.dependsOn,u.isDependedOn<<6|u.hasRedundancy<<4|u.paddingValue<<1|u.isNonSync,u.degradPrio&61440,u.degradPrio&15,d>>>24&255,d>>>16&255,d>>>8&255,d&255],12+16*o);return n.box(z.trun,a)}static initSegment(e){let t=n.moov(e);return We(n.FTYP,t)}static hvc1(e){let t=e.params,s=[e.vps,e.sps,e.pps],i=4,r=new Uint8Array([1,t.general_profile_space<<6|(t.general_tier_flag?32:0)|t.general_profile_idc,t.general_profile_compatibility_flags[0],t.general_profile_compatibility_flags[1],t.general_profile_compatibility_flags[2],t.general_profile_compatibility_flags[3],t.general_constraint_indicator_flags[0],t.general_constraint_indicator_flags[1],t.general_constraint_indicator_flags[2],t.general_constraint_indicator_flags[3],t.general_constraint_indicator_flags[4],t.general_constraint_indicator_flags[5],t.general_level_idc,240|t.min_spatial_segmentation_idc>>8,255&t.min_spatial_segmentation_idc,252|t.parallelismType,252|t.chroma_format_idc,248|t.bit_depth_luma_minus8,248|t.bit_depth_chroma_minus8,0,parseInt(t.frame_rate.fps),i-1|t.temporal_id_nested<<2|t.num_temporal_layers<<3|(t.frame_rate.fixed?64:0),s.length]),a=r.length;for(let g=0;g<s.length;g+=1){a+=3;for(let m=0;m<s[g].length;m+=1)a+=2+s[g][m].length}let o=new Uint8Array(a);o.set(r,0),a=r.length;let l=s.length-1;for(let g=0;g<s.length;g+=1){o.set(new Uint8Array([32+g|(g===l?128:0),0,s[g].length]),a),a+=3;for(let m=0;m<s[g].length;m+=1)o.set(new Uint8Array([s[g][m].length>>8,s[g][m].length&255]),a),a+=2,o.set(s[g][m],a),a+=s[g][m].length}let c=n.box(z.hvcC,o),h=e.width,u=e.height,d=e.pixelRatio[0],f=e.pixelRatio[1];return n.box(z.hvc1,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,h>>8&255,h&255,u>>8&255,u&255,0,72,0,0,0,72,0,0,0,0,0,0,0,1,18,100,97,105,108,121,109,111,116,105,111,110,47,104,108,115,46,106,115,0,0,0,0,0,0,0,0,0,0,0,0,0,0,24,17,17]),c,n.box(z.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),n.box(z.pasp,new Uint8Array([d>>24,d>>16&255,d>>8&255,d&255,f>>24,f>>16&255,f>>8&255,f&255])))}};ci=lt;lt.FTYP=ci.box(z.ftyp,Ka,Zu,Ka,Qu);lt.DINF=ci.box(z.dinf,ci.box(z.dref,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,12,117,114,108,32,0,0,0,1])));var Dl=9e4;function Bn(n,e,t=1,s=!1){let i=n*e*t;return s?Math.round(i):i}function Ju(n,e,t=1,s=!1){return Bn(n,e,1/t,s)}function qt(n,e=!1){return Bn(n,1e3,1/Dl,e)}function ed(n,e=1){return Bn(n,Dl,1/e)}function Ha(n){let{baseTime:e,timescale:t,trackId:s}=n;return`${e/t} (${e}/${t}) trackId: ${s}`}var td=10*1e3,sd=1024,id=1152,rd=1536,Pr=8589934592;function Ya(n,e,t,s){return{duration:e,size:t,cts:s,flags:{isLeading:0,isDependedOn:0,hasRedundancy:0,degradPrio:0,dependsOn:n?2:1,isNonSync:n?0:1,paddingValue:0}}}var $t=class extends we{constructor(e,t,s,i){super("mp4-remuxer",i),this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.ISGenerated=!1,this._initPTS=null,this._initDTS=null,this.nextVideoTs=null,this.nextAudioTs=null,this.videoSampleDuration=null,this.isAudioContiguous=!1,this.isVideoContiguous=!1,this.videoTrackConfig=void 0,this.observer=e,this.config=t,this.typeSupported=s,this.ISGenerated=!1}destroy(){this.config=this.videoTrackConfig=this._initPTS=this._initDTS=null}resetTimeStamp(e){let t=this._initPTS;(!t||!e||e.trackId!==t.trackId||e.baseTime!==t.baseTime||e.timescale!==t.timescale)&&this.log(`Reset initPTS: ${t&&Ha(t)} > ${e&&Ha(e)}`),this._initPTS=this._initDTS=e}resetNextTimestamp(){this.log("reset next timestamp"),this.isVideoContiguous=!1,this.isAudioContiguous=!1}resetInitSegment(){this.log("ISGenerated flag reset"),this.ISGenerated=!1,this.videoTrackConfig=void 0}getVideoStartPts(e){let t=!1,s=e[0].pts,i=e.reduce((r,a)=>{let o=a.pts,l=o-r;return l<-4294967296&&(t=!0,o=Ke(o,s),l=o-r),l>0?r:o},s);return t&&this.debug("PTS rollover detected"),i}remux(e,t,s,i,r,a,o,l,c){let h,u,d,f,g,m,y=r,E=r,T=!c.iframe&&e.pid>-1,v=t.pid>-1,x=t.samples.length,I=e.samples.length>0,A=o&&x>0||x>1;if((!T||I)&&(!v||A)||this.ISGenerated||o){if(this.ISGenerated){var _,L,P,D;let k=this.videoTrackConfig;(k&&(t.width!==k.width||t.height!==k.height||((_=t.pixelRatio)==null?void 0:_[0])!==((L=k.pixelRatio)==null?void 0:L[0])||((P=t.pixelRatio)==null?void 0:P[1])!==((D=k.pixelRatio)==null?void 0:D[1]))||!k&&A||this.nextAudioTs===null&&I)&&this.resetInitSegment()}this.ISGenerated||(d=this.generateIS(e,t,r,a));let M=this.isVideoContiguous,U=-1,B;if(A&&(U=nd(t.samples),!M&&this.config.forceKeyFrameOnDiscontinuity))if(m=!0,U>0){this.warn(`Dropped ${U} out of ${x} video samples due to a missing keyframe`);let k=this.getVideoStartPts(t.samples);t.samples=t.samples.slice(U),t.dropped+=U,E+=(t.samples[0].pts-k)/t.inputTimeScale,B=E}else U===-1&&(this.warn(`No keyframe found out of ${x} video samples`),m=!1);if(this.ISGenerated){if(I&&A&&r){let k=this.getVideoStartPts(t.samples),O=(Ke(e.samples[0].pts,k)-k)/t.inputTimeScale;y+=Math.max(0,O),E+=Math.max(0,-O)}if(I){if(e.samplerate||(this.warn("regenerate InitSegment as audio detected"),d=this.generateIS(e,t,r,a)),u=this.remuxAudio(e,y,this.isAudioContiguous,a,v||A||l===K.AUDIO?E:void 0,c),A){let k=u?u.endPTS-u.startPTS:0;t.inputTimeScale||(this.warn("regenerate InitSegment as video detected"),d=this.generateIS(e,t,r,a)),h=this.remuxVideo(t,E,M,k,c)}}else A&&(h=this.remuxVideo(t,E,M,0,c));h&&(h.firstKeyFrame=U,h.independent=U!==-1,h.firstKeyFramePTS=B)}}return this.ISGenerated&&this._initPTS&&this._initDTS&&(s.samples.length&&(g=Pl(s,r,this._initPTS,this._initDTS)),i.samples.length&&(f=Cl(i,r,this._initPTS))),{audio:u,video:h,initSegment:d,independent:m,text:f,id3:g}}computeInitPts(e,t,s,i){let r=Math.round(s*t),a=Ke(e,r);if(a<r)for(this.log(`Adjusting PTS for rollover in timeline near ${(r-a)/t} ${i}`);a<r;)a+=Pr;return a-r}generateIS(e,t,s,i){let r=e.samples,a=t.samples,o=this.typeSupported,l={},c=this._initPTS,h=!c||i,u="audio/mp4",d,f,g,m=-1;if(h&&(d=f=1/0),e.config&&r.length){switch(e.timescale=e.samplerate,e.segmentCodec){case"mp3":o.mpeg?(u="audio/mpeg",e.codec=""):o.mp3&&(e.codec="mp3");break;case"ac3":e.codec="ac-3";break}if(l.audio={id:"audio",container:u,codec:e.codec,initSegment:e.segmentCodec==="mp3"&&o.mpeg?new Uint8Array(0):lt.initSegment([e]),metadata:{channelCount:e.channelCount}},h){m=e.id,g=e.inputTimeScale;let y=this.computeInitPts(r[0].pts,g,s,"audio");(!c||g!==c.timescale||s===0&&y<c.baseTime)&&(d=f=y)}}if(t.sps&&t.pps&&a.length){if(t.timescale=t.inputTimeScale,l.video={id:"main",container:"video/mp4",codec:t.codec,initSegment:lt.initSegment([t]),metadata:{width:t.width,height:t.height}},h){m=t.id,g=t.inputTimeScale;let y=this.getVideoStartPts(a),E=Ke(a[0].dts,y),S=this.computeInitPts(E,g,s,"video"),T=this.computeInitPts(y,g,s,"video");if(!c||g!==c.timescale||$(d)||s===0&&T<c.baseTime){f=Math.min(f,S);let v=!c&&this.isVideoContiguous?T:S;d=Math.min(d,v)}}this.videoTrackConfig={width:t.width,height:t.height,pixelRatio:t.pixelRatio}}if(Object.keys(l).length)return this.ISGenerated=!0,h&&$(d)?(c&&this.warn(`Timestamps at playlist time: ${i?"":"~"}${s} ${d/g} != initPTS: ${c.baseTime/c.timescale} (${c.baseTime}/${c.timescale}) trackId: ${c.trackId}`),this.log(`Found initPTS at playlist time: ${s} offset: ${d/g} (${d}/${g}) trackId: ${m}`),this._initPTS={baseTime:d,timescale:g,trackId:m},this._initDTS={baseTime:f,timescale:g,trackId:m}):d=g=void 0,{tracks:l,initPTS:d,timescale:g,trackId:m}}remuxVideo(e,t,s,i,r){let a=e.inputTimeScale,o=e.samples,l=[],c=o.length,h=this._initPTS,u=h.baseTime*a/h.timescale,d=this.nextVideoTs,f=8,g=this.videoSampleDuration,m,y,E=Number.POSITIVE_INFINITY,S=Number.NEGATIVE_INFINITY,T=!1;if(!s||d===null){let N=u+t*a,G=o[0].pts-Ke(o[0].dts,o[0].pts);Xt()&&d!==null&&Math.abs(N-G-(d+u))<15e3?s=!0:d=N-G-u}let v=d+u;for(let N=0;N<c;N++){let G=o[N];G.pts=Ke(G.pts,v),G.dts=Ke(G.dts,v),G.dts<o[N>0?N-1:N].dts&&(T=!0)}T&&o.sort(function(N,G){let Z=N.dts-G.dts,q=N.pts-G.pts;return Z||q}),m=o[0].dts,y=o[o.length-1].dts;let x=y-m,I=x?Math.round(x/(c-1)):g||e.inputTimeScale/30;if(s){let N=m-v,G=N>I,Z=N<-1;if((G||Z)&&(G?this.warn(`${(e.segmentCodec||"").toUpperCase()}: ${qt(N,!0)} ms (${N}dts) hole between fragments detected at ${t.toFixed(3)}`):this.warn(`${(e.segmentCodec||"").toUpperCase()}: ${qt(-N,!0)} ms (${N}dts) overlapping between fragments detected at ${t.toFixed(3)}`),!Z||v>=o[0].pts||Xt())){m=v;let q=o[0].pts-N;if(G)o[0].dts=m,o[0].pts=q;else{let ie=!0;for(let j=0;j<o.length&&!(o[j].dts>q&&ie);j++){let ne=o[j].pts;if(o[j].dts-=N,o[j].pts-=N,j<o.length-1){let re=o[j+1].pts,ae=o[j].pts,Ee=re<=ae,Me=re<=ne;ie=Ee==Me}}}this.log(`Video: Initial PTS/DTS adjusted: ${qt(q,!0)}/${qt(m,!0)}, delta: ${qt(N,!0)} ms`)}}m=Math.max(0,m);let A=0,b=0,_=m;for(let N=0;N<c;N++){let G=o[N],Z=G.units,q=Z.length,ie=0;for(let j=0;j<q;j++)ie+=Z[j].data.length;b+=ie,A+=q,G.length=ie,G.dts<_?(G.dts=_,_+=I/4|0||1):_=G.dts,E=Math.min(G.pts,E),S=Math.max(G.pts,S)}y=o[c-1].dts;let L=b+4*A+8,P;try{P=new Uint8Array(L)}catch(N){this.observer.emit(p.ERROR,p.ERROR,{type:W.MUX_ERROR,details:R.REMUX_ALLOC_ERROR,fatal:!1,chunkMeta:r,error:N,bytes:L,reason:`fail allocating video mdat ${L}`});return}Te(P,0,L),Te(P,4,z.mdat);let D=!1,M=Number.POSITIVE_INFINITY,U=Number.POSITIVE_INFINITY,B=Number.NEGATIVE_INFINITY,k=Number.NEGATIVE_INFINITY;for(let N=0;N<c;N++){let G=o[N],Z=G.units,q=0;for(let ne=0,re=Z.length;ne<re;ne++){let ae=Z[ne],Ee=ae.data,Me=ae.data.byteLength;Te(P,f,Me),f+=4,P.set(Ee,f),f+=Me,q+=4+Me}let ie;if(N<c-1)g=o[N+1].dts-G.dts,ie=o[N+1].pts-G.pts;else{let ne=this.config,re=N>0?G.dts-o[N-1].dts:I;if(ie=N>0?G.pts-o[N-1].pts:I,ne.stretchShortVideoTrack&&this.nextAudioTs!==null){let ae=Math.floor(ne.maxBufferHole*a),Ee=(i?E+i*a:this.nextAudioTs+u)-G.pts;Ee>ae?(g=Ee-re,g<0?g=re:D=!0,this.log(`It is approximately ${Ee/90} ms to the next segment; using duration ${g/90} ms for the last video frame.`)):g=re}else g=re}let j=Math.round(G.pts-G.dts);if(M=Math.min(M,g),B=Math.max(B,g),U=Math.min(U,ie),k=Math.max(k,ie),!s&&N===0&&j>g){let ne=Math.round(j/I)*I;ne-j===1&&(this.log(`pad first CTS ${j} -> ${ne} of sn: ${r.sn}`),j=ne)}l.push(Ya(G.key,g,q,j))}if(l.length){let N=Xt();if(N){if(N<70){let G=l[0].flags;G.dependsOn=2,G.isNonSync=0}}else if(yh()&&k-U<B-M&&I/B<.025&&l[0].cts===0){this.warn("Found irregular gaps in sample duration. Using PTS instead of DTS to determine MP4 sample duration.");let G=m;for(let Z=0,q=l.length;Z<q;Z++){let ie=G+l[Z].duration,j=G+l[Z].cts;if(Z<q-1){let ne=ie+l[Z+1].cts;l[Z].duration=ne-j}else l[Z].duration=Z?l[Z-1].duration:I;l[Z].cts=0,G=ie}}}g=D||!g?I:g;let w=y+g;this.nextVideoTs=d=w-u,this.videoSampleDuration=g,this.isVideoContiguous=!0,r.iframe&&(l.length===1?(l[0].duration=g=r.duration*a,this.nextVideoTs=d=m+g-u):this.warn(`Not adjusting IFrame duration (sample count ${l.length})`));let H={data1:lt.moof(r.sn,m,he(e,{samples:l})),data2:P,startPTS:(E-u)/a,endPTS:(S+g-u)/a,startDTS:(m-u)/a,endDTS:d/a,type:"video",hasAudio:!1,hasVideo:!0,nb:l.length,dropped:e.dropped};return e.samples=[],e.dropped=0,H}getSamplesPerFrame(e){switch(e.segmentCodec){case"mp3":return id;case"ac3":return rd;default:return sd}}remuxAudio(e,t,s,i,r,a){let o=e.inputTimeScale,l=e.samplerate?e.samplerate:o,c=o/l,h=this.getSamplesPerFrame(e),u=h*c,d=this._initPTS,f=e.segmentCodec==="mp3"&&this.typeSupported.mpeg,g=[],m=r!==void 0,y=e.samples,E=f?0:8,S=this.nextAudioTs||-1,T=d.baseTime*o/d.timescale,v=T+t*o;if(this.isAudioContiguous=s=s||y.length&&S>0&&(i&&Math.abs(v-(S+T))<9e3||Math.abs(Ke(y[0].pts,v)-(S+T))<20*u),y.forEach(function(w){w.pts=Ke(w.pts,v)}),!s||S<0){let w=y.length;if(y=y.filter(O=>O.pts>=0),w!==y.length&&this.warn(`Removed ${y.length-w} of ${w} samples (initPTS ${T} / ${o})`),!y.length)return;r===0?S=0:i&&!m?S=Math.max(0,v-T):S=y[0].pts-T}if(e.segmentCodec==="aac"){let w=this.config.maxAudioFramesDrift;for(let O=0,F=S+T;O<y.length;O++){let H=y[O],N=H.pts,G=N-F,Z=Math.abs(1e3*G/o);if(G<=-w*u&&m)O===0&&(this.warn(`Audio frame @ ${(N/o).toFixed(3)}s overlaps marker by ${Math.round(1e3*G/o)} ms.`),this.nextAudioTs=S=N-T,F=N);else if(G>=w*u&&Z<td&&m){let q=Math.round(G/u);for(F=N-q*u;F<T&&q&&u;)q--,F+=u;O===0&&(this.nextAudioTs=S=F-T),this.warn(`Injecting ${q} audio frames @ ${((F-T)/o).toFixed(3)}s due to ${Math.round(1e3*G/o)} ms gap.`);for(let ie=0;ie<q;ie++){let j=Dr.getSilentFrame(e.parsedCodec||e.manifestCodec||e.codec,e.channelCount);j||(this.log("Unable to get silent frame for given audio codec; duplicating last frame instead."),j=H.unit.subarray()),y.splice(O,0,{unit:j,pts:F}),F+=u,O++}}H.pts=F,F+=u}}let x=null,I=null,A,b=0,_=y.length;for(;_--;)b+=y[_].unit.byteLength;for(let w=0,O=y.length;w<O;w++){let F=y[w],H=F.unit,N=F.pts;if(I!==null){let Z=g[w-1];Z.duration=Math.round((N-I)/c)}else if(s&&e.segmentCodec==="aac"&&(N=S+T),x=N,b>0){b+=E;try{A=new Uint8Array(b)}catch(Z){this.observer.emit(p.ERROR,p.ERROR,{type:W.MUX_ERROR,details:R.REMUX_ALLOC_ERROR,fatal:!1,chunkMeta:a,error:Z,bytes:b,reason:`fail allocating audio mdat ${b}`});return}f||(Te(A,0,b),Te(A,4,z.mdat))}else return;A&&A.set(H,E);let G=H.byteLength;E+=G,g.push(Ya(!0,h,G,0)),I=N}let L=g.length;if(!L)return;let P=g[g.length-1];S=I-T,this.nextAudioTs=S+c*P.duration;let D=f?new Uint8Array(0):lt.moof(e.sequenceNumber++,x/c,he({},e,{samples:g}));e.samples=[];let M=(x-T)/o,U=this.nextAudioTs/o,k={data1:D,data2:A,startPTS:M,endPTS:U,startDTS:M,endDTS:U,type:"audio",hasAudio:!0,hasVideo:!1,nb:L};return this.isAudioContiguous=!0,k}};function Ke(n,e){let t;if(e===null)return n;for(e<n?t=-Pr:t=Pr;Math.abs(n-e)>4294967296;)n+=t;return n}function nd(n){for(let e=0;e<n.length;e++)if(n[e].key)return e;return-1}function Pl(n,e,t,s){let i=n.samples.length;if(!i)return;let r=n.inputTimeScale;for(let o=0;o<i;o++){let l=n.samples[o];l.pts=Ke(l.pts-t.baseTime*r/t.timescale,e*r)/r,l.dts=Ke(l.dts-s.baseTime*r/s.timescale,e*r)/r}let a=n.samples;return n.samples=[],{samples:a}}function Cl(n,e,t){let s=n.samples.length;if(!s)return;let i=n.inputTimeScale;for(let a=0;a<s;a++){let o=n.samples[a];o.pts=Ke(o.pts-t.baseTime*i/t.timescale,e*i)/i}n.samples.sort((a,o)=>a.pts-o.pts);let r=n.samples;return n.samples=[],{samples:r}}var Cr=class extends we{constructor(e,t,s,i){super("passthrough-remuxer",i),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=e}destroy(){this.observer&&this.observer.removeAllListeners(),this.observer=null}resetTimeStamp(e){this.lastEndTime=null;let t=this.initPTS;t&&e&&t.baseTime===e.baseTime&&t.timescale===e.timescale||(this.initPTS=e)}resetNextTimestamp(){this.isVideoContiguous=!1,this.lastEndTime=null}resetInitSegment(e,t,s,i){this.audioCodec=t,this.videoCodec=s,this.decryptdata=i,this.pendingInitSegment=e,this.videoOnlyRemux=!1,this.initTracks=void 0,this.initData=void 0,this.emitInitSegment=!0}generateInitSegment(e,t,s){this.videoOnlyRemux=!1;let{audioCodec:i,videoCodec:r}=this;if(!(e!=null&&e.byteLength)){this.initTracks=void 0,this.initData=void 0;return}let{audio:a,video:o}=this.initData=s||Fo(e);if(t)ih(e,t);else{let c=a||o;c!=null&&c.encrypted&&this.warn(`Init segment with encrypted track with has no key ("${c.codec}")!`)}a&&(i=Wa(a,ue.AUDIO,this)),o&&(r=Wa(o,ue.VIDEO,this));let l={};a&&o?l.audiovideo={container:"video/mp4",codec:i+","+r,supplemental:o.supplemental,encrypted:o.encrypted,initSegment:e,id:"main"}:a?l.audio={container:"audio/mp4",codec:i,encrypted:a.encrypted,initSegment:e,id:"audio"}:o?l.video={container:"video/mp4",codec:r,supplemental:o.supplemental,encrypted:o.encrypted,initSegment:e,id:"main"}:this.warn("initSegment does not contain moov or trak boxes."),this.initTracks=l}remux(e,t,s,i,r,a,o,l,c,h,u){var d,f;let{initPTS:g,lastEndTime:m}=this,y={audio:void 0,video:void 0,text:void 0,id3:s,initSegment:void 0};$(m)||(m=this.lastEndTime=r||0);let E=t.samples;if(!E.length)return y;let S=this.pendingInitSegment;S&&(this.pendingInitSegment=void 0,this.generateInitSegment(S,this.decryptdata,h));let T={initPTS:void 0,timescale:void 0,trackId:void 0},v=this.initData;if((d=v)!=null&&d.length||(this.generateInitSegment(E),v=this.initData),!((f=v)!=null&&f.length))return this.warn("Failed to generate initSegment."),y;if(c.iframe&&v.audio&&v.video){var x;let J=(x=this.initTracks)==null||(x=x.audiovideo)==null?void 0:x.initSegment,te=J?Qc(J):null;if(te){var I;this.log("Converted muxed init segment to video-only for I-Frame playback"),this.generateInitSegment(te,this.decryptdata),(I=this.initData)!=null&&I.length&&(v=this.initData,this.emitInitSegment=!0,this.videoOnlyRemux=!0)}}this.emitInitSegment&&(T.tracks=this.initTracks,y.initSegment=T,this.emitInitSegment=!1);let A=c.iframe,b=u&&(!A||u.includeSampleDetails)?u.tracks:oh(E,v,c,this,A),_=v.audio?b[v.audio.id]:null,L=v.video?b[v.video.id]:null,P=!!v.audio,D=!!v.video,M="";P&&(M+="audio"),D&&(M+="video");let U=Rs(L,1/0),B=Rs(_,1/0),k=Rs(L,0,!0),w=Rs(_,0,!0),O=r,F=0;L&&_&&v.audio&&(B>k||U>w)&&this.warn(`audio and video track sample timestamps do not overlap. v: ${U}-${k} a: ${B}-${w}}`,L,_);let H=!!_&&(!L||!g&&B<U||!!g&&g.trackId===v.audio.id),N=H?_:L;if(!N)return this.log(`No media samples found in ${l} ${c.level} ${c.part===-1?"":`part: ${c.part} of`} sn: ${c.sn} at playlist time: ${r}`),y;let G=E,Z,q;if(L&&L.sampleCount>=1&&v.video&&c.iframe){let{trun:J,start:te}=L,ve=J.length===1,ye=J.length?ve?J[0].samples:J[0].samples.concat(...J.slice(1).map(Ce=>Ce.samples)):[];if(ye.length){let Ce=J[0],Fe=Ce;for(let Ae=J.length;Ae--;)if(J[Ae].samples.length){Fe=J[Ae];break}let It=Fe.lastSampleDurationOffset,{defaultSampleDurationOffset:Pe}=Ce,ke=Math.abs(c.duration-(k-U))>.05,Ne=ye.length<L.sampleCount;if(!(ke||Ne||this.videoOnlyRemux||!ve))F=k-U;else{let Ae=Ne?Fe.sampleOffset+Fe.samples.reduce((jn,dc)=>jn+dc.size,0):void 0,dt=ke?c.duration:k-U,ft=od(ye,dt*v.video.timescale,It,Pe),Ge=Zc(E,v.video.id,ye.length,Ae,ft);Ge?(G=Ge,q=ad(te,ye)):this.warn(`IFrame remux skipped (sn ${c.sn}); using native sample duration`),F=Ge&&ft?dt:k-U}}else this.warn(`Could not remux IFrame track fragment (no samples in range, trun count ${J.length})`),F=k-U}else F=H?w-B:k-U;if(this.videoOnlyRemux&&G===E)return this.warn(`Dropping muxed I-Frame fragment that could not be remuxed to video-only (sn: ${c.sn})`),y;let ie=N.timescale,j=N.start-r*ie,ne=H?v.audio.id:v.video.id;if(O=N.start/ie,!(!!g&&c.id>1)&&(a||!g)&&(ld(g,O,r,F)||ie!==g.timescale)){let J=!1,te=H?"audio":"video";if(g){let ve=r!==0?O/r:1+O/1;J=O>=0&&Math.abs(1-ve)<.001,this.log(`${te} timestamps in track ${ne} at playlist time: ${a?"":"~"}${r} maps to ${O} with initPTS: ${g.baseTime/g.timescale} (${j/ie-g.baseTime/g.timescale}s diff) (${M}) drift estimate: ${ve} ${J?"(ignoring drift)":"remapping timestamps (initPTS)"}`)}J||(this.log(`Found initPTS in ${te} track ${ne} at playlist time: ${r} offset: ${O-r} (${j}/${ie})`),g=null,T.initPTS=j,T.timescale=ie,T.trackId=ne)}g?(T.initPTS=g.baseTime,T.timescale=g.timescale,T.trackId=g.trackId):((!T.timescale||T.trackId===void 0||T.initPTS===void 0)&&(this.warn("Could not set initPTS"),T.initPTS=O,T.timescale=1,T.trackId=-1),this.initPTS=g={baseTime:T.initPTS,timescale:T.timescale,trackId:T.trackId});let ae=O-g.baseTime/g.timescale,Ee=ae+F,Me=D&&N?.ptsMin!==void 0?N.ptsMin/N.timescale-g.baseTime/g.timescale:ae,nt=q!==void 0&&L?q/L.timescale-g.baseTime/g.timescale:D&&N!=null&&N.ptsMax?N.ptsMax/N.timescale-g.baseTime/g.timescale:Ee;F>0?this.lastEndTime=Ee:(this.warn("Duration parsed from mp4 should be greater than zero"),this.resetNextTimestamp());let be=(v.audio?v.audio.encrypted:!1)||(v.video?v.video.encrypted:!1),Se={data1:G,data2:Z,startPTS:Me,startDTS:ae,endPTS:nt,endDTS:Ee,type:M,hasAudio:P,hasVideo:D,nb:1,dropped:0,encrypted:be};y.audio=P&&!D?Se:void 0,y.video=D?Se:void 0;let ht=this.isVideoContiguous,ee=L?.sampleCount;if(ee){let J=L.keyFrameIndex,te=J!==-1;Se.nb=ee,Se.dropped=J===0||ht?0:te?J:ee,Se.independent=te,Se.firstKeyFrame=J,te&&L.keyFrameStart&&(Se.firstKeyFramePTS=(L.keyFrameStart-g.baseTime)/g.timescale),ht||(y.independent=te),this.isVideoContiguous||(this.isVideoContiguous=te),Se.dropped&&this.warn(`fmp4 does not start with IDR: firstIDR ${J}/${ee} dropped: ${Se.dropped} start: ${Se.firstKeyFramePTS||"NA"}`)}return y.initSegment=T,y.id3=Pl(s,r,g,g),i.samples.length&&(y.text=Cl(i,r,g)),y}};function Rs(n,e,t=!1){return n?.start!==void 0?(n.start+(t?n.duration:0))/n.timescale:e}function ad(n,e){let t=n,s=n;for(let i=0;i<e.length;i++){let{cts:r,duration:a}=e[i];s=Math.max(s,t+(r||0)+a),t+=a}return s}function od(n,e,t,s){if(t!==void 0){let r=n[n.length-1],a=e;for(let o=0;o<n.length-1;o++)a-=n[o].duration;return a<=0&&(a=r.duration),r.duration=a,{durationOffset:t,value:a}}if(s===void 0)return;let i=Math.round(e/n.length);for(let r=0;r<n.length;r++)n[r].duration=i;return{durationOffset:s,value:i}}function ld(n,e,t,s){if(n===null)return!0;let i=Math.max(s,1),r=e-n.baseTime/n.timescale;return Math.abs(r-t)>=i}function Wa(n,e,t){let s=n.codec;return s&&s.length>4?s:e===ue.AUDIO?s==="ec-3"||s==="ac-3"||s==="alac"?s:s==="fLaC"||s==="Opus"?Hs(s,!1):(t.warn(`Unhandled audio codec "${s}" in mp4 MAP`),s||"mp4a"):s==="mjpg"?s:(t.warn(`Unhandled video codec "${s}" in mp4 MAP`),s||"avc1")}var yt;try{yt=self.performance.now.bind(self.performance)}catch{yt=Date.now}var Bs=[{demux:Ar,remux:Cr},{demux:oi,remux:$t},{demux:vr,remux:$t},{demux:Ir,remux:$t}];Bs.splice(2,0,{demux:xr,remux:$t});var hi=class{constructor(e,t,s,i,r,a){this.asyncResult=!1,this.logger=void 0,this.observer=void 0,this.typeSupported=void 0,this.config=void 0,this.id=void 0,this.demuxer=void 0,this.remuxer=void 0,this.decrypter=void 0,this.probe=void 0,this.decryptionPromise=null,this.transmuxConfig=void 0,this.currentTransmuxState=void 0,this.observer=e,this.typeSupported=t,this.config=s,this.id=r,this.logger=a}configure(e){this.transmuxConfig=e,this.decrypter&&this.decrypter.reset()}push(e,t,s,i){if(!this.observer)return bs(s);let r=s.transmuxing;r.executeStart=yt();let a=new Uint8Array(e),{currentTransmuxState:o,transmuxConfig:l}=this;i&&(this.currentTransmuxState=i);let{contiguous:c,discontinuity:h,trackSwitch:u,accurateTimeOffset:d,timeOffset:f,initSegmentChange:g}=i||o,{audioCodec:m,videoCodec:y,defaultInitPts:E,duration:S,initSegmentData:T}=l,v=cd(a,t);if(v&&Bt(v.method)){let b=this.getDecrypter(),_=On(v.method);return this.asyncResult=!0,this.decryptionPromise=b.decrypt(a,v.key.buffer,v.iv.buffer,_,s.decryptRange).then(L=>{let P=this.push(L,null,s);return this.decryptionPromise=null,P}),this.decryptionPromise}let x=this.needsProbing(h,u);if(x){let b=s.iframe&&T&&oi.probe(T,this.logger)?T:a,_=this.configureTransmuxer(b);if(_)return this.logger.warn(`[transmuxer] ${_.message}`),this.observer.emit(p.ERROR,p.ERROR,{type:W.MEDIA_ERROR,details:R.FRAG_PARSING_ERROR,fatal:!1,error:_,reason:_.message}),r.executeEnd=yt(),bs(s)}(h||u||g||x)&&this.resetInitSegment(T,m,y,S,t,s),(h||g||x)&&this.resetInitialTimestamp(E),c||this.resetContiguity();let I=this.transmux(a,v,f,d,s);this.asyncResult=gs(I);let A=this.currentTransmuxState;return A.contiguous=!0,A.discontinuity=!1,A.trackSwitch=!1,r.executeEnd=yt(),I}flush(e){let t=e.transmuxing;t.executeStart=yt();let{decrypter:s,currentTransmuxState:i,decryptionPromise:r}=this;if(r)return this.asyncResult=!0,r.then(()=>this.flush(e));let a=[],{timeOffset:o}=i;if(s){let u=s.flush();u&&a.push(this.push(u.buffer,null,e))}let{demuxer:l,remuxer:c}=this;if(!l||!c){t.executeEnd=yt();let u=[bs(e)];return this.asyncResult?Promise.resolve(u):u}let h=l.flush(o,e);return gs(h)?(this.asyncResult=!0,h.then(u=>(this.flushRemux(a,u,e),a))):(this.flushRemux(a,h,e),this.asyncResult?Promise.resolve(a):a)}flushRemux(e,t,s){if(!this.remuxer)return;let{audioTrack:i,videoTrack:r,id3Track:a,textTrack:o}=t,{accurateTimeOffset:l,timeOffset:c}=this.currentTransmuxState;this.logger.log(`[transmuxer.ts]: Flushed ${this.id} sn: ${s.sn}${s.part>-1?" part: "+s.part:""} of ${this.id} playlist ${s.level}`);let h=this.remuxer.remux(i,r,a,o,c,l,!0,this.id,s,t.initData,t.sampleData);e.push({remuxResult:h,chunkMeta:s}),s.transmuxing.executeEnd=yt()}resetInitialTimestamp(e){let{demuxer:t,remuxer:s}=this;!t||!s||(t.resetTimeStamp(e),s.resetTimeStamp(e))}resetContiguity(){let{demuxer:e,remuxer:t}=this;!e||!t||(e.resetContiguity(),t.resetNextTimestamp())}resetInitSegment(e,t,s,i,r,a){let{demuxer:o,remuxer:l}=this;!o||!l||(o.resetInitSegment(e,t,s,i,r,a),l.resetInitSegment(e,t,s,r))}destroy(){this.demuxer&&(this.demuxer.destroy(),this.demuxer=void 0),this.remuxer&&(this.remuxer.destroy(),this.remuxer=void 0),this.observer&&this.observer.removeAllListeners(),this.decryptionPromise=null,this.decrypter=this.observer=void 0,this.logger=this.config=this.probe=void 0}transmux(e,t,s,i,r){let a;return t?.method==="SAMPLE-AES"?a=this.transmuxSampleAes(e,t,s,i,r):a=this.transmuxUnencrypted(e,s,i,r),a}transmuxUnencrypted(e,t,s,i){let{demuxer:r,remuxer:a}=this;if(!r||!a)return bs(i);let o=r.demux(e,t,i,!1,!this.config.progressive),{audioTrack:l,videoTrack:c,id3Track:h,textTrack:u}=o;return{remuxResult:a.remux(l,c,h,u,t,s,!1,this.id,i,o.initData,o.sampleData),chunkMeta:i}}transmuxSampleAes(e,t,s,i,r){return this.demuxer?this.demuxer.demuxSampleAes(e,t,s,r).then(a=>({remuxResult:this.remuxer.remux(a.audioTrack,a.videoTrack,a.id3Track,a.textTrack,s,i,!1,this.id,r,a.initData,a.sampleData),chunkMeta:r})):Promise.reject(new Error("no demuxer"))}configureTransmuxer(e){let{config:t,observer:s,typeSupported:i}=this;if(!s)return;let r;try{for(let u=0,d=Bs.length;u<d;u++){var a;if((a=Bs[u].demux)!=null&&a.probe(e,this.logger)){r=Bs[u];break}}}catch(u){return u}if(!r)return new Error("Failed to find demuxer by probing fragment data");let o=this.demuxer,l=this.remuxer,c=r.demux,h=r.remux;(!o||!(o instanceof c))&&(this.logger.log(`Using ${c.name}`),this.demuxer=new c(s,t,i,this.logger),this.probe=c.probe),(!l||!(l instanceof h))&&(this.logger.log(`Using ${h.name}`),this.remuxer=new h(s,t,i,this.logger))}needsProbing(e,t){return!this.demuxer||!this.remuxer||e||t}getDecrypter(){let e=this.decrypter;return e||(e=this.decrypter=new cs(this.config)),e}};function cd(n,e){let t=null;return n.byteLength>0&&e?.key!=null&&e.iv!==null&&e.method!=null&&(t=e),t}var bs=n=>({remuxResult:{},chunkMeta:n});function gs(n){return"then"in n&&n.then instanceof Function}var kr=class{constructor(e,t,s,i,r){this.audioCodec=void 0,this.videoCodec=void 0,this.initSegmentData=void 0,this.duration=void 0,this.defaultInitPts=void 0,this.audioCodec=e,this.videoCodec=t,this.initSegmentData=s,this.duration=i,this.defaultInitPts=r||null}},Or=class{constructor(e,t,s,i,r,a){this.discontinuity=void 0,this.contiguous=void 0,this.accurateTimeOffset=void 0,this.trackSwitch=void 0,this.timeOffset=void 0,this.initSegmentChange=void 0,this.discontinuity=e,this.contiguous=t,this.accurateTimeOffset=s,this.trackSwitch=i,this.timeOffset=r,this.initSegmentChange=a}},qa=0,ui=class{constructor(e,t,s,i){this.error=null,this.hls=void 0,this.id=void 0,this.instanceNo=qa++,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=l=>{let c=l.data,h=this.hls;if(!(!h||!(c!=null&&c.event)||c.instanceNo!==this.instanceNo))switch(c.event){case"init":{var u;let d=(u=this.workerContext)==null?void 0:u.objectURL;d&&self.URL.revokeObjectURL(d);break}case"transmuxComplete":{this.handleTransmuxComplete(c.data);break}case"flush":{this.onFlush(c.data);break}case"workerLog":{h.logger[c.data.logType]&&h.logger[c.data.logType](c.data.message);break}default:{c.data=c.data||{},c.data.frag=this.frag,c.data.part=this.part,c.data.id=this.id,h.trigger(c.event,c.data);break}}},this.onWorkerError=l=>{if(!this.hls)return;let c=new Error(`${l.message} (${l.filename}:${l.lineno})`);this.hls.config.enableWorker=!1,this.hls.logger.warn(`Error in "${this.id}" Web Worker, fallback to inline`),this.hls.trigger(p.ERROR,{type:W.OTHER_ERROR,details:R.INTERNAL_EXCEPTION,fatal:!1,event:"demuxerWorker",error:c})};let r=e.config;this.hls=e,this.id=t,this.useWorker=!!r.enableWorker,this.onTransmuxComplete=s,this.onFlush=i;let a=(l,c)=>{c=c||{},c.frag=this.frag||void 0,l===p.ERROR&&(c=c,c.parent=this.id,c.part=this.part,this.error=c.error),this.hls.trigger(l,c)};this.observer=new Mn,this.observer.on(p.FRAG_DECRYPTED,a),this.observer.on(p.ERROR,a);let o=aa(r.preferManagedMediaSource);if(this.useWorker&&typeof Worker<"u"){let l=this.hls.logger;if(r.workerPath||Ru()){try{r.workerPath?(l.log(`loading Web Worker ${r.workerPath} for "${t}"`),this.workerContext=_u(r.workerPath)):(l.log(`injecting Web Worker for "${t}"`),this.workerContext=bu());let{worker:h}=this.workerContext;h.addEventListener("message",this.onWorkerMessage),h.addEventListener("error",this.onWorkerError),h.postMessage({instanceNo:this.instanceNo,cmd:"init",typeSupported:o,id:t,config:de(r)})}catch(h){l.warn(`Error setting up "${t}" Web Worker, fallback to inline`,h),this.terminateWorker(),this.error=null,this.transmuxer=new hi(this.observer,o,r,"",t,e.logger)}return}}this.transmuxer=new hi(this.observer,o,r,"",t,e.logger)}reset(){if(this.frag=null,this.part=null,this.workerContext){let e=this.instanceNo;this.instanceNo=qa++;let t=this.hls.config,s=aa(t.preferManagedMediaSource);this.workerContext.worker.postMessage({instanceNo:this.instanceNo,cmd:"reset",resetNo:e,typeSupported:s,id:this.id,config:de(t)})}}terminateWorker(){if(this.workerContext){let{worker:e}=this.workerContext;this.workerContext=null,e.removeEventListener("message",this.onWorkerMessage),e.removeEventListener("error",this.onWorkerError),Du(this.hls.config.workerPath)}}destroy(){if(this.workerContext)this.terminateWorker(),this.onWorkerMessage=this.onWorkerError=null;else{let t=this.transmuxer;t&&(t.destroy(),this.transmuxer=null)}let e=this.observer;e&&e.removeAllListeners(),this.frag=null,this.part=null,this.observer=null,this.hls=null}push(e,t,s,i,r,a,o,l,c,h){var u,d;c.transmuxing.start=self.performance.now();let{instanceNo:f,transmuxer:g}=this,m=a?a.start:r.start,y=r.decryptdata,E=this.frag,S=E?r.cc!==E.cc:!0,T=E?c.level!==E.level:!0,v=E?c.sn-E.sn:-1,x=this.part?c.part-this.part.index:-1,I=v===0&&c.id>1&&c.id===E?.stats.chunkCount,A=!T&&(v===1||v===0&&(x===1||I&&x<=0)),b=self.performance.now();(T||v||r.stats.parsing.start===0)&&(r.stats.parsing.start=b),a&&(x||!A)&&(a.stats.parsing.start=b);let _=!(E&&((u=r.initSegment)==null?void 0:u.url)===((d=E.initSegment)==null?void 0:d.url)),L=new Or(S,A,l,T,m,_);if(!A||S||_){this.hls.logger.log(`[transmuxer-interface]: Starting new transmux session for ${r.type} sn: ${c.sn}${c.part>-1?" part: "+c.part:""} ${this.id} playlist: ${c.level} id: ${c.id}
22
+ discontinuity: ${S}
23
+ trackSwitch: ${T}
24
+ contiguous: ${A}
25
+ accurateTimeOffset: ${l}
26
+ timeOffset: ${m}
27
+ initSegmentChange: ${_}`);let P=new kr(s,i,t,o,h);this.configureTransmuxer(P)}if(this.frag=r,this.part=a,this.workerContext)this.workerContext.worker.postMessage({instanceNo:f,cmd:"demux",data:e,decryptdata:y,chunkMeta:c,state:L},e instanceof ArrayBuffer?[e]:[]);else if(g){let P=g.push(e,y,c,L);gs(P)?P.then(D=>{this.handleTransmuxComplete(D)}).catch(D=>{this.transmuxerError(D,c,"transmuxer-interface push error")}):this.handleTransmuxComplete(P)}}flush(e){e.transmuxing.start=self.performance.now();let{instanceNo:t,transmuxer:s}=this;if(this.workerContext)this.workerContext.worker.postMessage({instanceNo:t,cmd:"flush",chunkMeta:e});else if(s){let i=s.flush(e);gs(i)?i.then(r=>{this.handleFlushResult(r,e)}).catch(r=>{this.transmuxerError(r,e,"transmuxer-interface flush error")}):this.handleFlushResult(i,e)}}transmuxerError(e,t,s){this.hls&&(this.error=e,this.hls.trigger(p.ERROR,{type:W.MEDIA_ERROR,details:R.FRAG_PARSING_ERROR,chunkMeta:t,frag:this.frag||void 0,part:this.part||void 0,fatal:!1,error:e,err:e,reason:s}))}handleFlushResult(e,t){e.forEach(s=>{this.handleTransmuxComplete(s)}),this.onFlush(t)}configureTransmuxer(e){let{instanceNo:t,transmuxer:s}=this;this.workerContext?this.workerContext.worker.postMessage({instanceNo:t,cmd:"configure",config:e}):s&&s.configure(e)}handleTransmuxComplete(e){e.chunkMeta.transmuxing.end=self.performance.now(),this.onTransmuxComplete(e)}},ja=100,wr=class extends us{constructor(e,t,s){super(e,t,s,"audio-stream-controller",K.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();let{hls:e}=this;e.on(p.LEVEL_LOADED,this.onLevelLoaded,this),e.on(p.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.on(p.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(p.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(p.BUFFER_RESET,this.onBufferReset,this),e.on(p.BUFFER_CREATED,this.onBufferCreated,this),e.on(p.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(p.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(p.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(p.FRAG_LOADING,this.onFragLoading,this),e.on(p.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){let{hls:e}=this;e&&(super.unregisterListeners(),e.off(p.LEVEL_LOADED,this.onLevelLoaded,this),e.off(p.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.off(p.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(p.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(p.BUFFER_RESET,this.onBufferReset,this),e.off(p.BUFFER_CREATED,this.onBufferCreated,this),e.off(p.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(p.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(p.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(p.FRAG_LOADING,this.onFragLoading,this),e.off(p.FRAG_BUFFERED,this.onFragBuffered,this))}onInitPtsFound(e,t){let{frag:s,id:i,initPTS:r,timescale:a,trackId:o,timestampOffsets:l}=t;if(i===K.MAIN){let c=s.cc,h=this.fragCurrent;if(this.initPTS=l,this.log(`InitPTS for cc: ${c} found from main: ${r/a} (${r}/${a}) trackId: ${o}`),this.mainAnchor=s,this.state===C.WAITING_INIT_PTS){let u=this.waitingData;(!u&&!this.loadingParts||u&&u.frag.cc!==c)&&this.syncWithAnchor(s,u?.frag)}else!this.hls.hasEnoughToStart&&h&&h.cc!==c?(h.abortRequests(),this.syncWithAnchor(s,h)):this.state===C.IDLE&&this.tick()}}getLoadPosition(){var e;return!this.startFragRequested&&this.nextLoadPosition>=0&&((e=this.switchingTrack)==null?void 0:e.flushImmediate)!==!1?this.nextLoadPosition:super.getLoadPosition()}syncWithAnchor(e,t){var s;let i=((s=this.mainFragLoading)==null?void 0:s.frag)||null;if(t&&i?.cc===t.cc)return;let r=(i||e).cc,a=this.getLevelDetails(),o=this.getLoadPosition(),l=Jo(a,r,o);l&&this.fragmentTracker.getState(l)!==fe.OK&&(this.log(`Syncing with main frag at ${l.start} cc ${l.cc}`),this.startFragRequested=!1,this.nextLoadPosition=l.start,this.resetLoadingState(),this.state===C.IDLE&&this.doTickIdle())}startLoad(e,t){if(!this.levels){this.startPosition=e,this.state=C.STOPPED;return}let s=this.lastCurrentTime;this.stopLoad(),this.setInterval(ja),s>0&&e===-1&&!t&&this.initPTS.length&&(this.log(`Override startPosition with lastCurrentTime @${s.toFixed(3)}`),e=s),this.state=C.IDLE,this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,!t&&!this.fragmentTracker.hasFragments(this.playlistType)&&(this.startFragRequested=!1),this.tick()}doTick(){switch(this.state){case C.IDLE:this.doTickIdle();break;case C.WAITING_TRACK:{let{levels:e,trackId:t}=this,s=e?.[t],i=s?.details;if(i&&!this.waitForLive(s)){if(this.waitForCdnTuneIn(i))break;this.state=C.WAITING_INIT_PTS}break}case C.FRAG_LOADING_WAITING_RETRY:{this.checkRetryDate();break}case C.WAITING_INIT_PTS:{let e=this.waitingData;if(e){let{frag:t,part:s,cache:i,complete:r}=e,a=this.mainAnchor;if(this.initPTS[t.cc]!==void 0){this.waitingData=null,this.state=C.FRAG_LOADING;let o=i.flush().buffer,l={frag:t,part:s,payload:o,networkDetails:null};this._handleFragmentLoadProgress(l),r&&super._handleFragmentLoadComplete(l)}else a&&a.cc!==e.frag.cc&&this.syncWithAnchor(a,e.frag)}else this.state=C.IDLE}}this.onTickEnd()}resetLoadingState(){let e=this.waitingData;e&&(this.fragmentTracker.removeFragment(e.frag),this.waitingData=null),super.resetLoadingState()}onTickEnd(){super.onTickEnd(),this.checkFragmentChanged()}doTickIdle(){var e;let{hls:t,levels:s,media:i,trackId:r}=this,a=t.config;if(!this.buffering||!i&&!this.primaryPrefetch&&(this.startFragRequested||!a.startFragPrefetch)||!(s!=null&&s[r]))return;let o=s[r],l=o.details;if(!l||this.waitForLive(o)||this.waitForCdnTuneIn(l)){this.state=C.WAITING_TRACK,this.startFragRequested=!1;return}let c=this.getBufferOutput();this.bufferFlushed&&c&&(this.bufferFlushed=!1,this.afterBufferFlushed(c,ue.AUDIO));let h=this.getFwdBufferInfo();if(h===null)return;if(!this.switchingTrack&&this._streamEnded(h,l)){t.trigger(p.BUFFER_EOS,{type:"audio"}),this.state=C.ENDED;return}let u=h.len,d=t.maxBufferLength,f=l.fragments,g=f[0].start,m=this.getLoadPosition(),y=this.flushing||this.switchingTrack&&!this.switchingTrack.flushImmediate?m:h.end;if(this.switchingTrack&&i){let T=m;l.PTSKnown&&T<g&&T>=this.timelineOffset&&(h.end>g||h.nextStart)&&(this.log(`Alt audio track ahead of main track, seek to start of alt audio track ${T} -> ${g} + 0.05`),i.currentTime=g+.05)}if(u>=d&&!this.switchingTrack&&y<f[f.length-1].start)return;let E=this.getNextFragment(y,l);if(E&&this.isLoopLoading(E,y)&&(E=this.getNextFragmentLoopLoading(E,l,h,K.MAIN,d)),!E){this.bufferFlushed=!0;return}if(this.exceedsMaxBuffer(h,d,E))return;let S=((e=this.mainFragLoading)==null?void 0:e.frag)||null;if(!this.audioOnly&&this.startFragRequested&&S&&pe(E)&&!E.endList&&(!l.live||!this.loadingParts&&y<this.hls.liveSyncPosition)&&(this.fragmentTracker.getState(S)===fe.OK&&(this.mainFragLoading=S=null),S&&pe(S))){if(E.start>S.end){let v=this.fragmentTracker.getFragAtPos(y,K.MAIN);v&&v.end>S.end&&(S=v,this.mainFragLoading={frag:v,targetBufferTime:null})}if(E.start>S.end)return}this.loadFragment(E,o,y)}onMediaDetaching(e,t){this.bufferFlushed=this.flushing=!1,super.onMediaDetaching(e,t)}onAudioTracksUpdated(e,{audioTracks:t}){this.resetTransmuxer(),this.levels=t.map(s=>new Pt(s))}onAudioTrackSwitching(e,t){let s=!!t.url;this.trackId=t.id;let{fragCurrent:i}=this;i&&(i.abortRequests(),this.removeUnbufferedFrags(i.start)),this.resetLoadingState(),s?(this.switchingTrack=t,t.flushImmediate||(this.nextTrackId=t.id,this.nextLevelSwitch()),this.flushAudioIfNeeded(t),this.state!==C.STOPPED&&(this.setInterval(ja),this.state=C.IDLE,this.tick())):(this.resetTransmuxer(),this.switchingTrack=null,this.bufferedTrack=t,this.clearInterval())}onManifestLoading(){super.onManifestLoading(),this.bufferFlushed=this.flushing=this.audioOnly=!1,this.resetItem(),this.trackId=-1}onLevelLoaded(e,t){this.mainDetails=t.details;let s=this.cachedTrackLoadedData;s&&(this.cachedTrackLoadedData=null,this.onAudioTrackLoaded(p.AUDIO_TRACK_LOADED,s))}onAudioTrackLoaded(e,t){var s;let{levels:i}=this,{details:r,id:a,groupId:o,track:l}=t;if(!i){this.warn(`Audio tracks reset while loading track ${a} "${l.name}" of "${o}"`);return}let c=this.mainDetails;if(!c||r.endCC>c.endCC||c.expired){this.cachedTrackLoadedData=t,this.state!==C.STOPPED&&(this.state=C.WAITING_TRACK);return}this.cachedTrackLoadedData=null,this.log(`Audio track ${a} "${l.name}" of "${o}" loaded [${r.startSN},${r.endSN}]${r.lastPartSn?`[part-${r.lastPartSn}-${r.lastPartIndex}]`:""},duration:${r.totalduration}`);let h=i[a],u=0;if(r.live||(s=h.details)!=null&&s.live){if(this.checkLiveUpdate(r),r.deltaUpdateFailed)return;if(h.details){var d;u=this.alignPlaylists(r,h.details,(d=this.levelLastLoaded)==null?void 0:d.details)}r.alignedSliding||(ti(c,r,this),u=r.fragmentStart)}h.details=r,this.levelLastLoaded=h,this.startFragRequested||this.setStartPosition(c,u),this.hls.trigger(p.AUDIO_TRACK_UPDATED,{details:r,id:a,groupId:t.groupId}),this.state===C.WAITING_TRACK&&!this.waitForCdnTuneIn(r)&&(this.state=C.IDLE),this.tick()}_handleFragmentLoadProgress(e){var t;let s=e.frag,{part:i,payload:r}=e,{config:a,trackId:o,levels:l}=this;if(!l){this.warn(`Audio tracks were reset while fragment load was in progress. Fragment ${s.sn} of level ${s.level} will not be buffered`);return}let c=l[o];if(!c){this.warn("Audio track is undefined on fragment load progress");return}let h=c.details;if(!h){this.warn("Audio track details undefined on fragment load progress"),this.removeUnbufferedFrags(s.start);return}let u=a.defaultAudioCodec||c.audioCodec||"mp4a.40.2",d=this.transmuxer;d||(d=this.transmuxer=new ui(this.hls,K.AUDIO,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)));let f=this.initPTS[s.cc],g=(t=s.initSegment)==null?void 0:t.data;if(f!==void 0){let y=i?i.index:-1,E=y!==-1,S=new hs(s.level,s.sn,s.stats.chunkCount,r.byteLength,y,E,s.duration);d.push(r,g,u,"",s,i,h.totalduration,!1,S,f)}else{this.log(`Unknown video PTS for cc ${s.cc}, waiting for video PTS before demuxing audio frag ${s.sn} of [${h.startSN} ,${h.endSN}],track ${o}`);let{cache:m}=this.waitingData=this.waitingData||{frag:s,part:i,cache:new ii,complete:!1};m.push(new Uint8Array(r)),this.state!==C.STOPPED&&(this.state=C.WAITING_INIT_PTS)}}_handleFragmentLoadComplete(e){if(this.waitingData){this.waitingData.complete=!0;return}super._handleFragmentLoadComplete(e)}onBufferReset(){this.mediaBuffer=null}onBufferCreated(e,t){this.bufferFlushed=this.flushing=!1;let s=t.tracks.audio;s&&(this.mediaBuffer=s.buffer||null)}onFragLoading(e,t){!this.audioOnly&&t.frag.type===K.MAIN&&pe(t.frag)&&(this.mainFragLoading=t,this.state===C.IDLE&&this.tick())}onFragBuffered(e,t){let{frag:s,part:i}=t;if(s.type!==K.AUDIO){!this.audioOnly&&s.type===K.MAIN&&!s.elementaryStreams.video&&!s.elementaryStreams.audiovideo&&(this.audioOnly=!0,this.mainFragLoading=null);return}if(this.fragContextChanged(s)){this.warn(`Fragment ${s.sn}${i?" p: "+i.index:""} of level ${s.level} finished buffering, but was aborted. state: ${this.state}, audioSwitch: ${this.switchingTrack?this.switchingTrack.name:"false"}`);return}if(pe(s)){let r=this.switchingTrack;r&&(this.bufferedTrack=r)}this.fragBufferedComplete(s,i),this.media&&this.tick()}getFwdBufferInfo(){let e=this.getBufferOutput();return super.getFwdBufferInfo(e,K.AUDIO)}getBufferOutput(){return this.mediaBuffer?this.mediaBuffer:this.media}checkFragmentChanged(){let e=this.fragPlaying;if(!this.checkFragPlaying())return!1;let{fragPlaying:s,switchingTrack:i}=this,r=!s||s.level!==e?.level;return r&&e&&this.cleanupBackBuffer(),i&&(r||s?.level===i.id)&&this.completeAudioSwitch(i),!0}onError(e,t){var s;if(t.fatal){this.state=C.ERROR;return}switch(t.details){case R.FRAG_GAP:case R.FRAG_PARSING_ERROR:case R.FRAG_DECRYPT_ERROR:case R.FRAG_LOAD_ERROR:case R.FRAG_LOAD_TIMEOUT:case R.KEY_LOAD_ERROR:case R.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(K.AUDIO,t);break;case R.AUDIO_TRACK_LOAD_ERROR:case R.AUDIO_TRACK_LOAD_TIMEOUT:case R.LEVEL_PARSING_ERROR:!t.levelRetry&&this.state===C.WAITING_TRACK&&((s=t.context)==null?void 0:s.type)===se.AUDIO_TRACK&&(this.state=C.IDLE);break;case R.BUFFER_APPEND_NO_PROGRESS:if(t.parent!=="audio")return;t.frag&&(t.appendsWithoutProgress||0)>=this.config.appendErrorMaxRetry&&(this.warn(`Marking fragment ${t.frag.sn} of track ${t.frag.level} as a gap after ${t.appendsWithoutProgress} appends without buffered range growth, to prevent loop loading`),this.fragmentTracker.addAsGap(t.frag));break;case R.MEDIA_SOURCE_REQUIRES_RESET:this.onSourceBufferError(K.AUDIO,t);break;case R.BUFFER_ADD_CODEC_ERROR:case R.BUFFER_APPEND_ERROR:if(t.parent!=="audio")return;this.reduceLengthAndFlushBuffer(t)||this.resetLoadingState();break;case R.BUFFER_FULL_ERROR:if(t.parent!=="audio")return;this.reduceLengthAndFlushBuffer(t)&&(this.bufferedTrack=null,super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"));break;case R.INTERNAL_EXCEPTION:this.recoverWorkerError(t);break}}onBufferFlushing(e,{type:t}){t!==ue.VIDEO&&(this.flushing=!0)}onBufferFlushed(e,{type:t}){if(t!==ue.VIDEO){this.flushing=!1,this.bufferFlushed=!0,this.state===C.ENDED&&(this.state=C.IDLE);let s=this.getBufferOutput();s&&(this.afterBufferFlushed(s,t),this.tick())}}_handleTransmuxComplete(e){var t;let s="audio",{hls:i}=this,{remuxResult:r,chunkMeta:a}=e,o=this.getCurrentContext(a);if(!o){this.resetWhenMissingContext(a);return}let{frag:l,part:c,level:h}=o,{details:u}=h,{audio:d,text:f,id3:g,initSegment:m}=r;if(this.fragContextChanged(l)||!u){this.fragmentTracker.removeFragment(l),m!=null&&m.tracks&&this.resetTransmuxer();return}if(this.state=C.PARSING,d&&this.switchingTrack&&!this.switchingTrack.flushImmediate){let{config:y}=this,E=y.nextAudioTrackBufferFlushForwardOffset,S=Math.max(this.getLoadPosition()+E,(c||l).start);super.flushMainBuffer(S,Number.POSITIVE_INFINITY,K.AUDIO)}if(m!=null&&m.tracks){let y=l.initSegment||l;if(this.unhandledEncryptionError(m,l))return;this._bufferInitSegment(h,m.tracks,y,a),i.trigger(p.FRAG_PARSING_INIT_SEGMENT,{frag:y,id:s,tracks:m.tracks})}if(d){let{startPTS:y,endPTS:E,startDTS:S,endDTS:T}=d;c&&(c.elementaryStreams[ue.AUDIO]={startPTS:y,endPTS:E,startDTS:S,endDTS:T}),l.setElementaryStreamInfo(ue.AUDIO,y,E,S,T),this.bufferFragmentData(d,l,c,a)}if(g!=null&&(t=g.samples)!=null&&t.length){let y=he({id:s,frag:l,details:u},g);i.trigger(p.FRAG_PARSING_METADATA,y)}if(f){let y=he({id:s,frag:l,details:u},f);i.trigger(p.FRAG_PARSING_USERDATA,y)}}_bufferInitSegment(e,t,s,i){if(this.state!==C.PARSING||(t.video&&delete t.video,t.audiovideo&&delete t.audiovideo,!t.audio))return;let r=t.audio;r.id=K.AUDIO;let a=e.audioCodec;this.log(`Init audio buffer, container:${r.container}, codecs[level/parsed]=[${a}/${r.codec}]`),a?.split(",").length===1&&(r.levelCodec=a),this.hls.trigger(p.BUFFER_CODECS,t);let o=r.initSegment;if(o!=null&&o.byteLength){let l={type:"audio",frag:s,part:null,chunkMeta:i,parent:s.type,data:o};this.hls.trigger(p.BUFFER_APPENDING,l)}this.tickImmediate()}loadFragment(e,t,s){let i=this.fragmentTracker.getState(e);if(this.switchingTrack||i===fe.NOT_LOADED||i===fe.PARTIAL){var r;if((r=t.details)!=null&&r.live&&!this.initPTS[e.cc]){this.log(`Waiting for video PTS in continuity counter ${e.cc} of live stream before loading audio fragment ${e.sn} of level ${this.trackId}`),this.state=C.WAITING_INIT_PTS;let a=this.mainDetails;a&&a.fragmentStart!==t.details.fragmentStart&&ti(a,t.details,this)}else super.loadFragment(e,t,s)}else this.clearTrackerIfNeeded(e)}flushAudioIfNeeded(e){if(this.media&&this.bufferedTrack&&e.flushImmediate){let{name:t,lang:s,assocLang:i,characteristics:r,audioCodec:a,channels:o}=this.bufferedTrack;_t({name:t,lang:s,assocLang:i,characteristics:r,audioCodec:a,channels:o},e,bt)||(qs(e.url,this.hls)?(this.log("Switching audio track : flushing all audio"),super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"),this.bufferedTrack=null):this.bufferedTrack=e)}}completeAudioSwitch(e){let{hls:t}=this;this.bufferedTrack=e,this.switchingTrack=null,t.trigger(p.AUDIO_TRACK_SWITCHED,Y({},e))}get nextAudioTrack(){return this.nextTrackId}},ms=class extends we{constructor(e,t){super(t,e.logger),this.hls=void 0,this.canLoad=!1,this.timer=-1,this.loadingSync=!1,this.hls=e}destroy(){this.clearTimer(),this.hls=null}clearTimer(){this.timer!==-1&&(self.clearTimeout(this.timer),this.timer=-1)}startLoad(){this.canLoad=!0,this.loadPlaylist()}stopLoad(){this.canLoad=!1,this.clearTimer()}switchParams(e,t,s){let i=t?.renditionReports;if(i){let r=-1;for(let a=0;a<i.length;a++){let o=i[a],l;try{l=new self.URL(o.URI,t.url).href}catch(c){this.warn(`Could not construct new URL for Rendition Report: ${c}`),l=o.URI||""}if(l===e){r=a;break}else l===e.substring(0,l.length)&&(r=a)}if(r!==-1){let a=i[r],o=parseInt(a["LAST-MSN"])||t.lastPartSn,l=parseInt(a["LAST-PART"])||t.lastPartIndex;if(this.hls.config.lowLatencyMode){let h=Math.min(t.age-t.partTarget,t.targetduration);l>=0&&h>t.partTarget&&(l+=1)}let c=s&&oa(s);return new Ws(o,l>=0?l:void 0,c)}}}loadPlaylist(e){this.clearTimer()}loadingPlaylist(e,t){this.clearTimer()}shouldLoadPlaylist(e){return this.canLoad&&!!e&&!!e.url&&(!e.details||e.details.live)}getUrlWithDirectives(e,t){if(t)try{return t.addDirectives(e)}catch(s){this.warn(`Could not construct new URL with HLS Delivery Directives: ${s}`)}return e}playlistLoaded(e,t,s){let{details:i,stats:r}=t,a=i.fragments,o=self.performance.now(),l=r.loading.first?Math.max(0,Math.floor(o-r.loading.first)):0;i.advancedDateTime=Date.now()-l;let c=this.hls.config.timelineOffset;if(c!==i.appliedTimelineOffset){let u=Math.max(c||0,0);i.appliedTimelineOffset=u,a.forEach(d=>{d?.setStart(d.playlistOffset+u)})}if(i.live||s!=null&&s.live){var h;let u="levelInfo"in t?t.levelInfo:t.track;i.reloaded(s);let d=(h=a[a.length-1])==null?void 0:h.type;if(i.misses>=this.hls.config.liveMaxUnchangedPlaylistRefresh){let x=new Error(`${d} playlist ${u.id} hit max allowed unchanged reloads.`);this.warn(x);let{networkDetails:I,context:A}=t;this.hls.trigger(p.ERROR,{type:W.NETWORK_ERROR,details:R.PLAYLIST_UNCHANGED_ERROR,fatal:!1,url:i.url,error:x,reason:x.message,level:t.level,parent:d,context:A,networkDetails:I,stats:r});return}if(s){gu(s,i,this);let x=i.playlistParsingError;if(x){this.warn(x);let I=this.hls;if(!I.config.ignorePlaylistParsingErrors){let{networkDetails:A}=t;I.trigger(p.ERROR,{type:W.NETWORK_ERROR,details:R.LEVEL_PARSING_ERROR,fatal:!1,url:i.url,error:x,reason:x.message,level:t.level,parent:d,networkDetails:A,stats:r});return}i.playlistParsingError=null}}i.requestScheduled===-1&&(i.requestScheduled=r.loading.start);let f=this.hls.mainForwardBufferInfo,g=f?f.end-f.len:0,m=(i.edge-g)*1e3,y=fl(i,m);i.requestScheduled+y<o?i.requestScheduled=o:i.requestScheduled<=o&&(i.requestScheduled+=y);let E=t.deliveryDirectives;if(this.log(`live playlist ${e} ${i.advanced?`REFRESHED ${i.lastPartSn} - ${i.lastPartIndex}`:i.updated?"UPDATED":`MISSED (received ${i.lastPartSn} - ${i.lastPartIndex}${E?` | requested ${E.msn} - ${E.part}`:""})`}`),!this.canLoad||!i.live)return;let S,T,v;if(i.canBlockReload&&i.advanced){let x=this.hls.config.lowLatencyMode,I=i.lastPartSn,A=i.endSN,b=i.lastPartIndex,_=b!==-1,L=I===A;_?L?(T=A+1,v=x?0:b):(T=I,v=x?b+1:i.maxPartIndex):T=A+1;let P=i.age,D=P+i.ageHeader,M=Math.min(D-i.partTarget,i.targetduration*1.5);if(M>0){if(D>i.targetduration*3)this.log(`Playlist last advanced ${P.toFixed(2)}s ago. Omitting segment and part directives.`),T=void 0,v=void 0;else if(s!=null&&s.tuneInGoal&&D-i.partTarget>s.tuneInGoal)this.warn(`CDN Tune-in goal increased from: ${s.tuneInGoal} to: ${M} with playlist age: ${i.age}`),M=0;else{let U=Math.floor(M/i.targetduration);if(T+=U,v!==void 0){let B=Math.round(M%i.targetduration/i.partTarget);v+=B}this.log(`CDN Tune-in age: ${i.ageHeader}s last advanced ${P.toFixed(2)}s goal: ${M} skip sn ${U} to part ${v}`)}i.tuneInGoal=M}if(S=this.getDeliveryDirectives(i,t.deliveryDirectives,T,v),x||!L){i.requestScheduled=o,this.loadingPlaylist(u,S);return}}else(i.canBlockReload||i.canSkipUntil)&&(S=this.getDeliveryDirectives(i,t.deliveryDirectives,T,v));S&&T!==void 0&&i.canBlockReload&&(i.requestScheduled=r.loading.first+Math.max(y-l*2,y/2)),this.scheduleLoading(u,S,i)}else this.clearTimer()}scheduleLoading(e,t,s){let i=s||e.details;if(!i){this.loadingPlaylist(e,t);return}let r=self.performance.now(),a=i.requestScheduled;if(r>=a&&!this.loadingSync){this.loadingSync=!0,this.loadingPlaylist(e,t),this.loadingSync=!1;return}let o=Math.max(a-r,0);this.log(`reload live playlist ${e.name||e.bitrate+"bps"} in ${Math.round(o)} ms`),this.clearTimer(),this.timer=self.setTimeout(()=>this.loadingPlaylist(e,t),o)}getDeliveryDirectives(e,t,s,i){let r=oa(e);return t!=null&&t.skip&&e.deltaUpdateFailed&&(s=t.msn,i=t.part,r=Fs.No),new Ws(s,i,r)}checkRetry(e){let t=e.details,s=Vs(e),i=e.errorAction,{action:r,retryCount:a=0,retryConfig:o}=i||{},l=!!i&&!!o&&(r===Re.RetryRequest||!i.resolved&&r===Re.SendAlternateToPenaltyBox);if(l){var c;if(a>=o.maxNumRetry)return!1;if(s&&(c=e.context)!=null&&c.deliveryDirectives)this.warn(`Retrying playlist loading ${a+1}/${o.maxNumRetry} after "${t}" without delivery-directives`),this.loadPlaylist();else{var h;let u=is((h=e.response)==null?void 0:h.code);if(this.clearTimer(),u)this.log("Waiting for connection (offline)"),e.reason="offline",this.timer=self.setTimeout(()=>this.checkOfflineStatus(),1e3);else{let d=Rn(o,a);this.warn(`Retrying playlist loading ${a+1}/${o.maxNumRetry} after "${t}" in ${d}ms`),this.timer=self.setTimeout(()=>this.loadPlaylist(),d)}}e.levelRetry=!0,i.resolved=!0}return l}checkOfflineStatus(){this.clearTimer(),is(0)?this.timer=self.setTimeout(()=>this.checkOfflineStatus(),1e3):(this.log("Connection restored (online)"),this.loadPlaylist())}};function kl(n,e){if(n.length!==e.length)return!1;for(let t=0;t<n.length;t++)if(!ps(n[t].attrs,e[t].attrs))return!1;return!0}function ps(n,e,t){let s=n["STABLE-RENDITION-ID"];return s&&!t?s===e["STABLE-RENDITION-ID"]:!(t||["LANGUAGE","NAME","CHARACTERISTICS","AUTOSELECT","DEFAULT","FORCED","ASSOC-LANGUAGE"]).some(i=>n[i]!==e[i])}var Mr=class extends ms{constructor(e){super(e,"audio-track-controller"),this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0,this.registerListeners()}registerListeners(){let{hls:e}=this;e.on(p.MANIFEST_LOADING,this.onManifestLoading,this),e.on(p.MANIFEST_PARSED,this.onManifestParsed,this),e.on(p.LEVEL_LOADING,this.onLevelLoading,this),e.on(p.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(p.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(p.ERROR,this.onError,this)}unregisterListeners(){let{hls:e}=this;e.off(p.MANIFEST_LOADING,this.onManifestLoading,this),e.off(p.MANIFEST_PARSED,this.onManifestParsed,this),e.off(p.LEVEL_LOADING,this.onLevelLoading,this),e.off(p.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(p.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(p.ERROR,this.onError,this)}destroy(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.currentTrack=null,super.destroy()}onManifestLoading(){this.tracks=[],this.tracksInGroup=[],this.groupIds=null,this.currentTrack=null,this.trackId=-1,this.selectDefaultTrack=!0}onManifestParsed(e,t){this.tracks=t.audioTracks||[]}onAudioTrackLoaded(e,t){let{id:s,groupId:i,details:r}=t,a=this.tracksInGroup[s];if(!a||a.groupId!==i){this.warn(`Audio track with id:${s} and group:${i} not found in active group ${a?.groupId}`);return}let o=a.details;a.details=t.details,this.log(`Audio track ${s} "${a.name}" lang:${a.lang} group:${i} loaded [${r.startSN}-${r.endSN}]`),s===this.trackId&&this.playlistLoaded(s,t,o)}onLevelLoading(e,t){this.switchLevel(t.level)}onLevelSwitching(e,t){this.switchLevel(t.level)}switchLevel(e){let t=this.hls.levels[e];if(!t)return;let s=t.audioGroups||null,i=this.groupIds,r=this.currentTrack;if(!s||i?.length!==s?.length||s!=null&&s.some(o=>i?.indexOf(o)===-1)){this.groupIds=s,this.trackId=-1,this.currentTrack=null;let o=this.tracks.filter(d=>ls(d.groupId,s));if(o.length)this.selectDefaultTrack&&!o.some(d=>d.default)&&(this.selectDefaultTrack=!1),o.forEach((d,f)=>{d.id=f});else if(!r&&!this.tracksInGroup.length)return;this.tracksInGroup=o;let l=this.hls.config.audioPreference;if(!r&&l){let d=it(l,o,bt);if(d>-1)r=o[d];else{let f=it(l,this.tracks);r=this.tracks[f]}}let c=this.findTrackId(r);c===-1&&r&&(c=this.findTrackId(null));let h={audioTracks:o};this.log(`Updating audio tracks, ${o.length} track(s) found in group(s): ${s?.join(",")}`),this.hls.trigger(p.AUDIO_TRACKS_UPDATED,h);let u=this.trackId;if(c!==-1&&u===-1)this.setAudioTrack(c);else if(o.length&&u===-1){var a;let d=new Error(`No audio track selected for current audio group-ID(s): ${(a=this.groupIds)==null?void 0:a.join(",")} track count: ${o.length}`);this.warn(d.message),this.hls.trigger(p.ERROR,{type:W.MEDIA_ERROR,details:R.AUDIO_TRACK_LOAD_ERROR,fatal:!0,error:d})}}}onError(e,t){t.fatal||!t.context||t.context.type===se.AUDIO_TRACK&&t.context.id===this.trackId&&ls(t.context.groupId,this.groupIds)&&this.checkRetry(t)}get allAudioTracks(){return this.tracks}get audioTracks(){return this.tracksInGroup}get audioTrack(){return this.trackId}set audioTrack(e){this.selectDefaultTrack=!1,this.setAudioTrack(e)}get nextAudioTrack(){return this.trackId}set nextAudioTrack(e){this.selectDefaultTrack=!1,this.setAudioTrack(e,!1)}setAudioOption(e){let t=this.hls;if(t.config.audioPreference=e,e){let s=this.allAudioTracks;if(this.selectDefaultTrack=!1,s.length){let i=this.currentTrack;if(i&&_t(e,i,bt))return i;let r=it(e,this.tracksInGroup,bt);if(r>-1){let a=this.tracksInGroup[r];return this.setAudioTrack(r,"flushImmediate"in e&&e.flushImmediate),a}else if(i){let a=t.loadLevel;a===-1&&(a=t.firstAutoLevel);let o=Gh(e,t.levels,s,a,bt);if(o===-1)return null;t.nextLoadLevel=o}if(e.channels||e.audioCodec){let a=it(e,s);if(a>-1)return s[a]}}}return null}setAudioTrack(e,t=!0){let s=this.tracksInGroup;if(e<0||e>=s.length){this.warn(`Invalid audio track id: ${e}`);return}this.selectDefaultTrack=!1;let i=this.currentTrack,r=s[e],a=r.details&&!r.details.live;if(e===this.trackId&&r===i&&a||(this.log(`Switching to audio-track ${e} "${r.name}" lang:${r.lang} group:${r.groupId} channels:${r.channels}`),this.trackId=e,this.currentTrack=r,this.hls.trigger(p.AUDIO_TRACK_SWITCHING,Y(Y({},r),{},{flushImmediate:t})),a))return;let o=this.switchParams(r.url,i?.details,r.details);this.loadPlaylist(o)}findTrackId(e){let t=this.tracksInGroup;for(let s=0;s<t.length;s++){let i=t[s];if(!(this.selectDefaultTrack&&!i.default)&&(!e||_t(e,i,bt)))return s}if(e){let{name:s,lang:i,assocLang:r,characteristics:a,audioCodec:o,channels:l}=e;for(let c=0;c<t.length;c++){let h=t[c];if(_t({name:s,lang:i,assocLang:r,characteristics:a,audioCodec:o,channels:l},h,bt))return c}for(let c=0;c<t.length;c++){let h=t[c];if(ps(e.attrs,h.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return c}for(let c=0;c<t.length;c++){let h=t[c];if(ps(e.attrs,h.attrs,["LANGUAGE"]))return c}}return-1}loadPlaylist(e){super.loadPlaylist();let t=this.currentTrack;this.shouldLoadPlaylist(t)&&qs(t.url,this.hls)&&this.scheduleLoading(t,e)}loadingPlaylist(e,t){super.loadingPlaylist(e,t);let s=e.id,i=e.groupId,r=this.getUrlWithDirectives(e.url,t),a=e.details,o=a?.age;this.log(`Loading audio-track ${s} "${e.name}" lang:${e.lang} group:${i}${t?.msn!==void 0?" at sn "+t.msn+" part "+t.part:""}${o&&a.live?" age "+o.toFixed(1)+(a.type&&" "+a.type||""):""} ${r}`),this.hls.trigger(p.AUDIO_TRACK_LOADING,{url:r,id:s,groupId:i,deliveryDirectives:t||null,track:e})}},Fr=class n{constructor(e){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=e,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.media=null,this.restrictedLevels=[],this.clientRect=null,this.registerListeners()}setStreamController(e){this.streamController=e}destroy(){this.hls&&this.unregisterListener(),(this.timer||this.observer)&&this.stopCapping(),this.media=this.clientRect=this.hls=null,this.streamController=void 0}registerListeners(){let{hls:e}=this;e&&(e.on(p.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.on(p.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(p.MANIFEST_PARSED,this.onManifestParsed,this),e.on(p.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(p.BUFFER_CODECS,this.onBufferCodecs,this),e.on(p.MEDIA_DETACHING,this.onMediaDetaching,this))}unregisterListener(){let{hls:e}=this;e&&(e.off(p.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.off(p.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(p.MANIFEST_PARSED,this.onManifestParsed,this),e.off(p.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(p.BUFFER_CODECS,this.onBufferCodecs,this),e.off(p.MEDIA_DETACHING,this.onMediaDetaching,this))}onFpsDropLevelCapping(e,t){if(!this.hls)return;let s=this.hls.levels[t.droppedLevel];this.isLevelAllowed(s)&&this.restrictedLevels.push({bitrate:s.bitrate,height:s.height,width:s.width})}onMediaAttaching(e,t){let s=t.media;this.clientRect=null,this.hls&&(s instanceof HTMLVideoElement?(this.media=s,this.hls.config.capLevelToPlayerSize&&this.observe()):this.media=null,(this.timer||this.observer)&&this.hls.levels.length>1&&this.detectPlayerSize())}onManifestParsed(e,t){this.restrictedLevels=[],t.video&&this.startCapping(),this.onLevelsUpdated()}onLevelsUpdated(){if(this.hls){if((this.timer||this.observer)&&($(this.autoLevelCapping)||this.clientRect))this.detectPlayerSize();else if(this.observer===void 0&&this.timer===void 0){let e=this.hls.levels;e.length>1&&e.some(t=>!!t.videoCodec)&&this.startCapping()}}}onBufferCodecs(e,t){t.video&&this.startCapping()}onMediaDetaching(){this.stopCapping(),this.media=null}detectPlayerSize(){if(this.media){if(this.mediaHeight<=0||this.mediaWidth<=0||!this.hls){this.clientRect=null;return}let e=this.hls.levels;if(e.length>1){let t=this.hls,s=this.getMaxLevel(e.length-1);s!==this.autoLevelCapping&&t.logger.log(`Setting autoLevelCapping to ${s}: ${e[s].height}p@${e[s].bitrate} for media ${this.mediaWidth}x${this.mediaHeight}`),t.autoLevelCapping=s,t.autoLevelEnabled&&t.autoLevelCapping>this.autoLevelCapping&&this.streamController&&this.streamController.nextLevelSwitch(),this.autoLevelCapping=t.autoLevelCapping}else e.length===1&&this.stopCapping()}}getMaxLevel(e){if(!this.hls)return-1;let t=this.hls.levels;if(!t.length)return-1;let s=t.filter((i,r)=>this.isLevelAllowed(i)&&r<=e);return this.observer||(this.clientRect=null),n.getMaxLevelByMediaSize(s,this.mediaWidth,this.mediaHeight)}observe(){let e=self.ResizeObserver;e&&(this.observer=new e(t=>{var s;let i=(s=t[0])==null?void 0:s.contentRect;i&&(this.clientRect=i,this.detectPlayerSize())})),this.observer&&this.media&&this.observer.observe(this.media)}startCapping(){var e;this.timer||this.observer||!((e=this.hls)!=null&&e.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;let e=this.media,t={width:0,height:0};if(e){let s=e.getBoundingClientRect();t.width=s.width,t.height=s.height,!t.width&&!t.height&&(t.width=s.right-s.left||e.width||0,t.height=s.bottom-s.top||e.height||0)}return this.clientRect=t,t}get mediaWidth(){return this.getDimensions().width*this.contentScaleFactor}get mediaHeight(){return this.getDimensions().height*this.contentScaleFactor}get contentScaleFactor(){let e=1;if(!this.hls)return e;let{ignoreDevicePixelRatio:t,maxDevicePixelRatio:s}=this.hls.config;if(!t)try{e=self.devicePixelRatio}catch{}return Math.min(e,s)}isLevelAllowed(e){return!this.restrictedLevels.some(s=>e.bitrate===s.bitrate&&e.width===s.width&&e.height===s.height)}static getMaxLevelByMediaSize(e,t,s){if(!(e!=null&&e.length))return-1;let i=(o,l)=>l?o.width!==l.width||o.height!==l.height:!0,r=e.length-1,a=Math.max(t,s);for(let o=0;o<e.length;o+=1){let l=e[o];if((l.width>=a||l.height>=a)&&i(l,e[o+1])){r=o;break}}return r}},Ue=class Nr{constructor(e,t){Array.isArray(e)&&(e=e.map(s=>s instanceof Nr?s:new Nr(s))),this.value=e,this.params=t}},hd="Dict";function ud(n){return Array.isArray(n)?JSON.stringify(n):n instanceof Map?"Map{}":n instanceof Set?"Set{}":typeof n=="object"?JSON.stringify(n):String(n)}function dd(n,e,t,s){return new Error(`failed to ${n} "${ud(e)}" as ${t}`,{cause:s})}var za="Bare Item",fd="Boolean",gd="Byte Sequence",md="Decimal",pd="Integer";function yd(n){return n<-999999999999999||999999999999999<n}var Ed="String",Td=/[\x00-\x1f\x7f]+/,Ol=class{constructor(n){this.description=n}},Sd="Token",vd="Key";function rt(n,e,t){return dd("serialize",n,e,t)}function xd(n){if(typeof n!="boolean")throw rt(n,fd);return n?"?1":"?0"}function Id(n){if(ArrayBuffer.isView(n)===!1)throw rt(n,gd);return`:${Oc(n)}:`}function wl(n){if(yd(n))throw rt(n,pd);return n.toString()}function Ad(n){return`@${wl(n.getTime()/1e3)}`}function Ld(n){let e=Ro(n,3);if(Math.floor(Math.abs(e)).toString().length>12)throw rt(n,md);let t=e.toString();return t.includes(".")?t:`${t}.0`}function Rd(n){if(Td.test(n))throw rt(n,Ed);return`"${n.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}function bd(n){return n.description||n.toString().slice(7,-1)}function Xa(n){let e=bd(n);if(/^([a-zA-Z*])([!#$%&'*+\-.^_`|~\w:/]*)$/.test(e)===!1)throw rt(e,Sd);return e}function Br(n){switch(typeof n){case"number":if(!$(n))throw rt(n,za);return Number.isInteger(n)?wl(n):Ld(n);case"string":return Rd(n);case"symbol":return Xa(n);case"boolean":return xd(n);case"object":if(n instanceof Date)return Ad(n);if(n instanceof Uint8Array)return Id(n);if(n instanceof Ol)return Xa(n);default:throw rt(n,za)}}function $r(n){if(/^[a-z*][a-z0-9\-_.*]*$/.test(n)===!1)throw rt(n,vd);return n}function $n(n){return n==null?"":Object.entries(n).map(([e,t])=>t===!0?`;${$r(e)}`:`;${$r(e)}=${Br(t)}`).join("")}function Ml(n){return n instanceof Ue?`${Br(n.value)}${$n(n.params)}`:Br(n)}function _d(n){return`(${n.value.map(Ml).join(" ")})${$n(n.params)}`}function Dd(n,e={whitespace:!0}){if(typeof n!="object"||n==null)throw rt(n,hd);let t=n instanceof Map?n.entries():Object.entries(n),s=e!=null&&e.whitespace?" ":"";return Array.from(t).map(([i,r])=>{r instanceof Ue||(r=new Ue(r));let a=$r(i);return r.value===!0?a+=$n(r.params):(a+="=",Array.isArray(r.value)?a+=_d(r):a+=Ml(r)),a}).join(`,${s}`)}function Fl(n,e){return Dd(n,e)}var Pd=["url"],Cd=["version","eventTargets","sid","transmissionMode"],kd=["customData","headers"],Qa=n=>n instanceof Ue?new Ue(Math.round(n.value),n.params):Math.round(n),Vi=n=>Array.isArray(n)?n.map(Qa):Qa(n),Ur=(n,e)=>Array.isArray(n)?n.map(t=>Ur(t,e)):n instanceof Ue&&typeof n.value=="string"?new Ue(Ur(n.value,e),n.params):(e.baseUrl&&(n=Nc(n,Fc(e.baseUrl))),e.version===1?encodeURIComponent(n):n),Za=n=>n instanceof Ue?new Ue(Math.round(n.value/100)*100,n.params):Math.round(n/100)*100,_s=n=>Array.isArray(n)?n.map(Za):Za(n),Od=(n,e)=>{let t=n;return e.version>=2&&(n instanceof Ue&&typeof n.value=="string"?t=new Ue([n]):typeof n=="string"&&(t=[n])),Ur(t,e)},wd={br:Vi,d:Vi,bl:_s,dl:_s,mtp:_s,nor:Od,rtp:_s,tb:Vi},ys=2,Nl="bc",Md="ps",Bl="pr",Fd="e",Ja="t",Nd="c",$l="b",Un="rr",Ul="ce",Ds={BITRATE_CHANGE:Nl,ERROR:Fd,RESPONSE_RECEIVED:Un,CUSTOM_EVENT:Ul},Gl=new Map([[Md,"sta"],[Bl,"pr"],[Nd,"cid"],[$l,"bg"],[Nl,"br"]]),Gn="event",Vn="request",Vl=["cen","e","h","ts"],Kl=["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"],Bd=/^[a-zA-Z0-9-.]+-[a-zA-Z0-9-.]+$/;function Kn(n){return Bd.test(n)}var $d=new Set(Kl);function Hl(n){return $d.has(n)||Kn(n)}var Yl=["cmsdd","cmsds","rc","smrt","ttfb","ttfbb","ttlb","url"],Ud=new Set(Yl);function Wl(n){return Ud.has(n)}var Gd=new Set(Vl);function Vd(n){return Hl(n)||Wl(n)||Gd.has(n)}var Kd=new Set(["ab","bl","br","bsa","bsd","bsda","lab","lb","mtp","pb","tab","tb","tbl","tpb"]),Ai=["bl","br","bs","cid","d","dl","mtp","nor","nrr","ot","pr","rtp","sf","sid","st","su","tb","v"],Hd=new Set(Ai);function Yd(n){return Hd.has(n)||Kn(n)}var Wd=new Set(["ot","sf","st","e","sta"]);function qd(n){return Wd.has(n)}function jd(n){return typeof n=="number"?$(n):n!=null&&n!==""&&n!==!1}var zd={[Gn]:Vd,[Vn]:Hl};function ql(n,e){if(Array.isArray(n)){let t;return e&&(t=n.find(s=>{var i;return((i=s.params)==null?void 0:i.ot)===e})),t||(t=n[0]),ql(t)}return n instanceof Ue?n.value:n}function Xd(n){let e={};for(let[s,i]of Object.entries(n)){if(i==null){e[s]=i;continue}if(s==="nor"){let r=(Array.isArray(i)?i:[i])[0];if(r instanceof Ue){var t;e.nor=r.value,(t=r.params)!=null&&t.r&&(e.nrr=r.params.r)}else e.nor=r}else Kd.has(s)?e[s]=ql(i,n.ot):e[s]=i}return e}function jl(n,e={}){let t={};if(n==null||typeof n!="object")return t;let s=e.version||n.v||ys,i=e.reportingMode||Vn,r=s===1?Xd(n):n,a=s===1?Yd:zd[i],o=Object.keys(r).filter(a);r.e&&r.e!==Un&&(o=o.filter(f=>!Wl(f)));let l=e.filter;typeof l=="function"&&(o=o.filter(l));let c=i===Gn;if(c){let f=r.e;!o.includes("e")&&f!=null&&o.push("e"),o.includes("ts")||o.push("ts"),!o.includes("cen")&&r.cen!=null&&f===Ul&&o.push("cen");let g=f?Gl.get(f):void 0;g&&r[g]!=null&&!o.includes(g)&&o.push(g)}if(o.length===0)return t;s>1&&!o.includes("v")&&o.push("v");let h={version:s,reportingMode:i,baseUrl:e.baseUrl};o.sort();for(let f of o){var u,d;let g=r[f],m=(u=(d=e.formatters)==null?void 0:d[f])!=null?u:wd[f];if(typeof m=="function"&&(g=m(g,h)),f==="v"){if(s===1)continue;g=s}if(f==="pr"&&g===1&&!(c&&r.e===Bl))continue;c&&f==="ts"&&!$(g)&&(g=Date.now());let y=c&&g===!1&&f==="bg"&&r.e===$l;!jd(g)&&!y||(qd(f)&&typeof g=="string"&&(g=new Ol(g)),t[f]=g)}return t}var ot="CMCD-Object",$e="CMCD-Request",wt="CMCD-Session",qe="CMCD-Status",Qd={REQUEST:$e},Zd={ab:ot,br:ot,d:ot,lab:ot,lb:ot,ot,tab:ot,tb:ot,tpb:ot,bl:$e,cs:$e,dfa:$e,dl:$e,ltc:$e,mtp:$e,nor:$e,nrr:$e,pb:$e,sn:$e,sta:$e,su:$e,tbl:$e,cid:wt,msd:wt,sf:wt,sid:wt,st:wt,v:wt,bg:qe,bs:qe,bsa:qe,bsd:qe,bsda:qe,cdn:qe,ec:qe,nr:qe,pr:qe,pt:qe,rtp:qe};function Jd(n){return Object.keys(n).reduce((e,t)=>{var s;return(s=n[t])==null||s.forEach(i=>e[i]=t),e},{})}function ef(n,e){let t={};if(!n)return t;let s=Object.keys(n),i=e?Jd(e):{};for(let a of s){var r;let o=Zd[a]||i[a]||Qd.REQUEST,l=(r=t[o])!=null?r:t[o]={};l[a]=n[a]}return t}function tf(n,e){let t={},s=ef(n,e);for(let[i,r]of Object.entries(s)){let a=Fl(r,{whitespace:!1});a&&(t[i]=a)}return t}var eo="CMCD";function zl(n){return Fl(n,{whitespace:!1})}function sf(n,e={}){return n?zl(jl(n,e)):""}var rf=30,Gr=[...Ai,...Kl,...Yl,...Vl].filter((n,e,t)=>t.indexOf(n)===e),nf="application/cmcd",af=1,_e={MANIFEST:"m",AUDIO:"a",VIDEO:"v",MUXED:"av",INIT:"i",CAPTION:"c",TIMED_TEXT:"tt",KEY:"k",OTHER:"o"},je={STARTING:"s",PLAYING:"p",SEEKING:"k",REBUFFERING:"r",PAUSED:"a",ENDED:"e",FATAL_ERROR:"f",PRELOADING:"d"},Hn="query",Xl="headers";function to(n,e,t){var s;let i=new Set((s=e.enabledKeys)!=null?s:[]);return{version:e.version||ys,reportingMode:n,filter:r=>i.has(r),baseUrl:t}}function of(n,e){if(n===e)return!0;if(n.length!==e.length)return!1;for(let t=0;t<n.length;t++){let s=n[t],i=e[t];if(s===i)continue;if(typeof s=="number"||typeof i=="number"||s.value!==i.value)return!1;let r=s.params,a=i.params,o=r&&Object.keys(r)[0],l=a&&Object.keys(a)[0];if(o!==l||o!==void 0&&l!==void 0&&r&&a&&r[o]!==a[l])return!1}return!0}var lf=Object.is,cf=n=>n,Ql=Array.from(Gl,([n,e])=>e==="br"?{event:n,field:e,equal:(t,s)=>t===void 0||s===void 0?t===s:of(t,s),snapshot:t=>t.slice()}:{event:n,field:e,equal:lf,snapshot:cf}),hf=new Map(Ql.map(n=>[n.event,n]));function uf(n){let{url:e}=n,t=vi(n,Pd);return fetch(e,t)}function df(n){let{version:e=ys,eventTargets:t=[],sid:s=bo(),transmissionMode:i=Hn}=n,r=vi(n,Cd);return Y(Y({},r),{},{version:e,transmissionMode:i,sid:s,eventTargets:t.reduce((a,o)=>{var l,c,h;return o!=null&&o.url&&(l=o.events)!=null&&l.length&&a.push({version:o.version||ys,enabledKeys:((c=o.enabledKeys)==null?void 0:c.slice())||[],url:o.url,events:o.events.slice(),interval:(h=o.interval)!=null?h:rf,batchSize:o.batchSize||1}),a},[])})}var ff=class{constructor(n,e=uf){var t;this.timeOrigin=performance.timeOrigin||((t=performance.timing)==null?void 0:t.fetchStart)||Date.now()-performance.now(),this.data={},this.msd=NaN,this.eventTargets=new Map,this.lastEmitted={},this.requestTarget={sn:0,msdSent:!1},this.config=df(n),this.data={cid:this.config.cid,sid:this.config.sid,v:this.config.version},this.requester=e;for(let s of this.config.eventTargets)this.eventTargets.set(s,{intervalId:void 0,sn:0,msdSent:!1,queue:[]})}start(){this.eventTargets.forEach((n,e)=>{if(this.disarmInterval(n),e.interval===0||!e.events.includes(Ja))return;let t=()=>{this.recordTargetEvent(n,e,Ja),this.processEventTargets()};n.intervalId=setInterval(t,e.interval*1e3),t()})}stop(n=!1){n&&this.flush(),this.eventTargets.forEach(e=>{this.disarmInterval(e)})}flush(){this.processEventTargets(!0)}update(n){n.sid&&n.sid!==this.data.sid&&this.resetSession(),n.msd&&!isNaN(n.msd)&&(this.msd=n.msd),this.data=Y(Y(Y({},this.data),n),{},{msd:void 0});for(let e of Ql)e.field in n&&!e.equal(this.data[e.field],this.lastEmitted[e.field])&&this.recordEvent(e.event)}recordEvent(n,e={}){let t=hf.get(n);if(t){let s=t.field,i=e[s];i!==void 0&&he(this.data,{[s]:i});let r=this.data[s];if(r===void 0||t.equal(r,this.lastEmitted[s]))return;he(this.lastEmitted,{[s]:t.snapshot(r)})}this.eventTargets.forEach((s,i)=>{this.recordTargetEvent(s,i,n,e)}),this.processEventTargets()}recordTargetEvent(n,e,t,s={}){var i;if(!e.events.includes(t))return;let r=Y(Y(Y({},this.data),s),{},{e:t,ts:(i=s.ts)!=null?i:Date.now(),sn:n.sn++});!isNaN(this.msd)&&!n.msdSent&&(r.msd=this.msd,n.msdSent=!0),n.queue.push(r)}recordResponseReceived(n,e={}){var t,s,i;let{request:r}=n,a=(t=e.url)!=null?t:r?.url;if(!a)return;let o=new URL(a);o.searchParams.delete(eo);let l={url:o.toString(),rc:n.status},c=n.resourceTiming;c&&(c.startTime!=null&&(l.ts=Math.round(this.timeOrigin+c.startTime),c.responseStart!=null&&(l.ttfb=Math.round(c.responseStart-c.startTime))),c.duration!=null&&(l.ttlb=Math.round(c.duration)));let h=(s=(i=r.customData)==null?void 0:i.cmcd)!=null?s:{};this.recordEvent(Un,Y(Y(Y({},h),l),e))}applyRequestReport(n){var e;return(e=this.createRequestReport(n))!=null?e:n}isRequestReportingEnabled(){var n;return!!((n=this.config.enabledKeys)!=null&&n.length)}createRequestReport(n,e){var t;let{customData:s={},headers:i={}}=n,r=vi(n,kd),a=Y(Y({},r),{},{headers:Y({},i),customData:Y(Y({},s),{},{cmcd:{}})});if(!((t=this.config.enabledKeys)!=null&&t.length)||!a.url)return a;let o=new URL(a.url),l=Y(Y(Y({},this.data),e),{},{sn:this.requestTarget.sn++}),c=to(Vn,this.config,a.url);!isNaN(this.msd)&&!this.requestTarget.msdSent&&(l.msd=this.msd,this.requestTarget.msdSent=!0);let h=a.customData.cmcd=jl(l,c);switch(this.config.transmissionMode){case Hn:let u=zl(h);u&&(o.searchParams.set(eo,u),a.url=o.toString());break;case Xl:he(a.headers,tf(h,c.customHeaderMap));break}return a}processEventTargets(n=!1){let e=!1;this.eventTargets.forEach((t,s)=>{let{queue:i}=t;if(!i.length||i.length<s.batchSize&&!n)return;let r=n?i.length:s.batchSize,a=i.splice(0,r);this.sendEventReport(s,a).catch(()=>{t.queue.unshift(...a)}),e||(e=i.length>0)}),e&&this.processEventTargets()}async sendEventReport(n,e){let t=to(Gn,n),{status:s}=await this.requester({url:n.url,method:"POST",headers:{"Content-Type":nf},body:e.map(i=>sf(i,t)).join(`
28
+ `)+`
29
+ `});if(s===410)this.disposeEventTarget(n);else if(s===429||s>499&&s<600)throw new Error(`Event report failed with status ${s}`)}disarmInterval(n){clearInterval(n.intervalId),n.intervalId=void 0}disposeEventTarget(n){let e=this.eventTargets.get(n);e&&(this.disarmInterval(e),this.eventTargets.delete(n))}resetSession(){this.eventTargets.forEach(n=>n.sn=0),this.requestTarget.sn=0,this.lastEmitted={}}},gf={HLS:"h"},Ki={VOD:"v",LIVE:"l",LOW_LATENCY:"ll"};function mf(n,e){return new Ue(n,e)}new Set(Ai);new Set(Gr);var pf=["includeKeys"];function so(n){return Object.keys(n).every(Kn)}var Vr=class{constructor(e){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(je.REBUFFERING)),this.buffering=!0},this.onPlay=()=>{this.initialized||this.setPlayerState(je.STARTING)},this.onPlaying=()=>{this.initialized||(this.initialized=!0),this.buffering=!1,this.setPlayerState(je.PLAYING)},this.onPause=()=>{this.media&&!this.media.ended&&this.setPlayerState(je.PAUSED)},this.onSeeking=()=>{this.initialized&&this.setPlayerState(je.SEEKING)},this.onSeeked=()=>{var i;this.initialized&&(i=this.media)!=null&&i.paused&&this.setPlayerState(je.PAUSED)},this.onRateChange=()=>{this.reporter&&this.media&&this.reporter.update({pr:this.media.playbackRate})},this.applyPlaylistData=i=>{try{this.apply(i,{ot:_e.MANIFEST,su:!this.initialized})}catch(r){this.hls.logger.warn("Could not generate manifest CMCD data.",r)}},this.applyFragmentData=i=>{try{let{frag:o,part:l}=i,c=this.hls.levels[o.level],h=this.getObjectType(o,c),u={d:(l||o).duration*1e3,ot:h};if(h===_e.VIDEO||h===_e.AUDIO||h===_e.MUXED||h==null&&(o.type==="main"||o.type==="audio")){var r;let f=c.bitrate/1e3;u.br=[f];let{cmcd:g}=this.config,m=(r=g?.rtpSafetyFactor)!=null?r:5;if(u.rtp=Math.round(f*m/100)*100,h===_e.MUXED||h==null&&o.type==="main"){let S=this.getTopBandwidth()/1e3;$(S)&&(u.tb=[S]);let T=this.getLowestBandwidth()/1e3;$(T)&&(u.lb=[T])}let y=this.getBufferLength(o);if($(y)){var a;u.bl=[y];let S=((a=this.media)==null?void 0:a.playbackRate)||1;u.dl=Math.round(y/S/100)*100}this.playheadLevel&&(u.pb=[this.playheadLevel.bitrate/1e3]);let E=this.hls.maxAutoLevel;if(E>=0){let S=this.hls.levels[E];S&&(u.tpb=[S.bitrate/1e3])}}let d=l?this.getNextPart(l):this.getNextFrag(o);d!=null&&d.url&&d.url!==o.url&&(d.byteRange.length>0?u.nor=[mf(d.url,{r:`${d.byteRange[0]}-${d.byteRange[1]}`})]:u.nor=[d.url]),this.apply(i,u)}catch(o){this.hls.logger.warn("Could not generate segment CMCD data.",o)}},this.recordFragmentResponse=(i,r,a)=>{var o;let{cmcd:l}=this.config,c=l==null||(o=l.eventTargets)==null?void 0:o.some(h=>{var u;return(u=h.events)==null?void 0:u.includes(Ds.RESPONSE_RECEIVED)});if(!(!this.reporter||!(a.loading.first>0)||!c))try{this.reporter.recordResponseReceived({request:{url:i},status:r.code,resourceTiming:{startTime:a.loading.start,responseStart:a.loading.first,duration:a.loading.end-a.loading.start,encodedBodySize:a.total}})}catch(h){this.hls.logger.warn("Could not record fragment response CMCD data.",h)}},this.hls=e;let t=this.config=e.config,{cmcd:s}=t;s!=null&&(t.pLoader=this.createPlaylistLoader(),t.fLoader=this.createFragmentLoader(),this.registerListeners())}createReporter(){var e,t;let{cmcd:s}=this.config;if(s==null)return;let i=s.version||af;if(this.reporter=new ff({sid:s.sessionId||this.hls.sessionId,cid:s.contentId,version:i,transmissionMode:s.useHeaders===!0?Xl:Hn,enabledKeys:(e=s.includeKeys)!=null?e:[...i>=ys?Gr:Ai],eventTargets:((t=s.eventTargets)!=null?t:[]).map(r=>{let{includeKeys:a}=r,o=vi(r,pf);return Y(Y({},o),{},{enabledKeys:a??Gr})})},s.loader),this.reporter.update({sf:gf.HLS,sta:this.playerState}),s.reporterCallback){let r=this.reporter,a={updateCustomData:o=>{so(o)&&r.update(o)},recordCustomEvent:(o,l={})=>{so(l)&&r.recordEvent(Ds.CUSTOM_EVENT,Y({cen:o},l))}};s.reporterCallback(a)}this.reporter.start()}registerListeners(){let e=this.hls;e.on(p.MANIFEST_LOADING,this.onManifestLoading,this),e.on(p.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(p.MEDIA_DETACHED,this.onMediaDetached,this),e.on(p.MEDIA_ENDED,this.onMediaEnded,this),e.on(p.ERROR,this.onError,this),e.on(p.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(p.LEVEL_SWITCHED,this.onLevelSwitched,this),e.on(p.BUFFER_APPENDED,this.onBufferInfoChange,this),e.on(p.BUFFER_FLUSHED,this.onBufferInfoChange,this)}unregisterListeners(){let e=this.hls;e.off(p.MANIFEST_LOADING,this.onManifestLoading,this),e.off(p.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(p.MEDIA_DETACHED,this.onMediaDetached,this),e.off(p.MEDIA_ENDED,this.onMediaEnded,this),e.off(p.ERROR,this.onError,this),e.off(p.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(p.LEVEL_SWITCHED,this.onLevelSwitched,this),e.off(p.BUFFER_APPENDED,this.onBufferInfoChange,this),e.off(p.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(e,t){let s=this.media=t.media;this.setPlayerState(this.media.autoplay?je.STARTING:je.PRELOADING),ce(s,"waiting",this.onWaiting),ce(s,"play",this.onPlay),ce(s,"playing",this.onPlaying),ce(s,"pause",this.onPause),ce(s,"seeking",this.onSeeking),ce(s,"seeked",this.onSeeked),ce(s,"ratechange",this.onRateChange)}onMediaDetached(){let e=this.media;e&&(le(e,"waiting",this.onWaiting),le(e,"play",this.onPlay),le(e,"playing",this.onPlaying),le(e,"pause",this.onPause),le(e,"seeking",this.onSeeking),le(e,"seeked",this.onSeeked),le(e,"ratechange",this.onRateChange),this.media=null)}onMediaEnded(e,t){this.setPlayerState(je.ENDED)}onManifestLoading(e,t){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(je.PRELOADING)}onError(e,t){t.fatal&&(this.setPlayerState(je.FATAL_ERROR),this.reporter&&this.reporter.recordEvent(Ds.ERROR,{ec:[t.details]}))}onLevelSwitching(e,t){var s;if(!this.reporter)return;let i={br:[t.bitrate/1e3]},r=(s=t.details)==null?void 0:s.fragments[0];r&&(i.ot=this.getObjectType(r,t)),this.reporter.recordEvent(Ds.BITRATE_CHANGE,i)}onLevelSwitched(e,t){let s=this.hls.levels[t.level];s&&(this.playheadLevel=s)}setPlayerState(e){this.playerState=e,this.reporter&&this.reporter.update({sta:e})}getStreamType(){let e=this.hls.latestLevelDetails;if(e)return e.live?e.partList&&e.canBlockReload?Ki.LOW_LATENCY:Ki.LIVE:Ki.VOD}apply(e,t={}){var s;if(!this.reporter)return;this.reporter.update({mtp:[this.hls.bandwidthEstimate/1e3],pr:(s=this.media)==null?void 0:s.playbackRate,st:this.getStreamType()});let i=t.ot===_e.INIT||t.ot===_e.VIDEO||t.ot===_e.MUXED;this.starved&&i&&(t.bs=!0,t.su=!0,this.starved=!1),t.su==null&&(t.su=this.buffering);let r=this.reporter.createRequestReport({url:e.url,headers:e.headers},t);e.url=r.url,e.headers=r.headers}getNextFrag(e){var t;let s=(t=this.hls.levels[e.level])==null?void 0:t.details;if(s){let i=e.sn-s.startSN;return s.fragments[i+1]}}getNextPart(e){var t;let{index:s,fragment:i}=e,r=(t=this.hls.levels[i.level])==null||(t=t.details)==null?void 0:t.partList;if(r){let{sn:a}=i;for(let o=r.length-1;o>=0;o--){let l=r[o];if(l.index===s&&l.fragment.sn===a)return r[o+1]}}}getObjectType(e,t){let{type:s}=e;if(s==="subtitle")return _e.TIMED_TEXT;if(e.sn==="initSegment")return _e.INIT;if(s==="audio")return _e.AUDIO;if(s==="main"){if(e.hasStreams){let i=e.elementaryStreams;if(i.audiovideo)return _e.MUXED;if(i.video)return _e.VIDEO;if(i.audio)return _e.AUDIO}if(t){let{audioCodec:i,videoCodec:r}=t;if(!this.hls.audioTracks.length){if(i&&r)return _e.MUXED;if(i)return _e.AUDIO}if(r)return _e.VIDEO}}}getTopBandwidth(){let e=0,t=this.hls,s=t.maxAutoLevel,i=s>-1?s+1:t.levels.length;return t.levels.slice(0,i).forEach(a=>{a.bitrate>e&&(e=a.bitrate)}),e>0?e:NaN}getLowestBandwidth(){let e=1/0,t=this.hls,s=t.maxAutoLevel,i=s>-1?s+1:t.levels.length;return t.levels.slice(0,i).forEach(a=>{a.bitrate<e&&(e=a.bitrate)}),$(e)?e:NaN}getBufferLength(e){if(!this.media)return NaN;let t=e.type==="audio"?this.hls.audioForwardBufferInfo:this.hls.mainForwardBufferInfo;return t?t.len*1e3:NaN}getEventBufferLength(){if(!this.media)return NaN;let e=this.hls.mainForwardBufferInfo,t=this.hls.audioForwardBufferInfo;if(e&&t)return Math.min(e.len,t.len)*1e3;let s=e||t;return s?s.len*1e3:NaN}onBufferInfoChange(e,t){if(!this.reporter)return;let s=this.getEventBufferLength();$(s)&&this.reporter.update({bl:[s]})}createPlaylistLoader(){let{pLoader:e}=this.config,t=this.applyPlaylistData,s=e||this.config.loader;return class{constructor(r){this.loader=void 0,this.loader=new s(r)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(r,a,o){t(r),this.loader.load(r,a,o)}}}createFragmentLoader(){let{fLoader:e}=this.config,t=this.applyFragmentData,s=this.recordFragmentResponse,i=e||this.config.loader;return class{constructor(a){this.loader=void 0,this.loader=new i(a)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(a,o,l){t(a);let{onSuccess:c}=l;this.loader.load(a,o,Y(Y({},l),{},{onSuccess:(h,u,d,f)=>{c(h,u,d,f),s(a.url,h,u)}}))}}}},yf=3e5,Kr=class extends we{constructor(e){super("content-steering",e.logger),this.hls=void 0,this.loader=null,this.uri=null,this.pathwayId=".",this._pathwayPriority=null,this.timeToLoad=300,this.reloadTimer=-1,this.updated=0,this.started=!1,this.enabled=!0,this.levels=null,this.audioTracks=null,this.subtitleTracks=null,this.penalizedPathways={},this.hls=e,this.registerListeners()}registerListeners(){let e=this.hls;e.on(p.MANIFEST_LOADING,this.onManifestLoading,this),e.on(p.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(p.MANIFEST_PARSED,this.onManifestParsed,this),e.on(p.ERROR,this.onError,this)}unregisterListeners(){let e=this.hls;e&&(e.off(p.MANIFEST_LOADING,this.onManifestLoading,this),e.off(p.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(p.MANIFEST_PARSED,this.onManifestParsed,this),e.off(p.ERROR,this.onError,this))}pathways(){return(this.levels||[]).reduce((e,t)=>(e.indexOf(t.pathwayId)===-1&&e.push(t.pathwayId),e),[])}get pathwayPriority(){return this._pathwayPriority}set pathwayPriority(e){this.updatePathwayPriority(e)}startLoad(){if(this.started=!0,this.clearTimeout(),this.enabled&&this.uri){if(this.updated){let e=this.timeToLoad*1e3-(performance.now()-this.updated);if(e>0){this.scheduleRefresh(this.uri,e);return}}this.loadSteeringManifest(this.uri)}}stopLoad(){this.started=!1,this.loader&&(this.loader.destroy(),this.loader=null),this.clearTimeout()}clearTimeout(){this.reloadTimer!==-1&&(self.clearTimeout(this.reloadTimer),this.reloadTimer=-1)}destroy(){this.unregisterListeners(),this.stopLoad(),this.hls=null,this.levels=this.audioTracks=this.subtitleTracks=null}removeLevel(e){let t=this.levels;t&&(this.levels=t.filter(s=>s!==e))}onManifestLoading(){this.stopLoad(),this.enabled=!0,this.timeToLoad=300,this.updated=0,this.uri=null,this.pathwayId=".",this.levels=this.audioTracks=this.subtitleTracks=null}onManifestLoaded(e,t){let{contentSteering:s}=t;s!==null&&(this.pathwayId=s.pathwayId,this.uri=s.uri,this.started&&this.startLoad())}onManifestParsed(e,t){this.audioTracks=t.audioTracks,this.subtitleTracks=t.subtitleTracks}onError(e,t){let{errorAction:s}=t;if(s?.action===Re.SendAlternateToPenaltyBox&&s.flags&Le.MoveAllAlternatesMatchingHost){let i=this.levels,r=this._pathwayPriority,a=this.pathwayId;if(t.context){let{groupId:o,pathwayId:l,type:c}=t.context;o&&i?a=this.getPathwayForGroupId(o,c,a):l&&(a=l)}a in this.penalizedPathways||(this.penalizedPathways[a]=performance.now()),!r&&i&&(r=this.pathways()),r&&r.length>1&&(this.updatePathwayPriority(r),s.resolved=this.pathwayId!==a,!s.resolved&&(t.details!==R.BUFFER_APPEND_ERROR||t.fatal)&&this.warn(`Could not resolve ${t.details} ("${t.error.message}") with content-steering for Pathway: ${a} levels: ${i&&i.length} priorities: ${de(r)} penalized: ${de(this.penalizedPathways)}`))}}filterParsedLevels(e){this.levels=e;let t=this.getLevelsForPathway(this.pathwayId);if(t.length===0){let s=e[0].pathwayId;this.log(`No levels found in Pathway ${this.pathwayId}. Setting initial Pathway to "${s}"`),t=this.getLevelsForPathway(s),this.pathwayId=s}return t.length!==e.length&&this.log(`Found ${t.length}/${e.length} levels in Pathway "${this.pathwayId}"`),t}getLevelsForPathway(e){return this.levels===null?[]:this.levels.filter(t=>e===t.pathwayId)}updatePathwayPriority(e){this._pathwayPriority=e;let t,s=this.penalizedPathways,i=performance.now();Object.keys(s).forEach(r=>{i-s[r]>yf&&delete s[r]});for(let r=0;r<e.length;r++){let a=e[r];if(a in s)continue;if(a===this.pathwayId)return;let o=this.hls.nextLoadLevel,l=this.hls.levels[o];if(t=this.getLevelsForPathway(a),t.length>0){this.log(`Setting Pathway to "${a}"`),this.pathwayId=a,ml(t),this.hls.trigger(p.LEVELS_UPDATED,{levels:t});let c=this.hls.levels[o];l&&c&&this.levels&&(c.attrs["STABLE-VARIANT-ID"]!==l.attrs["STABLE-VARIANT-ID"]&&c.bitrate!==l.bitrate&&this.log(`Unstable Pathways change from bitrate ${l.bitrate} to ${c.bitrate}`),this.hls.nextLoadLevel=o);break}}}getPathwayForGroupId(e,t,s){let i=this.getLevelsForPathway(s).concat(this.levels||[]);for(let r=0;r<i.length;r++)if(t===se.AUDIO_TRACK&&i[r].hasAudioGroup(e)||t===se.SUBTITLE_TRACK&&i[r].hasSubtitleGroup(e))return i[r].pathwayId;return s}clonePathways(e){let t=this.levels;if(!t)return;let s={},i={};e.forEach(r=>{let{ID:a,"BASE-ID":o,"URI-REPLACEMENT":l}=r;if(t.some(h=>h.pathwayId===a))return;let c=this.getLevelsForPathway(o).map(h=>{let u=new me(h.attrs);u["PATHWAY-ID"]=a;let d=u.AUDIO&&`${u.AUDIO}_clone_${a}`,f=u.SUBTITLES&&`${u.SUBTITLES}_clone_${a}`;d&&(s[u.AUDIO]=d,u.AUDIO=d),f&&(i[u.SUBTITLES]=f,u.SUBTITLES=f);let g=Zl(h.uri,u["STABLE-VARIANT-ID"],"PER-VARIANT-URIS",l),m=new Pt({attrs:u,audioCodec:h.audioCodec,bitrate:h.bitrate,height:h.height,name:h.name,url:g,videoCodec:h.videoCodec,width:h.width});if(h.audioGroups)for(let y=1;y<h.audioGroups.length;y++)m.addGroupId("audio",`${h.audioGroups[y]}_clone_${a}`);if(h.subtitleGroups)for(let y=1;y<h.subtitleGroups.length;y++)m.addGroupId("text",`${h.subtitleGroups[y]}_clone_${a}`);return m});t.push(...c),io(this.audioTracks,s,l,a),io(this.subtitleTracks,i,l,a)})}loadSteeringManifest(e){let t=this.hls.config,s=t.loader;this.loader&&this.loader.destroy(),this.loader=new s(t);let i;try{i=new self.URL(e)}catch{this.enabled=!1,this.log(`Failed to parse Steering Manifest URI: ${e}`);return}if(i.protocol!=="data:"){let h=(this.hls.bandwidthEstimate||t.abrEwmaDefaultEstimate)|0;Tt(i,"_HLS_pathway",this.pathwayId),Tt(i,"_HLS_throughput",""+h)}let r={type:se.STEERING_MANIFEST,responseType:"json",url:i.href},a=t.steeringManifestLoadPolicy.default,o=a.errorRetry||a.timeoutRetry||{},l={loadPolicy:a,timeout:a.maxLoadTimeMs,maxRetry:o.maxNumRetry||0,retryDelay:o.retryDelayMs||0,maxRetryDelay:o.maxRetryDelayMs||0},c={onSuccess:(h,u,d,f)=>{this.log(`Loaded steering manifest: "${i}"`);let g=h.data;if(g?.VERSION!==1){this.log(`Steering VERSION ${g.VERSION} not supported!`);return}this.updated=performance.now(),this.timeToLoad=g.TTL;let{"RELOAD-URI":m,"PATHWAY-CLONES":y,"PATHWAY-PRIORITY":E}=g;if(m)try{this.uri=new self.URL(m,i).href}catch{this.enabled=!1,this.log(`Failed to parse Steering Manifest RELOAD-URI: ${m}`);return}this.scheduleRefresh(this.uri||d.url),y&&this.clonePathways(y);let S={steeringManifest:g,url:i.toString()};this.hls.trigger(p.STEERING_MANIFEST_LOADED,S),E&&this.updatePathwayPriority(E)},onError:(h,u,d,f)=>{if(this.log(`Error loading steering manifest: ${h.code} ${h.text} (${u.url})`),this.stopLoad(),h.code===410){this.enabled=!1,this.log(`Steering manifest ${u.url} no longer available`);return}let g=this.timeToLoad*1e3;if(h.code===429){let m=this.loader;if(typeof m?.getResponseHeader=="function"){let y=m.getResponseHeader("Retry-After");y&&(g=parseFloat(y)*1e3)}this.log(`Steering manifest ${u.url} rate limited`);return}this.scheduleRefresh(this.uri||u.url,g)},onTimeout:(h,u,d)=>{this.log(`Timeout loading steering manifest (${u.url})`),this.scheduleRefresh(this.uri||u.url)}};this.log(`Requesting steering manifest: ${i}`),this.loader.load(r,l,c)}scheduleRefresh(e,t=this.timeToLoad*1e3){this.clearTimeout(),this.reloadTimer=self.setTimeout(()=>{var s;let i=(s=this.hls)==null?void 0:s.media;if(i&&!i.ended){this.loadSteeringManifest(e);return}this.scheduleRefresh(e,this.timeToLoad*1e3)},t)}};function io(n,e,t,s){n&&Object.keys(e).forEach(i=>{let r=n.filter(a=>a.groupId===i).map(a=>{let o=he({},a);return o.details=void 0,o.attrs=new me(o.attrs),o.url=o.attrs.URI=Zl(a.url,a.attrs["STABLE-RENDITION-ID"],"PER-RENDITION-URIS",t),o.groupId=o.attrs["GROUP-ID"]=e[i],o.attrs["PATHWAY-ID"]=s,o});n.push(...r)})}function Zl(n,e,t,s){if(e){let{[t]:o}=s;if(o){let l=o[e];if(l)return l}}let{HOST:i,PARAMS:r}=s,a=new self.URL(n);return i&&(a.hostname=i),r&&Object.keys(r).sort().forEach(o=>{o&&Tt(a,o,r[o])}),a.href}var Hr=class{constructor(){this.status="initialized",this.requestErrors=[],this.licenseXhr=void 0,this.onmessage=void 0,this.onkeystatuseschange=void 0,this.emitter=new Mn,this.error=void 0,this.ok=void 0}get errored(){return this.error}set errored(e){this.error=e,this.emitter.eventNames().length&&this.emitter.emit("error",e)}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((e,t)=>{this.emitter.on("error",t),this.emitter.on("resolved",e)})}reset(){this.emitter.removeAllListeners();let e=this.licenseXhr;e&&(e.readyState!==XMLHttpRequest.DONE&&e.abort(),this.licenseXhr=void 0),this.onmessage=this.onkeystatuseschange=void 0}},Ve=class extends Error{constructor(e,t){super(t),this.data=void 0,e.error||(e.error=new Error(t)),this.data=e,e.err=e.error}},di=class n extends we{constructor(e){super("eme",e.logger),this.hls=void 0,this.config=void 0,this.media=null,this.mediaResolved=void 0,this.keyFormatPromise=null,this.keySystemAccessPromises={},this.sessionSetupByUri={},this.mediaKeySessions=[],this.activeKeys={},this.mediaKeys=null,this.setMediaKeysChain=n.CDMCleanupPromise||Promise.resolve(),this.onMediaEncrypted=t=>{let{initDataType:s,initData:i}=t,r=`"${t.type}" event: init data type: "${s}"`;if(this.log(r),i!==null){if(!this.keyFormatPromise){let a=Object.keys(this.keySystemAccessPromises);a.length||(a=Ht(this.config));let o=a.map(Fi).filter(l=>!!l);this.keyFormatPromise=this.getKeyFormatPromise(o)}this.keyFormatPromise.then(a=>{let o,l=Ls(a),c=this.activeLevelKeys();if(l===ge.FAIRPLAY&&s==="sinf")try{let g=Ze(new Uint8Array(i)),m=Dn(JSON.parse(g).sinf),y=Bo(m);if(!y)throw new Error("'schm' box missing or not cbcs/cenc with schi > tenc");o=new Uint8Array(y.subarray(8,24))}catch(g){this.warn(`${r} Failed to parse sinf: ${g}`);return}else if(l===ge.PLAYREADY)o=wn(new Uint8Array(i));else if(l===ge.WIDEVINE){let g=Vo(i).filter(m=>m.systemId===ol.WIDEVINE);if(g.length){var h;let m=g[0];o=(h=m.kids)!=null&&h.length?m.kids[0]:null}}let u;if(o){let g=Ie(o);for(let m=0;m<c.length;m++){let y=c[m];if(y.keyId&&(Js(o,y.keyId)||y.uri.replace(/-/g,"").indexOf(g)!==-1)){y.pssh||(y.scheme=s,y.pssh=new Uint8Array(i),y.keyId=o,Ct.setKeyIdForUri(y.uri,o)),u=this.getSessionForKey(y,"encrypted-event-key-match");break}}}if(!u){if(c.length){var d,f;return(d=c[0]).scheme||(d.scheme=s),(f=c[0]).pssh||(f.pssh=new Uint8Array(i)),this.getSessionForKey(c[0],"encrypted-event-no-match")}if(o)throw new Error(`Key ID ${Ie(o)} not encountered in playlist`);this.log(`Ignoring "${t.type}" event - could not determine keyId`)}return u}).catch(a=>this.handleError(a))}},this.onWaitingForKey=t=>{this.log(`"${t.type}" event`)},this.hls=e,this.config=e.config,this.registerListeners()}destroy(){this.onDestroying(),this.onMediaDetached();let e=this.config;e.requestMediaKeySystemAccessFunc=null,e.licenseXhrSetup=e.licenseResponseCallback=void 0,e.drmSystems=e.drmSystemOptions={},this.hls=this.config=null,this.onMediaEncrypted=this.onWaitingForKey=null}registerListeners(){let{hls:e}=this;e&&(e.on(p.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(p.MEDIA_DETACHED,this.onMediaDetached,this),e.on(p.MANIFEST_LOADING,this.onManifestLoading,this),e.on(p.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(p.DESTROYING,this.onDestroying,this))}unregisterListeners(){let{hls:e}=this;e&&(e.off(p.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(p.MEDIA_DETACHED,this.onMediaDetached,this),e.off(p.MANIFEST_LOADING,this.onManifestLoading,this),e.off(p.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(p.DESTROYING,this.onDestroying,this))}attemptKeySystemAccess(e){if(!this.hls)return Promise.reject(new Error("destroyed"));let t=this.hls.levels,s=(a,o,l)=>!!a&&l.indexOf(a)===o,i=t.map(a=>a.audioCodec).filter(s),r=t.map(a=>a.videoCodec).filter(s);return i.length+r.length===0&&r.push("avc1.42e01e"),new Promise((a,o)=>{let l=c=>{let h=c.shift();this.getMediaKeysPromise(h,i,r).then(u=>a({keySystem:h,mediaKeys:u})).catch(u=>{c.length?l(c):u instanceof Ve?o(u):o(new Ve({type:W.KEY_SYSTEM_ERROR,details:R.KEY_SYSTEM_NO_ACCESS,error:u,fatal:!0},u.message))})};l(e)})}requestMediaKeySystemAccess(e,t){let{requestMediaKeySystemAccessFunc:s}=this.config;if(typeof s!="function"){let i=`Configured requestMediaKeySystemAccess is not a function ${s}`;return ll===null&&self.location.protocol==="http:"&&(i=`navigator.requestMediaKeySystemAccess is not available over insecure protocol ${location.protocol}`),Promise.reject(new Error(i))}return s(e,t)}getMediaKeysPromise(e,t,s){var i;let r=ru(e,t,s,this.config.drmSystemOptions||{}),a=this.keySystemAccessPromises[e],o=(i=a)==null?void 0:i.keySystemAccess;if(!o){this.log(`Requesting encrypted media "${e}" key-system access with config: ${de(r)}`),o=this.requestMediaKeySystemAccess(e,r);let l=a=this.keySystemAccessPromises[e]={keySystemAccess:o};return o.catch(c=>{this.log(`Failed to obtain access to key-system "${e}": ${c}`)}),o.then(c=>{this.throwIfDestroyed(),this.log(`Access for key-system "${c.keySystem}" obtained`);let h=this.fetchServerCertificate(e);this.log(`Create media-keys for "${e}"`);let u=l.mediaKeys=c.createMediaKeys().then(d=>(this.log(`Media-keys created for "${e}"`),l.createdMediaKeys=d,h.then(f=>f?this.setMediaKeysServerCertificate(d,e,f):d)));return u.catch(d=>{this.error(`Failed to create media-keys for "${e}"}: ${d}`)}),u})}return o.then(()=>a.mediaKeys)}getMediaKeySessionContext(e,t,s,i){let{mediaKeySessions:r}=this,a=` key-session "${e}" keyId: ${Ie(s.keyId||[])} keyUri: ${s.uri} for "${i}"`;for(let c=0;c<r.length;c++){let h=r[c];if(!h.initialized&&h.createdFor.levelKey.uri===s.uri)return this.log(`Reusing${a}`),h}this.log(`Creating${a}`);let o=t.createSession(),l={keySystem:e,mediaKeys:t,mediaKeysSession:o,keyRequests:{},keyStatuses:{},createdFor:{levelKey:s,reason:i},initialized:!1};return r.push(l),l}resetMediaKeys(){var e;let t=(e=this.mediaKeySessions[0])==null?void 0:e.keySystem,s=this.keySystemAccessPromises[t];s&&(this.log("reset mediaKeys"),this.mediaKeys=null,delete s.createdMediaKeys,delete s.mediaKeys,delete this.keySystemAccessPromises[t])}updateKeySession(e,t,s){let i=e.mediaKeysSession;return this.log(`Updating key-session "${i.sessionId}" for keyId ${Ie(t.keyId||[])}
30
+ } (data length: ${s.byteLength})`),i.update(s)}getSelectedKeySystemFormats(){return Object.keys(this.keySystemAccessPromises).map(e=>({keySystem:e,hasMediaKeys:!!this.keySystemAccessPromises[e].createdMediaKeys})).filter(({hasMediaKeys:e})=>!!e).map(({keySystem:e})=>Fi(e)).filter(e=>!!e)}getKeySystemAccess(e){return this.getKeySystemSelectionPromise(e).then(({keySystem:t,mediaKeys:s})=>this.attemptSetMediaKeys(t,s))}selectKeySystem(e){return this.getKeySystemSelectionPromise(e).then(({keySystem:t})=>{let s=Fi(t);if(!s)throw new Error(`Unable to find format for key-system "${t}"`);return s})}selectKeySystemFormat(e){let t=Object.keys(e.levelkeys||{});return this.keyFormatPromise||(this.log(`Selecting key-system from fragment (sn: ${e.sn} ${e.type}: ${e.level}) key formats ${t.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(t)),this.keyFormatPromise}getKeyFormatPromise(e){let t=Ht(this.config),s=e.map(Ls).filter(i=>!!i&&t.indexOf(i)!==-1);return this.selectKeySystem(s)}loadClear(e,t,s){if(this.config.emeEnabled&&!this.getSelectedKeySystemFormats().length){if(t.length)for(let i=0,r=t.length;i<r;i++){let a=t[i];if(e.cc<=a.cc&&(!pe(e)||!pe(a)||e.sn<a.sn)||!s&&i==r-1)return this.selectKeySystemFormat(a).then(o=>{if(!this.hls)return;a.setKeyFormat(o);let l=Ls(o);if(l)return this.getKeySystemAccess([l])})}if(this.config.requireKeySystemAccessOnStart){let i=Ht(this.config);if(i.length)return this.getKeySystemAccess(i)}}return null}getKeyStatus(e){let{mediaKeySessions:t}=this;for(let s=0;s<t.length;s++){let i=Hi(e,t[s]);if(i)return i}}loadKey(e){let t=e.decryptdata,s=this.getKeyStatus(t);if(s==="internal-error"){let o=ro(s,t);return o.data.frag=e,this.error(`${o.message} (${Ie(t.keyId||[])})`),Promise.reject(o)}let i=e.type,r=this.activeKeys,a=r[i];a&&!t.matches(a.decryptdata)&&(r.previous||(r.previous=[]),r.previous.push(a),delete r[i]),r[i]||(r[i]=e);for(let o=this.mediaKeySessions.length;o--;){let l=this.mediaKeySessions[o];if(t.keyId&&l.keyStatuses[Ie(t.keyId)]==="expired")return this.renewKeySession(t,l)}return this.updateUsablePromise(t,"playlist-key",e)}renewKeySession(e,t){return this.resetMediaKeys(),this.removeSession(t).then(()=>(this.throwIfDestroyed(),this.updateUsablePromise(e,"expired")))}updateUsablePromise(e,t,s){let i=this.getSessionForKey(e,t);return i.catch(r=>this.handleError(r,s)),i.then(r=>e)}getSessionForKey(e,t){let s=this.findContextForKey(e);if(s!==void 0)return Promise.resolve(s);let i=e.uri,r=this.sessionSetupByUri[i],a;r===void 0?a=this.resolveSessionForKey(e,t):a=r.catch(()=>{}).then(()=>(this.throwIfDestroyed(),this.resolveSessionForKey(e,t))),this.sessionSetupByUri[i]=a;let o=()=>{this.sessionSetupByUri[i]===a&&delete this.sessionSetupByUri[i]};return a.then(o,o),a}findContextForKey(e){let{mediaKeySessions:t}=this;for(let s=t.length;s--;){let i=t[s];if(Hi(e,i))return i}}resolveSessionForKey(e,t){return this.getKeySystemForKeyPromise(e).then(({keySystem:s,mediaKeys:i})=>{this.throwIfDestroyed();for(let r=this.mediaKeySessions.length;r--;){let a=this.mediaKeySessions[r];if(Hi(e,a))return a;let o=this.getUsableKeyPromise(a,e,t);if(o)return o}return this.attemptSetMediaKeys(s,i).then(()=>(this.throwIfDestroyed(),this.getMediaKeySessionContext(s,i,e,t))).then(r=>{this.throwIfDestroyed();let a=e.scheme||"cenc",o=e.pssh?e.pssh.buffer:null;return this.generateRequestWithPreferredKeySession(r,e,a,o,t)})})}getUsableKeyPromise(e,t,s){let i=e.keyRequests[t.uri];if(i)return this.log(`Waiting for usable key (${s} keyId: ${Sf(t)} format: "${t.keyFormat}" URI: ${t.uri})`),i.useable.then(()=>e)}throwIfDestroyed(e="Invalid state"){if(!this.hls)throw new Error("invalid state")}handleError(e,t){if(this.hls)if(e instanceof Ve){t&&(e.data.frag=t);let s=e.data.decryptdata;this.error(`${e.message}${s?` (${Ie(s.keyId||[])})`:""}`),this.hls.trigger(p.ERROR,e.data)}else this.error(e.message),this.hls.trigger(p.ERROR,{type:W.KEY_SYSTEM_ERROR,details:R.KEY_SYSTEM_NO_KEYS,error:e,fatal:!0,reason:`${e.name}: ${e.message}`})}getKeySystemForKeyPromise(e){let t=Ls(e.keyFormat),s=t?[t]:Ht(this.config);return this.attemptKeySystemAccess(s)}getKeySystemSelectionPromise(e){if(e.length||(e=Ht(this.config)),e.length===0)throw new Ve({type:W.KEY_SYSTEM_ERROR,details:R.KEY_SYSTEM_NO_CONFIGURED_LICENSE,fatal:!0},`Missing key-system license configuration options ${de({drmSystems:this.config.drmSystems})}`);return this.attemptKeySystemAccess(e)}activeLevelKeys(){let e=this.activeKeys,t=(e.previous||[]).map(s=>s.decryptdata);return e.audio&&t.unshift(e.audio.decryptdata),e.main&&t.unshift(e.main.decryptdata),t}queueSetMediaKeys(e){let t=this.setMediaKeysChain.then(e);return this.setMediaKeysChain=t.catch(s=>{this.log(`setMediaKeys failed: ${s}`)}),t}attemptSetMediaKeys(e,t){return this.mediaKeys===t?Promise.resolve():(this.log(`Setting media-keys for "${e}"`),this.mediaKeys=t,this.queueSetMediaKeys(()=>this.media?this.media.setMediaKeys(t):new Promise((s,i)=>{this.mediaResolved=()=>{if(this.mediaResolved=void 0,!this.media)return i(new Error("Attempted to set mediaKeys without media element attached"));this.mediaKeys=t,this.media.setMediaKeys(t).then(s).catch(i)}})).then(()=>{this.log(`Media-keys set for "${e}"`)},s=>{throw this.mediaKeys===t&&(this.mediaKeys=null),s}))}filterInitData(e,t,s,i,r){var a;let o=(a=this.config.drmSystems)==null||(a=a[e.keySystem])==null?void 0:a.generateRequest;if(o)try{let c=o.call(this.hls,s,i,he({},e,{decryptdata:t,reason:r}),r);if(!c)throw new Error("Invalid response from configured generateRequest filter");t.scheme=c.initDataType?c.initDataType:"cenc";let h=c.initData?c.initData:null;return t.pssh=h?new Uint8Array(h):null,c}catch(c){var l;if(this.warn(c.message),(l=this.hls)!=null&&l.config.debug)throw c}return{initDataType:s,initData:i}}generateRequestWithPreferredKeySession(e,t,s,i,r){let a=this.getUsableKeyPromise(e,t,r);if(a)return a;let o=this.filterInitData(e,t,s,i,r);if(o&&(i=o.initData?o.initData:null,s=o.initDataType),i===null)return r.startsWith("encrypted-event")?Promise.reject(new Error(`missing initialization data for "${r}"`)):(this.log(`Skipping key-session request for "${r}" (no initData)`),Promise.resolve(e));let l=t.uri,c=new Hr;e.keyRequests[l]=c;let h=d=>{let f=e.mediaKeysSession;if(!f){let y=new Error("invalid state");c.errored=y;return}let{messageType:g,message:m}=d;c.status=g,this.log(`"${g}" message event for session "${f.sessionId}" message size: ${m.byteLength}`),g==="license-request"||g==="license-renewal"?this.renewLicense(e,t,m).catch(y=>{c.errored=y,c.hasListeners||this.handleError(y),this.removeSession(e)}):g==="license-release"?e.keySystem===ge.FAIRPLAY&&this.updateKeySession(e,t,Tr("acknowledged")).then(()=>this.removeSession(e)).catch(y=>this.handleError(y)):this.warn(`unhandled media key message type "${g}"`)};return c.onmessage=h,ce(e.mediaKeysSession,"message",h),this.generateRequest(e,t,s,i,r,!1)}generateRequest(e,t,s,i,r,a){if(a){let f=this.filterInitData(e,t,s,i,r);f&&(i=f.initData?f.initData:i,s=f.initDataType)}let o=t.uri,l=e.keyRequests[o],c=Ie(t.keyId||[]),h=f=>{let g;f.startsWith("usable")?l.resolve():f==="internal-error"||f==="output-restricted"||f==="output-downscaled"?g=ro(f,t):f==="expired"?g=new Error(`key expired (keyId: ${c})`):f==="released"?g=new Error("key released"):f==="status-pending"||this.warn(`unhandled key status change "${f}" (keyId: ${c})`),g&&(l.errored=g,l.hasListeners||this.handleError(g))},u=f=>{if(!e.mediaKeysSession){let x=new Error("invalid state");l.errored=x;return}let m=e.keyStatuses=this.getKeyStatuses(e);if(!Object.keys(m).some(x=>m[x]!=="status-pending"))return;let E=this.activeLevelKeys();for(let x=0;x<E.length;x++){let I=Ie(E[x].keyId||[]);if(m[I]==="expired"){var S;this.log(`Expired key ${de(m)} in key-session "${(S=e.mediaKeysSession)==null?void 0:S.sessionId}"`),this.renewKeySession(t,e).catch(A=>this.handleError(A));break}}let T=m[c];if(T)h(T);else{var v;e.keyStatusTimeouts||(e.keyStatusTimeouts={}),(v=e.keyStatusTimeouts)[c]||(v[c]=self.setTimeout(()=>{var I;if(!e.mediaKeysSession)return;let A=this.getKeyStatus(t);if(A&&A!=="status-pending"){var b;return this.log(`No status for keyId ${c} in key-session "${(b=e.mediaKeysSession)==null?void 0:b.sessionId}". Using session key-status ${A} from other session.`),h(A)}this.log(`key status for ${c} in key-session "${(I=e.mediaKeysSession)==null?void 0:I.sessionId}" timed out after 1000ms`),T="internal-error",h(T)},1e3)),this.log(`No status for keyId ${c} (${de(m)}).`)}};l.onkeystatuseschange=u,ce(e.mediaKeysSession,"keystatuseschange",u);let d=l.useable;return this.log(`Generating key-session request for "${r}" keyId: ${c} URI: ${o} (init data type: ${s} length: ${i.byteLength})`),l.status="started",e.initialized=!0,e.mediaKeysSession.generateRequest(s,i).then(()=>{var f;l.status="generated",this.log(`Request generated for key-session "${(f=e.mediaKeysSession)==null?void 0:f.sessionId}" keyId: ${c} URI: ${o}`)}).catch(f=>{throw this.log(`mediaKeysSession.generateRequest failed: ${f}`),new Ve({type:W.KEY_SYSTEM_ERROR,details:R.KEY_SYSTEM_NO_SESSION,error:f,decryptdata:t,fatal:!1},`Error generating key-session request: ${f}`)}).then(()=>d).catch(f=>{var g;this.log(`mediaKeysSession.generateRequest failed: ${f}`);let m=(g=f.data)==null?void 0:g.details;return(m===R.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED||m===R.KEY_SYSTEM_STATUS_INTERNAL_ERROR)&&Object.keys(e.keyStatuses).some(y=>e.keyStatuses[y]==="usable")?(this.handleError(f),e):this.removeSession(e).then(()=>{throw f})}).then(()=>e)}getKeyStatuses(e){let t={},s=e.mediaKeysSession.sessionId;return e.mediaKeysSession.keyStatuses.forEach((i,r)=>{if(typeof r=="string"&&typeof i=="object"){let l=r;r=i,i=l}let a="buffer"in r?new Uint8Array(r.buffer,r.byteOffset,r.byteLength):new Uint8Array(r);if(e.keySystem===ge.PLAYREADY&&a.length===16){let l=Ie(a);t[l]=i,nl(a)}let o=Ie(a);this.log(`key status change "${i}" for keyStatuses keyId: ${o} key-session "${s}"`),t[o]=i}),t}fetchServerCertificate(e){let t=this.config,s=t.loader,i=new s(t),r=Tf(e,t);return r?(this.log(`Fetching server certificate for "${e}"`),new Promise((a,o)=>{let l={type:se.SERVER_CERTIFICATE,responseType:"arraybuffer",url:r},c=t.certLoadPolicy.default,h={loadPolicy:c,timeout:c.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},u={onSuccess:(d,f,g,m)=>{a(d.data)},onError:(d,f,g,m)=>{o(new Ve({type:W.KEY_SYSTEM_ERROR,details:R.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:g,response:Y({url:l.url,data:void 0},d)},`"${e}" certificate request failed (${r}). Status: ${d.code} (${d.text})`))},onTimeout:(d,f,g)=>{o(new Ve({type:W.KEY_SYSTEM_ERROR,details:R.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:g,response:{url:l.url,data:void 0}},`"${e}" certificate request timed out (${r})`))},onAbort:(d,f,g)=>{o(new Error("aborted"))}};i.load(l,h,u)})):(this.log(`No Server Certificate in config.drmSystems["${e}"]`),Promise.resolve())}setMediaKeysServerCertificate(e,t,s){return new Promise((i,r)=>{e.setServerCertificate(s).then(a=>{this.log(`setServerCertificate ${a?"success":"not supported by CDM"} (${s.byteLength}) on "${t}"`),i(e)}).catch(a=>{r(new Ve({type:W.KEY_SYSTEM_ERROR,details:R.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED,error:a,fatal:!0},a.message))})})}renewLicense(e,t,s){return this.requestLicense(e,t,new Uint8Array(s)).then(i=>this.updateKeySession(e,t,new Uint8Array(i)).catch(r=>{throw new Ve({type:W.KEY_SYSTEM_ERROR,details:R.KEY_SYSTEM_SESSION_UPDATE_FAILED,decryptdata:t,error:r,fatal:!1},r.message)}))}unpackPlayReadyKeyMessage(e,t){let s=Ze(new Uint16Array(t.buffer));if(!s.includes("PlayReadyKeyMessage"))return e.setRequestHeader("Content-Type","text/xml; charset=utf-8"),t;let i=new DOMParser().parseFromString(s,"application/xml"),r=i.querySelectorAll("HttpHeader");if(r.length>0){let h;for(let u=0,d=r.length;u<d;u++){var a,o;h=r[u];let f=(a=h.querySelector("name"))==null?void 0:a.textContent,g=(o=h.querySelector("value"))==null?void 0:o.textContent;f&&g&&e.setRequestHeader(f,g)}}let l=i.querySelector("Challenge"),c=l?.textContent;if(!c)throw new Error("Cannot find <Challenge> in key message");return Tr(atob(c))}setupLicenseXHR(e,t,s,i,r){let a=this.config.licenseXhrSetup;return a?Promise.resolve().then(()=>(this.throwIfDestroyed(),a.call(this.hls,e,t,Y(Y({},s),{},{decryptdata:i}),r))).catch(o=>{if(!s.mediaKeysSession)throw o;return e.open("POST",t,!0),a.call(this.hls,e,t,Y(Y({},s),{},{decryptdata:i}),r)}).then(o=>(e.readyState||e.open("POST",t,!0),{xhr:e,licenseChallenge:o||r})):(e.open("POST",t,!0),Promise.resolve({xhr:e,licenseChallenge:r}))}requestLicense(e,t,s){return new Promise((i,r)=>{let a=Ef(e.keySystem,this.config);if(!a)return r(new Error(`no license server URL configured for key-system "${e.keySystem}"`));let o=e.keyRequests[t.uri];if(!o)return r(new Error("License emitter removed"));this.log(`Sending license request to URL: ${a}`);let l=this.config.keyLoadPolicy.default,c=new XMLHttpRequest;c.responseType="arraybuffer",c.onreadystatechange=()=>{if(!this.hls||!e.mediaKeysSession)return r(new Error("invalid state"));if(c.readyState===4)if(c.status===200){o.requestErrors=[];let h=c.response;this.log(`License received ${h instanceof ArrayBuffer?h.byteLength:h}`);let u=this.config.licenseResponseCallback;if(u)try{h=u.call(this.hls,c,a,Y(Y({},e),{},{decryptdata:t}))}catch(d){this.error(d)}i(h)}else{let h=l.errorRetry,u=h?h.maxNumRetry:0;if(o.requestErrors.push({status:c.status,message:c.statusText}),o.requestErrors.length>u||c.status>=400&&c.status<500)r(new Ve({type:W.KEY_SYSTEM_ERROR,details:R.KEY_SYSTEM_LICENSE_REQUEST_FAILED,decryptdata:t,fatal:!0,networkDetails:c,response:{url:a,data:void 0,code:c.status,text:c.statusText}},`License Request XHR failed (${a}). Status: ${c.status} (${c.statusText})`));else{let d=u-o.requestErrors.length;this.warn(`Retrying license request, ${d} attempts left`),this.requestLicense(e,t,s).then(i,r)}}},o.licenseXhr&&o.licenseXhr.readyState!==XMLHttpRequest.DONE&&o.licenseXhr.abort(),o.licenseXhr=c,this.setupLicenseXHR(c,a,e,t,s).then(({xhr:h,licenseChallenge:u})=>{e.keySystem==ge.PLAYREADY&&(u=this.unpackPlayReadyKeyMessage(h,u)),h.send(u)}).catch(r)})}onDestroying(){this.unregisterListeners(),this._clear()}onMediaAttached(e,t){if(!this.config.emeEnabled)return;let s=t.media;this.media=s,ce(s,"encrypted",this.onMediaEncrypted),ce(s,"waitingforkey",this.onWaitingForKey);let i=this.mediaResolved;i?i():this.mediaKeys=s.mediaKeys}onMediaDetached(){let e=this.media;e&&(le(e,"encrypted",this.onMediaEncrypted),le(e,"waitingforkey",this.onWaitingForKey),this.media=null,this.mediaKeys=null)}_clear(e=!1){this.keyFormatPromise=null,e||(this.keySystemAccessPromises={}),this.activeKeys={},this.sessionSetupByUri={};let t=this.mediaResolved;if(t&&t(),!this.mediaKeys&&!this.mediaKeySessions.length)return;let s=this.media,i=e&&this.config.reuseKeySessions,r=i?[]:this.mediaKeySessions.slice();i||(this.mediaKeySessions=[],Ct.clearKeyUriToKeyIdMap()),e||(this.mediaKeys=null);let a=r.length,o=s&&!e?this.queueSetMediaKeys(()=>s.setMediaKeys(null)).catch(l=>{this.log(`Could not clear media keys: ${l}`),this.hls&&this.hls.trigger(p.ERROR,{type:W.OTHER_ERROR,details:R.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR,fatal:!1,error:new Error(`Could not clear media keys: ${l}`)})}):Promise.resolve();n.CDMCleanupPromise=Promise.all(r.map(l=>this.removeSession(l)).concat(o)).catch(l=>{this.log(`Could not close sessions and clear media keys: ${l}`),this.hls&&this.hls.trigger(p.ERROR,{type:W.OTHER_ERROR,details:R.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error(`Could not close sessions and clear media keys: ${l}`)})}).then(()=>{a&&this.log("finished closing key sessions and clearing media keys")})}onManifestLoading(){var e;let t=(e=this.hls)==null||(e=e.media)==null?void 0:e.mediaKeys,s=!!t&&Object.keys(this.keySystemAccessPromises).some(i=>{var r;return i!==ge.FAIRPLAY&&((r=this.keySystemAccessPromises[i])==null?void 0:r.createdMediaKeys)===t});this._clear(s),this.keyFormatPromise=null}onManifestLoaded(e,{sessionKeys:t}){if(!(!t||!this.config.emeEnabled)&&!this.keyFormatPromise){let s=t.reduce((i,r)=>(i.indexOf(r.keyFormat)===-1&&i.push(r.keyFormat),i),[]);this.log(`Selecting key-system from session-keys ${s.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(s),this.keyFormatPromise.catch(()=>{})}}removeSession(e){let{mediaKeysSession:t}=e;if(t){this.log(`Remove licenses and keys and close session "${t.sessionId}"`),Object.keys(e.keyRequests).forEach(o=>{let l=e.keyRequests[o];l.onmessage&&t.removeEventListener("message",l.onmessage),l.onkeystatuseschange&&t.removeEventListener("keystatuseschange",l.onkeystatuseschange),l.reset(),e.keyRequests[o]=void 0}),e.mediaKeysSession=void 0;let s=this.mediaKeySessions.indexOf(e);s>-1&&this.mediaKeySessions.splice(s,1);let{keyStatusTimeouts:i}=e;i&&Object.keys(i).forEach(o=>self.clearTimeout(i[o]));let{drmSystemOptions:r}=this.config;return(au(r)?new Promise((o,l)=>{self.setTimeout(()=>l(new Error("MediaKeySession.remove() timeout")),8e3),t.remove().then(o).catch(l)}):Promise.resolve()).catch(o=>{this.log(`Could not remove session: ${o}`),this.hls&&this.hls.trigger(p.ERROR,{type:W.OTHER_ERROR,details:R.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR,fatal:!1,error:new Error(`Could not remove session: ${o}`)})}).then(()=>t.close()).then(()=>t.closed).catch(o=>{this.log(`Could not close session: ${o}`),this.hls&&this.hls.trigger(p.ERROR,{type:W.OTHER_ERROR,details:R.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error(`Could not close session: ${o}`)})})}return Promise.resolve()}};di.CDMCleanupPromise=void 0;function Ef(n,e){let{drmSystems:t,widevineLicenseUrl:s}=e,i=t?.[n];if(i)return i.licenseUrl;if(n===ge.WIDEVINE&&s)return s}function Tf(n,e){let{drmSystems:t}=e,s=t?.[n];if(s)return s.serverCertificateUrl}function Sf(n){if(n.keyFormat===De.FAIRPLAY)return n.uri;if(n.keyId===null)throw new Error("keyId is null");return Ie(n.keyId)}function Hi(n,e){let t=n.keyId,s=e.mediaKeysSession;if(t&&s){let i=e.mediaKeysSession.keyStatuses;if(i.size)return i.has(t)?i.get(t):e.keyStatuses[Ie(t)]}}function ro(n,e){let t=n==="output-restricted",s=t?R.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:R.KEY_SYSTEM_STATUS_INTERNAL_ERROR;return new Ve({type:W.KEY_SYSTEM_ERROR,details:s,fatal:!1,decryptdata:e},t?"HDCP level output restricted":`key status changed to "${n}"`)}var Yr=class{constructor(e){this.hls=void 0,this.isVideoPlaybackQualityAvailable=!1,this.timer=void 0,this.media=null,this.lastTime=void 0,this.lastDroppedFrames=0,this.lastDecodedFrames=0,this.streamController=void 0,this.hls=e,this.registerListeners()}setStreamController(e){this.streamController=e}registerListeners(){this.hls.on(p.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.on(p.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListeners(){this.hls.off(p.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.off(p.MEDIA_DETACHING,this.onMediaDetaching,this)}destroy(){this.timer&&clearInterval(this.timer),this.unregisterListeners(),this.isVideoPlaybackQualityAvailable=!1,this.media=null}onMediaAttaching(e,t){let s=this.hls.config;if(s.capLevelOnFPSDrop){let i=t.media instanceof self.HTMLVideoElement?t.media:null;this.media=i,i&&typeof i.getVideoPlaybackQuality=="function"&&(this.isVideoPlaybackQualityAvailable=!0),self.clearInterval(this.timer),this.timer=self.setInterval(this.checkFPSInterval.bind(this),s.fpsDroppedMonitoringPeriod)}}onMediaDetaching(){this.media=null}checkFPS(e,t,s){let i=performance.now();if(t){if(this.lastTime){let r=i-this.lastTime,a=s-this.lastDroppedFrames,o=t-this.lastDecodedFrames,l=1e3*a/r,c=this.hls;if(c.trigger(p.FPS_DROP,{currentDropped:a,currentDecoded:o,totalDroppedFrames:s}),l>0&&a>c.config.fpsDroppedMonitoringThreshold*o){let h=c.currentLevel;c.logger.warn("drop FPS ratio greater than max allowed value for currentLevel: "+h),h>0&&(c.autoLevelCapping===-1||c.autoLevelCapping>=h)&&(h=h-1,c.trigger(p.FPS_DROP_LEVEL_CAPPING,{level:h,droppedLevel:c.currentLevel}),c.autoLevelCapping=h,this.streamController.nextLevelSwitch())}}this.lastTime=i,this.lastDroppedFrames=s,this.lastDecodedFrames=t}}checkFPSInterval(){let e=this.media;if(e)if(this.isVideoPlaybackQualityAvailable){let t=e.getVideoPlaybackQuality();this.checkFPS(e,t.totalVideoFrames,t.droppedVideoFrames)}else this.checkFPS(e,e.webkitDecodedFrameCount,e.webkitDroppedFrameCount)}},Yn=(function(){if(ei!=null&&ei.VTTCue)return self.VTTCue;let n=["","lr","rl"],e=["start","middle","end","left","right"];function t(o,l){if(typeof l!="string"||!Array.isArray(o))return!1;let c=l.toLowerCase();return~o.indexOf(c)?c:!1}function s(o){return t(n,o)}function i(o){return t(e,o)}function r(o,...l){let c=1;for(;c<arguments.length;c++){let h=arguments[c];for(let u in h)o[u]=h[u]}return o}function a(o,l,c){let h=this,u={enumerable:!0};h.hasBeenReset=!1;let d="",f=!1,g=o,m=l,y=c,E=null,S="",T=!0,v="auto",x="start",I=50,A="middle",b=50,_="middle";Object.defineProperty(h,"id",r({},u,{get:function(){return d},set:function(L){d=""+L}})),Object.defineProperty(h,"pauseOnExit",r({},u,{get:function(){return f},set:function(L){f=!!L}})),Object.defineProperty(h,"startTime",r({},u,{get:function(){return g},set:function(L){if(typeof L!="number")throw new TypeError("Start time must be set to a number.");g=L,this.hasBeenReset=!0}})),Object.defineProperty(h,"endTime",r({},u,{get:function(){return m},set:function(L){if(typeof L!="number")throw new TypeError("End time must be set to a number.");m=L,this.hasBeenReset=!0}})),Object.defineProperty(h,"text",r({},u,{get:function(){return y},set:function(L){y=""+L,this.hasBeenReset=!0}})),Object.defineProperty(h,"region",r({},u,{get:function(){return E},set:function(L){E=L,this.hasBeenReset=!0}})),Object.defineProperty(h,"vertical",r({},u,{get:function(){return S},set:function(L){let P=s(L);if(P===!1)throw new SyntaxError("An invalid or illegal string was specified.");S=P,this.hasBeenReset=!0}})),Object.defineProperty(h,"snapToLines",r({},u,{get:function(){return T},set:function(L){T=!!L,this.hasBeenReset=!0}})),Object.defineProperty(h,"line",r({},u,{get:function(){return v},set:function(L){if(typeof L!="number"&&L!=="auto")throw new SyntaxError("An invalid number or illegal string was specified.");v=L,this.hasBeenReset=!0}})),Object.defineProperty(h,"lineAlign",r({},u,{get:function(){return x},set:function(L){let P=i(L);if(!P)throw new SyntaxError("An invalid or illegal string was specified.");x=P,this.hasBeenReset=!0}})),Object.defineProperty(h,"position",r({},u,{get:function(){return I},set:function(L){if(L<0||L>100)throw new Error("Position must be between 0 and 100.");I=L,this.hasBeenReset=!0}})),Object.defineProperty(h,"positionAlign",r({},u,{get:function(){return A},set:function(L){let P=i(L);if(!P)throw new SyntaxError("An invalid or illegal string was specified.");A=P,this.hasBeenReset=!0}})),Object.defineProperty(h,"size",r({},u,{get:function(){return b},set:function(L){if(L<0||L>100)throw new Error("Size must be between 0 and 100.");b=L,this.hasBeenReset=!0}})),Object.defineProperty(h,"align",r({},u,{get:function(){return _},set:function(L){let P=i(L);if(!P)throw new SyntaxError("An invalid or illegal string was specified.");_=P,this.hasBeenReset=!0}})),h.displayState=void 0}return a.prototype.getCueAsHTML=function(){return self.WebVTT.convertCueToDOMTree(self,this.text)},a})(),Wr=class{decode(e,t){if(!e)return"";if(typeof e!="string")throw new Error("Error - expected string data.");return decodeURIComponent(encodeURIComponent(e))}};function Jl(n){function e(s,i,r,a){return(s|0)*3600+(i|0)*60+(r|0)+parseFloat(a||0)}let t=n.match(/^(?:(\d+):)?(\d{2}):(\d{2})(\.\d+)?/);return t?parseFloat(t[2])>59?e(t[2],t[3],0,t[4]):e(t[1],t[2],t[3],t[4]):null}var qr=class{constructor(){this.values=Object.create(null)}set(e,t){!this.get(e)&&t!==""&&(this.values[e]=t)}get(e,t,s){return s?this.has(e)?this.values[e]:t[s]:this.has(e)?this.values[e]:t}has(e){return e in this.values}alt(e,t,s){for(let i=0;i<s.length;++i)if(t===s[i]){this.set(e,t);break}}integer(e,t){/^-?\d+$/.test(t)&&this.set(e,parseInt(t,10))}percent(e,t){if(/^([\d]{1,3})(\.[\d]*)?%$/.test(t)){let s=parseFloat(t);if(s>=0&&s<=100)return this.set(e,s),!0}return!1}};function ec(n,e,t,s){let i=s?n.split(s):[n];for(let r in i){if(typeof i[r]!="string")continue;let a=i[r].split(t);if(a.length!==2)continue;let o=a[0],l=a[1];e(o,l)}}var jr=new Yn(0,0,""),Ps=jr.align==="middle"?"middle":"center";function vf(n,e,t){let s=n;function i(){let o=Jl(n);if(o===null)throw new Error("Malformed timestamp: "+s);return n=n.replace(/^[^\sa-zA-Z-]+/,""),o}function r(o,l){let c=new qr;ec(o,function(d,f){let g;switch(d){case"region":for(let m=t.length-1;m>=0;m--)if(t[m].id===f){c.set(d,t[m].region);break}break;case"vertical":c.alt(d,f,["rl","lr"]);break;case"line":g=f.split(","),c.integer(d,g[0]),c.percent(d,g[0])&&c.set("snapToLines",!1),c.alt(d,g[0],["auto"]),g.length===2&&c.alt("lineAlign",g[1],["start",Ps,"end"]);break;case"position":g=f.split(","),c.percent(d,g[0]),g.length===2&&c.alt("positionAlign",g[1],["start",Ps,"end","line-left","line-right","auto"]);break;case"size":c.percent(d,f);break;case"align":c.alt(d,f,["start",Ps,"end","left","right"]);break}},/:/,/\s/),l.region=c.get("region",null),l.vertical=c.get("vertical","");let h=c.get("line","auto");h==="auto"&&jr.line===-1&&(h=-1),l.line=h,l.lineAlign=c.get("lineAlign","start"),l.snapToLines=c.get("snapToLines",!0),l.size=c.get("size",100),l.align=c.get("align",Ps);let u=c.get("position","auto");u==="auto"&&jr.position===50&&(u=l.align==="start"||l.align==="left"?0:l.align==="end"||l.align==="right"?100:50),l.position=u}function a(){n=n.replace(/^\s+/,"")}if(a(),e.startTime=i(),a(),n.slice(0,3)!=="-->")throw new Error("Malformed time stamp (time stamps must be separated by '-->'): "+s);n=n.slice(3),a(),e.endTime=i(),a(),r(n,e)}function tc(n){return n.replace(/<br(?: \/)?>/gi,`
31
+ `)}var zr=class{constructor(){this.state="INITIAL",this.buffer="",this.decoder=new Wr,this.regionList=[],this.cue=null,this.oncue=void 0,this.onparsingerror=void 0,this.onflush=void 0}parse(e){let t=this;e&&(t.buffer+=t.decoder.decode(e,{stream:!0}));function s(){let r=t.buffer,a=0;for(r=tc(r);a<r.length&&r[a]!=="\r"&&r[a]!==`
32
+ `;)++a;let o=r.slice(0,a);return r[a]==="\r"&&++a,r[a]===`
33
+ `&&++a,t.buffer=r.slice(a),o}function i(r){ec(r,function(a,o){},/:/)}try{let r="";if(t.state==="INITIAL"){if(!/\r\n|\n/.test(t.buffer))return this;r=s();let o=r.match(/^()?WEBVTT([ \t].*)?$/);if(!(o!=null&&o[0]))throw new Error("Malformed WebVTT signature.");t.state="HEADER"}let a=!1;for(;t.buffer;){if(!/\r\n|\n/.test(t.buffer))return this;switch(a?a=!1:r=s(),t.state){case"HEADER":/:/.test(r)?i(r):r||(t.state="ID");continue;case"NOTE":r||(t.state="ID");continue;case"ID":if(/^NOTE($|[ \t])/.test(r)){t.state="NOTE";break}if(!r)continue;if(t.cue=new Yn(0,0,""),t.state="CUE",r.indexOf("-->")===-1){t.cue.id=r;continue}case"CUE":if(!t.cue){t.state="BADCUE";continue}try{vf(r,t.cue,t.regionList)}catch{t.cue=null,t.state="BADCUE";continue}t.state="CUETEXT";continue;case"CUETEXT":{let o=r.indexOf("-->")!==-1;if(!r||o&&(a=!0)){t.oncue&&t.cue&&t.oncue(t.cue),t.cue=null,t.state="ID";continue}if(t.cue===null)continue;t.cue.text&&(t.cue.text+=`
34
+ `),t.cue.text+=r}continue;case"BADCUE":r||(t.state="ID")}}}catch{t.state==="CUETEXT"&&t.cue&&t.oncue&&t.oncue(t.cue),t.cue=null,t.state=t.state==="INITIAL"?"BADWEBVTT":"BADCUE"}return this}flush(){let e=this;try{if((e.cue||e.state==="HEADER")&&(e.buffer+=`
35
+
36
+ `,e.parse()),e.state==="INITIAL"||e.state==="BADWEBVTT")throw new Error("Malformed WebVTT signature.")}catch(t){e.onparsingerror&&e.onparsingerror(t)}return e.onflush&&e.onflush(),this}};function Jt(n){let e=5381,t=n.length;for(;t;)e=e*33^n.charCodeAt(--t);return(e>>>0).toString()}var xf=/\r\n|\n\r|\n|\r/g,no="Missing initPTS for VTT ",If=function(e){let t=parseInt(e.slice(-3)),s=parseInt(e.slice(-6,-4)),i=parseInt(e.slice(-9,-7)),r=e.length>9?parseInt(e.substring(0,e.indexOf(":"))):0;if(!$(t)||!$(s)||!$(i)||!$(r))throw Error(`Malformed X-TIMESTAMP-MAP: Local:${e}`);return t+=1e3*s,t+=60*1e3*i,t+=3600*1e3*r,t};function Wn(n,e,t){return Jt(n.toString())+Jt(e.toString())+Jt(t)}function Af(n,e,t,s,i,r,a){let o=new zr,l=He(new Uint8Array(n)).trim().replace(xf,`
37
+ `).split(`
38
+ `),c=[],h=e?ed(e.baseTime,e.timescale):0,u="00:00.000",d=0,f=0,g=!1,m,y=!0;o.oncue=function(E){let S=t[s],T=t.ccOffset,v=(d-h)/9e4;if(g){if(S!=null&&S.new&&(T=t.ccOffset=S.start),v){if(!e){m=new Error(no+"MPEGTS");return}T=v-t.presentationOffset}}else if(e)T=-e.baseTime/e.timescale;else{m=new Error(no+"without X-TIMESTAMP-MAP");return}let x=E.endTime-E.startTime,I=Ke((E.startTime+T-f)*9e4,i*9e4)/9e4;E.startTime=Math.max(I,0),E.endTime=Math.max(I+x,0);let A=E.text.replace(/^[ \t\r\n\f]+|[ \t\r\n\f]+$/g,"");E.text=decodeURIComponent(encodeURIComponent(A)),E.id?s&&(E.id=`hlsjscc${s}_${E.id}`):E.id=Wn(E.startTime,E.endTime,A.trim()),E.endTime>0&&c.push(E)},o.onparsingerror=function(E){m=E},o.onflush=function(){if(m){a(m);return}r(c)},l.forEach(E=>{if(y)if(E.startsWith("X-TIMESTAMP-MAP=")){y=!1,g=!0,E.slice(16).split(",").forEach(S=>{S.startsWith("LOCAL:")?u=S.slice(6):S.startsWith("MPEGTS:")&&(d=parseInt(S.slice(7)))});try{f=If(u)/1e3}catch(S){m=S}return}else E===""&&(y=!1);o.parse(E+`
39
+ `)}),o.flush()}var Xr="stpp.ttml.im1t",sc=/^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/,ic=/^(\d*(?:\.\d*)?)(h|m|s|ms|f|t)$/,Lf={left:"start",center:"center",right:"end",start:"start",end:"end"};function ao(n,e,t,s){let i=Q(new Uint8Array(n),["mdat"]);if(i.length===0){s(new Error("Could not parse IMSC1 mdat"));return}let r=i.map(o=>He(o)),a=Ju(e.baseTime,1,e.timescale);try{r.forEach(o=>t(Rf(o,a)))}catch(o){s(o)}}function Rf(n,e){let i=new DOMParser().parseFromString(n,"text/xml").getElementsByTagName("tt")[0];if(!i)throw new Error("Invalid ttml");let r={frameRate:30,subFrameRate:1,tickRate:1},a=Object.keys(r).reduce((d,f)=>(d[f]=i.getAttribute(`ttp:${f}`)||r[f],d),{}),o=(i.getAttribute("ttp:frameRateMultiplier")||"").trim().split(/\s+/).map(Number);o.length===2&&o[0]>0&&o[1]>0&&(a.frameRate=Number(a.frameRate)*o[0]/o[1]),!i.getAttribute("ttp:tickRate")&&i.getAttribute("ttp:frameRate")&&(a.tickRate=Number(a.frameRate)*Number(a.subFrameRate));let l=i.getAttribute("xml:space")!=="preserve",c=oo(Yi(i,"styling","style")),h=oo(Yi(i,"layout","region")),u=Yi(i,"body","[begin]");return[].map.call(u,d=>{let f=bf(d,l);if(!f||!d.hasAttribute("begin"))return null;let g=qi(d.getAttribute("begin"),a),m=qi(d.getAttribute("dur"),a),y=qi(d.getAttribute("end"),a);if(g===null)throw lo(d);if(y===null){if(m===null)throw lo(d);y=g+m}let E=new Yn(g-e,y-e,f);E.id=Wn(E.startTime,E.endTime,E.text);let S=h[d.getAttribute("region")],T=c[d.getAttribute("style")],v=_f(S,T,c),{textAlign:x}=v;if(x){let I=Lf[x];I&&(E.lineAlign=I),E.align=x}return he(E,v),E}).filter(d=>d!==null)}function Yi(n,e,t){let s=n.getElementsByTagName(e)[0];return s?[].slice.call(s.querySelectorAll(t)):[]}function oo(n){return n.reduce((e,t)=>{let s=t.getAttribute("xml:id");return s&&(e[s]=t),e},{})}function bf(n,e){let t=rc(n,e);return e?t.split(`
40
+ `).map(s=>s.replace(/ {2,}/g," ").trim()).join(`
41
+ `):t}function rc(n,e){return[].slice.call(n.childNodes).reduce((t,s,i)=>{var r;return s.nodeName==="br"&&i?t+`
42
+ `:(r=s.childNodes)!=null&&r.length?t+rc(s,e):t+(e?s.textContent.replace(/\s+/g," "):s.textContent)},"")}function _f(n,e,t){let s="http://www.w3.org/ns/ttml#styling",i=null,r=["displayAlign","textAlign","color","backgroundColor","fontSize","fontFamily"],a=n!=null&&n.hasAttribute("style")?n.getAttribute("style"):null;return a&&t.hasOwnProperty(a)&&(i=t[a]),r.reduce((o,l)=>{let c=Wi(e,s,l)||Wi(n,s,l)||Wi(i,s,l);return c&&(o[l]=c),o},{})}function Wi(n,e,t){return n&&n.hasAttributeNS(e,t)?n.getAttributeNS(e,t):null}function lo(n){return new Error(`Could not parse ttml timestamp ${n}`)}function qi(n,e){if(!n)return null;if(sc.test(n))return Df(n,e);let t=Jl(n);return t===null&&ic.test(n)&&(t=Pf(n,e)),t}function Df(n,e){let t=sc.exec(n),s=(t[4]|0)+(t[5]|0)/e.subFrameRate;return(t[1]|0)*3600+(t[2]|0)*60+(t[3]|0)+s/e.frameRate}function Pf(n,e){let t=ic.exec(n),s=Number(t[1]);switch(t[2]){case"h":return s*3600;case"m":return s*60;case"ms":return s/1e3;case"f":return s/e.frameRate;case"t":return s/e.tickRate}return s}function qn(n,e,t,s="",i="disabled"){let r=n.ownerDocument.createElement("track");return r.kind=e,r.label=t,s&&(r.srclang=s),r.src="data:,WEBVTT",r.track.mode=i,n.appendChild(r),r}function Cf(n){return n.forced&&Th()?"forced":n.characteristics&&/transcribes-spoken-dialog/gi.test(n.characteristics)&&/describes-music-and-sound/gi.test(n.characteristics)?"captions":"subtitles"}function Qr(n,e){let t=n.mode;if(t==="disabled"&&(n.mode="hidden"),n.cues&&!n.cues.getCueById(e.id))try{if(n.addCue(e),!n.cues.getCueById(e.id))throw new Error(`addCue is failed for: ${e}`)}catch(s){oe.debug(`[texttrack-utils]: ${s}`);try{let i=new self.TextTrackCue(e.startTime,e.endTime,e.text);i.id=e.id,n.addCue(i)}catch(i){oe.debug(`[texttrack-utils]: Legacy TextTrackCue fallback failed: ${i}`)}}t==="disabled"&&(n.mode=t)}function Zr(n,e,t,s){let i=n.mode;if(i==="disabled"&&(n.mode="hidden"),n.cues&&n.cues.length>0){let r=Of(n.cues,e,t);for(let a=0;a<r.length;a++)(!s||s(r[a]))&&n.removeCue(r[a])}i==="disabled"&&(n.mode=i)}function kf(n,e){if(e<=n[0].startTime)return 0;let t=n.length-1;if(e>n[t].endTime)return-1;let s=0,i=t,r;for(;s<=i;)if(r=Math.floor((i+s)/2),e<n[r].startTime)i=r-1;else if(e>n[r].startTime&&s<t)s=r+1;else return r;return n[s].startTime-e<e-n[i].startTime?s:i}function Of(n,e,t){let s=[],i=kf(n,e);if(i>-1)for(let r=i,a=n.length;r<a;r++){let o=n[r];if(o.startTime>=e&&o.endTime<=t)s.push(o);else if(o.startTime>t)return s}return s}var Jr=class extends ms{constructor(e){super(e,"subtitle-track-controller"),this.media=null,this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0,this.queuedDefaultTrack=-1,this.useTextTrackPolling=!1,this.subtitlePollingInterval=-1,this._subtitleDisplay=!0,this.asyncPollTrackChange=()=>this.pollTrackChange(0),this.onTextTracksChanged=()=>{if(this.useTextTrackPolling||self.clearInterval(this.subtitlePollingInterval),!this.media||!this.hls.config.renderTextTracksNatively)return;let t=-1,s=!1;if(this.currentTrack){var i;let o=(i=this.currentTrack.trackNode)==null?void 0:i.track.mode;o==="showing"?(t=this.trackId,s=!0):o==="hidden"&&(t=this.trackId)}if(!s)for(let o=0;o<this.tracksInGroup.length;o++){var r;let l=(r=this.tracksInGroup[o].trackNode)==null?void 0:r.track.mode;if(l==="showing"){t=o;break}else t<0&&l==="hidden"&&(t=o)}if(t>-1){var a;this._subtitleDisplay=((a=this.tracksInGroup[t].trackNode)==null?void 0:a.track.mode)==="showing"}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(e){this._subtitleDisplay=e,this.trackId>-1&&this.toggleTrackModes()}registerListeners(){let{hls:e}=this;e.on(p.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(p.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(p.MANIFEST_LOADING,this.onManifestLoading,this),e.on(p.MANIFEST_PARSED,this.onManifestParsed,this),e.on(p.LEVEL_LOADING,this.onLevelLoading,this),e.on(p.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(p.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(p.ERROR,this.onError,this)}unregisterListeners(){let{hls:e}=this;e.off(p.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(p.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(p.MANIFEST_LOADING,this.onManifestLoading,this),e.off(p.MANIFEST_PARSED,this.onManifestParsed,this),e.off(p.LEVEL_LOADING,this.onLevelLoading,this),e.off(p.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(p.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(p.ERROR,this.onError,this)}createTracksInGroup(){var e;if(!this.media||!this.hls.config.renderTextTracksNatively)return;this.tracksInGroup.forEach(s=>{s.trackNode||(s.trackNode=qn(this.media,Cf(s),s.name,s.lang))});let t=(e=this.currentTrack)==null||(e=e.trackNode)==null?void 0:e.track;t?.mode==="disabled"&&(t.mode=this._subtitleDisplay?"showing":"hidden")}onMediaAttached(e,t){let s=t.media;this.media=s;let i=this.trackId;this.queuedDefaultTrack>-1&&(i=this.queuedDefaultTrack,this.queuedDefaultTrack=-1),this.setSubtitleTrack(i),this.createTracksInGroup(),this.useTextTrackPolling=!(s.textTracks&&"onchange"in s.textTracks),this.useTextTrackPolling?this.pollTrackChange(500):s.textTracks.addEventListener("change",this.asyncPollTrackChange)}pollTrackChange(e){self.clearInterval(this.subtitlePollingInterval),this.subtitlePollingInterval=self.setInterval(this.onTextTracksChanged,e)}onMediaDetaching(e,t){let s=this.media;if(!s)return;let i=!!t.transferMedia;self.clearInterval(this.subtitlePollingInterval),this.useTextTrackPolling||s.textTracks.removeEventListener("change",this.asyncPollTrackChange),this.trackId>-1&&(this.queuedDefaultTrack=this.trackId,this.setSubtitleTrack(-1)),this.media=null,!i&&this.hls.config.renderTextTracksNatively&&this.tracksInGroup.forEach(r=>{let a=r.trackNode;a&&(a.track.mode="hidden",a.remove(),r.trackNode=void 0)})}onManifestLoading(){this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0}onManifestParsed(e,t){this.tracks=t.subtitleTracks}onSubtitleTrackLoaded(e,t){let{id:s,groupId:i,details:r}=t,a=this.tracksInGroup[s];if(!a||a.groupId!==i){this.warn(`Subtitle track with id:${s} and group:${i} not found in active group ${a?.groupId}`);return}let o=a.details;a.details=t.details,this.log(`Subtitle track ${s} "${a.name}" lang:${a.lang} group:${i} loaded [${r.startSN}-${r.endSN}]`),s===this.trackId&&this.playlistLoaded(s,t,o)}onLevelLoading(e,t){this.switchLevel(t.level)}onLevelSwitching(e,t){this.switchLevel(t.level)}switchLevel(e){let t=this.hls.levels[e];if(!t)return;let s=t.subtitleGroups||null,i=this.groupIds,r=this.currentTrack;if(!s||i?.length!==s?.length||s!=null&&s.some(a=>i?.indexOf(a)===-1)){this.groupIds=s;let a=[];if(this.tracks.forEach(h=>{(h.textCodec===Xr?this.hls.config.enableIMSC1:this.hls.config.enableWebVTT)&&(!s||s.indexOf(h.groupId)>-1?(h.id=a.length,a.push(h)):h.trackNode&&(h.trackNode.remove(),h.trackNode=void 0))}),a.length===this.tracksInGroup.length){let h=!1;for(let u=0;u<a.length;u++)if(a[u]!==this.tracksInGroup[u]){h=!0;break}if(!h)return}a.length&&this.selectDefaultTrack&&!a.some(h=>h.default)&&(this.selectDefaultTrack=!1),this.tracksInGroup=a,this.trackId=-1,this.currentTrack=null;let o=this.hls.config.subtitlePreference;if(!r&&o){this.selectDefaultTrack=!1;let h=it(o,a);if(h>-1)r=a[h];else{let u=it(o,this.tracks);r=this.tracks[u]}}let l=this.findTrackId(r);l===-1&&r&&(l=this.findTrackId(null));let c={subtitleTracks:a};this.log(`Updating subtitle tracks, ${a.length} track(s) found in "${s?.join(",")}" group-id`),this.hls.trigger(p.SUBTITLE_TRACKS_UPDATED,c),this.setSubtitleTrack(l),this.createTracksInGroup()}}findTrackId(e){let t=this.tracksInGroup,s=this.selectDefaultTrack;for(let i=0;i<t.length;i++){let r=t[i];if(!(s&&!r.default||!s&&!e)&&(!e||_t(r,e)))return i}if(e){for(let i=0;i<t.length;i++){let r=t[i];if(ps(e.attrs,r.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return i}for(let i=0;i<t.length;i++){let r=t[i];if(ps(e.attrs,r.attrs,["LANGUAGE"]))return i}}return-1}onError(e,t){t.fatal||!t.context||t.context.type===se.SUBTITLE_TRACK&&t.context.id===this.trackId&&ls(t.context.groupId,this.groupIds)&&this.checkRetry(t)}get allSubtitleTracks(){return this.tracks}get subtitleTracks(){return this.tracksInGroup}get subtitleTrack(){return this.trackId}set subtitleTrack(e){this.selectDefaultTrack=!1,this.setSubtitleTrack(e,!0)}setSubtitleOption(e){if(this.hls.config.subtitlePreference=e,e){if(e.id===-1)return this.setSubtitleTrack(-1,!0),null;let t=this.allSubtitleTracks;if(this.selectDefaultTrack=!1,t.length){let s=this.currentTrack;if(s&&_t(e,s))return s;let i=it(e,this.tracksInGroup);if(i>-1){let r=this.tracksInGroup[i];return this.setSubtitleTrack(i,!0),r}else{if(s)return null;{let r=it(e,t);if(r>-1)return t[r]}}}}return null}loadPlaylist(e){super.loadPlaylist(),this.shouldLoadPlaylist(this.currentTrack)&&this.scheduleLoading(this.currentTrack,e)}loadingPlaylist(e,t){super.loadingPlaylist(e,t);let s=e.id,i=e.groupId,r=this.getUrlWithDirectives(e.url,t),a=e.details,o=a?.age;this.log(`Loading subtitle ${s} "${e.name}" lang:${e.lang} group:${i}${t?.msn!==void 0?" at sn "+t.msn+" part "+t.part:""}${o&&a.live?" age "+o.toFixed(1)+(a.type&&" "+a.type||""):""} ${r}`),this.hls.trigger(p.SUBTITLE_TRACK_LOADING,{url:r,id:s,groupId:i,deliveryDirectives:t||null,track:e})}toggleTrackModes(){if(!this.media||!this.hls.config.renderTextTracksNatively)return;let e=this.currentTrack;this.tracksInGroup.forEach(t=>{if(t.trackNode){let s=t===e?this._subtitleDisplay?"showing":"hidden":"disabled",i=t.trackNode.track;i.mode!==s&&(i.mode=s)}})}setSubtitleTrack(e,t=!1){let s=this.tracksInGroup;if(this.media||(this.queuedDefaultTrack=e),e<-1||e>=s.length||!$(e)){this.warn(`Invalid subtitle track id: ${e}`);return}let i=this.currentTrack,r=s[e]||null;if(this.trackId=e,this.currentTrack=r,t&&this.toggleTrackModes(),!r){i&&this.hls.trigger(p.SUBTITLE_TRACK_SWITCH,{id:e});return}let a=!!r.details&&!r.details.live;if(r===i&&a)return;this.log(`Switching to subtitle-track ${e}`+(r?` "${r.name}" lang:${r.lang} group:${r.groupId}`:""));let{id:o,groupId:l="",name:c,type:h,url:u}=r;this.hls.trigger(p.SUBTITLE_TRACK_SWITCH,{id:o,groupId:l,name:c,type:h,url:u});let d=this.switchParams(r.url,i?.details,r.details);this.loadPlaylist(d)}},$s=2,wf=100,en=class extends Qs{constructor(e,t){super("gap-controller",e.logger),this.hls=void 0,this.fragmentTracker=void 0,this.media=null,this.mediaSource=void 0,this.nudgeRetry=0,this.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 s;(s=this.media)!=null&&s.seeking||(this.waiting=self.performance.now(),this.tick())},this.onMediaEnded=()=>{if(this.hls){var s;this.ended=((s=this.media)==null?void 0:s.currentTime)||1,this.hls.trigger(p.MEDIA_ENDED,{stalled:!1})}},this.hls=e,this.fragmentTracker=t,this.lastCurrentTime=this.getCurrentTime(),this.registerListeners()}registerListeners(){let{hls:e}=this;e&&(e.on(p.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(p.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(p.BUFFER_APPENDED,this.onBufferAppended,this))}unregisterListeners(){let{hls:e}=this;e&&(e.off(p.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(p.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(p.BUFFER_APPENDED,this.onBufferAppended,this))}destroy(){super.destroy(),this.unregisterListeners(),this.media=this.hls=this.fragmentTracker=null,this.mediaSource=void 0}onMediaAttached(e,t){this.setInterval(wf),this.mediaSource=t.mediaSource;let s=this.media=t.media;ce(s,"playing",this.onMediaPlaying),ce(s,"waiting",this.onMediaWaiting),ce(s,"ended",this.onMediaEnded)}onMediaDetaching(e,t){this.clearInterval();let{media:s}=this;s&&(le(s,"playing",this.onMediaPlaying),le(s,"waiting",this.onMediaWaiting),le(s,"ended",this.onMediaEnded),this.media=null),this.mediaSource=void 0}onBufferAppended(e,t){this.buffered=t.timeRanges}get hasBuffered(){return Object.keys(this.buffered).length>0}getCurrentTime(){var e;let t=((e=this.hls)==null?void 0:e.config.timelineOffset)||0;return this.media?Math.max(this.media.currentTime,t):t}tick(){var e;if(!((e=this.media)!=null&&e.readyState)||!this.hasBuffered)return;let t=this.getCurrentTime();this.media.currentTime<t||(this.poll(t,this.lastCurrentTime),this.lastCurrentTime=t)}poll(e,t){var s,i;let r=(s=this.hls)==null?void 0:s.config;if(!r)return;let a=this.media;if(!a)return;let{seeking:o}=a,l=this.seeking&&!o,c=!this.seeking&&o,h=a.paused&&!o||a.ended||a.playbackRate===0;if(this.seeking=o,e!==t){t&&(this.ended=0),this.moved=!0,o||(this.skipRetry=this.nudgeRetry=0,r.nudgeOnVideoHole&&!h&&e>t&&this.nudgeOnVideoHole(e,t)),this.waiting===0&&this.stallResolved(e);return}if(c||l){l&&this.stallResolved(e);return}if(h){this.skipRetry=this.nudgeRetry=0,this.stallResolved(e),!this.ended&&a.ended&&this.hls&&(this.ended=e||1,this.hls.trigger(p.MEDIA_ENDED,{stalled:!1}));return}if(!X.getBuffered(a).length){this.skipRetry=this.nudgeRetry=0;return}let u=X.bufferInfo(a,e,0),d=this.fragmentTracker;d&&this.hls&&uo(u,e,d,this.hls);let f=u.nextStart||0;if(o&&d&&this.hls){let I=co(this.hls.inFlightFragments,e),A=u.len>$s,b=!f||I||f-e>$s&&!d.getPartialFragment(e);if(A||b)return;this.moved=!1}let g=(i=this.hls)==null?void 0:i.latestLevelDetails;if(!this.moved&&this.stalled!==null&&d){if(!(u.len>0)&&!f)return;let A=Math.max(f,u.start||0)-e,_=!!(g!=null&&g.live)?g.targetduration*2:$s,L=zt(e,d);if(A>0&&(A<=_||L)){a.paused||this._trySkipBufferHole(L);return}}let m=r.detectStallWithCurrentTimeMs,y=self.performance.now(),E=this.waiting,S=this.stalled;if(S===null)if(E>0&&y-E<m)S=this.stalled=E;else{this.stalled=y;return}let T=y-S;if(!o&&(T>=m||E&&this.moved)&&this.hls){var v;if(((v=this.mediaSource)==null?void 0:v.readyState)==="ended"&&!(g!=null&&g.live)&&Math.abs(e-(g?.edge||0))<1){if(this.ended)return;this.ended=e||1,this.hls.trigger(p.MEDIA_ENDED,{stalled:!0});return}if(this._reportStall(u),!this.media||!this.hls)return;if(a.currentTime!==e){let I=e;e=a.currentTime,this.moved=!0,this.log(`currentTime changed ${I} > ${e}`);return}}let x=X.bufferInfo(a,e,r.maxBufferHole);this._tryFixBufferStall(x,T,e)}stallResolved(e){let t=this.stalled;if(t&&this.hls&&(this.stalled=null,this.stallReported)){let s=self.performance.now()-t;this.log(`playback not stuck anymore @${e}, after ${Math.round(s)}ms`),this.stallReported=!1,this.waiting=0,this.hls.trigger(p.STALL_RESOLVED,{})}}nudgeOnVideoHole(e,t){var s;let i=this.buffered.video;if(this.hls&&this.media&&this.fragmentTracker&&(s=this.buffered.audio)!=null&&s.length&&i&&i.length>1&&e>i.end(0)){let r=X.bufferedInfo(X.timeRangesToArray(this.buffered.audio),e,0);if(r.len>1&&t>=r.start){let a=X.timeRangesToArray(i),o=X.bufferedInfo(a,t,0).bufferedIndex;if(o>-1&&o<a.length-1){let l=X.bufferedInfo(a,e,0).bufferedIndex,c=a[o].end,h=a[o+1].start;if((l===-1||l>o)&&h-c<1&&e-c<2){let u=new Error(`nudging playhead to flush pipeline after video hole. currentTime: ${e} hole: ${c} -> ${h} buffered index: ${l}`);this.warn(u.message),this.media.currentTime+=1e-6;let d=zt(e,this.fragmentTracker);d&&"fragment"in d?d=d.fragment:d||(d=void 0);let f=X.bufferInfo(this.media,e,0);this.hls.trigger(p.ERROR,{type:W.MEDIA_ERROR,details:R.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:u,reason:u.message,frag:d,buffer:f.len,bufferInfo:f})}}}}}_tryFixBufferStall(e,t,s){var i,r;let{fragmentTracker:a,media:o}=this,l=(i=this.hls)==null?void 0:i.config;if(!o||!a||!l)return;let c=(r=this.hls)==null?void 0:r.latestLevelDetails,h=zt(s,a);if((h||c!=null&&c.live&&s<c.fragmentStart)&&(this._trySkipBufferHole(h)||!this.media))return;let u=e.buffered,d=this.adjacentTraversal(e,s);(u&&u.length>1&&e.len>l.maxBufferHole||e.nextStart&&(e.nextStart-s<l.maxBufferHole||d))&&(t>l.highBufferWatchdogPeriod*1e3||this.waiting)&&(this.warn("Trying to nudge playhead over buffer-hole"),this._tryNudgeBuffer(e))}adjacentTraversal(e,t){let s=this.fragmentTracker,i=e.nextStart;if(s&&i){let r=s.getFragAtPos(t,K.MAIN),a=s.getFragAtPos(i,K.MAIN);if(r&&a)return a.sn-r.sn<2}return!1}_reportStall(e){let{hls:t,media:s,stallReported:i,stalled:r}=this;if(!i&&r!==null&&s&&t){this.stallReported=!0;let a=new Error(`Playback stalling at @${s.currentTime} due to low buffer (${de(e)})`);this.warn(a.message),t.trigger(p.ERROR,{type:W.MEDIA_ERROR,details:R.BUFFER_STALLED_ERROR,fatal:!1,error:a,buffer:e.len,bufferInfo:e,stalled:{start:r}})}}_trySkipBufferHole(e){let{fragmentTracker:t,media:s,hls:i}=this,r=i?.config;if(!s||!t||!r)return 0;let a=s.currentTime,o=X.bufferInfo(s,a,0);uo(o,a,t,i);let l=a<o.start?o.start:o.nextStart;if(l){let h=o.len<=r.maxBufferHole,u=o.len>0&&o.len<1&&s.readyState<3,d=l-a;if(d>0&&(h||u)){if(d>r.maxBufferHole){let E=!1;if(a===0){let S=t.getAppendedFrag(0,K.MAIN);S&&l<S.end&&(E=!0)}if(!E&&e){var c;if(!((c=i.loadLevelObj)!=null&&c.details)||co(i.inFlightFragments,l))return 0;let T=!1,v=e.end;for(;v<l;){let x=zt(v,t),I=x?x.duration:0;if(I>0)v+=I;else{T=!0;break}}if(T)return 0}}let{nudgeMaxRetry:f,skipBufferHolePadding:g}=r,m=++this.skipRetry>f,y=Math.max(l,a)+g;if(m||(this.warn(`skipping hole, adjusting currentTime from ${a} to ${y}`),this.moved=!0,s.currentTime=y),!(e!=null&&e.gap)||m){let E=new Error(m?`Playhead still not moving after seeking over buffer hole from ${a} to ${y} after ${r.nudgeMaxRetry} attempts.`:`fragment loaded with buffer holes, seeking from ${a} to ${y}`),S={type:W.MEDIA_ERROR,details:R.BUFFER_SEEK_OVER_HOLE,fatal:m,error:E,reason:E.message,buffer:o.len,bufferInfo:o};e&&("fragment"in e?S.part=e:S.frag=e),i.trigger(p.ERROR,S)}return y}}return 0}_tryNudgeBuffer(e){let{hls:t,media:s,nudgeRetry:i}=this,r=t?.config;if(!s||!r)return 0;let a=s.currentTime;if(this.nudgeRetry++,i<r.nudgeMaxRetry){let o=a+(i+1)*r.nudgeOffset,l=new Error(`Nudging 'currentTime' from ${a} to ${o}`);this.warn(l.message),s.currentTime=o,t.trigger(p.ERROR,{type:W.MEDIA_ERROR,details:R.BUFFER_NUDGE_ON_STALL,error:l,fatal:!1,buffer:e.len,bufferInfo:e})}else{let o=new Error(`Playhead still not moving while enough data buffered @${a} after ${r.nudgeMaxRetry} nudges`);this.error(o.message),t.trigger(p.ERROR,{type:W.MEDIA_ERROR,details:R.BUFFER_STALLED_ERROR,error:o,fatal:!0,buffer:e.len,bufferInfo:e})}}};function co(n,e){let t=ho(n.main);if(t&&t.start<=e)return t;let s=ho(n.audio);return s&&s.start<=e?s:null}function ho(n){if(!n)return null;switch(n.state){case C.IDLE:case C.STOPPED:case C.ENDED:case C.ERROR:return null}return n.frag}function zt(n,e){return e.getAppendedFrag(n,K.MAIN)||e.getPartialFragment(n)}function uo(n,e,t,s){let i=s.latestLevelDetails,r=zt(e,t);if(si(s.config)&&!n.nextStart&&i&&r&&s.interstitialsManager){let a="type"in r?r:r.fragment,o=el(i,a.sn);o?.level===a.level&&yl(o,s.interstitialsManager.playerQueue,e)&&(n.nextStart=o.start)}}var Mf=.25;function tn(){if(!(typeof self>"u"))return self.VTTCue||self.TextTrackCue}function ji(n,e,t,s,i){let r=new n(e,t,"");try{r.value=s,i&&(r.type=i)}catch{r=new n(e,t,de(i?Y({type:i},s):s))}return r}var Cs=(()=>{let n=tn();try{n&&new n(0,Number.POSITIVE_INFINITY,"")}catch{return Number.MAX_VALUE}return Number.POSITIVE_INFINITY})(),sn=class{constructor(e){this.hls=void 0,this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.removeCues=!0,this.assetCue=void 0,this.onEventCueEnter=()=>{this.hls&&this.hls.trigger(p.EVENT_CUE_ENTER,{})},this.hls=e,this._registerListeners()}destroy(){this._unregisterListeners(),this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.hls=this.onEventCueEnter=null}_registerListeners(){let{hls:e}=this;e&&(e.on(p.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(p.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(p.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(p.MANIFEST_LOADING,this.onManifestLoading,this),e.on(p.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.on(p.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(p.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(p.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))}_unregisterListeners(){let{hls:e}=this;e&&(e.off(p.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(p.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(p.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(p.MANIFEST_LOADING,this.onManifestLoading,this),e.off(p.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.off(p.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(p.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(p.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))}onMediaAttaching(e,t){this.media=t.media}onMediaAttached(){var e;let t=(e=this.hls)==null?void 0:e.latestLevelDetails;t&&this.updateDateRangeCues(t)}onMediaDetaching(e,t){this.media=null,!t.transferMedia&&(this.id3Track&&(this.id3Track.remove(),this.id3Track=null),this.dateRangeCuesAppended={})}onManifestLoading(){this.dateRangeCuesAppended={}}createTrack(e){return qn(e,"metadata","id3","","hidden")}onFragParsingMetadata(e,t){if(!this.media||!this.hls)return;let{enableEmsgMetadataCues:s,enableID3MetadataCues:i}=this.hls.config;if(!s&&!i)return;let{samples:r}=t;this.id3Track||(this.id3Track=this.createTrack(this.media));let a=tn();if(a)for(let o=0;o<r.length;o++){let l=r[o].type;if(l===Oe.emsg&&!s||!i)continue;let c=Do(r[o].data),h=r[o].pts,u=h+r[o].duration;u>Cs&&(u=Cs),u-h<=0&&(u=h+Mf);for(let f=0;f<c.length;f++){let g=c[f];if(!Po(g)){this.updateId3CueEnds(h,l);let m=ji(a,h,u,g,l);m&&this.id3Track.track.addCue(m)}}}}updateId3CueEnds(e,t){var s;let i=(s=this.id3Track)==null?void 0:s.track.cues;if(i)for(let r=i.length;r--;){let a=i[r];a.type===t&&a.startTime<e&&a.endTime===Cs&&(a.endTime=e)}}onBufferFlushing(e,{startOffset:t,endOffset:s,type:i}){let{id3Track:r,hls:a}=this;if(!a)return;let{config:{enableEmsgMetadataCues:o,enableID3MetadataCues:l}}=a;if(r&&(o||l)){let c;i==="audio"?c=h=>h.type===Oe.audioId3&&l:i==="video"?c=h=>h.type===Oe.emsg&&o:c=h=>h.type===Oe.audioId3&&l||h.type===Oe.emsg&&o,Zr(r.track,t,s,c)}}onLevelUpdated(e,{details:t}){this.updateDateRangeCues(t,!0)}onLevelPtsUpdated(e,t){Math.abs(t.drift)>.01&&this.updateDateRangeCues(t.details)}updateDateRangeCues(e,t){if(!this.hls||!this.media)return;let{assetPlayerId:s,timelineOffset:i,enableDateRangeMetadataCues:r,interstitialsController:a}=this.hls.config;if(!r)return;let o=tn();if(s&&i&&!a){let{fragmentStart:m,fragmentEnd:y}=e,E=this.assetCue;E?(E.startTime=m,E.endTime=y):o&&(E=this.assetCue=ji(o,m,y,{assetPlayerId:this.hls.config.assetPlayerId},"hlsjs.interstitial.asset"),E&&(E.id=s,this.id3Track||(this.id3Track=this.createTrack(this.media)),this.id3Track.track.addCue(E),E.addEventListener("enter",this.onEventCueEnter)))}if(!e.hasProgramDateTime)return;let{id3Track:l}=this,{dateRanges:c}=e,h=Object.keys(c),u=this.dateRangeCuesAppended;if(l&&t){var d;if((d=l.track.cues)!=null&&d.length){let m=Object.keys(u).filter(y=>h.indexOf(y)===-1);for(let y=m.length;y--;){var f;let E=m[y],S=(f=u[E])==null?void 0:f.cues;delete u[E],S&&Object.keys(S).forEach(T=>{let v=S[T];if(v){v.removeEventListener("enter",this.onEventCueEnter);try{l.track.removeCue(v)}catch{}}})}}else u=this.dateRangeCuesAppended={}}let g=e.fragments[e.fragments.length-1];if(!(h.length===0||!$(g?.programDateTime))){this.id3Track||(this.id3Track=this.createTrack(this.media));for(let m=0;m<h.length;m++){let y=h[m],E=c[y],S=E.startTime,T=u[y],v=T?.cues||{},x=T?.durationKnown||!1,I=Cs,{duration:A,endDate:b}=E;if(b&&A!==null)I=S+A,x=!0;else if(E.endOnNext&&!x){let L=h.reduce((P,D)=>{if(D!==E.id){let M=c[D];if(M.class===E.class&&M.startDate>E.startDate&&(!P||E.startDate<P.startDate))return M}return P},null);L&&(I=L.startTime,x=!0)}let _=Object.keys(E.attr);for(let L=0;L<_.length;L++){let P=_[L];if(!tu(P))continue;let D=v[P];if(D)x&&!(T!=null&&T.durationKnown)?D.endTime=I:Math.abs(D.startTime-S)>.01&&(D.startTime=S,D.endTime=I);else if(o){let M=E.attr[P];su(P)&&(M=Co(M));let B=ji(o,S,I,{key:P,data:M},Oe.dateRange);B&&(B.id=y,this.id3Track.track.addCue(B),v[P]=B,a&&(P==="X-ASSET-LIST"||P==="X-ASSET-URL")&&B.addEventListener("enter",this.onEventCueEnter))}}u[y]={cues:v,dateRange:E,durationKnown:x}}}}};function nc(){return self.SourceBuffer||self.WebKitSourceBuffer}function ac(){if(!vt())return!1;let e=nc();return!e||e.prototype&&typeof e.prototype.appendBuffer=="function"&&typeof e.prototype.remove=="function"}function Ff(){if(!ac())return!1;let n=vt();return typeof n?.isTypeSupported=="function"&&(["avc1.42E01E,mp4a.40.2","av01.0.01M.08","vp09.00.50.08"].some(e=>n.isTypeSupported(os(e,"video")))||["mp4a.40.2","fLaC"].some(e=>n.isTypeSupported(os(e,"audio"))))}function Nf(){var n;let e=nc();return typeof(e==null||(n=e.prototype)==null?void 0:n.changeType)=="function"}var ze={DISABLED:0,SWITCHING:1,SWITCHED:2},Bf=100,fi=class extends us{constructor(e,t,s){super(e,t,s,"stream-controller",K.MAIN),this.audioCodecSwap=!1,this.level=-1,this._forceStartLoad=!1,this._hasEnoughToStart=!1,this.altAudio=ze.DISABLED,this.audioOnly=!1,this._couldBacktrack=!1,this._backtrackFragment=void 0,this.audioCodecSwitch=!1,this.videoBuffer=null,this.onMediaPlaying=()=>{this.tick()},this.onMediaSeeked=()=>{let i=this.media,r=i?i.currentTime:null;if(r===null||!$(r)||(this.log(`Media seeked to ${r}`),!this.getBufferedFrag(r)))return;let a=this.getFwdBufferInfoAtPos(i,r,K.MAIN,0);if(!a||a.len===0){this.log(`Main buffer empty at ${r} on "seeked" event: ${a&&a.len}`);return}this.tick()},this.registerListeners()}registerListeners(){super.registerListeners();let{hls:e}=this;e.on(p.MANIFEST_PARSED,this.onManifestParsed,this),e.on(p.LEVEL_LOADING,this.onLevelLoading,this),e.on(p.LEVEL_LOADED,this.onLevelLoaded,this),e.on(p.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.on(p.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(p.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.on(p.BUFFER_CREATED,this.onBufferCreated,this),e.on(p.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(p.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(p.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){super.unregisterListeners();let{hls:e}=this;e.off(p.MANIFEST_PARSED,this.onManifestParsed,this),e.off(p.LEVEL_LOADED,this.onLevelLoaded,this),e.off(p.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.off(p.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(p.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.off(p.BUFFER_CREATED,this.onBufferCreated,this),e.off(p.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(p.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(p.FRAG_BUFFERED,this.onFragBuffered,this)}onHandlerDestroying(){this.onMediaPlaying=this.onMediaSeeked=null,this.unregisterListeners(),super.onHandlerDestroying()}startLoad(e,t){if(this.levels){let{lastCurrentTime:s,hls:i}=this;if(this.stopLoad(),this.setInterval(Bf),this.level=-1,!this.startFragRequested){let r=i.startLevel;r===-1&&(i.config.testBandwidth&&this.levels.length>1?(r=0,this.bitrateTest=!0):r=i.firstAutoLevel),i.nextLoadLevel=r,this.level=i.loadLevel,this._hasEnoughToStart=!!t}s>0&&e===-1&&!t&&this.initPTS.length&&(this.log(`Override startPosition with lastCurrentTime @${s}`),e=s),this.state=C.IDLE,this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,!t&&!this.fragmentTracker.hasFragments(this.playlistType)&&(this._hasEnoughToStart=this.startFragRequested=!1),this.tick()}else this._forceStartLoad=!0,this.state=C.STOPPED}stopLoad(){this._forceStartLoad=!1,super.stopLoad()}doTick(){switch(this.state){case C.WAITING_LEVEL:{let{levels:e,level:t}=this,s=e?.[t],i=s?.details;if(i&&(!i.live||this.levelLastLoaded===s&&!this.waitForLive(s))){if(this.waitForCdnTuneIn(i))break;this.state=C.IDLE;break}else if(this.hls.nextLoadLevel!==this.level){this.state=C.IDLE;break}break}case C.FRAG_LOADING_WAITING_RETRY:this.checkRetryDate();break}this.state===C.IDLE&&this.doTickIdle(),this.onTickEnd()}onTickEnd(){super.onTickEnd(),this.checkFragmentChanged()}doTickIdle(){let{hls:e,levelLastLoaded:t,levels:s,media:i}=this;if(t===null||!i&&!this.primaryPrefetch&&(this.startFragRequested||!e.config.startFragPrefetch)||this.altAudio&&this.audioOnly)return;let r=this.buffering?e.nextLoadLevel:e.loadLevel;if(!(s!=null&&s[r]))return;let a=s[r],o=this.getMainFwdBufferInfo();if(o===null)return;let l=this.getLevelDetails();if(l&&this._streamEnded(o,l)&&this.altAudio!==ze.SWITCHING){let m={type:this.targetBufferType()};this.hls.trigger(p.BUFFER_EOS,m),this.state=C.ENDED;return}if(!this.buffering)return;e.loadLevel!==r&&e.manualLevel===-1&&this.log(`Adapting to level ${r} from level ${this.level}`),this.level=e.nextLoadLevel=r;let c=a.details;if(!c||this.state===C.WAITING_LEVEL||this.waitForLive(a)){this.level=r,this.state=C.WAITING_LEVEL,this.startFragRequested=!1;return}let h=o.len,u=this.getMaxBufferLength(a.maxBitrate);if(h>=u)return;this.backtrackFragment&&this.backtrackFragment.start>o.end&&(this.backtrackFragment=void 0);let d=this.backtrackFragment?this.backtrackFragment.start:o.end,f=this.getNextFragment(d,c);if(this.couldBacktrack&&!this.fragPrevious&&f&&pe(f)&&this.fragmentTracker.getState(f)!==fe.OK){var g;let y=((g=this.backtrackFragment)!=null?g:f).sn-c.startSN,E=c.fragments[y-1];E&&f.cc===E.cc&&(f=E,this.fragmentTracker.removeFragment(E))}else this.backtrackFragment&&o.len&&(this.backtrackFragment=void 0);if(f&&this.isLoopLoading(f,d)){if(!f.gap){let y=this.audioOnly&&!this.altAudio?ue.AUDIO:ue.VIDEO,E=(y===ue.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;E&&this.afterBufferFlushed(E,y)}f=this.getNextFragmentLoopLoading(f,c,o,K.MAIN,u)}f&&(this.exceedsMaxBuffer(o,u,f)||this.loadFragment(f,a,d))}loadFragment(e,t,s){let i=this.fragmentTracker.getState(e);i===fe.NOT_LOADED||i===fe.PARTIAL?this.bitrateTest?(this.log(`Fragment ${e.sn} of level ${e.level} is being downloaded to test bitrate and will not be buffered`),this._loadBitrateTestFrag(e,t)):super.loadFragment(e,t,s):this.clearTrackerIfNeeded(e)}immediateLevelSwitch(){if(this.abortCurrentFrag(),this.flushMainBuffer(0,Number.POSITIVE_INFINITY),this.altAudio!==ze.DISABLED){var e;(((e=this.getLevelDetails())==null?void 0:e.fragmentStart)||0)>this.lastCurrentTime&&super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio")}}getBufferOutput(){return this.mediaBuffer&&this.altAudio===ze.SWITCHED?this.mediaBuffer:this.media}checkFragmentChanged(){let e=this.fragPlaying;if(!this.checkFragPlaying())return!1;let s=this.fragPlaying;if(s){let i=s.level;this.hls.trigger(p.FRAG_CHANGED,{frag:s,previousFrag:e}),e?.level!==i&&this.hls.trigger(p.LEVEL_SWITCHED,{level:i})}return!0}get backtrackFragment(){return this._backtrackFragment}set backtrackFragment(e){this._backtrackFragment=e}get couldBacktrack(){return this._couldBacktrack}set couldBacktrack(e){this._couldBacktrack=e}abortCurrentFrag(){this.backtrackFragment=void 0,super.abortCurrentFrag()}flushMainBuffer(e,t){super.flushMainBuffer(e,t,this.targetBufferType())}targetBufferType(){return this.altAudio===ze.SWITCHED&&!this.audioOnly?"video":null}onMediaAttached(e,t){super.onMediaAttached(e,t);let s=t.media;ce(s,"playing",this.onMediaPlaying),ce(s,"seeked",this.onMediaSeeked)}onMediaDetaching(e,t){let{media:s}=this;s&&(le(s,"playing",this.onMediaPlaying),le(s,"seeked",this.onMediaSeeked)),this.videoBuffer=null,super.onMediaDetaching(e,t),!t.transferMedia&&(this._hasEnoughToStart=!1)}onManifestLoading(){super.onManifestLoading(),this.log("Trigger BUFFER_RESET"),this.hls.trigger(p.BUFFER_RESET,void 0),this.couldBacktrack=!1,this.backtrackFragment=void 0,this.altAudio=ze.DISABLED,this.audioOnly=!1}onManifestParsed(e,t){let s=!1,i=!1;for(let r=0;r<t.levels.length;r++){let a=t.levels[r].audioCodec;a&&(s=s||a.indexOf("mp4a.40.2")!==-1,i=i||a.indexOf("mp4a.40.5")!==-1)}this.audioCodecSwitch=s&&i&&!Nf(),this.audioCodecSwitch&&this.log("Both AAC/HE-AAC audio found in levels; declaring level codec as HE-AAC"),this.levels=t.levels,this.startFragRequested=!1}onLevelLoading(e,t){let{levels:s}=this;if(!s||this.state!==C.IDLE)return;let i=t.levelInfo;(!i.details||i.details.live&&(this.levelLastLoaded!==i||i.details.expired)||this.waitForCdnTuneIn(i.details))&&(this.state=C.WAITING_LEVEL)}onLevelLoaded(e,t){var s;let{levels:i,startFragRequested:r}=this,a=t.level,o=t.details,l=o.totalduration;if(!i){this.warn(`Levels were reset while loading level ${a}`);return}this.log(`Level ${a} loaded [${o.startSN},${o.endSN}]${o.lastPartSn?`[part-${o.lastPartSn}-${o.lastPartIndex}]`:""}, cc [${o.startCC}, ${o.endCC}] duration:${l}`);let c=t.levelInfo,h=this.fragCurrent;h&&(this.state===C.FRAG_LOADING||this.state===C.FRAG_LOADING_WAITING_RETRY)&&h.level!==t.level&&h.loader&&this.abortCurrentFrag();let u=0;if(o.live||(s=c.details)!=null&&s.live){var d;if(this.checkLiveUpdate(o),o.deltaUpdateFailed)return;u=this.alignPlaylists(o,c.details,(d=this.levelLastLoaded)==null?void 0:d.details)}if(c.details=o,this.levelLastLoaded=c,r||this.setStartPosition(o,u),this.hls.trigger(p.LEVEL_UPDATED,{details:o,level:a}),this.state===C.WAITING_LEVEL){if(this.waitForCdnTuneIn(o))return;this.state=C.IDLE}r&&o.live&&this.synchronizeToLiveEdge(o),this.initPTS.some((f,g)=>{if(g>=o.startCC)return!0;delete this.initPTS[g]}),this.tick()}synchronizeToLiveEdge(e){let{config:t,media:s}=this;if(!s)return;let i=this.hls.liveSyncPosition,r=this.playhead,a=e.fragmentStart,o=e.edge,l=r>=a-t.maxFragLookUpTolerance&&r<=o;if(i!==null&&s.duration>i&&(r<i||!l)){let h=t.liveMaxLatencyDuration!==void 0?t.liveMaxLatencyDuration:t.liveMaxLatencyDurationCount*e.targetduration;if((!l&&s.readyState<4||r<o-h)&&(this._hasEnoughToStart||(this.nextLoadPosition=i),s.readyState))if(this.warn(`Playback: ${r} is located too far from the end of live sliding playlist: ${o}, reset currentTime to : ${i}`),this.config.liveSyncMode==="buffered"){var c;let u=X.bufferInfo(s,i,0);if(!((c=u.buffered)!=null&&c.length)){s.currentTime=i;return}if(u.start<=r){s.currentTime=i;return}let{nextStart:f}=X.bufferedInfo(u.buffered,r,0);f&&(s.currentTime=f)}else s.currentTime=i}}_handleFragmentLoadProgress(e){var t;let s=e.frag,{part:i,payload:r}=e,{levels:a}=this;if(!a){this.warn(`Levels were reset while fragment load was in progress. Fragment ${s.sn} of level ${s.level} will not be buffered`);return}let o=a[s.level];if(!o){this.warn(`Level ${s.level} not found on progress`);return}let l=o.details;if(!l){this.warn(`Dropping fragment ${s.sn} of level ${s.level} after level details were reset`),this.fragmentTracker.removeFragment(s);return}let c=o.videoCodec,h=l.PTSKnown||!l.live,u=(t=s.initSegment)==null?void 0:t.data,d=this._getAudioCodec(o),f=this.transmuxer=this.transmuxer||new ui(this.hls,K.MAIN,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)),g=i?i.index:-1,m=g!==-1,{decryptRange:y,byteRange:E}=Xs(s,i,this.iframesOnly),S=new hs(s.level,s.sn,s.stats.chunkCount,E?E.end-E.start:r.byteLength,g,m,s.duration,this.iframesOnly,y),T=this.initPTS[s.cc];f.push(r,u,d,c,s,i,l.totalduration,h,S,T)}onAudioTrackSwitching(e,t){let s=this.hls,i=this.altAudio!==ze.DISABLED;if(qs(t.url,s))this.altAudio=ze.SWITCHING;else{if(this.mediaBuffer!==this.media){this.log("Switching on main audio, use media.buffered to schedule main fragment loading"),this.mediaBuffer=this.media;let a=this.fragCurrent;a&&(this.log("Switching to main audio track, cancel main fragment load"),a.abortRequests(),this.fragmentTracker.removeFragment(a)),this.resetTransmuxer(),this.resetLoadingState()}else this.audioOnly&&this.resetTransmuxer();if(i){this.altAudio=ze.DISABLED,this.fragmentTracker.removeAllFragments(),s.once(p.BUFFER_FLUSHED,()=>{this.hls&&this.hls.trigger(p.AUDIO_TRACK_SWITCHED,t)}),s.trigger(p.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:null});return}s.trigger(p.AUDIO_TRACK_SWITCHED,t)}}onAudioTrackSwitched(e,t){let s=qs(t.url,this.hls);if(s){let i=this.videoBuffer;i&&this.mediaBuffer!==i&&(this.log("Switching on alternate audio, use video.buffered to schedule main fragment loading"),this.mediaBuffer=i)}this.altAudio=s?ze.SWITCHED:ze.DISABLED,this.tick()}onBufferCreated(e,t){let s=t.tracks,i,r,a=!1;for(let o in s){let l=s[o];if(l.id==="main"){if(r=o,i=l,o==="video"){let c=s[o];c&&(this.videoBuffer=c.buffer)}}else a=!0}a&&i?(this.log(`Alternate track found, use ${r}.buffered to schedule main fragment loading`),this.mediaBuffer=i.buffer):this.mediaBuffer=this.media}onFragBuffered(e,t){let{frag:s,part:i}=t,r=s.type===K.MAIN;if(r){if(this.fragContextChanged(s)){this.warn(`Fragment ${s.sn}${i?" p: "+i.index:""} of level ${s.level} finished buffering, but was aborted. state: ${this.state}`),this.state===C.PARSED&&(this.state=C.IDLE);return}let l=!1;if(pe(s)&&(l=!!s.gap&&!s.tagList.some(c=>c[0]==="GAP")),this.fragBufferedComplete(s,i),l){var a;s.stats.retry++;let c=(a=this.levels)==null?void 0:a[s.level];c&&c.fragmentError++}}let o=this.media;o&&(!this._hasEnoughToStart&&X.getBuffered(o).length&&(this.seekToStartPos(),this._hasEnoughToStart=!0),r&&this.tick())}get hasEnoughToStart(){return this._hasEnoughToStart}onError(e,t){var s;if(t.fatal){this.state=C.ERROR;return}switch(t.details){case R.FRAG_GAP:case R.FRAG_PARSING_ERROR:case R.FRAG_DECRYPT_ERROR:case R.FRAG_LOAD_ERROR:case R.FRAG_LOAD_TIMEOUT:case R.KEY_LOAD_ERROR:case R.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(K.MAIN,t);break;case R.LEVEL_LOAD_ERROR:case R.LEVEL_LOAD_TIMEOUT:case R.LEVEL_PARSING_ERROR:!t.levelRetry&&this.state===C.WAITING_LEVEL&&((s=t.context)==null?void 0:s.type)===se.LEVEL&&(this.state=C.IDLE);break;case R.BUFFER_APPEND_NO_PROGRESS:if(t.parent!=="main")return;t.frag&&(t.appendsWithoutProgress||0)>=this.config.appendErrorMaxRetry&&(this.warn(`Marking fragment ${t.frag.sn} of level ${t.frag.level} as a gap after ${t.appendsWithoutProgress} appends without buffered range growth, to prevent loop loading`),this.fragmentTracker.addAsGap(t.frag));break;case R.MEDIA_SOURCE_REQUIRES_RESET:this.onSourceBufferError(K.MAIN,t);break;case R.BUFFER_ADD_CODEC_ERROR:case R.BUFFER_APPEND_ERROR:if(t.parent!=="main")return;this.reduceLengthAndFlushBuffer(t)&&this.resetLoadingState();break;case R.BUFFER_FULL_ERROR:if(t.parent!=="main")return;this.reduceLengthAndFlushBuffer(t)&&(!this.config.interstitialsController&&this.config.assetPlayerId?this._hasEnoughToStart=!0:this.flushMainBuffer(0,Number.POSITIVE_INFINITY));break;case R.INTERNAL_EXCEPTION:this.recoverWorkerError(t);break}}onFragLoadEmergencyAborted(){this.state=C.IDLE,this._hasEnoughToStart||(this.startFragRequested=!1,this.nextLoadPosition=this.lastCurrentTime),this.tickImmediate()}onBufferFlushed(e,{type:t}){if(t!==ue.AUDIO||!this.altAudio){let s=(t===ue.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;s&&(this.afterBufferFlushed(s,t),this.tick())}}onLevelsUpdated(e,t){this.level>-1&&this.fragCurrent&&(this.level=this.fragCurrent.level,this.level===-1&&this.resetWhenMissingContext(this.fragCurrent)),this.levels=t.levels}swapAudioCodec(){this.audioCodecSwap=!this.audioCodecSwap}seekToStartPos(){let{media:e}=this;if(!e)return;let t=e.currentTime,s=this.startPosition;if(s>=0&&t<s){if(e.seeking){this.log(`could not seek to ${s}, already seeking at ${t}`);return}let i=this.timelineOffset;i&&s&&(s+=i);let r=this.getLevelDetails(),a=X.getBuffered(e),o=a.length?a.start(0):0,l=o-s,c=Math.max(this.config.maxBufferHole,this.config.maxFragLookUpTolerance);(this.config.startOnSegmentBoundary||l>0&&(l<c||this.loadingParts&&l<2*(r?.partTarget||0)))&&(this.log(`adjusting start position by ${l} to match buffer start`),s+=l,this.startPosition=s),t<s&&(this.log(`seek to target start position ${s} from current time ${t} buffer start ${o}`),e.currentTime=s)}}_getAudioCodec(e){let t=this.config.defaultAudioCodec||e.audioCodec;return this.audioCodecSwap&&t&&(this.log("Swapping audio codec"),t.indexOf("mp4a.40.5")!==-1?t="mp4a.40.2":t="mp4a.40.5"),t}_loadBitrateTestFrag(e,t){e.bitrateTest=!0,this._doFragLoad(e,t).then(s=>{let{hls:i}=this,r=s?.frag;if(!r||this.fragContextChanged(r))return;t.fragmentError=0,this.state=C.IDLE,this.startFragRequested=!1,this.bitrateTest=!1;let a=r.stats;a.parsing.start=a.parsing.end=a.buffering.start=a.buffering.end=self.performance.now(),i.trigger(p.FRAG_LOADED,s),r.bitrateTest=!1}).catch(s=>{this.state===C.STOPPED||this.state===C.ERROR||(this.warn(s),this.resetFragmentLoading(e))})}_handleTransmuxComplete(e){let t=this.playlistType,{hls:s}=this,{remuxResult:i,chunkMeta:r}=e,a=this.getCurrentContext(r);if(!a){this.resetWhenMissingContext(r);return}let{frag:o,part:l,level:c}=a,{video:h,text:u,id3:d,initSegment:f}=i,{details:g}=c,m=this.altAudio?void 0:i.audio;if(this.fragContextChanged(o)){this.fragmentTracker.removeFragment(o);return}if(this.state=C.PARSING,f){let y=f.tracks;if(y){let v=o.initSegment||o;if(this.unhandledEncryptionError(f,o))return;this._bufferInitSegment(c,y,v,r),s.trigger(p.FRAG_PARSING_INIT_SEGMENT,{frag:v,id:t,tracks:y})}let E=f.initPTS,S=f.timescale,T=this.initPTS[o.cc];if($(E)&&(!T||T.baseTime!==E||T.timescale!==S)){let v=f.trackId;this.initPTS[o.cc]={baseTime:E,timescale:S,trackId:v};let x=this.initPTS.slice(0);s.trigger(p.INIT_PTS_FOUND,{timestampOffsets:x,frag:o,id:t,initPTS:E,timescale:S,trackId:v})}}if(h&&g){m&&h.type==="audiovideo"&&this.logMuxedErr(o);let y=g.fragments[o.sn-1-g.startSN],E=o.sn===g.startSN,S=!y||o.cc>y.cc;if(i.independent!==!1){let{startPTS:T,endPTS:v,startDTS:x,endDTS:I}=h;if(l)l.elementaryStreams[h.type]={startPTS:T,endPTS:v,startDTS:x,endDTS:I};else if(h.firstKeyFrame&&h.independent&&r.id===1&&!S&&(this.couldBacktrack=!0),h.dropped&&h.independent){let A=this.getMainFwdBufferInfo(),b=(A?A.end:this.getLoadPosition())+this.config.maxBufferHole,_=h.firstKeyFramePTS?h.firstKeyFramePTS:T;if(!E&&b<_-this.config.maxBufferHole&&!S){this.backtrack(o);return}else S&&(o.gap=!0);o.setElementaryStreamInfo(h.type,o.start,v,o.start,I,!0)}else E&&T-(g.appliedTimelineOffset||0)>$s&&(o.gap=!0);o.setElementaryStreamInfo(h.type,T,v,x,I),this.backtrackFragment&&(this.backtrackFragment=o),this.bufferFragmentData(h,o,l,r,E||S)}else if(E||S)o.gap=!0;else{this.backtrack(o);return}}if(m){let{startPTS:y,endPTS:E,startDTS:S,endDTS:T}=m;l&&(l.elementaryStreams[ue.AUDIO]={startPTS:y,endPTS:E,startDTS:S,endDTS:T}),o.setElementaryStreamInfo(ue.AUDIO,y,E,S,T),this.bufferFragmentData(m,o,l,r)}if(g&&d!=null&&d.samples.length){let y={id:t,frag:o,details:g,samples:d.samples};s.trigger(p.FRAG_PARSING_METADATA,y)}if(g&&u){let y={id:t,frag:o,details:g,samples:u.samples};s.trigger(p.FRAG_PARSING_USERDATA,y)}}logMuxedErr(e){this.warn(`${pe(e)?"Media":"Init"} segment with muxed audiovideo where only video expected: ${e.url}`)}_bufferInitSegment(e,t,s,i){if(this.state!==C.PARSING)return;this.audioOnly=!!t.audio&&!t.video,this.altAudio&&!this.audioOnly&&(delete t.audio,t.audiovideo&&this.logMuxedErr(s));let{audio:r,video:a,audiovideo:o}=t;if(r){let c=e.audioCodec,h=Ms(r.codec,c);if(h==="mp4a"&&(h="mp4a.40.5"),this.audioCodecSwitch){h&&(h.indexOf("mp4a.40.5")!==-1?h="mp4a.40.2":h="mp4a.40.5");let u=r.metadata;u&&"channelCount"in u&&(u.channelCount||1)!==1&&!Eh()&&(h="mp4a.40.5")}h&&h.indexOf("mp4a.40.5")!==-1&&Sh()&&r.container!=="audio/mpeg"&&(h="mp4a.40.2",this.log(`Android: force audio codec to ${h}`)),c&&c!==h&&this.log(`Swapping manifest audio codec "${c}" for "${h}"`),r.levelCodec=h,r.id=K.MAIN,this.log(`Init audio buffer, container:${r.container}, codecs[selected/level/parsed]=[${h||""}/${c||""}/${r.codec}]`),delete t.audiovideo}if(a){a.levelCodec=e.videoCodec,a.id=K.MAIN;let c=a.codec;if(c?.length===4)switch(c){case"hvc1":case"hev1":a.codec="hvc1.1.6.L120.90";break;case"av01":a.codec="av01.0.04M.08";break;case"avc1":a.codec="avc1.42e01e";break}this.log(`Init video buffer, container:${a.container}, codecs[level/parsed]=[${e.videoCodec||""}/${c}]${a.codec!==c?" parsed-corrected="+a.codec:""}${a.supplemental?" supplemental="+a.supplemental:""}`),delete t.audiovideo}o&&(this.iframesOnly&&this.logMuxedErr(s),this.log(`Init audiovideo buffer, container:${o.container}, codecs[level/parsed]=[${e.codecs}/${o.codec}]`),delete t.video,delete t.audio);let l=Object.keys(t);if(l.length){if(this.hls.trigger(p.BUFFER_CODECS,t),!this.hls)return;l.forEach(c=>{let u=t[c].initSegment;u!=null&&u.byteLength&&this.hls.trigger(p.BUFFER_APPENDING,{type:c,data:u,frag:s,part:null,chunkMeta:i,parent:s.type})})}this.tickImmediate()}getMainFwdBufferInfo(){let e=this.getBufferOutput();return this.getFwdBufferInfo(e,K.MAIN)}get maxBufferLength(){let{levels:e,level:t}=this,s=e?.[t];return s?this.getMaxBufferLength(s.maxBitrate):this.config.maxBufferLength}backtrack(e){this.couldBacktrack=!0,this.backtrackFragment=e,this.resetTransmuxer(),this.flushBufferGap(e),this.fragmentTracker.removeFragment(e),this.fragPrevious=null,this.nextLoadPosition=e.start,this.state=C.IDLE}get nextLevel(){let e=this.nextBufferedFrag;return e?e.level:-1}get currentFrag(){var e;if(this.fragPlaying)return this.fragPlaying;let t=((e=this.media)==null?void 0:e.currentTime)||this.lastCurrentTime;return $(t)?this.getAppendedFrag(t):null}get currentProgramDateTime(){var e;let t=((e=this.media)==null?void 0:e.currentTime)||this.lastCurrentTime;if($(t)){let s=this.getLevelDetails(),i=this.currentFrag||(s?Gt(null,s.fragments,t):null);if(i){let r=i.programDateTime;if(r!==null){let a=r+(t-i.start)*1e3;return new Date(a)}}}return null}get currentLevel(){let e=this.currentFrag;return e?e.level:-1}get nextBufferedFrag(){let e=this.currentFrag;return e?this.followingBufferedFrag(e):null}get forceStartLoad(){return this._forceStartLoad}},gi=class extends fi{constructor(...e){super(...e),this.currentOp=void 0,this.nextOp=void 0,this.cached=[],this.cachedSize=0,this.cacheFragmentData=!0,this.initDetails=void 0,this.onBufferedToEnd=()=>{let t=this.media;t!=null&&t.seeking&&(t.currentTime=t.currentTime)},this.onMediaSeeking=()=>{}}setInitPts(e){this.initPTS=e.slice()}loadMediaAt(e,t){if(!this.hls)return;let{seekOnAppend:s}=t,i=e+this.timelineOffset;switch(this.nextLoadPosition=this.lastCurrentTime=i,this.startPosition=e,this.state){case C.STOPPED:case C.ENDED:case C.ERROR:this.state=C.IDLE}this.state===C.IDLE?(this.hls.resumeBuffering(),this.tick(),this.currentOp=[i,t]):this.nextOp=[i,t],this.hls.off(p.BUFFERED_TO_END,this.onBufferedToEnd);let r=this.media;s&&r&&this.seekTo(i)&&(this.currentOp=[i,t],this.nextOp=void 0,this.flushPipeline(i,!0))}seekTo(e){let t=this.media;if(t){var s;let i=(s=this.getLevelDetails())==null?void 0:s.edge,r=i!==void 0?i:t.duration;if(e>=r&&(e=r-.01),X.bufferInfo(t,e,0).len>0&&this.getBufferedAt(e))return t.currentTime=e,!0}return!1}getBufferedAt(e){return this.fragmentTracker.getBufferedFrag(e,K.MAIN)}cacheSet(e,t){if(!this.hls)return;e.data=t;let s=this.cached;s.push(e),this.cachedSize+=t.buffer.byteLength;let i=this.hls.config.iframeCacheLimit;for(;this.cachedSize>i&&s.length>1;){let r=s.shift();if(r.data)this.cachedSize-=r.data.byteLength,r.data=void 0;else{this.cached=s.filter(a=>!!a.data),this.cachedSize=s.reduce((a,{data:o})=>o?o.buffer.byteLength:0,0);break}}}onHandlerDestroying(){this.cached.length=0,this.cachedSize=0,super.onHandlerDestroying()}_handleFragmentLoadProgress(e){let t=e.frag,{part:s,payload:i}=e;this.cacheFragmentData&&!s&&i!=null&&i.byteLength&&!t.data&&pe(t)&&this.cacheSet(t,new Uint8Array(i.slice(0))),super._handleFragmentLoadProgress(e)}loadFragment(e,t,s){let i=this.fragmentTracker.getState(e);if((i===fe.NOT_LOADED||i===fe.PARTIAL)&&this.canReplayCached(e)){this.replayCachedFragment(e);return}super.loadFragment(e,t,s)}canReplayCached(e){var t;if(!this.cacheFragmentData||!((t=e.data)!=null&&t.byteLength))return!1;let s=e.decryptdata;return s?.keyFormat!=="identity"||!!s.key}replayCachedFragment(e){let t=e.data.slice().buffer;this.log(`Buffering cached ${e.type} sn: ${e.sn} of level ${e.level} (${t.byteLength} bytes)`),this.fragCurrent=e,this.startFragRequested=!0;let s=e.stats=new ts;s.loading.start=s.loading.first=s.loading.end=self.performance.now(),s.loaded=s.total=t.byteLength,s.chunkCount=1,this.state=C.FRAG_LOADING;let i={frag:e,part:null,payload:t,networkDetails:null};this._handleFragmentLoadProgress(i),this.hls.trigger(p.FRAG_LOADED,i),this._handleFragmentLoadComplete(i)}fragBufferedComplete(e,t){super.fragBufferedComplete(e,t);let{currentOp:s,nextOp:i}=this;this.currentOp=this.nextOp=void 0,this.state=C.STOPPED,s!=null&&s[1].seekOnAppend&&(this.flushPipeline(s[0],!i),this.seekTo(s[0])||this.log(`Could not seek to ${s[0]} after fragment buffered (superseded or flushed) buffer: ${this.media?js(X.getBuffered(this.media)):"none"}`)),i&&this.loadMediaAt.apply(this,i)}flushPipeline(e,t){if(t){let s=this.media;if(s){let i=X.bufferInfo(s,e,0),r=i.len?i.nextStart:0;r&&(this.fragmentTracker.removeFragmentsInRange(r,1/0,K.MAIN),this.flushMainBuffer(r,1/0))}this.hls.once(p.BUFFERED_TO_END,this.onBufferedToEnd)}this.hls.trigger(p.BUFFER_EOS,{type:"video"})}get playhead(){return this.nextLoadPosition}startLoad(){if(!this.startFragRequested){let e=this.hls;e.nextLoadLevel=e.startLevel===-1?0:e.firstAutoLevel}}seekToStartPos(){}setStartPosition(){}alignPlaylists(e,t,s){let i=this.initDetails;return this.initDetails=null,super.alignPlaylists(e,t,s||i||void 0)}getMainFwdBufferInfo(){let e=this.playhead,t=this.getBufferedAt(e);if(t){let s=t.duration;return{len:s,start:e,end:e+s,bufferedIndex:-1}}return{len:0,start:e,end:e,bufferedIndex:-1}}_streamEnded(){let e=this.playhead,t=this.fragmentTracker.getBufferedFrag(e,K.MAIN);return!!(t!=null&&t.endList)}},rn=class extends gi{constructor(...e){super(...e),this._img=void 0,this.queued=void 0,this.cacheFragmentData=!1}get image(){return this._img}set image(e){var t;let s=(t=this._img)==null?void 0:t.src;s&&self.URL.revokeObjectURL(s),this._img=e}loadMediaAt(e){if(!this.hls)return;let t=e+this.timelineOffset;switch(this.nextLoadPosition=this.lastCurrentTime=t,this.startPosition=e,this.state){case C.STOPPED:case C.ENDED:case C.ERROR:this.state=C.IDLE}if(this.state===C.IDLE){if(this.hls.resumeBuffering(),this.media||(this.media={}),this.tick(),this.state===C.IDLE){let s=this.getBufferedAt(e);s&&(this.fragCurrent=s,this.updateImage(s,null))}}else{let s=this.fragCurrent;(!s||e>=s.start&&e<s.end)&&(this.queued=[t])}}updateImage(e,t,s){let i=e.data;i||this.fragmentTracker.removeFragment(e);let r=this._img;if(r&&i){let a=self.performance.now(),o=t?t.stats:e.stats;o.buffering.start=e.stats.buffering.start=a,r.onload=()=>{if(!this.hls)return;let h=this.hls.levels[e.level];h!=null&&h.fragmentError&&(h.fragmentError=0,e.stats.retry=0);let u=self.performance.now(),d=t?t.stats:e.stats;d.buffering.end=e.stats.buffering.end=u,this.hls.trigger(p.FRAG_BUFFERED,{frag:e,part:t,stats:d,id:e.type,chunkMeta:s})},r.onerror=()=>{this.handleError("Image decode error",e,t,s)};let l=r.src;l&&self.URL.revokeObjectURL(l);let c=new Blob([i],{type:"image/jpeg"});r.src=self.URL.createObjectURL(c)}else this.state=C.STOPPED,this.processQueued()}processQueued(){let e=this.queued;this.queued=void 0,e&&this.loadMediaAt.apply(this,e)}handleError(e,t,s,i){if(!this.hls)return;let r=new Error(e);this.hls.trigger(p.ERROR,{type:W.MEDIA_ERROR,details:R.FRAG_PARSING_ERROR,chunkMeta:i,frag:t,part:s,fatal:!1,error:r,err:r})}_bufferInitSegment(){}bufferFragmentData(e,t,s,i){super.bufferFragmentData(e,t,s,i,!0);let r=Q(new Uint8Array(e.data1),["mdat"]);if(r.length===0){this.handleError("Could not find I-Frame mdat",t,s,i);return}let a=t;this.cacheSet(a,r[0]),this.updateImage(a,s,i)}fragBufferedComplete(e,t){this.fragmentTracker.fragBuffered(e,!0),super.fragBufferedComplete(e,t),this.processQueued()}checkFragPlaying(){var e;let t=(e=this.fragPrevious)==null?void 0:e.start;if(t!==void 0){let s=this.getAppendedFrag(t);if(s&&!jt(s,this.fragPlaying))return this.fragPlaying=s,!0}return!1}getMainFwdBufferInfo(){return{len:0,start:this.playhead,end:this.playhead,bufferedIndex:-1}}},$f=10,Uf="Image I-Frame player does not accept HTMLMediaElements",fo={seekOnAppend:!0},ks,zi,nn=class extends we{constructor(e,t){super("iframes",e.logger),this.hls=void 0,this.stats=void 0,this.variableList=null,this.initPTS=[],this.iframeInstances=void 0,this.instanceCounter=0,ks||(ks=Gf(t)),zi||(zi=Vf(ks)),this.hls=e,this.iframeInstances=[],this.registerListeners()}registerListeners(){let e=this.hls;e&&(e.on(p.MANIFEST_LOADING,this.clearAsset,this),e.on(p.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(p.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(p.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(p.FRAG_BUFFERED,this.onFragBuffered,this),e.on(p.DESTROYING,this.onDestroying,this))}unregisterListeners(){let e=this.hls;e&&(e.off(p.MANIFEST_LOADING,this.clearAsset,this),e.off(p.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(p.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(p.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(p.FRAG_BUFFERED,this.onFragBuffered,this),e.off(p.DESTROYING,this.onDestroying,this))}clearAsset(){this.stats=void 0,this.variableList=null,this.initPTS=[],this.iframeInstances.forEach(e=>e.destroy()),this.iframeInstances.length=0}onDestroying(){this.unregisterListeners(),this.clearAsset(),this.hls=void 0}onManifestLoaded(e,t){this.stats=t.stats,this.variableList=t.variableList}onLevelsUpdated(e,{levels:t}){var s;let i=(s=this.hls)==null?void 0:s.pathwayPriority;t.length&&i&&this.iframeInstances.forEach(r=>{r.pathwayPriority=i})}onInitPtsFound(e,{id:t,timestampOffsets:s}){t===K.MAIN&&(this.initPTS=s)}onFragBuffered(e,t){var s;let i=this.hls;i&&i.hasEnoughToStart&&(((s=i.mainForwardBufferInfo)==null?void 0:s.len)||0)>$f&&this.iframeInstances.forEach(r=>{if(!r.loadingEnabled){var a;r.startLoad(((a=this.hls)==null||(a=a.media)==null?void 0:a.currentTime)||0)}})}createIFramePlayer(e){var t;return this.createInstance(ks,(t=this.hls)==null?void 0:t.iframeVariants,e)}createImageIFramePlayer(e){var t;let s=(t=this.hls)==null?void 0:t.iframeVariants.filter(i=>i.imageCodec);return this.createInstance(zi,s,e,"image-")}createInstance(e,t,s,i){let{hls:r}=this;if(!r)return null;let{url:a,userConfig:o,latestLevelDetails:l,loadLevelObj:c,loadLevel:h,bandwidthEstimate:u,sessionId:d}=r,{stats:f,variableList:g}=this;if(!(t!=null&&t.length)||!f||!a)return null;let m=`${i||""}iframe-player-${this.instanceCounter++}`,y=r.levels,E=c||y[h],S=Qo(E,o.videoPreference),T=E?.pathwayId||".",v=Y(Y({},o),{},{loggerId:m,primarySessionId:d,videoPreference:S,abrEwmaDefaultEstimate:u,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},s),x=new e(v,a,this.initPTS,l);return this.iframeInstances=this.iframeInstances.filter(I=>!I.url),this.iframeInstances.push(x),x.trigger(p.MANIFEST_LOADED,{levels:t,contentSteering:{uri:"",pathwayId:T},sessionKeys:null,audioTracks:[],iframeVariants:[],sessionData:null,startTimeOffset:null,stats:f,networkDetails:null,url:a,variableList:g}),x}};function Gf(n){return class extends n{constructor(t,s,i,r){t.streamController||(t.streamController=gi),super(t),this._url=s,this.streamController.setInitPts(i),this.streamController.initDetails=r}loadSource(){}loadMediaAt(t,s=fo){if(t<0)return;let i=Y(Y({},fo),s);this.loadingEnabled||this.startLoad(t),this.streamController.loadMediaAt(t,i)}}}function Vf(n){return class extends n{constructor(t,s,i,r){t.cmcdController=void 0,t.emeController=void 0,t.streamController||(t.streamController=rn),t.capLevelController=void 0,t.bufferController=void 0,super(t,s,i,r)}attachImage(t){this.streamController.image=t}detachImage(){this.streamController.image=void 0}loadSource(){}attachMedia(){throw new Error(Uf)}detachMedia(){}recoverMediaError(){}transferMedia(){return null}loadMediaAt(t){if(t<0)return null;this.loadingEnabled||this.startLoad(t),this.streamController.loadMediaAt(t)}}}var St=.025,mi=(function(n){return n[n.Point=0]="Point",n[n.Range=1]="Range",n})({});function Kf(n,e,t){return`${n.identifier}-${t+1}-${Jt(e)}`}var an=class{constructor(e,t){this.base=void 0,this._duration=null,this._timelineStart=null,this.appendInPlaceDisabled=void 0,this.appendInPlaceStarted=void 0,this.dateRange=void 0,this.hasPlayed=!1,this.cumulativeDuration=0,this.resumeOffset=NaN,this.playoutLimit=NaN,this.restrictions={skip:!1,jump:!1},this.snapOptions={out:!1,in:!1},this.assetList=[],this.assetListLoader=void 0,this.assetListResponse=null,this.resumeAnchor=void 0,this.error=void 0,this.resetOnResume=void 0,this.base=t,this.dateRange=e,this.setDateRange(e)}setDateRange(e){this.dateRange=e,this.resumeOffset=e.attr.optionalFloat("X-RESUME-OFFSET",this.resumeOffset),this.playoutLimit=e.attr.optionalFloat("X-PLAYOUT-LIMIT",this.playoutLimit),this.restrictions=e.attr.enumeratedStringList("X-RESTRICT",this.restrictions),this.snapOptions=e.attr.enumeratedStringList("X-SNAP",this.snapOptions)}reset(){var e;this.appendInPlaceStarted=!1,(e=this.assetListLoader)==null||e.destroy(),this.assetListLoader=void 0,this.supplementsPrimary||(this.assetListResponse=null,this.assetList=[],this._duration=null)}isAssetPastPlayoutLimit(e){var t;if(e>0&&e>=this.assetList.length)return!0;let s=this.playoutLimit;return e<=0||isNaN(s)?!1:s===0?!0:(((t=this.assetList[e])==null?void 0:t.startOffset)||0)>s}findAssetIndex(e){return this.assetList.indexOf(e)}get identifier(){return this.dateRange.id}get startDate(){return this.dateRange.startDate}get startTime(){let e=this.dateRange.startTime;if(this.snapOptions.out){let t=this.dateRange.tagAnchor;if(t)return go(t,e)?Us(e,t):e}return e}get startOffset(){return this.cue.pre?0:this.startTime}get startIsAligned(){if(this.startTime===0||this.snapOptions.out)return!0;let e=this.dateRange.tagAnchor;if(e){let t=this.dateRange.startTime,s=Us(t,e);return t-s<.1}return!1}get resumptionOffset(){let e=this.resumeOffset,t=$(e)?e:this.duration;return this.cumulativeDuration+t}get resumeTime(){let e=this.startOffset+this.resumptionOffset;if(this.snapOptions.in){let t=this.resumeAnchor;if(t)return go(t,e)?Us(e,t):e}return e}get appendInPlace(){return this.appendInPlaceStarted?!0:this.appendInPlaceDisabled?!1:!!(!this.cue.once&&!this.cue.pre&&this.startIsAligned&&(isNaN(this.playoutLimit)&&isNaN(this.resumeOffset)||this.resumeOffset&&this.duration&&Math.abs(this.resumeOffset-this.duration)<St))}set appendInPlace(e){if(this.appendInPlaceStarted){this.resetOnResume=!e;return}this.appendInPlaceDisabled=!e}get timelineStart(){return this._timelineStart!==null?this._timelineStart:this.startTime}set timelineStart(e){this._timelineStart=e}get duration(){let e=this.playoutLimit,t;return this._duration!==null?t=this._duration:this.dateRange.duration?t=this.dateRange.duration:t=this.dateRange.plannedDuration||0,!isNaN(e)&&e<t&&(t=e),t}set duration(e){this._duration=e}get cue(){return this.dateRange.cue}get timelineOccupancy(){return this.dateRange.attr["X-TIMELINE-OCCUPIES"]==="RANGE"?mi.Range:mi.Point}get supplementsPrimary(){return this.dateRange.attr["X-TIMELINE-STYLE"]==="PRIMARY"}get contentMayVary(){return this.dateRange.attr["X-CONTENT-MAY-VARY"]!=="NO"}get assetUrl(){return this.dateRange.attr["X-ASSET-URI"]}get assetListUrl(){return this.dateRange.attr["X-ASSET-LIST"]}get baseUrl(){return this.base.url}get assetListLoaded(){return this.assetList.length>0||this.assetListResponse!==null}toString(){return Hf(this)}};function Us(n,e){return n-e.start<e.duration/2&&!(Math.abs(n-(e.start+e.duration))<St)?e.start:e.start+e.duration}function go(n,e){return e>n.start-St&&e<n.start+n.duration+St}function oc(n,e,t){let s=new self.URL(n,t);return s.protocol!=="data:"&&Tt(s,"_HLS_primary_id",e),s}function Xi(n,e){for(;(t=n.assetList[++e])!=null&&t.error;)var t;return e}function Hf(n){return`["${n.identifier}" ${n.cue.pre?"<pre>":n.cue.post?"<post>":""}${n.timelineStart.toFixed(2)}-${n.resumeTime.toFixed(2)}]`}function Mt(n){let e=n.timelineStart,t=n.duration||0;return`["${n.identifier}" ${e.toFixed(2)}-${(e+t).toFixed(2)}]`}var on=class{constructor(e,t,s,i){this.hls=void 0,this.interstitial=void 0,this.assetItem=void 0,this.tracks=null,this.hasDetails=!1,this.mediaAttached=null,this._currentTime=void 0,this._bufferedEosTime=void 0,this.checkPlayout=()=>{this.reachedPlayout(this.currentTime)&&this.hls&&this.hls.trigger(p.PLAYOUT_LIMIT_REACHED,{})};let r=this.hls=new e(t);this.interstitial=s,this.assetItem=i;let a=()=>{this.hasDetails=!0};r.once(p.LEVEL_LOADED,a),r.once(p.AUDIO_TRACK_LOADED,a),r.once(p.SUBTITLE_TRACK_LOADED,a),r.on(p.MEDIA_ATTACHING,(o,{media:l})=>{this.removeMediaListeners(),this.mediaAttached=l,this.interstitial.playoutLimit&&(l.addEventListener("timeupdate",this.checkPlayout),this.appendInPlace&&r.on(p.BUFFER_APPENDED,()=>{let h=this.bufferedEnd;this.reachedPlayout(h)&&(this._bufferedEosTime=h,r.trigger(p.BUFFERED_TO_END,void 0))}))})}get appendInPlace(){return this.interstitial.appendInPlace}loadSource(){let e=this.hls;if(e)if(e.url)e.levels.length&&!e.started&&e.startLoad(-1,!0);else{let t=this.assetItem.uri;try{t=oc(t,e.config.primarySessionId||"").href}catch{}e.loadSource(t)}}bufferedInPlaceToEnd(e,t){var s;if(!this.appendInPlace)return!1;if((s=this.hls)!=null&&s.bufferedToEnd)return!0;if(!e)return!1;let i=Math.min(this._bufferedEosTime||1/0,this.duration),r=this.timelineOffset+(t||0),a=X.bufferInfo(e,r,.02);return this.getAssetTime(a.end)>=i-.02}reachedPlayout(e){let s=this.interstitial.playoutLimit;return this.startOffset+e>=s}get destroyed(){var e;return!((e=this.hls)!=null&&e.userConfig)}get assetId(){return this.assetItem.identifier}get interstitialId(){return this.assetItem.parentIdentifier}get media(){var e;return((e=this.hls)==null?void 0:e.media)||null}get bufferedEnd(){let e=this.media||this.mediaAttached;if(!e)return this._bufferedEosTime?this._bufferedEosTime:this.currentTime;let t=X.bufferInfo(e,e.currentTime,.001);return this.getAssetTime(t.end)}get currentTime(){let e=this.media||this.mediaAttached;return e?this.getAssetTime(e.currentTime):this._currentTime||0}get duration(){let e=this.assetItem.duration;if(!e)return 0;let t=this.interstitial.playoutLimit;if(t){let s=t-this.startOffset;if(s>0&&s<e)return s}return e}get remaining(){let e=this.duration;return e?Math.max(0,e-this.currentTime):0}get startOffset(){return this.assetItem.startOffset}get timelineOffset(){var e;return((e=this.hls)==null?void 0:e.config.timelineOffset)||0}set timelineOffset(e){let t=this.timelineOffset;if(e!==t){let s=e-t;if(Math.abs(s)>1/9e4&&this.hls){if(this.hasDetails)throw new Error("Cannot set timelineOffset after playlists are loaded");this.hls.config.timelineOffset=e}}}getAssetTime(e){let t=this.timelineOffset,s=this.duration;return Math.min(Math.max(0,e-t),s)}removeMediaListeners(){let e=this.mediaAttached;e&&(this._currentTime=e.currentTime,this.bufferSnapShot(),e.removeEventListener("timeupdate",this.checkPlayout))}bufferSnapShot(){if(this.mediaAttached){var e;(e=this.hls)!=null&&e.bufferedToEnd&&(this._bufferedEosTime=this.bufferedEnd)}}destroy(){this.removeMediaListeners(),this.hls&&this.hls.destroy(),this.hls=null,this.tracks=this.mediaAttached=this.checkPlayout=null}attachMedia(e){var t;this.loadSource(),(t=this.hls)==null||t.attachMedia(e)}detachMedia(){var e;this.removeMediaListeners(),this.mediaAttached=null,(e=this.hls)==null||e.detachMedia()}resumeBuffering(){var e;(e=this.hls)==null||e.resumeBuffering()}pauseBuffering(){var e;(e=this.hls)==null||e.pauseBuffering()}transferMedia(){var e;return this.bufferSnapShot(),((e=this.hls)==null?void 0:e.transferMedia())||null}resetDetails(){let e=this.hls;if(e&&this.hasDetails){e.stopLoad();let t=s=>delete s.details;e.levels.forEach(t),e.allAudioTracks.forEach(t),e.allSubtitleTracks.forEach(t),this.hasDetails=!1}}on(e,t,s){var i;(i=this.hls)==null||i.on(e,t)}once(e,t,s){var i;(i=this.hls)==null||i.once(e,t)}off(e,t,s){var i;(i=this.hls)==null||i.off(e,t)}toString(){var e;return`HlsAssetPlayer: ${Mt(this.assetItem)} ${(e=this.hls)==null?void 0:e.sessionId} ${this.appendInPlace?"append-in-place":""}`}},Qi=.033,ln=class extends we{constructor(e,t){super("interstitials-sched",t),this.onScheduleUpdate=void 0,this.eventMap={},this.events=null,this.items=null,this.durations={primary:0,playout:0,integrated:0},this.onScheduleUpdate=e}destroy(){this.reset(),this.onScheduleUpdate=null}reset(){this.eventMap={},this.setDurations(0,0,0),this.events&&this.events.forEach(e=>e.reset()),this.events=this.items=null}resetErrorsInRange(e,t){return this.events?this.events.reduce((s,i)=>e<=i.startOffset&&t>i.startOffset?(delete i.error,s+1):s,0):0}get duration(){let e=this.items;return e?e[e.length-1].end:0}get length(){return this.items?this.items.length:0}getEvent(e){return e&&this.eventMap[e]||null}hasEvent(e){return e in this.eventMap}findItemIndex(e,t){if(e.event)return this.findEventIndex(e.event.identifier);let s=-1;e.nextEvent?s=this.findEventIndex(e.nextEvent.identifier)-1:e.previousEvent&&(s=this.findEventIndex(e.previousEvent.identifier)+1);let i=this.items;if(i)for(i[s]||(t===void 0&&(t=e.start),s=this.findItemIndexAtTime(t));s>=0&&(r=i[s])!=null&&r.event;){var r;s--}return s}findItemIndexAtTime(e,t){let s=this.items;if(s)for(let i=0;i<s.length;i++){let r=s[i];t&&t!=="primary"&&(r=r[t]);let a=r.start,o=s[i].event,l=o!=null&&o.cue.pre?o.duration:r.end;if(e===a||e>a&&e<l)return i}return-1}findJumpRestrictedIndex(e,t){let s=this.items;if(s)for(let i=e;i<=t&&s[i];i++){let r=s[i].event;if(r!=null&&r.restrictions.jump&&!r.appendInPlace)return i}return-1}findEventIndex(e){let t=this.items;if(t)for(let i=t.length;i--;){var s;if(((s=t[i].event)==null?void 0:s.identifier)===e)return i}return-1}findAssetIndex(e,t){let s=e.assetList,i=s.length;if(i>1)for(let r=0;r<i;r++){let a=s[r];if(!a.error){let o=a.timelineStart;if(t===o||t>o&&(t<o+(a.duration||0)||r===i-1))return r}}return 0}get assetIdAtEnd(){var e;let t=(e=this.items)==null||(e=e[this.length-1])==null?void 0:e.event;if(t){let s=t.assetList,i=s[s.length-1];if(i)return i.identifier}return null}parseInterstitialDateRanges(e,t,s=0){let i=e.main.details,{dateRanges:r}=i,a=this.events,o=this.parseDateRanges(r,{url:i.url},t),l=Object.keys(r),c=a?a.filter(h=>l.indexOf(h.identifier)===-1):[];o.length&&o.sort((h,u)=>{let d=h.cue.pre,f=h.cue.post,g=u.cue.pre,m=u.cue.post;if(d&&!g)return-1;if(g&&!d||f&&!m)return 1;if(m&&!f)return-1;if(!d&&!g&&!f&&!m){let y=h.startTime,E=u.startTime;if(y!==E)return y-E}return h.dateRange.tagOrder-u.dateRange.tagOrder}),this.events=o,c.forEach(h=>{this.removeEvent(h)}),this.updateSchedule(e,c,s)}updateSchedule(e,t=[],s=0,i=!1){let r=this.events||[];if(r.length||t.length||this.length<2){let a=this.items,o=this.parseSchedule(r,e,s);(i||t.length||a?.length!==o.length||o.some((c,h)=>Math.abs(c.playout.start-a[h].playout.start)>.005||Math.abs(c.playout.end-a[h].playout.end)>.005))&&(this.items=o,this.onScheduleUpdate(t,a))}}parseDateRanges(e,t,s){let i=[],r=Object.keys(e);for(let a=0;a<r.length;a++){let o=r[a],l=e[o];if(l.isInterstitial){let c=this.eventMap[o];c?c.setDateRange(l):(c=new an(l,t),this.eventMap[o]=c,s===!1&&(c.appendInPlace=s)),i.push(c)}}return i}parseSchedule(e,t,s=0){let i=[],r=t.main.details,a=r.live?1/0:r.edge,o=0;if(e=e.filter(c=>!c.error&&!(c.cue.once&&c.hasPlayed)),e.length){this.resolveOffsets(e,t);let c=0,h=0;if(e.forEach((u,d)=>{let f=u.cue.pre,g=u.cue.post,m=e[d-1]||null,y=u.appendInPlace,E=g?a:u.startOffset,S=u.duration,T=u.timelineOccupancy===mi.Range?S:0,v=f&&r.live?s+(u.resumeOffset||0):0,x=v||u.resumptionOffset,I=m?.startTime===E,A=E+u.cumulativeDuration,b=y?A+S:E+x;if(f||!g&&E<=0){let L=h;h+=T,u.timelineStart=A;let P=o;o+=S,i.push({event:u,start:A,end:b,playout:{start:P,end:o},integrated:{start:L,end:h}})}else if(E<=a){if(!I){let D=E-c;if(D>Qi){let M=c,U=h;h+=D;let B=o;o+=D;let k={previousEvent:e[d-1]||null,nextEvent:u,start:M,end:M+D,playout:{start:B,end:o},integrated:{start:U,end:h}};i.push(k)}else D>0&&m&&(m.cumulativeDuration+=D,i[i.length-1].end=E)}g&&(b=A),u.timelineStart=A;let L=h;h+=T;let P=o;o+=S,i.push({event:u,start:A,end:b,playout:{start:P,end:o},integrated:{start:L,end:h}})}else return;let _=v||u.resumeTime;g||_>a?c=a:!f&&b&&u.appendInPlaceStarted&&_-b>Qi?c=b:c=_}),c<a){var l;let u=c,d=h,f=a-c;h+=f;let g=o;o+=f,i.push({previousEvent:((l=i[i.length-1])==null?void 0:l.event)||null,nextEvent:null,start:c,end:u+f,playout:{start:g,end:o},integrated:{start:d,end:h}})}this.setDurations(a,o,h)}else i.push({previousEvent:null,nextEvent:null,start:0,end:a,playout:{start:0,end:a},integrated:{start:0,end:a}}),this.setDurations(a,a,a);return i}setDurations(e,t,s){this.durations={primary:e,playout:t,integrated:s}}resolveOffsets(e,t){let s=t.main.details,i=s.live?1/0:s.edge,r=0,a=-1;e.forEach((o,l)=>{let c=o.cue.pre,h=o.cue.post,u=c?0:h?i:o.startTime;this.updateAssetDurations(o),a===u?o.cumulativeDuration=r:(r=0,a=u),!h&&o.snapOptions.in&&(o.resumeAnchor=Gt(null,s.fragments,o.startOffset+o.resumptionOffset,0,0)||void 0),o.appendInPlace&&!o.appendInPlaceStarted&&(this.primaryCanResumeInPlaceAt(o,t)||(o.appendInPlace=!1)),!o.appendInPlace&&l+1<e.length&&e[l+1].startTime-e[l].resumeTime<Qi&&(e[l+1].appendInPlace=!1,e[l+1].appendInPlace&&this.warn(`Could not change append strategy for abutting event ${o}`));let f=$(o.resumeOffset)?o.resumeOffset:o.duration;r+=f})}primaryCanResumeInPlaceAt(e,t){let s=e.resumeTime,i=e.startTime+e.resumptionOffset;return Math.abs(s-i)>St?(this.log(`"${e.identifier}" resumption ${s} not aligned with estimated timeline end ${i}`),!1):!Object.keys(t).some(a=>{let o=t[a].details,l=o.edge;if(s>=l)return this.log(`"${e.identifier}" resumption ${s} past ${a} playlist end ${l}`),!1;let c=Gt(null,o.fragments,s);if(!c)return this.log(`"${e.identifier}" resumption ${s} does not align with any fragments in ${a} playlist (${o.fragStart}-${o.fragmentEnd})`),!0;let h=a==="audio"?.175:0;return Math.abs(c.start-s)<St+h||Math.abs(c.end-s)<St+h?!1:(this.log(`"${e.identifier}" resumption ${s} not aligned with ${a} fragment bounds (${c.start}-${c.end} sn: ${c.sn} cc: ${c.cc})`),!0)})}updateAssetDurations(e){if(!e.assetListLoaded)return;let t=e.timelineStart,s=0,i=!1,r=!1;for(let a=0;a<e.assetList.length;a++){let o=e.assetList[a],l=t+s;o.startOffset=s,o.timelineStart=l,i||(i=o.duration===null),r||(r=!!o.error);let c=o.error?0:o.duration||0;s+=c}i&&!r?e.duration=Math.max(s,e.duration):e.duration=s}removeEvent(e){e.reset(),delete this.eventMap[e.identifier]}};function Be(n){return`[${n.event?'"'+n.event.identifier+'"':"primary"}: ${n.start.toFixed(2)}-${n.end.toFixed(2)}]`}var cn=class{constructor(e){this.hls=void 0,this.hls=e}destroy(){this.hls=null}loadAssetList(e,t){let s=e.assetListUrl,i;try{i=oc(s,this.hls.sessionId,e.baseUrl)}catch(d){let f=this.assignAssetListError(e,R.ASSET_LIST_LOAD_ERROR,d,s);this.hls.trigger(p.ERROR,f);return}t&&i.protocol!=="data:"&&Tt(i,"_HLS_start_offset",""+t);let r=this.hls.config,a=r.loader,o=new a(r),l={type:se.INTERSTITIAL_ASSET_LIST,responseType:"json",url:i.href},c=r.interstitialAssetListLoadPolicy.default,h={loadPolicy:c,timeout:c.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},u={onSuccess:(d,f,g,m)=>{let y=d.data,E=y?.ASSETS;if(!Array.isArray(E)){let S=this.assignAssetListError(e,R.ASSET_LIST_PARSING_ERROR,new Error("Invalid interstitial asset list"),g.url,f,m);this.hls.trigger(p.ERROR,S);return}e.assetListResponse=y,this.hls.trigger(p.ASSET_LIST_LOADED,{event:e,assetListResponse:y,networkDetails:m})},onError:(d,f,g,m)=>{let y=this.assignAssetListError(e,R.ASSET_LIST_LOAD_ERROR,new Error(`Error loading X-ASSET-LIST: HTTP status ${d.code} ${d.text} (${f.url})`),f.url,m,g);this.hls.trigger(p.ERROR,y)},onTimeout:(d,f,g)=>{let m=this.assignAssetListError(e,R.ASSET_LIST_LOAD_TIMEOUT,new Error(`Timeout loading X-ASSET-LIST (${f.url})`),f.url,d,g);this.hls.trigger(p.ERROR,m)}};return o.load(l,h,u),this.hls.trigger(p.ASSET_LIST_LOADING,{event:e}),o}assignAssetListError(e,t,s,i,r,a){return e.error=s,{type:W.NETWORK_ERROR,details:t,fatal:!1,interstitial:e,url:i,error:s,networkDetails:a,stats:r}}};function mo(n){var e;n==null||(e=n.play())==null||e.catch(()=>{})}function Lt(n,e){return`[${n}] Advancing timeline position to ${e}`}var hn=class extends we{constructor(e,t){super("interstitials",e.logger),this.HlsPlayerClass=void 0,this.hls=void 0,this.assetListLoader=void 0,this.mediaSelection=null,this.altSelection=null,this.media=null,this.detachedData=null,this.requiredTracks=null,this.manager=null,this.playerQueue=[],this.bufferedPos=-1,this.timelinePos=-1,this.schedule=void 0,this.playingItem=null,this.bufferingItem=null,this.waitingItem=null,this.endedItem=null,this.playingAsset=null,this.endedAsset=null,this.bufferingAsset=null,this.bufferPastEdge=!1,this.shouldPlay=!1,this.onPlay=()=>{this.shouldPlay=!0},this.onPause=()=>{this.shouldPlay=!1},this.onSeeking=()=>{let s=this.currentTime;if(s===void 0||this.playbackDisabled||!this.schedule)return;let i=s-this.timelinePos;if(Math.abs(i)<1/7056e5)return;let a=i<=-.01;this.timelinePos===-1&&!this.effectivePlayingItem&&this.checkStart(),this.timelinePos=s,this.bufferedPos=s;let o=this.playingItem;if(!o){this.checkBuffer();return}if(a&&this.schedule.resetErrorsInRange(s,s-i)&&this.updateSchedule(!0),this.checkBuffer(),a&&s<o.start||s>=o.end){var l;let f=this.findItemIndex(o),g=this.schedule.findItemIndexAtTime(s);if(g===-1&&(g=f+(a?-1:1),this.log(`seeked ${a?"back ":""}to position not covered by schedule ${s} (resolving from ${f} to ${g})`)),!this.isInterstitial(o)&&(l=this.media)!=null&&l.paused&&(this.shouldPlay=!1),!a&&g>f){let m=this.schedule.findJumpRestrictedIndex(f+1,g);if(m>f){this.setSchedulePosition(m);return}}this.setSchedulePosition(g);return}let c=this.playingAsset;if(!c){if(this.playingLastItem&&this.isInterstitial(o)){let f=o.event.assetList[0];f&&(this.endedItem=this.playingItem,this.playingItem=null,this.setScheduleToAssetAtTime(s,f))}return}let h=c.timelineStart,u=c.duration||0;if(a&&s<h||s>=h+u){var d;(d=o.event)!=null&&d.appendInPlace&&(this.clearAssetPlayers(o.event,o),this.flushFrontBuffer(s)),this.setScheduleToAssetAtTime(s,c)}},this.onTimeupdate=()=>{let s=this.currentTime;if(s===void 0||this.playbackDisabled)return;if(this.timelinePos===-1&&!this.effectivePlayingItem&&this.checkStart(),s>this.timelinePos)this.timelinePos=s,s>this.bufferedPos&&this.checkBuffer();else return;let i=this.playingItem;if(!i||this.playingLastItem)return;if(s>=i.end){this.timelinePos=i.end;let o=this.findItemIndex(i);this.setSchedulePosition(o+1)}let r=this.playingAsset;if(!r)return;let a=r.timelineStart+(r.duration||0);s>=a&&this.setScheduleToAssetAtTime(s,r)},this.onScheduleUpdate=(s,i)=>{let r=this.schedule;if(!r)return;let a=this.playingItem,o=r.events||[],l=r.items||[],c=r.durations,h=s.map(y=>y.identifier),u=!!(o.length||h.length);(u||i)&&this.log(`INTERSTITIALS_UPDATED (${o.length}): ${o}
43
+ Schedule: ${l.map(y=>Be(y))} pos: ${this.timelinePos}`),h.length&&this.log(`Removed events ${h}`);let d=null,f=null;a&&(d=this.updateItem(a,this.timelinePos),this.itemsMatch(a,d)?this.playingItem=d:this.waitingItem=null);let g=this.waitingItem;g&&(this.waitingItem=this.updateItem(g),!this.waitingItem&&!a&&(this.log(`INTERSTITIAL_ENDED unresolved ${Be(g)}`),this.hls.trigger(p.INTERSTITIAL_ENDED,{event:g.event,schedule:l.slice(0),scheduleIndex:-1})));let m=this.bufferingItem;if(m&&(f=this.updateItem(m,this.bufferedPos),this.itemsMatch(m,f)?this.bufferingItem=f:m.event&&(this.bufferingItem=this.playingItem,this.clearInterstitial(m.event,null))),s.forEach(y=>{y.assetList.forEach(E=>{this.clearAssetPlayer(E.identifier,null)})}),this.playerQueue.forEach(y=>{if(y.interstitial.appendInPlace){let E=y.assetItem.timelineStart,S=y.timelineOffset-E;if(S)try{y.timelineOffset=E}catch(T){Math.abs(S)>St&&this.warn(`${T} ("${y.assetId}" ${y.timelineOffset}->${E})`)}}}),u||i){if(this.hls.trigger(p.INTERSTITIALS_UPDATED,{events:o.slice(0),schedule:l.slice(0),durations:c,removedIds:h}),this.isInterstitial(a)&&h.indexOf(a.event.identifier)>-1){this.warn(`Interstitial "${a.event.identifier}" removed while playing`),this.primaryFallback(a.event);return}a&&this.trimInPlace(d,a),m&&f!==d&&this.trimInPlace(f,m),this.checkBuffer()}},this.hls=e,this.HlsPlayerClass=t,this.assetListLoader=new cn(e),this.schedule=new ln(this.onScheduleUpdate,e.logger),this.registerListeners()}registerListeners(){let e=this.hls;e&&(e.on(p.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(p.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(p.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(p.MANIFEST_LOADING,this.onManifestLoading,this),e.on(p.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(p.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(p.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),e.on(p.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.on(p.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),e.on(p.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),e.on(p.ASSET_LIST_LOADED,this.onAssetListLoaded,this),e.on(p.BUFFER_APPENDED,this.onBufferAppended,this),e.on(p.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(p.BUFFERED_TO_END,this.onBufferedToEnd,this),e.on(p.MEDIA_ENDED,this.onMediaEnded,this),e.on(p.ERROR,this.onError,this),e.on(p.DESTROYING,this.onDestroying,this))}unregisterListeners(){let e=this.hls;e&&(e.off(p.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(p.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(p.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(p.MANIFEST_LOADING,this.onManifestLoading,this),e.off(p.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(p.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(p.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),e.off(p.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.off(p.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),e.off(p.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),e.off(p.ASSET_LIST_LOADED,this.onAssetListLoaded,this),e.off(p.BUFFER_CODECS,this.onBufferCodecs,this),e.off(p.BUFFER_APPENDED,this.onBufferAppended,this),e.off(p.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(p.BUFFERED_TO_END,this.onBufferedToEnd,this),e.off(p.MEDIA_ENDED,this.onMediaEnded,this),e.off(p.ERROR,this.onError,this),e.off(p.DESTROYING,this.onDestroying,this))}startLoad(){this.resumeBuffering()}stopLoad(){this.pauseBuffering()}resumeBuffering(){var e;(e=this.getBufferingPlayer())==null||e.resumeBuffering()}pauseBuffering(){var e;(e=this.getBufferingPlayer())==null||e.pauseBuffering()}destroy(){this.unregisterListeners(),this.stopLoad(),this.assetListLoader&&this.assetListLoader.destroy(),this.emptyPlayerQueue(),this.clearScheduleState(),this.schedule&&this.schedule.destroy(),this.media=this.detachedData=this.mediaSelection=this.requiredTracks=this.altSelection=this.schedule=this.manager=null,this.hls=this.HlsPlayerClass=null,this.assetListLoader=null,this.onPlay=this.onPause=this.onSeeking=this.onTimeupdate=null,this.onScheduleUpdate=null}onDestroying(){let e=this.primaryMedia||this.media;e&&this.removeMediaListeners(e)}removeMediaListeners(e){le(e,"play",this.onPlay),le(e,"pause",this.onPause),le(e,"seeking",this.onSeeking),le(e,"timeupdate",this.onTimeupdate)}onMediaAttaching(e,t){let s=this.media=t.media;ce(s,"seeking",this.onSeeking),ce(s,"timeupdate",this.onTimeupdate),ce(s,"play",this.onPlay),ce(s,"pause",this.onPause)}onMediaAttached(e,t){let s=this.effectivePlayingItem,i=this.detachedData;if(this.detachedData=null,s===null)this.checkStart();else if(!i){this.clearScheduleState();let r=this.findItemIndex(s);this.setSchedulePosition(r)}}clearScheduleState(){this.log("clear schedule state"),this.playingItem=this.bufferingItem=this.waitingItem=this.endedItem=this.playingAsset=this.endedAsset=this.bufferingAsset=null}onMediaDetaching(e,t){let s=!!t.transferMedia,i=this.media;if(this.media=null,!s&&(i&&this.removeMediaListeners(i),this.detachedData)){let r=this.getBufferingPlayer();r&&(this.log(`Removing schedule state for detachedData and ${r}`),this.playingAsset=this.endedAsset=this.bufferingAsset=this.bufferingItem=this.waitingItem=this.detachedData=null,r.detachMedia()),this.shouldPlay=!1}}get interstitialsManager(){if(!this.hls)return null;if(this.manager)return this.manager;let e=this,t=()=>e.bufferingItem||e.waitingItem,s=u=>u&&e.getAssetPlayer(u.identifier),i=(u,d,f,g,m)=>{if(u){let y=u[d].start,E=u.event;if(E){if(d==="playout"||E.timelineOccupancy!==mi.Point){let S=s(f);S?.interstitial===E&&(y+=S.assetItem.startOffset+S[m])}}else{let S=g==="bufferedPos"?a():e[g];y+=S-u.start}return y}return 0},r=(u,d)=>{var f;if(u!==0&&d!=="primary"&&(f=e.schedule)!=null&&f.length){var g;let m=e.schedule.findItemIndexAtTime(u),y=(g=e.schedule.items)==null?void 0:g[m];if(y){let E=y[d].start-y.start;return u+E}}return u},a=()=>{let u=e.bufferedPos;return u===Number.MAX_VALUE?o("primary"):Math.max(u,0)},o=u=>{var d,f;return(d=e.primaryDetails)!=null&&d.live?e.primaryDetails.edge:((f=e.schedule)==null?void 0:f.durations[u])||0},l=(u,d)=>{var f,g;let m=e.effectivePlayingItem;if(m!=null&&(f=m.event)!=null&&f.restrictions.skip||!e.schedule)return;e.log(`seek to ${u} "${d}"`);let y=e.effectivePlayingItem,E=e.schedule.findItemIndexAtTime(u,d),S=(g=e.schedule.items)==null?void 0:g[E],T=e.getBufferingPlayer(),v=T?.interstitial,x=v?.appendInPlace,I=y&&e.itemsMatch(y,S);if(y&&(x||I)){let A=s(e.playingAsset),b=A?.media||e.primaryMedia;if(b){let _=d==="primary"?b.currentTime:i(y,d,e.playingAsset,"timelinePos","currentTime"),L=u-_,P=(x?_:b.currentTime)+L;if(P>=0&&(!A||x||P<=A.duration)){b.currentTime=P;return}}}if(S){let A=u;if(d!=="primary"){let _=S[d].start,L=u-_;A=S.start+L}let b=!e.isInterstitial(S);if((!e.isInterstitial(y)||y.event.appendInPlace)&&(b||S.event.appendInPlace)){let _=e.media||(x?T?.media:null);_&&(_.currentTime=A)}else if(y){let _=e.findItemIndex(y);if(E>_){let P=e.schedule.findJumpRestrictedIndex(_+1,E);if(P>_){e.setSchedulePosition(P);return}}let L=0;if(b)e.timelinePos=A,e.checkBuffer();else{let P=S.event.assetList,D=u-(S[d]||S).start;for(let M=P.length;M--;){let U=P[M];if(U.duration&&D>=U.startOffset&&D<U.startOffset+U.duration){L=M;break}}}e.setSchedulePosition(E,L)}}},c=()=>{let u=e.effectivePlayingItem;if(e.isInterstitial(u))return u;let d=t();return e.isInterstitial(d)?d:null},h={get bufferedEnd(){let u=t(),d=e.bufferingItem;if(d&&d===u){var f;return i(d,"playout",e.bufferingAsset,"bufferedPos","bufferedEnd")-d.playout.start||((f=e.bufferingAsset)==null?void 0:f.startOffset)||0}return 0},get currentTime(){let u=c(),d=e.effectivePlayingItem;return d&&d===u?i(d,"playout",e.effectivePlayingAsset,"timelinePos","currentTime")-d.playout.start:0},set currentTime(u){let d=c(),f=e.effectivePlayingItem;f&&f===d&&l(u+f.playout.start,"playout")},get duration(){let u=c();return u?u.playout.end-u.playout.start:0},get assetPlayers(){var u;let d=(u=c())==null?void 0:u.event.assetList;return d?d.map(f=>e.getAssetPlayer(f.identifier)):[]},get playingIndex(){var u;let d=(u=c())==null?void 0:u.event;return d&&e.effectivePlayingAsset?d.findAssetIndex(e.effectivePlayingAsset):-1},get scheduleItem(){return c()}};return this.manager={get events(){var u;return((u=e.schedule)==null||(u=u.events)==null?void 0:u.slice(0))||[]},get schedule(){var u;return((u=e.schedule)==null||(u=u.items)==null?void 0:u.slice(0))||[]},get interstitialPlayer(){return c()?h:null},get playerQueue(){return e.playerQueue.slice(0)},get bufferingAsset(){return e.bufferingAsset},get bufferingItem(){return t()},get bufferingIndex(){let u=t();return e.findItemIndex(u)},get playingAsset(){return e.effectivePlayingAsset},get playingItem(){return e.effectivePlayingItem},get playingIndex(){let u=e.effectivePlayingItem;return e.findItemIndex(u)},primary:{get bufferedEnd(){return a()},get currentTime(){let u=e.timelinePos;return u>0?u:0},set currentTime(u){l(u,"primary")},get duration(){return o("primary")},get seekableStart(){return e.seekableStart}},integrated:{get bufferedEnd(){return i(t(),"integrated",e.bufferingAsset,"bufferedPos","bufferedEnd")},get currentTime(){return i(e.effectivePlayingItem,"integrated",e.effectivePlayingAsset,"timelinePos","currentTime")},set currentTime(u){l(u,"integrated")},get duration(){return o("integrated")},get seekableStart(){return r(e.seekableStart,"integrated")}},skip:()=>{let u=e.effectivePlayingItem,d=u?.event;if(d&&!d.restrictions.skip){let f=e.findItemIndex(u);if(d.appendInPlace){let g=u.playout.start+u.event.duration;l(g+.001,"playout")}else e.advanceAfterAssetEnded(d,f,1/0)}}}}get effectivePlayingItem(){return this.waitingItem||this.playingItem||this.endedItem}get effectivePlayingAsset(){return this.playingAsset||this.endedAsset}get playingLastItem(){var e;let t=this.playingItem,s=(e=this.schedule)==null?void 0:e.items;return!this.playbackStarted||!t||!s?!1:this.findItemIndex(t)===s.length-1}get playbackStarted(){return this.effectivePlayingItem!==null}get currentTime(){var e,t;if(this.mediaSelection===null)return;let s=this.waitingItem||this.playingItem;if(this.isInterstitial(s)&&!s.event.appendInPlace)return;let i=this.media;!i&&(e=this.bufferingItem)!=null&&(e=e.event)!=null&&e.appendInPlace&&(i=this.primaryMedia);let r=(t=i)==null?void 0:t.currentTime;if(!(r===void 0||!$(r)))return r}get primaryMedia(){var e;return this.media||((e=this.detachedData)==null?void 0:e.media)||null}isInterstitial(e){return!!(e!=null&&e.event)}retreiveMediaSource(e,t){let s=this.getAssetPlayer(e);s&&this.transferMediaFromPlayer(s,t)}transferMediaFromPlayer(e,t){let s=e.interstitial.appendInPlace,i=e.media;if(s&&i===this.primaryMedia){if(this.bufferingAsset=null,(!t||this.isInterstitial(t)&&!t.event.appendInPlace)&&t&&i){this.detachedData={media:i};return}let r=e.transferMedia();this.log(`transfer MediaSource from ${e} ${de(r)}`),this.detachedData=r}else t&&i&&(this.shouldPlay||(this.shouldPlay=!i.paused))}transferMediaTo(e,t){var s,i;if(e.media===t)return;let r=null,a=this.hls,o=e!==a,l=o&&e.interstitial.appendInPlace,c=(s=this.detachedData)==null?void 0:s.mediaSource,h;if(a.media)l&&(r=a.transferMedia(),this.detachedData=r),h="Primary";else{let g=this.getBufferingPlayer();g?(r=g.transferMedia(),this.detachedData=r,h=`${g}`):c?h="detached MediaSource":h="detached media"}if(!r){if(c)r=this.detachedData,this.log(`using detachedData: MediaSource ${de(r)}`);else if(!this.detachedData||a.media===t){let g=this.playerQueue;g.length>1&&g.forEach(m=>{if(o&&m.interstitial.appendInPlace!==l){let y=m.interstitial;this.clearInterstitial(m.interstitial,null),y.appendInPlace=!1,y.appendInPlace&&this.warn(`Could not change append strategy for queued assets ${y}`)}}),this.hls.detachMedia(),this.detachedData={media:t}}}let u=r&&"mediaSource"in r&&((i=r.mediaSource)==null?void 0:i.readyState)!=="closed";if(this.log(`${u?"transfering MediaSource":"attaching media"} to ${o?e:"Primary"} from ${h} (media.currentTime: ${t.currentTime})`),!u&&!o){e.attachMedia(t);return}let d=u&&r?Y({},r):{media:t},f=this.schedule;if(f&&o){let g=e.assetId===f.assetIdAtEnd;d.overrides={duration:f.duration,endOfStream:g||e.appendInPlace===!1}}if(!u&&l){let g=e,m=g.assetItem.timelineStart;if(m){let y=g.hls,E=Math.max(this.timelinePos-m,Number.EPSILON);y.startPosition!==E&&(this.log(`Set ${g} startPosition: ${E}`),y.config.startPosition=E,y.loadingEnabled&&y.startLoad(E))}}e.attachMedia(d)}onInterstitialCueEnter(){this.onTimeupdate()}checkStart(){let e=this.schedule,t=e?.events,s=this.hls;if(!t||this.playbackDisabled||!this.media||!s)return;this.bufferedPos===-1&&(this.bufferedPos=0);let i=this.timelinePos,r=this.effectivePlayingItem;if(i===-1){if(!s.loadingEnabled){this.log("waiting for startLoad( <startPosition> )");return}let a=s.startPosition;if(this.timelinePos=a,t.length===0)this.setSchedulePosition(0);else if(t[0].cue.pre){this.log(Lt("checkStart (preroll)",a));let o=e.findEventIndex(t[0].identifier);this.setSchedulePosition(o)}else if(a>=0||!this.primaryLive){this.log(Lt("checkStart",a));let o=this.timelinePos=a>0?a:0,l=e.findItemIndexAtTime(o);this.setSchedulePosition(l)}else s.liveSyncPosition===0?this.setSchedulePosition(0):this.log("[checkStart] waiting for live start")}else if(r&&!this.playingItem){this.log(Lt("checkStart (playing item)",r.start));let a=e.findItemIndex(r);this.setSchedulePosition(a)}}advanceAssetBuffering(e,t){let s=e.event,i=s.findAssetIndex(t),r=Xi(s,i);if(!s.isAssetPastPlayoutLimit(r))this.bufferedToEvent(e,r);else if(this.schedule){var a;let o=this.getNextItemIndex(e,!0),l=(a=this.schedule.items)==null?void 0:a[o];l&&this.bufferedToItem(l)}}livePrerollResumption(e,t){if(e.cue.pre&&this.primaryLive&&!$(e.resumeOffset)&&this.hls){let s=this.getLiveStartPos();if(t){let i=this.getBufferingPlayer(),r=i!=null&&i.interstitial.cue.pre?i.remaining:0;return s+r}return s}}getNextItemIndex(e,t){if(this.schedule){let s=this.livePrerollResumption(e.event,t);if(s!==void 0)return this.log(`find next item index @${s}`),this.schedule.findItemIndexAtTime(s)}return this.findItemIndex(e)+1}advanceAfterAssetEnded(e,t,s){let i=Xi(e,s);if(e.isAssetPastPlayoutLimit(i)){if(this.schedule){let r=this.schedule.items;if(r){let a=r[t],o=a.event?this.getNextItemIndex(a):t+1,l=r.length;if(o>=l){this.setSchedulePosition(-1);return}let c=e.resumeTime;this.timelinePos<c&&(this.log(Lt("advanceAfterAssetEnded",c)),this.timelinePos=c,e.appendInPlace&&!r[o].event&&this.hls.startLoad(c+.01),this.checkBuffer(this.bufferedPos<c)),this.setSchedulePosition(o)}}}else{if(e.appendInPlace){let r=e.assetList[i];r&&this.advanceInPlace(r.timelineStart)}this.setSchedulePosition(t,i)}}setScheduleToAssetAtTime(e,t){let s=this.schedule;if(!s)return;let i=t.parentIdentifier,r=s.getEvent(i);if(r){let a=s.findEventIndex(i),o=s.findAssetIndex(r,e);this.advanceAfterAssetEnded(r,a,o-1)}}setSchedulePosition(e,t){var s;let i=(s=this.schedule)==null?void 0:s.items;if(!i||this.playbackDisabled)return;let r=e>=0?i[e]:null;this.log(`setSchedulePosition ${e}, ${t} (${r&&Be(r)}) pos: ${this.timelinePos}`);let a=this.waitingItem||this.playingItem,o=this.playingLastItem;if(this.isInterstitial(a)){let u=a.event,d=this.playingAsset,f=d?.identifier,g=f?this.getAssetPlayer(f):null;if(g&&f&&(!this.eventItemsMatch(a,r)||t!==void 0&&f!==u.assetList[t].identifier)){var l;let m=u.findAssetIndex(d);if(this.log(`INTERSTITIAL_ASSET_ENDED ${m+1}/${u.assetList.length} ${Mt(d)}`),this.endedAsset=d,this.playingAsset=null,this.hls.trigger(p.INTERSTITIAL_ASSET_ENDED,{asset:d,assetListIndex:m,event:u,schedule:i.slice(0),scheduleIndex:e,player:g}),a!==this.playingItem){this.itemsMatch(a,this.playingItem)&&!this.playingAsset&&this.advanceAfterAssetEnded(u,this.findItemIndex(this.playingItem),m);return}this.retreiveMediaSource(f,r),g.media&&!((l=this.detachedData)!=null&&l.mediaSource)&&g.detachMedia()}if(!this.eventItemsMatch(a,r)&&(this.endedItem=a,this.playingItem=this.waitingItem=null,this.log(`INTERSTITIAL_ENDED ${u} ${Be(a)}`),u.hasPlayed=!0,this.hls.trigger(p.INTERSTITIAL_ENDED,{event:u,schedule:i.slice(0),scheduleIndex:e}),u.cue.once&&this.hls)){var c;this.updateSchedule();let m=(c=this.schedule)==null?void 0:c.items;if(r&&m){let y=this.findItemIndex(r),E=this.livePrerollResumption(u);if(E!==void 0){let S=E,T=this.getNextItemIndex(a);if(!this.isInterstitial(i[T])){var h;let v=(h=this.primaryDetails)==null?void 0:h.fragments;if(u.snapOptions.in&&v){let x=Gt(null,v,E);x&&(S=Math.min(Math.max(i[T].start,Us(S,x)),i[T].end))}}if(this.log(Lt("live join (preroll)",S)),this.timelinePos=S,T!==y&&(T||T===0)){this.advanceSchedule(T,m,void 0,a,o);return}}this.advanceSchedule(y,m,t,a,o)}return}}this.advanceSchedule(e,i,t,a,o)}advanceSchedule(e,t,s,i,r){let a=this.schedule;if(!a)return;let o=t[e]||null,l=this.primaryMedia,c=this.playerQueue;if(c.length&&c.forEach(h=>{let u=h.interstitial,d=a.findEventIndex(u.identifier);(d<e||d>e+1)&&this.clearInterstitial(u,o)}),this.isInterstitial(o)){this.timelinePos=Math.min(Math.max(this.timelinePos,o.start),o.end);let h=o.event;if(s===void 0){s=h.cue.pre?0:a.findAssetIndex(h,this.timelinePos);let g=Xi(h,s-1);if(h.isAssetPastPlayoutLimit(g)||h.appendInPlace&&this.timelinePos===o.end){this.advanceAfterAssetEnded(h,e,s);return}s=g}let u=this.waitingItem;this.assetsBuffered(o,l)||this.setBufferingItem(o);let d=this.preloadAssets(h,s);if(this.eventItemsMatch(o,u||i)||(this.waitingItem=o,this.log(`INTERSTITIAL_STARTED ${Be(o)} ${h.appendInPlace?"append in place":""}`),h.hasPlayed=!1,this.hls.trigger(p.INTERSTITIAL_STARTED,{event:h,schedule:t.slice(0),scheduleIndex:e})),!h.assetListLoaded){this.log(`Waiting for ASSET-LIST to complete loading ${h}`);return}if(h.assetListLoader&&(h.assetListLoader.destroy(),h.assetListLoader=void 0),!l){this.log(`Waiting for attachMedia to start Interstitial ${h}`);return}this.waitingItem=this.endedItem=null,this.playingItem=o;let f=h.assetList[s];if(!f){this.advanceAfterAssetEnded(h,e,s||0);return}if(d||(d=this.getAssetPlayer(f.identifier)),d===null||d.destroyed){let g=h.assetList.length;this.warn(`asset ${s+1}/${g} player destroyed ${h}`),d=this.createAssetPlayer(h,f,s),d.loadSource()}if(!this.eventItemsMatch(o,this.bufferingItem)&&h.appendInPlace&&this.isAssetBuffered(f))return;this.startAssetPlayer(d,s,t,e,l),this.shouldPlay&&mo(d.media)}else o?(this.resumePrimary(o,e,i),this.shouldPlay&&mo(this.hls.media)):r&&this.isInterstitial(i)&&(this.endedItem=null,this.playingItem=i,i.event.appendInPlace||this.attachPrimary(a.durations.primary,null))}get playbackDisabled(){return this.hls.config.enableInterstitialPlayback===!1}get primaryDetails(){var e;return(e=this.mediaSelection)==null?void 0:e.main.details}get primaryLive(){var e;return!!((e=this.primaryDetails)!=null&&e.live)}resumePrimary(e,t,s){var i,r;this.playingItem=e,this.playingAsset=this.endedAsset=null,this.waitingItem=null,this.bufferedToItem(e),this.endedItem=null,this.log(`resuming ${Be(e)}`);let a=this.timelinePos;if((i=this.detachedData)!=null&&i.mediaSource?this.primaryLive&&this.startLoadingPrimaryAt(a):((a<e.start||a>=e.end||a<this.seekableStart)&&(a=this.getPrimaryResumption(e,t),this.log(Lt("resumePrimary",a)),this.timelinePos=a),this.attachPrimary(a,e)),!s)return;let o=(r=this.schedule)==null?void 0:r.items;o&&(this.log(`INTERSTITIALS_PRIMARY_RESUMED ${Be(e)}`),this.hls.trigger(p.INTERSTITIALS_PRIMARY_RESUMED,{schedule:o.slice(0),scheduleIndex:t}),this.checkBuffer())}get seekableStart(){var e;return this.primaryLive&&((e=this.primaryDetails)==null?void 0:e.fragmentStart)||0}getPrimaryResumption(e,t,s){let i=e.start;if(this.primaryLive){if(t===0)return this.hls.startPosition;let r=this.endedItem||this.playingItem,a=r!=null&&r.event?this.livePrerollResumption(r.event,s):void 0;if(a!==void 0)return a;let o=this.primaryDetails;if(o){let{fragmentStart:l,edge:c}=o;if(i<l||i>c&&!s){let h=this.hls.liveSyncPosition;return this.log(`primary resumption out of bounds (${i} [${l}-${c}]) snapping to liveSync ${h}`),h||l}}}return this.log(`primary resumption itemStart: ${i}`),i}getLiveStartPos(){var e;let t=this.hls.startPosition,s=this.hls.liveSyncPosition||0,i=(((e=this.primaryDetails)==null?void 0:e.targetduration)||10)*3;return t===-1||s&&s-t<i?s||0:t}isAssetBuffered(e){let t=this.getAssetPlayer(e.identifier);return t!=null&&t.hls?t.hls.bufferedToEnd:X.bufferInfo(this.primaryMedia,this.timelinePos,0).end+1>=e.timelineStart+(e.duration||0)}attachPrimary(e,t,s){t?this.setBufferingItem(t):this.bufferingItem=this.playingItem,this.bufferingAsset=null;let i=this.primaryMedia;if(!i)return;let r=this.hls;r.media?this.checkBuffer():(this.transferMediaTo(r,i),s&&this.startLoadingPrimaryAt(e,s)),s||(this.log(Lt("attachPrimary",e)),this.timelinePos=e,this.startLoadingPrimaryAt(e,s))}startLoadingPrimaryAt(e,t){let s=this.hls,{loadingEnabled:i,bufferingEnabled:r,startPosition:a}=s,o=s.hasEnoughToStart;if(this.log(`Start loading primary @${e} bufferedPos: ${this.bufferedPos} startPosition: ${a} skip seek: ${t} has enough ${o} loadingEnabled: ${i} bufferingEnabled: ${r}`),!t&&o||!i||Math.abs(a-e)>.1){let l=this.primaryDetails;if(l!=null&&l.live&&e+.5>=l.edge){let c=this.bufferingItem;this.log(`Resume primary loading when live passes ${e} buffering item: ${c?Be(c):null}`),s.pauseBuffering(),this.bufferPastEdge=!0;return}s.startLoad(e,t)}else r||s.resumeBuffering()}onManifestLoading(){var e;this.stopLoad(),(e=this.schedule)==null||e.reset(),this.emptyPlayerQueue(),this.clearScheduleState(),this.shouldPlay=!1,this.bufferedPos=this.timelinePos=-1,this.mediaSelection=this.altSelection=this.manager=this.requiredTracks=null,this.hls.off(p.BUFFER_CODECS,this.onBufferCodecs,this),this.hls.on(p.BUFFER_CODECS,this.onBufferCodecs,this)}onLevelUpdated(e,t){if(t.level===-1||!this.schedule)return;let s=this.hls.levels[t.level];if(!s.details)return;let i=Y(Y({},this.mediaSelection||this.altSelection),{},{main:s});this.mediaSelection=i;let r=this.hls.startPosition;if(this.schedule.parseInterstitialDateRanges(i,this.hls.config.interstitialAppendInPlace,r===-1?0:r),!!this.schedule.items){if(!this.effectivePlayingItem)this.checkStart();else if(this.bufferPastEdge){let o=this.primaryDetails,l=this.bufferedPos;if(o!=null&&o.live&&l+.5<o.edge){this.bufferPastEdge=!1;let c=this.bufferingItem;if(this.log(`Live edge ${o.edge} passed buffer: ${l} buffering item: ${c?Be(c):null}`),c?.end===1/0){let u=this.playingItem,d=this.isInterstitial(u)&&u.event.appendInPlace;this.hls.startLoad(Math.max(l,c.start),d)}else{let u=this.getBufferingPlayer();u&&u.bufferedInPlaceToEnd(this.primaryMedia,u.currentTime)&&u.hls&&u.hls.trigger(p.BUFFERED_TO_END,void 0)}}}}}onAudioTrackUpdated(e,t){let s=this.hls.audioTracks[t.id],i=this.mediaSelection;if(!i){this.altSelection=Y(Y({},this.altSelection),{},{audio:s});return}let r=Y(Y({},i),{},{audio:s});this.mediaSelection=r}onSubtitleTrackUpdated(e,t){let s=this.hls.subtitleTracks[t.id],i=this.mediaSelection;if(!i){this.altSelection=Y(Y({},this.altSelection),{},{subtitles:s});return}let r=Y(Y({},i),{},{subtitles:s});this.mediaSelection=r}onAudioTrackSwitching(e,t){let s=ca(t);this.playerQueue.forEach(({hls:i})=>i&&(i.setAudioOption(t)||i.setAudioOption(s)))}onSubtitleTrackSwitch(e,t){let s=ca(t);this.playerQueue.forEach(({hls:i})=>i&&(i.setSubtitleOption(t)||t.id!==-1&&i.setSubtitleOption(s)))}onBufferCodecs(e,t){let s=t.tracks;s&&(this.requiredTracks=s)}onBufferAppended(e,t){this.checkBuffer()}onBufferFlushed(e,t){let s=this.playingItem;if(s&&!this.itemsMatch(s,this.bufferingItem)&&!this.isInterstitial(s)){let i=this.timelinePos;this.bufferedPos=i,this.checkBuffer()}}onBufferedToEnd(e){if(!this.schedule)return;let t=this.schedule.events;if(this.bufferedPos<Number.MAX_VALUE&&t){for(let s=0;s<t.length;s++){let i=t[s];if(i.cue.post){let r=this.getEventItem(i.identifier);r&&this.eventItemsMatch(r,this.bufferingItem)&&this.bufferedToItem(r,0);break}}this.bufferedPos=Number.MAX_VALUE}}onMediaEnded(e){let t=this.playingItem;if(!this.playingLastItem&&t){let s=this.findItemIndex(t);this.setSchedulePosition(s+1)}else this.shouldPlay=!1}updateItem(e,t){var s;let i=(s=this.schedule)==null?void 0:s.items;if(e&&i){let r=this.findItemIndex(e,t);return i[r]||null}return null}trimInPlace(e,t){if(this.isInterstitial(e)&&e.event.appendInPlace&&t.end-e.end>.25){e.event.assetList.forEach((r,a)=>{e.event.isAssetPastPlayoutLimit(a)&&this.clearAssetPlayer(r.identifier,null)});let s=e.end+.25,i=X.bufferInfo(this.primaryMedia,s,0);(i.end>s||(i.nextStart||0)>s)&&(this.log(`trim buffered interstitial ${Be(e)} (was ${Be(t)})`),this.attachPrimary(s,null,!0),this.flushFrontBuffer(s))}}itemsMatch(e,t){return!!t&&(e===t||e.event&&t.event&&this.eventItemsMatch(e,t)||!e.event&&!t.event&&this.findItemIndex(e)===this.findItemIndex(t))}eventItemsMatch(e,t){var s;return!!t&&(e===t||e.event.identifier===((s=t.event)==null?void 0:s.identifier))}findEventIndex(e){return this.schedule?this.schedule.findEventIndex(e):-1}getEventItem(e){if(this.schedule){var t;let s=(t=this.schedule.items)==null?void 0:t[this.findEventIndex(e)];if(this.isInterstitial(s)&&s.event.identifier===e)return s}}findItemIndex(e,t){return e&&this.schedule?this.schedule.findItemIndex(e,t):-1}updateSchedule(e=!1){var t,s;let i=this.mediaSelection;if(!i)return;let r=((t=this.hls)==null?void 0:t.liveSyncPosition)||0;(s=this.schedule)==null||s.updateSchedule(i,[],r,e)}checkBuffer(e){var t;let s=(t=this.schedule)==null?void 0:t.items;if(!s)return;let i=X.bufferInfo(this.primaryMedia,this.timelinePos,0);e&&(this.bufferedPos=this.timelinePos),e||(e=i.len<1),this.updateBufferedPos(i.end,s,e)}updateBufferedPos(e,t,s){let i=this.schedule,r=this.bufferingItem;if(this.bufferedPos>e||!i)return;if(t.length===1&&this.itemsMatch(t[0],r)){this.bufferedPos=e;return}let a=this.playingItem,o=this.findItemIndex(a),l=i.findItemIndexAtTime(e);if(this.bufferedPos<e){var c;let h=this.findItemIndex(r),u=Math.min(h+1,t.length-1),d=t[u];if((l===-1&&r&&e>=r.end||(c=d.event)!=null&&c.appendInPlace&&e+.01>=d.start)&&(l=u),this.isInterstitial(r)){let f=r.event;if(u-o>1&&f.appendInPlace===!1||f.assetList.length===0&&f.assetListLoader)return}if(this.bufferedPos=e,l>h&&l>o)this.bufferedToItem(d);else{let f=this.primaryDetails;this.primaryLive&&f&&e>f.edge-f.targetduration&&d.start<f.edge+this.hls.config.interstitialLiveLookAhead&&this.isInterstitial(d)&&this.preloadAssets(d.event,0)}}else s&&a&&!this.itemsMatch(a,r)&&(l===o?this.bufferedToItem(a):l===o+1&&this.bufferedToItem(t[l]))}assetsBuffered(e,t){return e.event.assetList.length===0?!1:!e.event.assetList.some(i=>{let r=this.getAssetPlayer(i.identifier);return!(r!=null&&r.bufferedInPlaceToEnd(t))})}setBufferingItem(e){let t=this.bufferingItem,s=this.schedule;if(!this.itemsMatch(e,t)&&s){let{items:i,events:r}=s;if(!i||!r)return t;let a=this.isInterstitial(e),o=this.getBufferingPlayer();this.bufferingItem=e,this.bufferedPos=Math.max(e.start,Math.min(e.end,this.timelinePos));let l=o?o.remaining:t?t.end-this.timelinePos:0;if(this.log(`INTERSTITIALS_BUFFERED_TO_BOUNDARY ${Be(e)}`+(t?` (${l.toFixed(2)} remaining)`:"")),!this.playbackDisabled)if(a){let c=s.findAssetIndex(e.event,this.bufferedPos);e.event.assetList.forEach((h,u)=>{let d=this.getAssetPlayer(h.identifier);d&&(u===c&&d.loadSource(),d.resumeBuffering())})}else this.hls.resumeBuffering(),this.playerQueue.forEach(c=>c.pauseBuffering());this.hls.trigger(p.INTERSTITIALS_BUFFERED_TO_BOUNDARY,{events:r.slice(0),schedule:i.slice(0),bufferingIndex:this.findItemIndex(e),playingIndex:this.findItemIndex(this.playingItem)})}else this.bufferingItem!==e&&(this.bufferingItem=e);return t}bufferedToItem(e,t=0){let s=this.setBufferingItem(e);if(!this.playbackDisabled){if(this.isInterstitial(e))this.bufferedToEvent(e,t);else if(s!==null){this.bufferingAsset=null;let i=this.getPrimaryResumption(e,this.findItemIndex(e),!0),r=this.bufferedPos=Math.max(i,Math.min(this.bufferedPos,e.end),this.timelinePos,e.start),a=this.detachedData;if(a)a.mediaSource?this.attachPrimary(r,e,!0):this.startLoadingPrimaryAt(r);else{let o=this.playingItem,l=this.isInterstitial(o)&&o.event.appendInPlace;this.startLoadingPrimaryAt(r,l)}}}}bufferedToEvent(e,t){let s=e.event,i=s.assetList.length===0&&!s.assetListLoader,r=s.cue.once;if(i||!r){let a=this.preloadAssets(s,t);if(a!=null&&a.interstitial.appendInPlace){let o=this.primaryMedia;o&&this.bufferAssetPlayer(a,o)}}}preloadAssets(e,t){let s=e.assetUrl,i=e.assetList.length,r=i===0&&!e.assetListLoader,a=e.cue.once;if(r){let l=e.timelineStart,c=this.playingItem,h=this.getBufferingPlayer();if(e.appendInPlace){var o;!this.isInterstitial(c)&&(c==null||(o=c.nextEvent)==null?void 0:o.identifier)===e.identifier&&this.flushFrontBuffer(l+.25)}let u,d=0;if((!h||h.interstitial.cue.pre)&&this.primaryLive&&(d=this.getLiveStartPos(),h&&(d+=h.remaining)),d&&!(e.cue.pre||e.cue.post)){let g=d-l;g>0&&(u=Math.round(g*1e3)/1e3)}if(this.log(`Load interstitial asset ${t+1}/${s?1:i} ${e}${d?` live-start: ${d} start-offset: ${u} (timeline-start: ${l})`:""}`),s)return this.createAsset(e,0,0,l,e.duration,s);let f=this.assetListLoader.loadAssetList(e,u);f&&(e.assetListLoader=f)}else if(!a&&i){for(let c=t;c<i;c++){let h=e.assetList[c],u=this.getAssetPlayerQueueIndex(h.identifier);(u===-1||this.playerQueue[u].destroyed)&&!h.error&&this.createAssetPlayer(e,h,c)}let l=e.assetList[t];if(l){let c=this.getAssetPlayer(l.identifier);return c&&c.loadSource(),c}}return null}flushFrontBuffer(e){let t=this.requiredTracks;if(!t)return;let s=this.primaryDetails;if(s&&e>=s.edge)return;this.log(`Removing front buffer starting at ${e}`),Object.keys(t).forEach(r=>{this.hls.trigger(p.BUFFER_FLUSHING,{startOffset:e,endOffset:1/0,type:r})})}getAssetPlayerQueueIndex(e){let t=this.playerQueue;for(let s=0;s<t.length;s++)if(e===t[s].assetId)return s;return-1}getAssetPlayer(e){let t=this.getAssetPlayerQueueIndex(e);return this.playerQueue[t]||null}getBufferingPlayer(){let{playerQueue:e,primaryMedia:t}=this;if(t){for(let s=0;s<e.length;s++)if(e[s].media===t)return e[s]}return null}createAsset(e,t,s,i,r,a){let o={parentIdentifier:e.identifier,identifier:Kf(e,a,t),duration:r,startOffset:s,timelineStart:i,uri:a};return this.createAssetPlayer(e,o,t)}createAssetPlayer(e,t,s){let i=this.hls,r=i.userConfig,a=i.loadLevelObj||i.levels[i.currentLevel],o=Qo(a,r.videoPreference),l=i.audioTracks[i.audioTrack],c=i.subtitleTracks[i.subtitleTrack],h=0;if(this.primaryLive||e.appendInPlace){let v=this.timelinePos-t.timelineStart;if(v>=0){let x=t.duration;x&&v<x&&(h=v)}}let u=t.identifier,d=Y(Y({},r),{},{maxMaxBufferLength:Math.min(15,i.config.maxMaxBufferLength),autoStartLoad:!0,startFragPrefetch:!0,primarySessionId:i.sessionId,assetPlayerId:u,abrEwmaDefaultEstimate:i.bandwidthEstimate,interstitialsController:void 0,startPosition:h,liveDurationInfinity:!1,testBandwidth:!1,videoPreference:o,audioPreference:l||r.audioPreference,subtitlePreference:c||r.subtitlePreference});e.appendInPlace&&(e.appendInPlaceStarted=!0,t.timelineStart&&(d.timelineOffset=t.timelineStart));let f=d.cmcd;f!=null&&f.sessionId&&f.contentId&&(d.cmcd=he({},f,{contentId:Jt(t.uri)})),this.getAssetPlayer(u)&&this.warn(`Duplicate date range identifier ${e} and asset ${u}`);let g=new on(this.HlsPlayerClass,d,e,t);this.playerQueue.push(g),e.assetList[s]=t;let m=!0,y=v=>{if(v.live){let A=new Error(`Interstitials MUST be VOD assets ${e}`),b={fatal:!0,type:W.OTHER_ERROR,details:R.INTERSTITIAL_ASSET_ITEM_ERROR,error:A},_=this.findEventIndex(e.identifier);this.handleAssetItemError(b,e,_,s,A.message);return}let x=v.edge-v.fragmentStart,I=t.duration;(m||I===null||x>I)&&(m=!1,this.log(`Interstitial asset "${u}" duration change ${I} > ${x}`),t.duration=x,this.updateSchedule())};g.on(p.LEVEL_UPDATED,(v,{details:x})=>y(x)),g.on(p.LEVEL_PTS_UPDATED,(v,{details:x})=>y(x)),g.on(p.EVENT_CUE_ENTER,()=>this.onInterstitialCueEnter());let E=(v,x)=>{let I=this.getAssetPlayer(u);if(I&&x.tracks){I.off(p.BUFFER_CODECS,E),I.tracks=x.tracks;let A=this.primaryMedia;this.bufferingAsset===I.assetItem&&A&&!I.media&&this.bufferAssetPlayer(I,A)}};g.on(p.BUFFER_CODECS,E);let S=()=>{let v=this.getAssetPlayer(u);if(this.log(`buffered to end of asset ${v}`),!v||!this.schedule)return;let x=this.getEventItem(e.identifier);x&&this.advanceAssetBuffering(x,v.assetItem)};g.on(p.BUFFERED_TO_END,S);let T=v=>()=>{if(!this.getAssetPlayer(u)||!this.schedule)return;this.shouldPlay=!0;let I=this.findEventIndex(e.identifier);this.advanceAfterAssetEnded(e,I,v)};return g.once(p.MEDIA_ENDED,T(s)),g.once(p.PLAYOUT_LIMIT_REACHED,T(1/0)),g.on(p.ERROR,(v,x)=>{if(!this.schedule)return;let I=this.getAssetPlayer(u);if(x.details===R.BUFFER_STALLED_ERROR){if(I!=null&&I.appendInPlace){this.handleInPlaceStall(e);return}this.onTimeupdate(),this.checkBuffer(!0);return}else if(x.details===R.BUFFER_SEEK_OVER_HOLE)return;this.handleAssetItemError(x,e,this.findEventIndex(e.identifier),s,`Asset player error ${x.error} ${e}`)}),g.on(p.DESTROYING,()=>{if(!this.getAssetPlayer(u)||!this.schedule)return;let x=new Error(`Asset player destroyed unexpectedly ${u}`),I={fatal:!0,type:W.OTHER_ERROR,details:R.INTERSTITIAL_ASSET_ITEM_ERROR,error:x};this.handleAssetItemError(I,e,this.findEventIndex(e.identifier),s,x.message)}),this.log(`INTERSTITIAL_ASSET_PLAYER_CREATED ${Mt(t)}`),this.hls.trigger(p.INTERSTITIAL_ASSET_PLAYER_CREATED,{asset:t,assetListIndex:s,event:e,player:g}),g}clearInterstitial(e,t){this.clearAssetPlayers(e,t),e.reset()}clearAssetPlayers(e,t){e.assetList.forEach(s=>{this.clearAssetPlayer(s.identifier,t)})}resetAssetPlayer(e){let t=this.getAssetPlayerQueueIndex(e);if(t!==-1){this.log(`reset asset player "${e}" after error`);let s=this.playerQueue[t];this.transferMediaFromPlayer(s,null),s.resetDetails()}}clearAssetPlayer(e,t){let s=this.getAssetPlayerQueueIndex(e);if(s!==-1){let i=this.playerQueue[s];this.log(`clear ${i} toSegment: ${t&&Be(t)}`),this.transferMediaFromPlayer(i,t),this.playerQueue.splice(s,1),i.destroy()}}emptyPlayerQueue(){let e;for(;e=this.playerQueue.pop();)e.destroy();this.playerQueue=[]}startAssetPlayer(e,t,s,i,r){let{interstitial:a,assetItem:o,assetId:l}=e,c=a.assetList.length,h=this.playingAsset;this.endedAsset=null,this.playingAsset=o,h?.identifier!==l&&(h&&(this.clearAssetPlayer(h.identifier,s[i]),delete h.error),this.log(`INTERSTITIAL_ASSET_STARTED ${t+1}/${c} ${Mt(o)}`),this.hls.trigger(p.INTERSTITIAL_ASSET_STARTED,{asset:o,assetListIndex:t,event:a,schedule:s.slice(0),scheduleIndex:i,player:e})),this.bufferAssetPlayer(e,r)}bufferAssetPlayer(e,t){var s;if(!this.schedule)return;let{interstitial:i,assetItem:r}=e,a=this.getEventItem(i.identifier);if(!a)return;if(e.loadSource(),this.setBufferingItem(a),this.bufferingAsset=r,e.bufferedInPlaceToEnd(this.primaryMedia,e.currentTime)){this.advanceAssetBuffering(a,r);return}let o=this.getBufferingPlayer();if(o===e)return;let l=i.appendInPlace;if(l&&o?.interstitial.appendInPlace===!1)return;let c=o?.tracks||((s=this.detachedData)==null?void 0:s.tracks)||this.requiredTracks;if(l&&r!==this.playingAsset){if(!e.tracks){this.log(`Waiting for track info before buffering ${e}`);return}if(c&&!Lo(c,e.tracks)){let h=new Error(`Asset ${Mt(r)} SourceBuffer tracks ('${Object.keys(e.tracks)}') are not compatible with primary content tracks ('${Object.keys(c)}')`),u={fatal:!0,type:W.OTHER_ERROR,details:R.INTERSTITIAL_ASSET_ITEM_ERROR,error:h},d=i.findAssetIndex(r);this.handleAssetItemError(u,i,this.findEventIndex(i.identifier),d,h.message);return}}this.transferMediaTo(e,t)}handleInPlaceStall(e){let t=this.schedule,s=this.primaryMedia;if(!t||!s)return;let i=s.currentTime,r=t.findAssetIndex(e,i),a=e.assetList[r];if(a){let o=this.getAssetPlayer(a.identifier);if(o){let l=o.currentTime||i-a.timelineStart,c=o.duration-l;if(this.warn(`Stalled at ${l} of ${l+c} in ${o} ${e} (media.currentTime: ${i})`),l&&(c/s.playbackRate<.5||o.bufferedInPlaceToEnd(s,o.currentTime))&&o.hls){let h=t.findEventIndex(e.identifier);this.advanceAfterAssetEnded(e,h,r)}}}}advanceInPlace(e){let t=this.primaryMedia;if(t&&t.currentTime<e){let s=`advance currentTime to ${e}, duration: ${t.duration}`;t.duration>e?(this.log(s),t.currentTime=e):this.log(`Cannot ${s}`)}}handleAssetItemError(e,t,s,i,r){if(e.details===R.BUFFER_STALLED_ERROR)return;let a=t.assetList[i]||null;if(this.warn(`INTERSTITIAL_ASSET_ERROR ${a&&Mt(a)} ${e.error}`),!this.schedule)return;let o=a?.identifier||"",l=this.getAssetPlayerQueueIndex(o),c=this.playerQueue[l]||null,h=this.schedule.items,u=he({},e,{fatal:!1,errorAction:Qt(!0),asset:a,assetListIndex:i,event:t,schedule:h,scheduleIndex:s,player:c});if(this.hls.trigger(p.INTERSTITIAL_ASSET_ERROR,u),!e.fatal)return;let d=this.playingAsset,f=this.bufferingAsset,g=new Error(r);if(a&&(this.clearAssetPlayer(o,null),a.error=g),!t.assetList.some(m=>!m.error))t.error=g;else for(let m=i;m<t.assetList.length;m++)this.resetAssetPlayer(t.assetList[m].identifier);this.updateSchedule(!0),t.error?this.primaryFallback(t):d?.identifier===o?this.advanceAfterAssetEnded(t,s,i):f?.identifier===o&&this.isInterstitial(this.bufferingItem)&&this.advanceAssetBuffering(this.bufferingItem,f)}primaryFallback(e){let t=e.timelineStart,s=this.effectivePlayingItem,i=this.playingItem,r=this.seekableStart,a=this.hls.startPosition,o=this.timelinePos;if(this.isInterstitial(s)){this.log(`Fallback to primary from event "${e.identifier}" start: ${t} pos: ${o} playing: ${Be(s)} startPosition: ${a} seekableStart: ${r} error: ${e.error}`),o===-1&&(o=a),o=Math.max(o,r);let c=this.updateItem(s,o);this.itemsMatch(s,c)&&this.clearInterstitial(e,null),e.appendInPlace&&(this.attachPrimary(t,null),this.flushFrontBuffer(t))}else if(o===-1){this.checkStart();return}if(!this.schedule||i&&!this.isInterstitial(i))return;let l=this.schedule.findItemIndexAtTime(o);this.setSchedulePosition(l)}onAssetListLoaded(e,t){var s,i;let r=t.event,a=r.identifier,o=t.assetListResponse.ASSETS;if(!((s=this.schedule)!=null&&s.hasEvent(a)))return;let l=r.timelineStart,c=r.duration,h=0;o.forEach((g,m)=>{let y=parseFloat(g.DURATION);this.createAsset(r,m,h,l+h,y,g.URI),h+=y}),r.duration=h,this.log(`Loaded asset-list with duration: ${h} (was: ${c}) ${r}`);let u=this.waitingItem,d=u?.event.identifier===a;this.updateSchedule();let f=(i=this.bufferingItem)==null?void 0:i.event;if(d){let g=this.findEventIndex(a),m=this.getEventItem(a);if(m){if(!this.playingItem&&this.timelinePos>m.end&&this.schedule.findItemIndexAtTime(this.timelinePos)!==g){r.error=new Error(`Interstitial ${o.length?"no longer within playback range":"asset-list is empty"} ${this.timelinePos} ${r}`),this.log(r.error.message),this.updateSchedule(!0),this.primaryFallback(r);return}this.setBufferingItem(m)}this.setSchedulePosition(g)}else if(f?.identifier===a){let g=r.assetList[0];if(g){let m=this.getAssetPlayer(g.identifier);if(f.appendInPlace){let y=this.primaryMedia;m&&y&&this.bufferAssetPlayer(m,y)}else m&&m.loadSource()}}}onError(e,t){if(this.schedule)switch(t.details){case R.ASSET_LIST_PARSING_ERROR:case R.ASSET_LIST_LOAD_ERROR:case R.ASSET_LIST_LOAD_TIMEOUT:{let s=t.interstitial;s&&(this.updateSchedule(!0),this.primaryFallback(s));break}case R.BUFFER_STALLED_ERROR:{let s=this.endedItem||this.waitingItem||this.playingItem;if(this.isInterstitial(s)&&s.event.appendInPlace){this.handleInPlaceStall(s.event);return}let i=this.primaryMedia;this.log(`Primary player stall @${this.timelinePos} currentTime: ${i?.currentTime} bufferedPos: ${this.bufferedPos}`),this.onTimeupdate(),this.checkBuffer(!0);break}}}},un=class{constructor(e){this.hls=void 0,this.media=null,this.currentTime=0,this.stallCount=0,this._latency=null,this._targetLatencyUpdated=!1,this.onTimeupdate=()=>{var t;let{media:s}=this,i=this.levelDetails;if(!s||!i||!this.hls)return;this.currentTime=s.currentTime;let r=this.hls.config,a=this.computeLatency();if(a===null)return;this._latency=a;let{lowLatencyMode:o,maxLiveSyncPlaybackRate:l}=r;if(!o||l===1||!i.live)return;let c=this.targetLatency;if(c===null)return;let h=a-c,u=Math.min(this.maxLatency,c+i.targetduration),d=h<u,f=si(r)&&!!((t=this.hls.interstitialsManager)!=null&&(t=t.playingItem)!=null&&t.event);if(d&&h>.05&&this.forwardBufferLength>1&&!f){let g=Math.min(2,Math.max(1,l)),m=Math.round(2/(1+Math.exp(-.75*h-this.edgeStalled))*20)/20,y=Math.min(g,Math.max(1,m));this.changeMediaPlaybackRate(s,y)}else s.playbackRate!==1&&s.playbackRate!==0&&this.changeMediaPlaybackRate(s,1)},this.hls=e,this.registerListeners()}get levelDetails(){var e;return((e=this.hls)==null?void 0:e.latestLevelDetails)||null}get latency(){return this._latency||0}get maxLatency(){var e;let t=(e=this.hls)==null?void 0:e.config;if(!t)return 0;if(t.liveMaxLatencyDuration!==void 0)return t.liveMaxLatencyDuration;let s=this.levelDetails;return s?t.liveMaxLatencyDurationCount*s.targetduration:0}get targetLatency(){let e=this.levelDetails;if(e===null||!this.hls)return null;let t=this.hls.config,{holdBack:s,partHoldBack:i,targetduration:r}=e,{liveSyncDuration:a,liveSyncDurationCount:o,lowLatencyMode:l}=t,c=this.hls.userConfig,h=l&&i||s;(this._targetLatencyUpdated||c.liveSyncDuration||c.liveSyncDurationCount||h===0)&&(h=a!==void 0?a:o*r);let u=r;return h+Math.min(this.stallCount*t.liveSyncOnStallIncrease,u)}set targetLatency(e){this.hls&&(this.stallCount=0,this.hls.config.liveSyncDuration=e,this._targetLatencyUpdated=!0)}get liveSyncPosition(){let e=this.estimateLiveEdge(),t=this.targetLatency;if(e===null||t===null||!this.hls)return null;let s=this.levelDetails;if(s===null)return null;let i=s.edge,r=e-t-this.edgeStalled,a=i-s.totalduration,o=i-(this.hls.config.lowLatencyMode&&s.partTarget||s.targetduration);return Math.min(Math.max(a,r),o)}get drift(){let e=this.levelDetails;return e===null?1:e.drift}get edgeStalled(){let e=this.levelDetails;if(e===null||!this.hls)return 0;let t=(this.hls.config.lowLatencyMode&&e.partTarget||e.targetduration)*3;return Math.max(e.age-t,0)}get forwardBufferLength(){let{media:e}=this,t=this.levelDetails;if(!e||!t)return 0;let s=e.buffered.length;return(s?e.buffered.end(s-1):t.edge)-this.currentTime}destroy(){this.unregisterListeners(),this.onMediaDetaching(),this.hls=null}registerListeners(){let{hls:e}=this;e&&(e.on(p.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(p.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(p.MANIFEST_LOADING,this.onManifestLoading,this),e.on(p.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(p.ERROR,this.onError,this),e.on(p.INTERSTITIAL_ASSET_STARTED,this.onAssetStarted,this))}unregisterListeners(){let{hls:e}=this;e&&(e.off(p.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(p.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(p.MANIFEST_LOADING,this.onManifestLoading,this),e.off(p.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(p.ERROR,this.onError,this),e.off(p.INTERSTITIAL_ASSET_STARTED,this.onAssetStarted,this))}onMediaAttached(e,t){this.media=t.media,this.media.addEventListener("timeupdate",this.onTimeupdate)}onMediaDetaching(){this.media&&(this.media.removeEventListener("timeupdate",this.onTimeupdate),this.media=null)}onManifestLoading(){this._latency=null,this.stallCount=0}onLevelUpdated(e,{details:t}){t.advanced&&this.onTimeupdate(),!t.live&&this.media&&this.media.removeEventListener("timeupdate",this.onTimeupdate)}onAssetStarted(e,t){var s;let i=this.hls,r=this.media||t.event.appendInPlace&&(i==null||(s=i.interstitialsManager)==null?void 0:s.playerQueue.reduce((a,o)=>a||o.media,null));i&&r&&r.playbackRate>1&&r.playbackRate<=i.config.maxLiveSyncPlaybackRate&&this.changeMediaPlaybackRate(r,1)}onError(e,t){var s;t.details===R.BUFFER_STALLED_ERROR&&(this.stallCount++,this.hls&&(s=this.levelDetails)!=null&&s.live&&this.hls.logger.warn("[latency-controller]: Stall detected, adjusting target latency"))}changeMediaPlaybackRate(e,t){var s,i;e.playbackRate!==t&&((s=this.hls)==null||s.logger.debug(`[latency-controller]: latency=${this.latency.toFixed(3)}, targetLatency=${(i=this.targetLatency)==null?void 0:i.toFixed(3)}, forwardBufferLength=${this.forwardBufferLength.toFixed(3)}: adjusting playback rate from ${e.playbackRate} to ${t}`),e.playbackRate=t)}estimateLiveEdge(){let e=this.levelDetails;return e===null?null:e.edge+e.age}computeLatency(){let e=this.estimateLiveEdge();return e===null?null:e-this.currentTime}},po=500,Yf=1e-6,dn=class extends us{constructor(e,t,s){super(e,t,s,"subtitle-stream-controller",K.SUBTITLE),this.currentTrackId=-1,this.tracksBuffered=[],this.mainDetails=null,this.registerListeners()}onHandlerDestroying(){this.unregisterListeners(),super.onHandlerDestroying(),this.mainDetails=null}registerListeners(){super.registerListeners();let{hls:e}=this;e.on(p.LEVEL_LOADED,this.onLevelLoaded,this),e.on(p.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(p.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.on(p.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(p.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.on(p.BUFFER_FLUSHING,this.onBufferFlushing,this)}unregisterListeners(){super.unregisterListeners();let{hls:e}=this;e.off(p.LEVEL_LOADED,this.onLevelLoaded,this),e.off(p.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(p.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.off(p.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(p.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.off(p.BUFFER_FLUSHING,this.onBufferFlushing,this)}startLoad(e,t){this.stopLoad(),this.state=C.IDLE,this.setInterval(po),this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,this.tick()}onManifestLoading(){super.onManifestLoading(),this.mainDetails=null}onMediaDetaching(e,t){this.tracksBuffered=[],super.onMediaDetaching(e,t)}onLevelLoaded(e,t){this.mainDetails=t.details}onSubtitleFragProcessed(e,t){var s,i;let{frag:r,part:a,success:o}=t;if(!o)return;let l=(s=this.tracksBuffered)[i=r.level]||(s[i]=[]);if(!l)return;let c,h=(a||r).start;for(let d=0;d<l.length;d++)if(h>=l[d].start&&h<=l[d].end){c=l[d];break}let u=h+(a||r).duration;if(c?c.end=u:(c={start:h,end:u},l.push(c)),!a||u>=r.end-Yf){let d=this.fragmentTracker.fragBuffered(r);a&&d&&(d.range.subs={time:[{startPTS:r.start,endPTS:u}],partial:!0}),pe(r)&&!this.fragContextChanged(r)&&(this.fragPrevious=r),this.fragBufferedComplete(r,a),this.media&&this.tickImmediate()}}onBufferFlushing(e,t){let{startOffset:s,endOffset:i}=t;if(s===0&&i!==Number.POSITIVE_INFINITY){let r=i-1;if(r<=0)return;t.endOffsetSubtitles=Math.max(0,r),this.tracksBuffered.forEach(a=>{if(a)for(let o=0;o<a.length;){if(a[o].end<=r){a.shift();continue}else if(a[o].start<r)a[o].start=r;else break;o++}}),this.fragmentTracker.removeFragmentsInRange(s,r,K.SUBTITLE)}}onError(e,t){let s=t.frag;s?.type===K.SUBTITLE&&(t.details===R.FRAG_GAP&&this.fragmentTracker.addAsGap(s),this.fragCurrent&&this.fragCurrent.abortRequests(),this.state!==C.STOPPED&&(this.state=C.IDLE))}onSubtitleTracksUpdated(e,{subtitleTracks:t}){if(this.levels&&kl(this.levels,t)){this.levels=t.map(s=>new Pt(s));return}this.tracksBuffered=[],this.levels=t.map(s=>new Pt(s)),this.fragmentTracker.removeFragmentsInRange(0,Number.POSITIVE_INFINITY,K.SUBTITLE),this.fragPrevious=null,this.mediaBuffer=null}onSubtitleTrackSwitch(e,t){var s;if(this.currentTrackId=t.id,this.abortCurrentFrag(),!((s=this.levels)!=null&&s.length)||this.currentTrackId===-1){this.clearInterval();return}let i=this.levels[this.currentTrackId];if(!(i!=null&&i.details)){this.mediaBuffer=null;return}this.mediaBuffer=this.mediaBufferTimeRanges,this.state!==C.STOPPED&&this.setInterval(po)}onSubtitleTrackLoaded(e,t){var s;let{currentTrackId:i,levels:r}=this,{details:a,id:o}=t;if(!r){this.warn(`Subtitle tracks were reset while loading level ${o}`);return}let l=r[o];if(o>=r.length||!l)return;this.log(`Subtitle track ${o} loaded [${a.startSN},${a.endSN}]${a.lastPartSn?`[part-${a.lastPartSn}-${a.lastPartIndex}]`:""},duration:${a.totalduration}`),this.mediaBuffer=this.mediaBufferTimeRanges;let c=this.mainDetails,h=0;if(a.live||(s=l.details)!=null&&s.live){if(a.deltaUpdateFailed)return;if(!c){this.startFragRequested=!1;return}if(l.details){var u;h=this.alignPlaylists(a,l.details,(u=this.levelLastLoaded)==null?void 0:u.details)}a.alignedSliding||(ti(c,a,this),h=a.fragmentStart)}l.details=a,this.levelLastLoaded=l,c&&!this.startFragRequested&&this.setStartPosition(c,h),o===i&&(this.hls.trigger(p.SUBTITLE_TRACK_UPDATED,{details:a,id:o,groupId:t.groupId}),this.tickImmediate())}_handleFragmentLoadProgress(e){let{frag:t,part:s,payload:i}=e;!s||!(i!=null&&i.byteLength)||!this.shouldDecrypt(t)||this.decryptPayload(i,t,s)}_handleFragmentLoadComplete(e){let{frag:t,payload:s}=e;this.fragContextChanged(t)||!(s!=null&&s.byteLength)||!this.shouldDecrypt(t)||this.decryptPayload(s,t,null)}shouldDecrypt(e){let t=e.decryptdata;return!!(t!=null&&t.key&&t.iv&&Bt(t.method))}decryptPayload(e,t,s){let i=t.decryptdata,r=performance.now();this.decrypter.decrypt(new Uint8Array(e),i.key.buffer,i.iv.buffer,On(i.method)).then(a=>{this.fragContextChanged(t)||this.hls.trigger(p.FRAG_DECRYPTED,{frag:t,part:s,payload:a,stats:{tstart:r,tdecrypt:performance.now()}})}).catch(a=>{this.hls.trigger(p.ERROR,{type:W.MEDIA_ERROR,details:R.FRAG_DECRYPT_ERROR,fatal:!1,error:a,reason:a.message,frag:t,part:s}),s||(this.warn(`${a.name}: ${a.message}`),this.state=C.IDLE)})}doTick(){if(this.state===C.IDLE&&this.levels){var e;if(!this.media&&!this.primaryPrefetch&&(this.startFragRequested||!this.config.startFragPrefetch))return;let{currentTrackId:s,levels:i}=this,r=i[s],a=r?.details;if(!a||this.waitForLive(r)||this.waitForCdnTuneIn(a)){this.startFragRequested=!1;return}let{config:o}=this,l=this.playhead,c=X.bufferedInfo(this.tracksBuffered[s]||[],l,o.maxBufferHole),{end:h,len:u}=c,d=Math.max(this.hls.maxBufferLength+a.levelTargetDuration,((e=this.hls.mainForwardBufferInfo)==null?void 0:e.len)||0);if(u>d||u&&!this.buffering)return;let f=this.getNextFragment(h,a);if(!f)return;if(pe(f)){var t;if(f.end===c.end)return;let g=f.sn-a.startSN,m=a.fragments[g-1];f.cc===m?.cc&&!((t=a.partList)!=null&&t.length)&&this.fragmentTracker.getState(m)===fe.NOT_LOADED&&(f=m)}this.loadFragment(f,r,h)}}loadFragment(e,t,s){let i=this.fragmentTracker.getState(e);(i===fe.NOT_LOADED||i===fe.PARTIAL)&&super.loadFragment(e,t,s)}get mediaBufferTimeRanges(){return new fn(this.tracksBuffered[this.currentTrackId]||[])}},fn=class{constructor(e){this.buffered=void 0;let t=(s,i,r)=>{if(i=i>>>0,i>r-1)throw new DOMException(`Failed to execute '${s}' on 'TimeRanges': The index provided (${i}) is greater than the maximum bound (${r})`);return e[i][s]};this.buffered={get length(){return e.length},end(s){return t("end",s,e.length)},start(s){return t("start",s,e.length)}}}},Wf={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},lc=n=>String.fromCharCode(Wf[n]||n),Qe=15,Xe=42,qf={17:1,18:3,21:5,22:7,23:9,16:11,19:12,20:14},jf={17:2,18:4,21:6,22:8,23:10,19:13,20:15},zf={25:1,26:3,29:5,30:7,31:9,24:11,27:12,28:14},Xf={25:2,26:4,29:6,30:8,31:10,27:13,28:15},Qf=["white","green","blue","cyan","red","yellow","magenta","black","transparent"],gn=class{constructor(){this.time=null,this.verboseLevel=0}log(e,t){if(this.verboseLevel>=e){let s=typeof t=="function"?t():t;oe.log(`${this.time} [${e}] ${s}`)}}},Rt=function(e){let t=[];for(let s=0;s<e.length;s++)t.push(e[s].toString(16));return t},mn=Object.freeze({foreground:"white",underline:!1,italics:!1,background:"black",flash:!1}),pi=class{constructor(){this.styles=mn}get foreground(){return this.styles.foreground}set foreground(e){let t=this.styles;this.styles={foreground:e,underline:t.underline,italics:t.italics,background:t.background,flash:t.flash}}get underline(){return this.styles.underline}set underline(e){let t=this.styles;this.styles={foreground:t.foreground,underline:e,italics:t.italics,background:t.background,flash:t.flash}}get italics(){return this.styles.italics}set italics(e){let t=this.styles;this.styles={foreground:t.foreground,underline:t.underline,italics:e,background:t.background,flash:t.flash}}get background(){return this.styles.background}set background(e){let t=this.styles;this.styles={foreground:t.foreground,underline:t.underline,italics:t.italics,background:e,flash:t.flash}}get flash(){return this.styles.flash}set flash(e){let t=this.styles;this.styles={foreground:t.foreground,underline:t.underline,italics:t.italics,background:t.background,flash:e}}reset(){this.styles=mn}setStyles(e){let t=this.styles,s=Object.prototype.hasOwnProperty;this.styles={foreground:s.call(e,"foreground")?e.foreground:t.foreground,underline:s.call(e,"underline")?e.underline:t.underline,italics:s.call(e,"italics")?e.italics:t.italics,background:s.call(e,"background")?e.background:t.background,flash:s.call(e,"flash")?e.flash:t.flash}}toString(){return"color="+this.foreground+", underline="+this.underline+", italics="+this.italics+", background="+this.background+", flash="+this.flash}},pn=class{constructor(){this.uchar=" ",this.penState=new pi}reset(){this.uchar=" ",this.penState.reset()}setChar(e,t){this.uchar=e,this.penState.styles=t.styles}setPenState(e){this.penState.styles=e.styles}copy(e){this.uchar=e.uchar,this.penState.styles=e.penState.styles}},yn=class{constructor(e){this.chars=[],this.pos=0,this.currPenState=new pi,this.cueStartTime=null,this.logger=void 0;for(let t=0;t<Xe;t++)this.chars.push(new pn);this.logger=e}equals(e){let t=this.chars,s=e.chars;for(let i=0;i<Xe;i++){let r=t[i],a=s[i];if(r.uchar!==a.uchar)return!1;let o=r.penState.styles,l=a.penState.styles;if(o!==l&&(o.foreground!==l.foreground||o.underline!==l.underline||o.italics!==l.italics||o.background!==l.background||o.flash!==l.flash))return!1}return!0}copy(e){for(let t=0;t<Xe;t++)this.chars[t].copy(e.chars[t])}isEmpty(){let e=this.chars;for(let t=0;t<Xe;t++){let s=e[t];if(s.uchar!==" ")return!1;let i=s.penState.styles;if(i!==mn&&(i.foreground!=="white"||i.underline||i.italics||i.background!=="black"||i.flash))return!1}return!0}setCursor(e){this.pos!==e&&(this.pos=e),this.pos<0?(this.logger.log(3,"Negative cursor position "+this.pos),this.pos=0):this.pos>=Xe&&(this.logger.log(3,"Too large cursor position "+this.pos),this.pos=Xe-1)}moveCursor(e){let t=Math.min(this.pos+e,Xe);if(e>1)for(let s=this.pos+1;s<t;s++)this.chars[s].setPenState(this.currPenState);this.setCursor(t)}backSpace(){this.moveCursor(-1),this.chars[this.pos].setChar(" ",this.currPenState)}insertChar(e){e>=144&&this.backSpace();let t=lc(e);if(this.pos>=Xe){this.logger.log(0,()=>"Cannot insert "+e.toString(16)+" ("+t+") at position "+this.pos+". Skipping it!");return}this.chars[this.pos].setChar(t,this.currPenState),this.moveCursor(1)}clearFromPos(e){let t;for(t=e;t<Xe;t++)this.chars[t].reset()}clear(){this.clearFromPos(0),this.pos=0,this.currPenState.reset()}clearToEndOfRow(){this.clearFromPos(this.pos)}getTextString(){let e=[],t=!0;for(let s=0;s<Xe;s++){let i=this.chars[s].uchar;i!==" "&&(t=!1),e.push(i)}return t?"":e.join("")}setPenStyles(e){this.currPenState.setStyles(e),this.chars[this.pos].setPenState(this.currPenState)}},es=class{constructor(e){this.rows=[],this.currRow=Qe-1,this.nrRollUpRows=null,this.lastOutputScreen=null,this.logger=void 0;for(let t=0;t<Qe;t++)this.rows.push(new yn(e));this.logger=e}reset(){for(let e=0;e<Qe;e++)this.rows[e].clear();this.currRow=Qe-1}equals(e){let t=!0;for(let s=0;s<Qe;s++)if(!this.rows[s].equals(e.rows[s])){t=!1;break}return t}copy(e){for(let t=0;t<Qe;t++){let s=this.rows[t].chars,i=e.rows[t].chars;for(let r=0;r<Xe;r++){let a=s[r],o=i[r];a.uchar=o.uchar,a.penState.styles=o.penState.styles}}}isEmpty(){let e=!0;for(let t=0;t<Qe;t++)if(!this.rows[t].isEmpty()){e=!1;break}return e}backSpace(){this.rows[this.currRow].backSpace()}clearToEndOfRow(){this.rows[this.currRow].clearToEndOfRow()}insertChar(e){this.rows[this.currRow].insertChar(e)}setPen(e){this.rows[this.currRow].setPenStyles(e)}moveCursor(e){this.rows[this.currRow].moveCursor(e)}setCursor(e){this.logger.log(2,"setCursor: "+e),this.rows[this.currRow].setCursor(e)}setPAC(e){this.logger.log(2,()=>"pacData = "+de(e));let t=e.row-1;if(this.nrRollUpRows&&t<this.nrRollUpRows-1&&(t=this.nrRollUpRows-1),this.nrRollUpRows&&this.currRow!==t){for(let o=0;o<Qe;o++)this.rows[o].clear();let r=this.currRow+1-this.nrRollUpRows,a=this.lastOutputScreen;if(a){let o=a.rows[r].cueStartTime,l=this.logger.time;if(o!==null&&l!==null&&o<l)for(let c=0;c<this.nrRollUpRows;c++)this.rows[t-this.nrRollUpRows+c+1].copy(a.rows[r+c])}}this.currRow=t;let s=this.rows[this.currRow];if(e.indent!==null){let r=e.indent,a=Math.max(r-1,0);s.setCursor(e.indent),e.color=s.chars[a].penState.foreground}let i={foreground:e.color,underline:e.underline,italics:e.italics,background:"black",flash:!1};this.setPen(i)}setBkgData(e){this.logger.log(2,()=>"bkgData = "+de(e)),this.backSpace(),this.setPen(e),this.insertChar(32)}setRollUpRows(e){this.nrRollUpRows=e}rollUp(){if(this.nrRollUpRows===null){this.logger.log(3,"roll_up but nrRollUpRows not set yet");return}this.logger.log(1,()=>this.getDisplayText());let e=this.currRow+1-this.nrRollUpRows,t=this.rows.splice(e,1)[0];t.clear(),this.rows.splice(this.currRow,0,t),this.logger.log(2,"Rolling up")}getDisplayText(e){e=e||!1;let t=[],s="",i=-1;for(let r=0;r<Qe;r++){let a=this.rows[r].getTextString();a&&(i=r+1,e?t.push("Row "+i+": '"+a+"'"):t.push(a.trim()))}return t.length>0&&(e?s="["+t.join(" | ")+"]":s=t.join(`
44
+ `)),s}getTextAndFormat(){return this.rows}},En=class{constructor(e,t,s){this.chNr=void 0,this.outputFilter=void 0,this.mode=void 0,this.verbose=void 0,this.displayedMemory=void 0,this.nonDisplayedMemory=void 0,this.lastOutputScreen=void 0,this.currRollUpRow=void 0,this.writeScreen=void 0,this.cueStartTime=void 0,this.logger=void 0,this.chNr=e,this.outputFilter=t,this.mode=null,this.verbose=0,this.displayedMemory=new es(s),this.nonDisplayedMemory=new es(s),this.lastOutputScreen=new es(s),this.currRollUpRow=this.displayedMemory.rows[Qe-1],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null,this.logger=s}reset(){this.mode=null,this.displayedMemory.reset(),this.nonDisplayedMemory.reset(),this.lastOutputScreen.reset(),this.outputFilter.reset(),this.currRollUpRow=this.displayedMemory.rows[Qe-1],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null}getHandler(){return this.outputFilter}setHandler(e){this.outputFilter=e}setPAC(e){this.writeScreen.setPAC(e)}setBkgData(e){this.writeScreen.setBkgData(e)}setMode(e){e!==this.mode&&(this.mode=e,this.logger.log(2,()=>"MODE="+e),this.mode==="MODE_POP-ON"?this.writeScreen=this.nonDisplayedMemory:(this.writeScreen=this.displayedMemory,this.writeScreen.reset()),this.mode!=="MODE_ROLL-UP"&&(this.displayedMemory.nrRollUpRows=null,this.nonDisplayedMemory.nrRollUpRows=null),this.mode=e)}insertChars(e){for(let s=0;s<e.length;s++)this.writeScreen.insertChar(e[s]);let t=this.writeScreen===this.displayedMemory?"DISP":"NON_DISP";this.logger.log(2,()=>t+": "+this.writeScreen.getDisplayText(!0)),(this.mode==="MODE_PAINT-ON"||this.mode==="MODE_ROLL-UP")&&(this.logger.log(1,()=>"DISPLAYED: "+this.displayedMemory.getDisplayText(!0)),this.outputDataUpdate())}ccRCL(){this.logger.log(2,"RCL - Resume Caption Loading"),this.setMode("MODE_POP-ON")}ccBS(){this.logger.log(2,"BS - BackSpace"),this.mode!=="MODE_TEXT"&&(this.writeScreen.backSpace(),this.writeScreen===this.displayedMemory&&this.outputDataUpdate())}ccAOF(){}ccAON(){}ccDER(){this.logger.log(2,"DER- Delete to End of Row"),this.writeScreen.clearToEndOfRow(),this.outputDataUpdate()}ccRU(e){this.logger.log(2,"RU("+e+") - Roll Up"),this.writeScreen=this.displayedMemory,this.setMode("MODE_ROLL-UP"),this.writeScreen.setRollUpRows(e)}ccFON(){this.logger.log(2,"FON - Flash On"),this.writeScreen.setPen({flash:!0})}ccRDC(){this.logger.log(2,"RDC - Resume Direct Captioning"),this.setMode("MODE_PAINT-ON")}ccTR(){this.logger.log(2,"TR"),this.setMode("MODE_TEXT")}ccRTD(){this.logger.log(2,"RTD"),this.setMode("MODE_TEXT")}ccEDM(){this.logger.log(2,"EDM - Erase Displayed Memory"),this.displayedMemory.reset(),this.outputDataUpdate(!0)}ccCR(){this.logger.log(2,"CR - Carriage Return"),this.writeScreen.rollUp(),this.outputDataUpdate(!0)}ccENM(){this.logger.log(2,"ENM - Erase Non-displayed Memory"),this.nonDisplayedMemory.reset()}ccEOC(){if(this.logger.log(2,"EOC - End Of Caption"),this.mode==="MODE_POP-ON"){let e=this.displayedMemory;this.displayedMemory=this.nonDisplayedMemory,this.nonDisplayedMemory=e,this.writeScreen=this.nonDisplayedMemory,this.logger.log(1,()=>"DISP: "+this.displayedMemory.getDisplayText())}this.outputDataUpdate(!0)}ccTO(e){this.logger.log(2,"TO("+e+") - Tab Offset"),this.writeScreen.moveCursor(e)}ccMIDROW(e){let t={flash:!1};if(t.underline=e%2===1,t.italics=e>=46,t.italics)t.foreground="white";else{let s=Math.floor(e/2)-16,i=["white","green","blue","cyan","red","yellow","magenta"];t.foreground=i[s]}this.logger.log(2,"MIDROW: "+de(t)),this.writeScreen.setPen(t)}outputDataUpdate(e=!1){let t=this.logger.time;t!==null&&this.outputFilter&&(this.cueStartTime===null&&!this.displayedMemory.isEmpty()?this.cueStartTime=t:this.displayedMemory.equals(this.lastOutputScreen)||(this.outputFilter.newCue(this.cueStartTime,t,this.lastOutputScreen),e&&this.outputFilter.dispatchCue&&this.outputFilter.dispatchCue(),this.cueStartTime=this.displayedMemory.isEmpty()?null:t),this.lastOutputScreen.copy(this.displayedMemory))}cueSplitAtTime(e){this.outputFilter&&(this.displayedMemory.isEmpty()||(this.outputFilter.newCue&&this.outputFilter.newCue(this.cueStartTime,e,this.displayedMemory),this.cueStartTime=e))}},yi=class{constructor(e,t,s){this.channels=[null,null,null],this.currentChannel=0,this.cmdHistory=Jf(),this.logger=void 0,this.field=void 0,this.outputFilters=void 0,this.logger=new gn,this.field=e,this.outputFilters=[null,t,s]}getHandler(e){return this.outputFilters[e]}setHandler(e,t){var s;this.outputFilters[e]=t,(s=this.channels[e])==null||s.setHandler(t)}getChannel(e){let t=this.channels[e];return t||(t=this.channels[e]=new En(this.field+e-1,this.outputFilters[e],this.logger)),t}addData(e,t){this.logger.time=e;for(let s=0;s<t.length;s+=2){let i=t[s]&127,r=t[s+1]&127,a=!1,o=null;if(i===0&&r===0)continue;this.logger.log(3,()=>"["+Rt([t[s],t[s+1]])+"] -> ("+Rt([i,r])+")");let l=this.cmdHistory;if(i>=16&&i<=31){if(Zf(i,r,l)){Os(null,null,l),this.logger.log(3,()=>"Repeated command ("+Rt([i,r])+") is dropped");continue}Os(i,r,this.cmdHistory),a=this.parseCmd(i,r),a||(a=this.parseMidrow(i,r)),a||(a=this.parsePAC(i,r)),a||(a=this.parseBackgroundAttributes(i,r))}else Os(null,null,l);if(!a&&(o=this.parseChars(i,r),o)){let h=this.currentChannel;h&&h>0?this.getChannel(h).insertChars(o):this.logger.log(2,"No channel found yet. TEXT-MODE?")}!a&&!o&&this.logger.log(2,()=>"Couldn't parse cleaned data "+Rt([i,r])+" orig: "+Rt([t[s],t[s+1]]))}}parseCmd(e,t){let s=(e===20||e===28||e===21||e===29)&&t>=32&&t<=47,i=(e===23||e===31)&&t>=33&&t<=35;if(!(s||i))return!1;let r=e===20||e===21||e===23?1:2,a=this.getChannel(r);return e===20||e===21||e===28||e===29?t===32?a.ccRCL():t===33?a.ccBS():t===34?a.ccAOF():t===35?a.ccAON():t===36?a.ccDER():t===37?a.ccRU(2):t===38?a.ccRU(3):t===39?a.ccRU(4):t===40?a.ccFON():t===41?a.ccRDC():t===42?a.ccTR():t===43?a.ccRTD():t===44?a.ccEDM():t===45?a.ccCR():t===46?a.ccENM():t===47&&a.ccEOC():a.ccTO(t-32),this.currentChannel=r,!0}parseMidrow(e,t){let s=0;if((e===17||e===25)&&t>=32&&t<=47){if(e===17?s=1:s=2,s!==this.currentChannel)return this.logger.log(0,"Mismatch channel in midrow parsing"),!1;let i=this.channels[s];return i?(i.ccMIDROW(t),this.logger.log(3,()=>"MIDROW ("+Rt([e,t])+")"),!0):!1}return!1}parsePAC(e,t){let s,i=(e>=17&&e<=23||e>=25&&e<=31)&&t>=64&&t<=127,r=(e===16||e===24)&&t>=64&&t<=95;if(!(i||r))return!1;let a=e<=23?1:2;return t>=64&&t<=95?s=a===1?qf[e]:zf[e]:s=a===1?jf[e]:Xf[e],this.getChannel(a).setPAC(this.interpretPAC(s,t)),this.currentChannel=a,!0}interpretPAC(e,t){let s,i={color:null,italics:!1,indent:null,underline:!1,row:e};return t>95?s=t-96:s=t-64,i.underline=(s&1)===1,s<=13?i.color=["white","green","blue","cyan","red","yellow","magenta","white"][Math.floor(s/2)]:s<=15?(i.italics=!0,i.color="white"):i.indent=Math.floor((s-16)/2)*4,i}parseChars(e,t){let s,i=null,r=null;if(e>=25?(s=2,r=e-8):(s=1,r=e),r>=17&&r<=19){let a;r===17?a=t+80:r===18?a=t+112:a=t+144,this.logger.log(2,()=>"Special char '"+lc(a)+"' in channel "+s),i=[a]}else e>=32&&e<=127&&(i=t===0?[e]:[e,t]);return i&&this.logger.log(3,()=>"Char codes = "+Rt(i).join(",")),i}parseBackgroundAttributes(e,t){let s=(e===16||e===24)&&t>=32&&t<=47,i=(e===23||e===31)&&t>=45&&t<=47;if(!(s||i))return!1;let r,a={};e===16||e===24?(r=Math.floor((t-32)/2),a.background=Qf[r],t%2===1&&(a.background=a.background+"_semi")):t===45?a.background="transparent":(a.foreground="black",t===47&&(a.underline=!0));let o=e<=23?1:2;return this.getChannel(o).setBkgData(a),!0}reset(){for(let e=0;e<Object.keys(this.channels).length;e++){let t=this.channels[e];t&&t.reset()}Os(null,null,this.cmdHistory)}cueSplitAtTime(e){for(let t=0;t<this.channels.length;t++){let s=this.channels[t];s&&s.cueSplitAtTime(e)}}};function Os(n,e,t){t.a=n,t.b=e}function Zf(n,e,t){return t.a===n&&t.b===e}function Jf(){return{a:null,b:null}}var Nt=class{constructor(e,t){this.timelineController=void 0,this.cueRanges=[],this.trackName=void 0,this.startTime=null,this.endTime=null,this.screen=null,this.timelineController=e,this.trackName=t}dispatchCue(){this.startTime!==null&&(this.timelineController.addCues(this.trackName,this.startTime,this.endTime,this.screen,this.cueRanges),this.startTime=null)}newCue(e,t,s){(this.startTime===null||this.startTime>e)&&(this.startTime=e),this.endTime=t,this.screen=s,this.timelineController.createCaptionsTrack(this.trackName)}reset(){this.cueRanges=[],this.startTime=null}},Tn=class{constructor(e){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=yo(),this.captionsProperties=void 0,this.hls=e,this.config=e.config,this.Cues=e.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}},e.on(p.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(p.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(p.MANIFEST_LOADING,this.onManifestLoading,this),e.on(p.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(p.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(p.FRAG_LOADING,this.onFragLoading,this),e.on(p.FRAG_LOADED,this.onFragLoaded,this),e.on(p.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.on(p.FRAG_DECRYPTED,this.onFragDecrypted,this),e.on(p.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(p.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.on(p.BUFFER_APPENDED,this.onBufferAppended,this),e.on(p.BUFFER_FLUSHING,this.onBufferFlushing,this)}destroy(){let{hls:e}=this;e.off(p.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(p.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(p.MANIFEST_LOADING,this.onManifestLoading,this),e.off(p.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(p.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(p.FRAG_LOADING,this.onFragLoading,this),e.off(p.FRAG_LOADED,this.onFragLoaded,this),e.off(p.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.off(p.FRAG_DECRYPTED,this.onFragDecrypted,this),e.off(p.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(p.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.off(p.BUFFER_APPENDED,this.onBufferAppended,this),e.off(p.BUFFER_FLUSHING,this.onBufferFlushing,this),this.hls=this.config=this.media=null,this.cea608Parser1=this.cea608Parser2=void 0}initCea608Parsers(){let e=new Nt(this,"textTrack1"),t=new Nt(this,"textTrack2"),s=new Nt(this,"textTrack3"),i=new Nt(this,"textTrack4");this.cea608Parser1=new yi(1,e,t),this.cea608Parser2=new yi(3,s,i)}addCues(e,t,s,i,r){let a=!1;for(let l=r.length;l--;){let c=r[l],h=eg(c[0],c[1],t,s);if(h>=0&&(c[0]=Math.min(c[0],t),c[1]=Math.max(c[1],s),a=!0,h/(s-t)>.5))return}if(a||r.push([t,s]),this.config.renderTextTracksNatively){let l=this.cueCache[e];if(l){let c=this.Cues.newCue(null,t,s,i);c.length&&l.push.apply(l,c)}else{let c=this.captionsTracks[e].track;this.Cues.newCue(c,t,s,i)}}else{var o;let l=this.Cues.newCue(null,t,s,i),c=(o=this.captionsProperties[e])==null?void 0:o.media;this.hls.trigger(p.CUES_PARSED,{type:"captions",cues:l,track:e,closedCaptions:c})}}onInitPtsFound(e,{id:t,timestampOffsets:s}){let{unparsedFrags:i}=this;t===K.MAIN&&(this.initPTS=s),i.length&&(this.unparsedFrags=[],i.forEach(r=>{this.initPTS[r.frag.cc]?this.onFragLoaded(p.FRAG_LOADED,r):this.hls.trigger(p.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:r.frag,part:null,error:new Error("Subtitle discontinuity domain does not match main")})}))}createCaptionsTrack(e){this.config.renderTextTracksNatively?this.createNativeTrack(e):this.createNonNativeTrack(e)}createNativeTrack(e){if(this.captionsTracks[e])return;let{captionsProperties:t,captionsTracks:s,cueCache:i,media:r}=this,{label:a,languageCode:o}=t[e];r&&(i[e]=[],s[e]=qn(r,"captions",a,o,"hidden"))}createNonNativeTrack(e){if(this.nonNativeCaptionsTracks[e])return;let t=this.captionsProperties[e];if(!t)return;let s=t.label,i={_id:e,label:s,kind:"captions",default:t.media?!!t.media.default:!1,closedCaptions:t.media};this.nonNativeCaptionsTracks[e]=i,this.hls.trigger(p.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:[i]})}onMediaAttaching(e,t){this.media=t.media}onMediaDetaching(e,t){let s=!!t.transferMedia;if(this.media=null,!s){if(this.config.renderTextTracksNatively){let{captionsTracks:i,cueCache:r}=this;for(let a in i)i[a].remove(),delete r[a]}this.cueCache={},this.captionsTracks={},this.nonNativeCaptionsTracks={}}}onManifestLoading(){this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs=yo(),this.tracks=[],this.captionsTracks={},this.nonNativeCaptionsTracks={},this.unparsedFrags=[],this.initPTS=[],this.cea608Parser1&&this.cea608Parser2&&(this.cea608Parser1.reset(),this.cea608Parser2.reset())}onSubtitleTracksUpdated(e,t){let s=t.subtitleTracks||[];if(s.length&&!this.config.renderTextTracksNatively&&!kl(this.tracks,s)){let i=s.map(r=>({label:r.name,kind:r.type.toLowerCase(),default:r.default,subtitleTrack:r}));this.hls.trigger(p.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:i})}this.tracks=s}onManifestLoaded(e,t){this.config.enableCEA708Captions&&t.captions&&t.captions.forEach(s=>{let i=/(?:CC|SERVICE)([1-4])/.exec(s.instreamId);if(!i)return;let r=`textTrack${i[1]}`,a=this.captionsProperties[r];a&&(a.label=s.name,s.lang&&(a.languageCode=s.lang),a.media=s)})}closedCaptionsForLevel(e){let t=this.hls.levels[e.level];return t?.attrs["CLOSED-CAPTIONS"]}onFragLoading(e,t){if(this.enabled&&t.frag.type===K.MAIN){var s,i;let{cea608Parser1:r,cea608Parser2:a,lastSn:o}=this,{cc:l,sn:c}=t.frag,h=(s=(i=t.part)==null?void 0:i.index)!=null?s:-1;r&&a&&(c!==o+1||c===o&&h!==this.lastPartIndex+1||l!==this.lastCc)&&(r.reset(),a.reset()),this.lastCc=l,this.lastSn=c,this.lastPartIndex=h}}onFragLoaded(e,t){let{frag:s,payload:i}=t;if(s.level<this.tracks.length&&s.type===K.SUBTITLE){var r;if(i.byteLength||(r=s.initSegment)!=null&&(r=r.data)!=null&&r.byteLength){let a=s.decryptdata,o="stats"in t;if(a==null||!a.encrypted||o){let l=this.tracks[s.level],c=this.vttCCs;c[s.cc]||(c[s.cc]={start:s.start,prevCC:this.prevCC,new:!0},this.prevCC=s.cc),l?.textCodec===Xr?this._parseIMSC1(t):this._parseVTTs(t)}}else{let a="part"in t?t.part:null;this.hls.trigger(p.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:s,part:a,error:new Error("Empty subtitle payload")})}}}_parseIMSC1(e){let{frag:t,payload:s}=e,i="part"in e?e.part:null;if(!this.initPTS[t.cc]){this.unparsedFrags.push(e);return}let r=this.hls;ao(s,this.initPTS[t.cc],a=>{this._appendCues(a,t.level),r.trigger(p.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:t,part:i})},a=>{r.logger.log(`Cannot parse IMSC1 (sn: ${t.sn} @${t.start}): ${a}`),r.trigger(p.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:t,part:i,error:a})})}_parseVTTs(e){var t;let{frag:s,payload:i}=e,r="part"in e?e.part:null,{initPTS:a,unparsedFrags:o}=this,l=a.length-1;if(!a[s.cc]&&l===-1){o.push(e);return}let c=this.hls,h=(t=s.initSegment)==null?void 0:t.data,u=h?We(h,new Uint8Array(i)).buffer:i;Af(u,this.initPTS[s.cc],this.vttCCs,s.cc,(r&&!h?r:s).start,d=>{this._appendCues(d,s.level),c.trigger(p.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:s,part:r})},d=>{let f=d.message.startsWith("Missing initPTS");if(c.logger.log(`${f?"Deferred parsing of":"Cannot parse"} VTT cue (sn: ${s.sn} @${s.start}): ${d}`),f){o.push(e);return}else this.config.enableIMSC1&&this._fallbackToIMSC1(e);c.trigger(p.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:s,part:r,error:d})})}_fallbackToIMSC1(e){let{frag:t,payload:s}=e,i=this.tracks[t.level];i.textCodec||ao(s,this.initPTS[t.cc],()=>{i.textCodec=Xr,this._parseIMSC1(e)},()=>{i.textCodec="wvtt"})}_appendCues(e,t){let s=this.hls;if(this.config.renderTextTracksNatively){var i;let r=(i=this.tracks[t].trackNode)==null?void 0:i.track;if(!r||r.mode==="disabled")return;e.forEach(a=>Qr(r,a))}else{let r=this.tracks[t];if(!r)return;let a=r.default?"default":"subtitles"+t;s.trigger(p.CUES_PARSED,{type:"subtitles",cues:e,track:a,subtitleTrack:r})}}onFragDecrypted(e,t){let{frag:s}=t;s.type===K.SUBTITLE&&this.onFragLoaded(p.FRAG_LOADED,t)}onSubtitleTracksCleared(){this.tracks=[],this.captionsTracks={}}onFragParsingUserdata(e,t){if(!this.enabled||!this.config.enableCEA708Captions)return;let{frag:s,samples:i}=t;if(!(s.type===K.MAIN&&this.closedCaptionsForLevel(s)==="NONE"))for(let r=0;r<i.length;r++){let a=i[r].bytes;if(a){this.cea608Parser1||this.initCea608Parsers();let o=this.extractCea608Data(a);this.cea608Parser1.addData(i[r].pts,o[0]),this.cea608Parser2.addData(i[r].pts,o[1])}}}onBufferAppended(e,t){if(this.config.renderTextTracksNatively){var s;let{type:i,timeRanges:r}=t;if(i==="video"&&(s=r[i])!=null&&s.length){let{captionsTracks:a,cueCache:o}=this;Object.keys(o).forEach(l=>{var c;let h=(c=a[l])==null?void 0:c.track;if(h){let u=o[l];for(let d=0;d<u.length;d++)Qr(h,u[d])}delete o[l]})}}}onBufferFlushing(e,t){let{startOffset:s,endOffset:i,endOffsetSubtitles:r,type:a}=t,{media:o}=this;if(!(!o||o.currentTime<i)){if(!a||a==="video"){let{captionsTracks:l,cueCache:c}=this;Object.keys(l).forEach(h=>Zr(l[h].track,s,i)),Object.keys(c).forEach(h=>{let u=c[h];for(let d=u.length;d--;){let f=u[d];f.startTime>=s&&f.endTime<=i&&u.splice(d,1)}})}this.config.renderTextTracksNatively&&s===0&&r!==void 0&&this.tracks.forEach(l=>{var c;let h=(c=l.trackNode)==null?void 0:c.track;h&&Zr(h,s,r)})}}extractCea608Data(e){let t=[[],[]],s=e[0]&31,i=2;for(let r=0;r<s;r++){let a=e[i++],o=127&e[i++],l=127&e[i++];if(o===0&&l===0)continue;if((4&a)!==0){let h=3&a;(h===0||h===1)&&(t[h].push(o),t[h].push(l))}}return t}};function eg(n,e,t,s){return Math.min(e,s)-Math.max(n,t)}function yo(){return{ccOffset:0,presentationOffset:0,0:{start:0,prevCC:-1,new:!0}}}var tg=/\s/,sg={newCue(n,e,t,s){let i=[],r,a,o,l,c,h=self.VTTCue||self.TextTrackCue;for(let d=0;d<s.rows.length;d++)if(r=s.rows[d],o=!0,l=0,c="",!r.isEmpty()){var u;for(let m=0;m<r.chars.length;m++)tg.test(r.chars[m].uchar)&&o?l++:(c+=r.chars[m].uchar,o=!1);r.cueStartTime=e,e===t&&(t+=1e-4),l>=16?l--:l++;let f=tc(c.trim()),g=Wn(e,t,f);n!=null&&(u=n.cues)!=null&&u.getCueById(g)||(a=new h(e,t,f),a.id=g,a.line=d+1,a.align="left",a.position=10+Math.min(80,Math.floor(l*8/32)*10),i.push(a))}return n&&i.length&&(i.sort((d,f)=>d.line==="auto"||f.line==="auto"?0:d.line>8&&f.line>8?f.line-d.line:d.line-f.line),i.forEach(d=>Qr(n,d))),i}},Ei=class{constructor(){this.requestTimeout=void 0,this.retryTimeout=void 0,this.retryDelay=0,this.config=null,this.callbacks=null,this.context=null,this.stats=new ts}destroy(){this.callbacks=this.context=this.config=null,this.abortInternal(),this.stats=null}load(e,t,s){let i=this.stats;if(i.loading.start)throw new Error("Loader can only be used once.");i.loading.start=self.performance.now(),this.context=e,this.config=t,this.callbacks=s,this.loadInternal()}abort(){var e;this.abortInternal(),(e=this.callbacks)!=null&&e.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.getNetworkDetails())}loadtimeout(){if(!this.config)return;let e=this.config.loadPolicy.timeoutRetry,t=this.stats.retry;if(ss(e,t,!0))this.retry(e);else{var s;oe.warn(`timeout while loading ${(s=this.context)==null?void 0:s.url}`);let i=this.callbacks;i&&(this.abortInternal(),i.onTimeout(this.stats,this.context,this.getNetworkDetails()))}}retry(e){let{context:t,stats:s}=this;this.retryDelay=Rn(e,s.retry),s.retry++,oe.warn(`${status?"HTTP Status "+status:"Timeout"} while loading ${t?.url}, retrying ${s.retry}/${e.maxNumRetry} in ${this.retryDelay}ms`),this.abortInternal(),this.resetInternalLoader(),self.clearTimeout(this.retryTimeout),this.retryTimeout=self.setTimeout(()=>this.loadInternal(),this.retryDelay)}};function ig(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch{}return!1}var rg=/(\d+)-(\d+)\/(\d+)/,Ti=class extends Ei{constructor(e){super(),this.fetchSetup=void 0,this.request=null,this.response=null,this.controller=null,this.fetchSetup=e.fetchSetup||lg}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(){let{config:e,context:t,stats:s}=this;if(!e||!t)return;s.loading.first=0,s.loaded=0,s.aborted=!1,this.controller=new self.AbortController;let i=ng(t,this.controller.signal),r=t.responseType==="arraybuffer",a=r?"byteLength":"length",{maxTimeToFirstByteMs:o,maxLoadTimeMs:l}=e.loadPolicy;this.request=this.fetchSetup(t,i),self.clearTimeout(this.requestTimeout),e.timeout=o&&$(o)?o:l,this.requestTimeout=self.setTimeout(()=>{this.loadtimeout()},e.timeout),(gs(this.request)?this.request.then(self.fetch):self.fetch(this.request)).then(h=>{var u;this.response=h;let d=Math.max(self.performance.now(),s.loading.start);if(self.clearTimeout(this.requestTimeout),e.timeout=l,this.requestTimeout=self.setTimeout(()=>{this.loadtimeout()},l-(d-s.loading.start)),!h.ok){let{status:g,statusText:m}=h;throw new Sn(m||"fetch, bad network response",g,h)}s.loading.first=d,s.total=og(h.headers)||s.total;let f=(u=this.callbacks)==null?void 0:u.onProgress;return f&&$(e.highWaterMark)?this.loadProgressively(h,s,t,e.highWaterMark,f):r?h.arrayBuffer():t.responseType==="json"?h.json():h.text()}).then(h=>{var u,d;let f=this.response;if(!f)throw new Error("loader destroyed");self.clearTimeout(this.requestTimeout),s.loading.end=Math.max(self.performance.now(),s.loading.first);let g=h[a];g&&(s.loaded=s.total=g);let m={url:f.url,data:h,code:f.status},y=(u=this.callbacks)==null?void 0:u.onProgress;y&&!$(e.highWaterMark)&&y(s,t,h,f),(d=this.callbacks)==null||d.onSuccess(m,s,t,f)}).catch(h=>{if(self.clearTimeout(this.requestTimeout),s.aborted)return;let u=h&&h.code||0,d=h?h.message:null,f=e.loadPolicy.errorRetry,g=s.retry,m={url:t.url,data:void 0,code:u};if(ss(f,g,!1,m))this.retry(f);else{var y;oe.error(`${u} while loading ${t.url}`),(y=this.callbacks)==null||y.onError({code:u,text:d},t,h?h.details:null,s)}})}getCacheAge(){let e=null;if(this.response){let t=this.response.headers.get("age");e=t?parseFloat(t):null}return e}getResponseHeader(e){return this.response?this.response.headers.get(e):null}loadProgressively(e,t,s,i=0,r){let a=new ii,o=e.body.getReader(),l=()=>o.read().then(c=>{if(c.done)return a.dataLength&&r(t,s,a.flush().buffer,e),Promise.resolve(new ArrayBuffer(0));let h=c.value,u=h.length;return t.loaded+=u,u<i||a.dataLength?(a.push(h),a.dataLength>=i&&r(t,s,a.flush().buffer,e)):r(t,s,h.buffer,e),l()}).catch(()=>Promise.reject());return l()}};function ng(n,e){let t={method:"GET",mode:"cors",credentials:"same-origin",signal:e,headers:new self.Headers(he({},n.headers))};return n.rangeEnd&&t.headers.set("Range","bytes="+n.rangeStart+"-"+String(n.rangeEnd-1)),t}function ag(n){let e=rg.exec(n);if(e)return parseInt(e[2])-parseInt(e[1])+1}function og(n){let e=n.get("Content-Range");if(e){let s=ag(e);if($(s))return s}let t=n.get("Content-Length");if(t)return parseInt(t)}function lg(n,e){return new self.Request(n.url,e)}var Sn=class extends Error{constructor(e,t,s){super(e),this.code=void 0,this.details=void 0,this.code=t,this.details=s}},cg=(n,e,t)=>Math.max(e,Math.min(n,t)),hg=/^age:\s*[\d.]+\s*$/im,Si=class extends Ei{constructor(e){super(),this.xhrSetup=void 0,this.loader=null,this.xhrSetup=e.xhrSetup||null}destroy(){super.destroy(),this.loader=null,this.xhrSetup=null}abortInternal(){let e=this.loader;self.clearTimeout(this.requestTimeout),self.clearTimeout(this.retryTimeout),e&&(e.onreadystatechange=null,e.onprogress=null,e.readyState!==4&&(this.stats.aborted=!0,e.abort()))}getNetworkDetails(){return this.loader}resetInternalLoader(){this.loader=null}loadInternal(){let{config:e,context:t}=this;if(!e||!t)return;let s=this.loader=new self.XMLHttpRequest,i=this.stats;i.loading.first=0,i.loaded=0,i.aborted=!1;let r=this.xhrSetup;r?Promise.resolve().then(()=>{if(!(this.loader!==s||this.stats.aborted))return r.call(this,s,t.url,t)}).catch(a=>{if(!(this.loader!==s||this.stats.aborted))return s.open("GET",t.url,!0),r.call(this,s,t.url,t)}).then(()=>{this.loader!==s||this.stats.aborted||this.openAndSendXhr(s,t,e)}).catch(a=>{var o;(o=this.callbacks)==null||o.onError({code:s.status,text:a.message},t,s,i)}):this.openAndSendXhr(s,t,e)}openAndSendXhr(e,t,s){e.readyState||e.open("GET",t.url,!0);let i=t.headers,{maxTimeToFirstByteMs:r,maxLoadTimeMs:a}=s.loadPolicy;if(i)for(let o in i)e.setRequestHeader(o,i[o]);t.rangeEnd&&e.setRequestHeader("Range",`bytes=${t.rangeStart}-${t.rangeEnd-1}`),e.onreadystatechange=this.readystatechange.bind(this),e.onprogress=this.loadprogress.bind(this),e.responseType=t.responseType,self.clearTimeout(this.requestTimeout),s.timeout=r&&$(r)?r:a,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),s.timeout),e.send()}readystatechange(){let{context:e,loader:t,stats:s}=this;if(!e||!t)return;let i=t.readyState,r=this.config;if(!s.aborted&&i>=2&&(s.loading.first===0&&(s.loading.first=Math.max(self.performance.now(),s.loading.start),r.timeout!==r.loadPolicy.maxLoadTimeMs&&(self.clearTimeout(this.requestTimeout),r.timeout=r.loadPolicy.maxLoadTimeMs,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),r.loadPolicy.maxLoadTimeMs-(s.loading.first-s.loading.start)))),i===4)){self.clearTimeout(this.requestTimeout),t.onreadystatechange=null,t.onprogress=null;let c=t.status,h=t.responseType==="text"?t.responseText:null;if(c>=200&&c<300){let g=h??t.response;if(g!=null){var a,o;s.loading.end=Math.max(self.performance.now(),s.loading.first);let m=t.responseType==="arraybuffer"?g.byteLength:g.length;s.loaded=s.total=m,s.bwEstimate=s.total*8e3/(s.loading.end-s.loading.first);let y=(a=this.callbacks)==null?void 0:a.onProgress;y&&y(s,e,g,t);let E={url:t.responseURL,data:g,code:c};e.rangeEnd&&m!==e.rangeEnd-e.rangeStart&&oe.warn(`Payload length ${m} does not match requested Range: bytes=${e.rangeStart}-${e.rangeEnd-1}`),(o=this.callbacks)==null||o.onSuccess(E,s,e,t);return}}let u=r.loadPolicy.errorRetry,d=s.retry,f={url:e.url,data:void 0,code:c};if(ss(u,d,!1,f))this.retry(u);else{var l;oe.error(`${c} while loading ${e.url}`),(l=this.callbacks)==null||l.onError({code:c,text:t.statusText},e,t,s)}}}loadprogress(e){let t=this.stats;t.loaded=e.loaded,e.lengthComputable&&(t.total=e.total)}getCacheAge(){let e=null;if(this.loader&&hg.test(this.loader.getAllResponseHeaders())){let t=this.loader.getResponseHeader("age");e=t?parseFloat(t):null}return e}getResponseHeader(e){return this.loader&&new RegExp(`^${e}:\\s*[\\d.]+\\s*$`,"im").test(this.loader.getAllResponseHeaders())?this.loader.getResponseHeader(e):null}},ug={maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:null,errorRetry:null},dg=Y(Y({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:60*1e3*1e3,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:Si,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:ll,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:2*1024*1024,useMediaCapabilities:!0,preserveManualLevelOnError:!1,errorPenaltyExpireMs:0,certLoadPolicy:{default:ug},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:fi,abrController:lr,bufferController:fr,capLevelController:Fr,errorController:hr,fpsController:Yr,id3TrackController:sn,gapController:en,latencyController:un},fg()),{},{subtitleStreamController:dn,subtitleTrackController:Jr,timelineController:Tn,audioStreamController:wr,audioTrackController:Mr,emeController:di,cmcdController:Vr,contentSteeringController:Kr,iframeController:nn,interstitialsController:hn});function fg(){return{cueHandler:sg,enableWebVTT:!0,enableIMSC1:!0,enableCEA708Captions:!0,captionsTextTrack1Label:"English",captionsTextTrack1LanguageCode:"en",captionsTextTrack2Label:"Spanish",captionsTextTrack2LanguageCode:"es",captionsTextTrack3Label:"Unknown CC",captionsTextTrack3LanguageCode:"",captionsTextTrack4Label:"Unknown CC",captionsTextTrack4LanguageCode:"",renderTextTracksNatively:!0}}function gg(n,e,t){if((e.liveSyncDurationCount||e.liveMaxLatencyDurationCount)&&(e.liveSyncDuration||e.liveMaxLatencyDuration))throw new Error("Illegal hls.js config: don't mix up liveSyncDurationCount/liveMaxLatencyDurationCount and liveSyncDuration/liveMaxLatencyDuration");if(e.liveMaxLatencyDurationCount!==void 0&&(e.liveSyncDurationCount===void 0||e.liveMaxLatencyDurationCount<=e.liveSyncDurationCount))throw new Error('Illegal hls.js config: "liveMaxLatencyDurationCount" must be greater than "liveSyncDurationCount"');if(e.liveMaxLatencyDuration!==void 0&&(e.liveSyncDuration===void 0||e.liveMaxLatencyDuration<=e.liveSyncDuration))throw new Error('Illegal hls.js config: "liveMaxLatencyDuration" must be greater than "liveSyncDuration"');if(e.liveMaxUnchangedPlaylistRefresh!==void 0){let a=e.liveMaxUnchangedPlaylistRefresh,o=cg(a,2,1/0);o!==a&&t.warn(`hls.js config: "liveMaxUnchangedPlaylistRefresh" clamped from ${a} to ${o}.`),e.liveMaxUnchangedPlaylistRefresh=o}let s=vn(n),i=["manifest","level","frag"],r=["TimeOut","MaxRetry","RetryDelay","MaxRetryTimeout"];return i.forEach(a=>{let o=`${a==="level"?"playlist":a}LoadPolicy`,l=e[o]===void 0,c=[];r.forEach(h=>{let u=`${a}Loading${h}`,d=e[u];if(d!==void 0&&l){c.push(u);let f=s[o].default;switch(e[o]={default:f},h){case"TimeOut":f.maxLoadTimeMs=d,f.maxTimeToFirstByteMs=d;break;case"MaxRetry":f.errorRetry.maxNumRetry=d,f.timeoutRetry.maxNumRetry=d;break;case"RetryDelay":f.errorRetry.retryDelayMs=d,f.timeoutRetry.retryDelayMs=d;break;case"MaxRetryTimeout":f.errorRetry.maxRetryDelayMs=d,f.timeoutRetry.maxRetryDelayMs=d;break}}}),c.length&&t.warn(`hls.js config: "${c.join('", "')}" setting(s) are deprecated, use "${o}": ${de(e[o])}`)}),Y(Y({},s),e)}function vn(n){return n&&typeof n=="object"?Array.isArray(n)?n.map(vn):Object.keys(n).reduce((e,t)=>(e[t]=vn(n[t]),e),{}):n}function mg(n,e){let t=n.loader;t!==Ti&&t!==Si?(e.log("[config]: Custom loader detected, cannot enable progressive streaming"),n.progressive=!1):ig()&&(n.loader=Ti,n.progressive=!0,n.enableSoftwareAES=!0,e.log("[config]: Progressive streaming enabled, using FetchLoader"))}var xn=class extends ms{constructor(e,t){super(e,"level-controller"),this._levels=[],this._firstLevel=-1,this._maxAutoLevel=-1,this._startLevel=void 0,this.currentLevel=null,this.currentLevelIndex=-1,this.manualLevelIndex=-1,this.steering=void 0,this.lastABRSwitchTime=-1,this._iframeVariants=[],this.onParsedComplete=void 0,this.steering=t,this._registerListeners()}_registerListeners(){let{hls:e}=this;e.on(p.MANIFEST_LOADING,this.onManifestLoading,this),e.on(p.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(p.LEVEL_LOADED,this.onLevelLoaded,this),e.on(p.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(p.FRAG_BUFFERED,this.onFragBuffered,this),e.on(p.ERROR,this.onError,this)}_unregisterListeners(){let{hls:e}=this;e.off(p.MANIFEST_LOADING,this.onManifestLoading,this),e.off(p.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(p.LEVEL_LOADED,this.onLevelLoaded,this),e.off(p.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(p.FRAG_BUFFERED,this.onFragBuffered,this),e.off(p.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(e,t){this.resetLevels()}onManifestLoaded(e,t){let s=this.hls.config.preferManagedMediaSource,i=[],r={},a={},o=!1,l=!1,c=!1,h=!1;t.levels.forEach(u=>{let d=u.attrs,f=Eo(u,s),{audioCodec:g,videoCodec:m,imageCodec:y,width:E,height:S}=u;if(!f){this.log(`Some or all CODECS not supported "${d.CODECS}"`);return}o||(o=!!(E&&S)),l||(l=!!m),c||(c=!!g),h||(h=!!y);let{CODECS:T,"FRAME-RATE":v,"HDCP-LEVEL":x,"PATHWAY-ID":I,RESOLUTION:A,"VIDEO-RANGE":b}=d,L=`${`${I||"."}-`}${u.bitrate}-${A}-${v}-${T}-${b}-${x}`;if(r[L])if(r[L].uri!==u.url&&!u.attrs["PATHWAY-ID"]){let P=a[L]+=1;u.attrs["PATHWAY-ID"]=new Array(P+1).join(".");let D=this.createLevel(u);r[L]=D,i.push(D)}else u.iframes||(r[L].addGroupId("audio",d.AUDIO),r[L].addGroupId("text",d.SUBTITLES));else{let P=this.createLevel(u);r[L]=P,a[L]=1,i.push(P)}}),this.filterAndSortMediaOptions(i,t,o,l,c,h)}createLevel(e){let t=new Pt(e),s=e.supplemental;if(s!=null&&s.videoCodec&&!hc(s.videoCodec,this.hls.config.preferManagedMediaSource)){let i=new Error(`SUPPLEMENTAL-CODECS not supported "${s.videoCodec}"`);this.log(i.message),t.supportedResult=Wo(i,[])}return t}filterAndSortMediaOptions(e,t,s,i,r,a){var o;let l=[],c=[],h=e,u=((o=t.stats)==null?void 0:o.parsing)||{},d=this.hls.config.preferManagedMediaSource;if((s||i)&&r&&(h=h.filter(({videoCodec:x,videoRange:I,width:A,height:b})=>(!!x||!!(A&&b))&&Oh(I))),i&&a&&(h=h.filter(x=>!x.imageCodec)),h.length===0){Promise.resolve().then(()=>{if(this.hls){let x="no level with compatible codecs found in manifest",I=x;t.levels.length&&(I=`one or more CODECS in variant not supported: ${de(t.levels.map(b=>b.attrs.CODECS).filter((b,_,L)=>L.indexOf(b)===_))}`,this.warn(I),x+=` (${I})`);let A=new Error(x);this.hls.trigger(p.ERROR,{type:W.MEDIA_ERROR,details:R.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:t.url,error:A,reason:I})}}),u.end=performance.now();return}t.audioTracks&&(l=t.audioTracks.filter(x=>!x.audioCodec||cc(x.audioCodec,d)),To(l)),t.subtitles&&(c=t.subtitles,To(c));let f=h.slice(0);h.sort((x,I)=>{if(x.attrs["HDCP-LEVEL"]!==I.attrs["HDCP-LEVEL"])return(x.attrs["HDCP-LEVEL"]||"")>(I.attrs["HDCP-LEVEL"]||"")?1:-1;if(s&&x.height!==I.height)return x.height-I.height;if(x.frameRate!==I.frameRate)return x.frameRate-I.frameRate;if(x.videoRange!==I.videoRange)return Ys.indexOf(x.videoRange)-Ys.indexOf(I.videoRange);if(x.videoCodec!==I.videoCodec){let A=ra(x.videoCodec),b=ra(I.videoCodec);if(A!==b)return b-A}if(x.uri===I.uri&&x.codecSet!==I.codecSet){let A=Ks(x.codecSet),b=Ks(I.codecSet);if(A!==b)return b-A}return x.averageBitrate!==I.averageBitrate?x.averageBitrate-I.averageBitrate:0});let g=f[0];if(this.steering&&(h=this.steering.filterParsedLevels(h),h.length!==f.length)){for(let x=0;x<f.length;x++)if(f[x].pathwayId===h[0].pathwayId){g=f[x];break}}this._levels=h;for(let x=0;x<h.length;x++)if(h[x]===g){var m;this._firstLevel=x;let I=g.bitrate,A=this.hls.bandwidthEstimate;if(this.log(`manifest loaded, ${h.length} level(s) found, first bitrate: ${I}`),((m=this.hls.userConfig)==null?void 0:m.abrEwmaDefaultEstimate)===void 0){let b=Math.min(I,this.hls.config.abrEwmaDefaultEstimateMax);b>A&&A===this.hls.abrEwmaDefaultEstimate&&(this.hls.bandwidthEstimate=b)}break}let y=t.iframeVariants.filter(x=>Eo(x,d));this._iframeVariants=y;let E=r&&!i,S=this.hls.config,T=!!(S.audioStreamController&&S.audioTrackController),v={levels:h,audioTracks:l,subtitleTracks:c,iframeVariants:y,sessionData:t.sessionData,sessionKeys:t.sessionKeys,firstLevel:this._firstLevel,stats:t.stats,audio:r,video:i,altAudio:T&&!E&&l.some(x=>!!x.url)};u.end=performance.now(),this.hls.trigger(p.MANIFEST_PARSED,v)}get iframeVariants(){return this._iframeVariants.length===0?null:this._iframeVariants}get levels(){return this._levels.length===0?null:this._levels}get loadLevelObj(){return this.currentLevel}get level(){return this.currentLevelIndex}set level(e){let t=this._levels;if(t.length===0)return;if(e<0||e>=t.length){let h=new Error("invalid level idx"),u=e<0;if(this.hls.trigger(p.ERROR,{type:W.OTHER_ERROR,details:R.LEVEL_SWITCH_ERROR,level:e,fatal:u,error:h,reason:h.message}),u)return;e=Math.min(e,t.length-1)}let s=this.currentLevelIndex,i=this.currentLevel,r=i?i.attrs["PATHWAY-ID"]:void 0,a=t[e],o=a.attrs["PATHWAY-ID"];if(this.currentLevelIndex=e,this.currentLevel=a,s===e&&i&&r===o)return;this.log(`Switching to level ${e} (${a.height?a.height+"p ":""}${a.videoRange?a.videoRange+" ":""}${a.codecSet?a.codecSet+" ":""}@${a.bitrate})${o?" with Pathway "+o:""} from level ${s}${r?" with Pathway "+r:""}`);let l={level:e,attrs:a.attrs,details:a.details,bitrate:a.bitrate,averageBitrate:a.averageBitrate,maxBitrate:a.maxBitrate,realBitrate:a.realBitrate,width:a.width,height:a.height,codecSet:a.codecSet,audioCodec:a.audioCodec,videoCodec:a.videoCodec,audioGroups:a.audioGroups,subtitleGroups:a.subtitleGroups,loaded:a.loaded,loadError:a.loadError,fragmentError:a.fragmentError,name:a.name,id:a.id,uri:a.uri,url:a.url,urlId:0,audioGroupIds:a.audioGroupIds,textGroupIds:a.textGroupIds};this.hls.trigger(p.LEVEL_SWITCHING,l);let c=a.details;if(!c||c.live){let h=this.switchParams(a.uri,i?.details,c);this.loadPlaylist(h)}}get manualLevel(){return this.manualLevelIndex}set manualLevel(e){this.manualLevelIndex=e,this._startLevel===void 0&&(this._startLevel=e),e!==-1&&(this.level=e)}get firstLevel(){return this._firstLevel}set firstLevel(e){this._firstLevel=e}get startLevel(){if(this._startLevel===void 0){let e=this.hls.config.startLevel;return e!==void 0?e:this.hls.firstAutoLevel}return this._startLevel}set startLevel(e){this._startLevel=e}get pathways(){return this.steering?this.steering.pathways():[]}get pathwayPriority(){return this.steering?this.steering.pathwayPriority:null}set pathwayPriority(e){if(this.steering){let t=this.steering.pathways(),s=e.filter(i=>t.indexOf(i)!==-1);if(e.length<1){this.warn(`pathwayPriority ${e} should contain at least one pathway from list: ${t}`);return}this.steering.pathwayPriority=s}}onError(e,t){t.fatal||!t.context||t.context.type===se.LEVEL&&t.context.level===this.level&&this.checkRetry(t)}onFragBuffered(e,{frag:t}){if(t.type===K.MAIN){let s=t.elementaryStreams;if(!Object.keys(s).some(r=>!!s[r]))return;let i=this._levels[t.level];i!=null&&i.loadError&&(this.log(`Resetting level error count of ${i.loadError} on frag buffered`),i.loadError=0)}}onLevelLoaded(e,t){var s;let{level:i,details:r}=t,a=t.levelInfo;if(!a){var o;this.warn(`Invalid level index ${i}`),(o=t.deliveryDirectives)!=null&&o.skip&&(r.deltaUpdateFailed=!0);return}if(a===this.currentLevel||t.withoutMultiVariant){a.fragmentError===0&&(a.loadError=0);let l=a.details;l===t.details&&l.advanced&&(l=void 0),this.playlistLoaded(i,t,l)}else(s=t.deliveryDirectives)!=null&&s.skip&&(r.deltaUpdateFailed=!0)}loadPlaylist(e){super.loadPlaylist(),this.shouldLoadPlaylist(this.currentLevel)&&this.scheduleLoading(this.currentLevel,e)}loadingPlaylist(e,t){super.loadingPlaylist(e,t);let s=this.getUrlWithDirectives(e.uri,t),i=this.currentLevelIndex,r=e.attrs["PATHWAY-ID"],a=e.details,o=a?.age;this.log(`Loading level index ${i}${t?.msn!==void 0?" at sn "+t.msn+" part "+t.part:""}${r?" Pathway "+r:""}${o&&a.live?" age "+o.toFixed(1)+(a.type&&" "+a.type||""):""} ${s}`),this.hls.trigger(p.LEVEL_LOADING,{url:s,level:i,levelInfo:e,pathwayId:e.attrs["PATHWAY-ID"],id:0,deliveryDirectives:t||null})}get nextLoadLevel(){return this.manualLevelIndex!==-1?this.manualLevelIndex:this.hls.nextAutoLevel}set nextLoadLevel(e){let t=this.currentLevelIndex;if(this.manualLevelIndex===-1&&e!==t&&e!==-1){let i=this.hls.config.abrSwitchInterval;if(i>0){let r=performance.now(),a=r-this.lastABRSwitchTime,o=i*1e3;if(this.lastABRSwitchTime>-1&&a<o){this.warn(`Preventing ABR level switch: ${t} -> ${e} (${Math.round(a)}ms < ${o}ms / ${i}s)`);return}this.lastABRSwitchTime=r,this.log(`Allowing ABR level switch: ${t} -> ${e} (${Math.round(a)}ms >= ${o}ms / ${i}s)`)}}this.level=e,this.manualLevelIndex===-1&&(this.hls.nextAutoLevel=e)}removeLevel(e){var t;if(this._levels.length===1)return;let s=this._levels.filter((r,a)=>a!==e?!0:(this.steering&&this.steering.removeLevel(r),r===this.currentLevel&&(this.currentLevel=null,this.currentLevelIndex=-1,r.details&&r.details.fragments.forEach(o=>o.level=-1)),!1));ml(s),this._levels=s,this.currentLevelIndex>-1&&(t=this.currentLevel)!=null&&t.details&&(this.currentLevelIndex=this.currentLevel.details.fragments[0].level),this.manualLevelIndex>-1&&(this.manualLevelIndex=this.currentLevelIndex);let i=s.length-1;this._firstLevel=Math.min(this._firstLevel,i),this._startLevel&&(this._startLevel=Math.min(this._startLevel,i)),this.hls.trigger(p.LEVELS_UPDATED,{levels:s})}onLevelsUpdated(e,{levels:t}){this._levels=t}checkMaxAutoUpdated(){let{autoLevelCapping:e,maxAutoLevel:t,maxHdcpLevel:s}=this.hls;this._maxAutoLevel!==t&&(this._maxAutoLevel=t,this.hls.trigger(p.MAX_AUTO_LEVEL_UPDATED,{autoLevelCapping:e,levels:this.levels,maxAutoLevel:t,minAutoLevel:this.hls.minAutoLevel,maxHdcpLevel:s}))}};function cc(n,e){return as(n,"audio",e)}function hc(n,e){return as(n,"video",e)}function Eo(n,e){let{audioCodec:t,videoCodec:s}=n;t&&(n.audioCodec=t=Hs(t,e)||void 0),s&&(s=n.videoCodec=Ah(s));let{unknownCodecs:i}=n;return!(i?.length||0||t&&!cc(t,e)||s&&!hc(s,e))}function To(n){let e={};n.forEach(t=>{let s=t.groupId||"";t.id=e[s]=e[s]||0,e[s]++})}var In=class extends we{constructor(e,t){super("key-loader",t),this.config=void 0,this.keyLoaderInfo={},this.emeController=null,this.config=e}abort(e){for(let s in this.keyLoaderInfo){let i=this.keyLoaderInfo[s].loader;if(i){var t;if(e&&e!==((t=i.context)==null?void 0:t.frag.type))return;i.abort()}}}destroy(){for(let e in this.keyLoaderInfo){let t=this.keyLoaderInfo[e].loader;t&&t.destroy()}this.emeController=null,this.keyLoaderInfo={}}loadClear(e,t,s){return this.emeController?this.emeController.loadClear(e,t,s):null}load(e,t){return!e.decryptdata&&e.encrypted&&this.emeController&&this.config.emeEnabled?this.emeController.selectKeySystemFormat(e).then(s=>this.loadInternal(e,t,s)):this.loadInternal(e,t)}loadInternal(e,t,s){s&&e.setKeyFormat(s);let i=e.decryptdata;if(!i){let a=new Error(s?`Expected frag.decryptdata to be defined after setting format ${s}`:`Missing decryption data on fragment in onKeyLoading (emeEnabled with controller: ${this.emeController&&this.config.emeEnabled})`);return Promise.reject(gt(e,R.KEY_LOAD_ERROR,a))}let r=e;switch(i.method){case"SAMPLE-AES":case"SAMPLE-AES-CENC":case"SAMPLE-AES-CTR":return i.keyFormat==="identity"?this.loadKeyHTTP(r):t?t.then(()=>this.loadKeyEME(r)):this.loadKeyEME(r);case"AES-128":case"AES-256":case"AES-256-CTR":return this.loadKeyHTTP(r);default:return Promise.reject(gt(e,R.KEY_LOAD_ERROR,new Error(`Key supplied with unsupported METHOD: "${i.method}"`)))}}loadKeyEME(e){if(this.emeController&&this.config.emeEnabled){var t;if(!e.decryptdata.keyId&&(t=e.initSegment)!=null&&t.data){let s=rh(e.initSegment.data);if(s.length){let i=s[0],r=e.decryptdata.uri;if(i.some(a=>a!==0))this.log(`Using keyId found in init segment ${Ie(i)} keyUri: ${r}`),Ct.setKeyIdForUri(r,i);else{let a=Ct.addKeyIdForUri(r);this.log(`Patching empty keyId with ${Ie(a)} keyUri: ${r}`),i=a}e.decryptdata.keyId=i}}return this.emeController.loadKey(e).then(()=>({frag:e,keyInfo:{decryptdata:e.decryptdata}}))}return Promise.reject(gt(e,R.KEY_LOAD_ERROR,new Error(`emeEnabled with controller: ${this.emeController&&this.config.emeEnabled})`)))}loadKeyHTTP(e){let t=e.decryptdata,s=t.uri;if(!s)return Promise.reject(gt(e,R.KEY_LOAD_ERROR,new Error(`Invalid key URI: "${s}"`)));let i=this.keyLoaderInfo[s];if(i){if(i.decryptdata.key)return t.key=i.decryptdata.key,i.keyLoadPromise=null,Promise.resolve({frag:e,keyInfo:i});if(i.keyLoadPromise)return i.keyLoadPromise.then(c=>(t.key=i.decryptdata.key,Y(Y({},c),{},{frag:e})))}this.log(`Loading${t.keyId?" keyId: "+Ie(t.keyId):""} URI: ${t.uri} from ${e.type} ${e.level}`);let r=this.config,a=r.loader,o=new a(r);e.keyLoader=o;let l=this.keyLoaderInfo[s]={decryptdata:t,keyLoadPromise:null,loader:o};return l.keyLoadPromise=new Promise((c,h)=>{let u={type:se.KEY,keyInfo:l,frag:e,responseType:"arraybuffer",url:s},d=r.keyLoadPolicy.default,f={loadPolicy:d,timeout:d.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},g={onSuccess:(m,y,E,S)=>{let{frag:T,keyInfo:v,url:x}=E;if(!T.decryptdata||v!==this.keyLoaderInfo[x])return this.resetLoader(E),h(gt(T,R.KEY_LOAD_ERROR,new Error("after key load, decryptdata unset or changed"),S));v.decryptdata.key=T.decryptdata.key=new Uint8Array(m.data),T.keyLoader=v.loader=v.keyLoadPromise=null,c({frag:T,keyInfo:v})},onError:(m,y,E,S)=>{this.resetLoader(y),h(gt(e,R.KEY_LOAD_ERROR,new Error(`HTTP Error ${m.code} loading key ${m.text}`),E,Y({url:s,data:void 0},m)))},onTimeout:(m,y,E)=>{this.resetLoader(y),h(gt(e,R.KEY_LOAD_TIMEOUT,new Error("key loading timed out"),E))},onAbort:(m,y,E)=>{this.resetLoader(y),h(gt(e,R.INTERNAL_ABORTED,new Error("key loading aborted"),E))}};o.load(u,f,g)})}resetLoader(e){let{frag:t,keyInfo:s,url:i}=e,r=s.loader;t.keyLoader===r&&(t.keyLoader=s.loader=s.keyLoadPromise=null),delete this.keyLoaderInfo[i],r&&r.destroy()}};function gt(n,e=R.KEY_LOAD_ERROR,t,s,i){return new Ye({type:W.NETWORK_ERROR,details:e,fatal:!1,frag:n,response:i,error:t,networkDetails:s||null})}function So(n){let{type:e}=n;switch(e){case se.AUDIO_TRACK:return K.AUDIO;case se.SUBTITLE_TRACK:return K.SUBTITLE;default:return K.MAIN}}function Zi(n,e){let t=n.url;return(t===void 0||t.indexOf("data:")===0)&&(t=e.url),t}var An=class{constructor(e){this.hls=void 0,this.loaders=Object.create(null),this.variableList=null,this.onManifestLoaded=this.checkAutostartLoad,this.hls=e,this.registerListeners()}startLoad(e){}stopLoad(){this.destroyInternalLoaders()}registerListeners(){let{hls:e}=this;e.on(p.MANIFEST_LOADING,this.onManifestLoading,this),e.on(p.LEVEL_LOADING,this.onLevelLoading,this),e.on(p.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.on(p.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),e.on(p.LEVELS_UPDATED,this.onLevelsUpdated,this)}unregisterListeners(){let{hls:e}=this;e.off(p.MANIFEST_LOADING,this.onManifestLoading,this),e.off(p.LEVEL_LOADING,this.onLevelLoading,this),e.off(p.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.off(p.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),e.off(p.LEVELS_UPDATED,this.onLevelsUpdated,this)}createInternalLoader(e){let t=this.hls.config,s=t.pLoader,i=t.loader,r=s||i,a=new r(t);return this.loaders[e.type]=a,a}getInternalLoader(e){return this.loaders[e.type]}resetInternalLoader(e){this.loaders[e]&&delete this.loaders[e]}destroyInternalLoaders(){for(let e in this.loaders){let t=this.loaders[e];t&&t.destroy(),this.resetInternalLoader(e)}}destroy(){this.variableList=null,this.unregisterListeners(),this.destroyInternalLoaders()}onManifestLoading(e,t){let{url:s}=t;this.variableList=null,this.load({id:null,level:0,responseType:"text",type:se.MANIFEST,url:s,deliveryDirectives:null,levelOrTrack:null})}onLevelLoading(e,t){let{id:s,level:i,pathwayId:r,url:a,deliveryDirectives:o,levelInfo:l}=t;this.load({id:s,level:i,pathwayId:r,responseType:"text",type:se.LEVEL,url:a,deliveryDirectives:o,levelOrTrack:l})}onAudioTrackLoading(e,t){let{id:s,groupId:i,url:r,deliveryDirectives:a,track:o}=t;this.load({id:s,groupId:i,level:null,responseType:"text",type:se.AUDIO_TRACK,url:r,deliveryDirectives:a,levelOrTrack:o})}onSubtitleTrackLoading(e,t){let{id:s,groupId:i,url:r,deliveryDirectives:a,track:o}=t;this.load({id:s,groupId:i,level:null,responseType:"text",type:se.SUBTITLE_TRACK,url:r,deliveryDirectives:a,levelOrTrack:o})}onLevelsUpdated(e,t){let s=this.loaders[se.LEVEL];if(s){let i=s.context;i&&!t.levels.some(r=>r===i.levelOrTrack)&&(s.abort(),delete this.loaders[se.LEVEL])}}load(e){var t;let s=this.hls.config,i=this.getInternalLoader(e);if(i){let c=this.hls.logger,h=i.context;if(h?.levelOrTrack===e.levelOrTrack&&(h.url===e.url||h.deliveryDirectives&&!e.deliveryDirectives)){h.url===e.url?c.log(`[playlist-loader]: ignore ${e.url} ongoing request`):c.log(`[playlist-loader]: ignore ${e.url} in favor of ${h.url}`);return}c.log(`[playlist-loader]: aborting previous loader for type: ${e.type}`),i.abort()}let r;if(e.type===se.MANIFEST?r=s.manifestLoadPolicy.default:r=he({},s.playlistLoadPolicy.default,{timeoutRetry:null,errorRetry:null}),i=this.createInternalLoader(e),$((t=e.deliveryDirectives)==null?void 0:t.part)){let c;if(e.type===se.LEVEL&&e.level!==null?c=this.hls.levels[e.level].details:e.type===se.AUDIO_TRACK&&e.id!==null?c=this.hls.audioTracks[e.id].details:e.type===se.SUBTITLE_TRACK&&e.id!==null&&(c=this.hls.subtitleTracks[e.id].details),c){let h=c.partTarget,u=c.targetduration;if(h&&u){let d=Math.max(h*3,u*.8)*1e3;r=he({},r,{maxTimeToFirstByteMs:Math.min(d,r.maxTimeToFirstByteMs),maxLoadTimeMs:Math.min(d,r.maxTimeToFirstByteMs)})}}}let a=r.errorRetry||r.timeoutRetry||{},o={loadPolicy:r,timeout:r.maxLoadTimeMs,maxRetry:a.maxNumRetry||0,retryDelay:a.retryDelayMs||0,maxRetryDelay:a.maxRetryDelayMs||0},l={onSuccess:(c,h,u,d)=>{let f=this.getInternalLoader(u);this.resetInternalLoader(u.type);let g=c.data;h.parsing.start=performance.now(),Et.isMediaPlaylist(g)||u.type!==se.MANIFEST?this.handleTrackOrLevelPlaylist(c,h,u,d||null,f):this.handleMasterPlaylist(c,h,u,d)},onError:(c,h,u,d)=>{this.handleNetworkError(h,u,!1,c,d)},onTimeout:(c,h,u)=>{this.handleNetworkError(h,u,!0,void 0,c)}};i.load(e,o,l)}checkAutostartLoad(){if(!this.hls)return;let{config:{autoStartLoad:e,startPosition:t},forceStartLoad:s}=this.hls;(e||s)&&(this.hls.logger.log(`${e?"auto":"force"} startLoad with configured startPosition ${t}`),this.hls.startLoad(t))}handleMasterPlaylist(e,t,s,i){let r=this.hls,a=e.data,o=Zi(e,s),l=Et.parseMasterPlaylist(a,o);if(l.playlistParsingError){t.parsing.end=performance.now(),this.handleManifestParsingError(e,s,l.playlistParsingError,i,t);return}let{contentSteering:c,levels:h,iframeVariants:u,sessionData:d,sessionKeys:f,startTimeOffset:g,variableList:m}=l;this.variableList=m,h.forEach(T=>{let{unknownCodecs:v}=T;if(v){let{preferManagedMediaSource:x}=this.hls.config,{audioCodec:I,videoCodec:A}=T;for(let b=v.length;b--;){let _=v[b];as(_,"audio",x)?(T.audioCodec=I=I?`${I},${_}`:_,Ut.audio[I.substring(0,4)]=2,v.splice(b,1)):as(_,"video",x)&&(T.videoCodec=A=A?`${A},${_}`:_,Ut.video[A.substring(0,4)]=2,v.splice(b,1))}}});let{AUDIO:y=[],SUBTITLES:E,"CLOSED-CAPTIONS":S}=Et.parseMasterPlaylistMedia(a,o,l);y.length&&!y.some(v=>!v.url)&&h[0].audioCodec&&!h[0].attrs.AUDIO&&(this.hls.logger.log("[playlist-loader]: audio codec signaled in quality level, but no embedded audio track signaled, create one"),y.unshift({type:"main",name:"main",groupId:"main",default:!1,autoselect:!1,forced:!1,id:-1,attrs:new me({}),bitrate:0,url:""})),r.trigger(p.MANIFEST_LOADED,{levels:h,audioTracks:y,subtitles:E,iframeVariants:u,captions:S,contentSteering:c,url:o,stats:t,networkDetails:i,sessionData:d,sessionKeys:f,startTimeOffset:g,variableList:m})}handleTrackOrLevelPlaylist(e,t,s,i,r){let a=this.hls,{id:o,level:l,type:c}=s,h=Zi(e,s),u=$(l)?l:$(o)?o:0,d=So(s),f=Et.parseLevelPlaylist(e.data,h,u,d,0,this.variableList);if(c===se.MANIFEST){let g={attrs:new me({}),bitrate:0,details:f,name:"",url:h};f.requestScheduled=t.loading.start+fl(f,0),a.trigger(p.MANIFEST_LOADED,{levels:[g],audioTracks:[],iframeVariants:[],url:h,stats:t,networkDetails:i,sessionData:null,sessionKeys:null,contentSteering:null,startTimeOffset:null,variableList:null})}t.parsing.end=performance.now(),s.levelDetails=f,this.handlePlaylistLoaded(f,e,t,s,i,r)}handleManifestParsingError(e,t,s,i,r){this.hls.trigger(p.ERROR,{type:W.NETWORK_ERROR,details:R.MANIFEST_PARSING_ERROR,fatal:t.type===se.MANIFEST,url:e.url,err:s,error:s,reason:s.message,response:e,context:t,networkDetails:i,stats:r})}handleNetworkError(e,t,s=!1,i,r){let a=`A network ${s?"timeout":"error"+(i?" (status "+i.code+")":"")} occurred while loading ${e.type}`;e.type===se.LEVEL?a+=`: ${e.level} id: ${e.id}`:(e.type===se.AUDIO_TRACK||e.type===se.SUBTITLE_TRACK)&&(a+=` id: ${e.id} group-id: "${e.groupId}"`);let o=new Error(a);this.hls.logger.warn(`[playlist-loader]: ${a}`);let l=R.UNKNOWN,c=!1,h=this.getInternalLoader(e);switch(e.type){case se.MANIFEST:l=s?R.MANIFEST_LOAD_TIMEOUT:R.MANIFEST_LOAD_ERROR,c=!0;break;case se.LEVEL:l=s?R.LEVEL_LOAD_TIMEOUT:R.LEVEL_LOAD_ERROR,c=!1;break;case se.AUDIO_TRACK:l=s?R.AUDIO_TRACK_LOAD_TIMEOUT:R.AUDIO_TRACK_LOAD_ERROR,c=!1;break;case se.SUBTITLE_TRACK:l=s?R.SUBTITLE_TRACK_LOAD_TIMEOUT:R.SUBTITLE_LOAD_ERROR,c=!1;break}h&&this.resetInternalLoader(e.type);let u={type:W.NETWORK_ERROR,details:l,fatal:c,url:e.url,loader:h,context:e,error:o,networkDetails:t,stats:r};if(i){let d=e.url;t&&"url"in t&&(d=t.url),u.response=Y({url:d,data:void 0},i)}this.hls.trigger(p.ERROR,u)}handlePlaylistLoaded(e,t,s,i,r,a){let o=this.hls,{type:l,level:c,levelOrTrack:h,id:u,groupId:d,deliveryDirectives:f}=i,g=Zi(t,i),m=So(i),y=typeof i.level=="number"&&m===K.MAIN?c:void 0;h&&"iframes"in h&&h.iframes&&!e.iframesOnly&&(e.playlistParsingError=new Error("EXT-X-I-FRAME-STREAM-INF media playlist MUST contain an EXT-X-I-FRAMES-ONLY tag"),e.iframesOnly=!0);let E=e.playlistParsingError;if(E){if(this.hls.logger.warn(`${E} ${e.url}`),!o.config.ignorePlaylistParsingErrors){o.trigger(p.ERROR,{type:W.NETWORK_ERROR,details:R.LEVEL_PARSING_ERROR,fatal:!1,url:g,error:E,reason:E.message,response:t,context:i,level:y,parent:m,networkDetails:r,stats:s});return}e.playlistParsingError=null}if(!e.fragments.length){let S=e.playlistParsingError=new Error("No Segments found in Playlist");o.trigger(p.ERROR,{type:W.NETWORK_ERROR,details:R.LEVEL_EMPTY_ERROR,fatal:!1,url:g,error:S,reason:S.message,response:t,context:i,level:y,parent:m,networkDetails:r,stats:s});return}switch(e.live&&a&&(a.getCacheAge&&(e.ageHeader=a.getCacheAge()||0),(!a.getCacheAge||isNaN(e.ageHeader))&&(e.ageHeader=0)),l){case se.MANIFEST:case se.LEVEL:if(y){if(!h)y=0;else if(h!==o.levels[y]){let S=o.levels.indexOf(h);S>-1&&(y=S)}}o.trigger(p.LEVEL_LOADED,{details:e,levelInfo:h||o.levels[0],level:y||0,id:u||0,stats:s,networkDetails:r,deliveryDirectives:f,withoutMultiVariant:l===se.MANIFEST,context:i});break;case se.AUDIO_TRACK:o.trigger(p.AUDIO_TRACK_LOADED,{details:e,track:h,id:u||0,groupId:d||"",stats:s,networkDetails:r,deliveryDirectives:f,context:i});break;case se.SUBTITLE_TRACK:o.trigger(p.SUBTITLE_TRACK_LOADED,{details:e,track:h,id:u||0,groupId:d||"",stats:s,networkDetails:r,deliveryDirectives:f,context:i});break}}},ct=class n{static get version(){return ds}static isMSESupported(){return ac()}static isSupported(){return Ff()}static getMediaSource(){return vt()}static get Events(){return p}static get MetadataSchema(){return Oe}static get ErrorTypes(){return W}static get ErrorDetails(){return R}static get DefaultConfig(){return n.defaultConfig?n.defaultConfig:dg}static set DefaultConfig(e){n.defaultConfig=e}constructor(e={}){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 Mn,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;let t=this.logger=Cc(e.debug||!1,"Hls instance",e.loggerId||e.assetPlayerId),s=this.config=gg(n.DefaultConfig,e,t);this.userConfig=e,s.progressive&&mg(s,t);let{streamController:i,abrController:r,bufferController:a,capLevelController:o,errorController:l,fpsController:c,id3TrackController:h,iframeController:u,gapController:d}=s,f=new l(this),g=this.abrController=new r(this),m=new gr(this),y=s.interstitialsController,E=y?this.interstitialsController=new y(this,n):null,S=a?this.bufferController=new a(this,m):null,T=o?this.capLevelController=new o(this):null,v=c?new c(this):null,x=s.cmcdController,I=x?this.cmcdController=new x(this):null,A=new An(this),b=s.contentSteeringController,_=b?new b(this):null,L=this.levelController=new xn(this,_),P=h?new h(this):void 0,D=new In(this.config,this.logger),M=this.streamController=new i(this,m,D),U=this.gapController=d?new d(this,m):void 0;T&&T.setStreamController(M);let B=[A,L,M];E&&B.splice(1,0,E),_&&B.splice(1,0,_),this.networkControllers=B;let k=[g];S&&k.push(S),U&&k.push(U),T&&k.push(T),v&&(v.setStreamController(M),k.push(v)),P&&k.push(P),k.push(m),this.audioTrackController=this.createController(s.audioTrackController,B);let w=s.audioStreamController;w&&B.push(this.audioStreamController=new w(this,m,D)),this.subtitleTrackController=this.createController(s.subtitleTrackController,B);let O=s.subtitleStreamController;O&&B.push(this.subtititleStreamController=new O(this,m,D)),this.createController(s.timelineController,k),D.emeController=this.emeController=this.createController(s.emeController,k),I&&k.push(I),this.latencyController=this.createController(s.latencyController,k),this.coreComponents=k,this.iframeController=u?new u(this,n):void 0,B.push(f);let F=f.onErrorOut;typeof F=="function"&&this.on(p.ERROR,F,f),this.on(p.MANIFEST_LOADED,A.onManifestLoaded,A)}createController(e,t){if(e){let s=new e(this);return t&&t.push(s),s}return null}on(e,t,s=this){this._emitter.on(e,t,s)}once(e,t,s=this){this._emitter.once(e,t,s)}removeAllListeners(e){this._emitter.removeAllListeners(e)}off(e,t,s=this,i){this._emitter.off(e,t,s,i)}listeners(e){return this._emitter.listeners(e)}emit(e,t,s){return this._emitter.emit(e,t,s)}trigger(e,t){if(this.config.debug)return this.emit(e,e,t);try{return this.emit(e,e,t)}catch(s){if(this.logger.error("An internal error happened while handling event "+e+'. Error message: "'+s.message+'". Here is a stacktrace:',s),!this.triggeringException){this.triggeringException=!0;let i=e===p.ERROR;this.trigger(p.ERROR,{type:W.OTHER_ERROR,details:R.INTERNAL_EXCEPTION,fatal:i,event:e,error:s}),this.triggeringException=!1}}return!1}listenerCount(e){return this._emitter.listenerCount(e)}destroy(){this.logger.log("destroy"),this.trigger(p.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;let e=this.config;e.xhrSetup=e.fetchSetup=void 0,this.userConfig=null}attachMedia(e){if(!e||"media"in e&&!e.media){let r=new Error(`attachMedia failed: invalid argument (${e})`);this.trigger(p.ERROR,{type:W.OTHER_ERROR,details:R.ATTACH_MEDIA_ERROR,fatal:!0,error:r});return}this.logger.log("attachMedia"),this._media&&(this.logger.warn("media must be detached before attaching"),this.detachMedia());let t="media"in e,s=t?e.media:e,i=t?e:{media:s};this._media=s,this.trigger(p.MEDIA_ATTACHING,i)}detachMedia(){this.logger.log("detachMedia");let e={};this.trigger(p.MEDIA_DETACHING,e),this._media=null,this.trigger(p.MEDIA_DETACHED,e)}transferMedia(){var e;this._media=null;let t=((e=this.bufferController)==null?void 0:e.transferMedia())||null,s={transferMedia:t};return this.trigger(p.MEDIA_DETACHING,s),this.trigger(p.MEDIA_DETACHED,s),t}loadSource(e){var t;this.stopLoad();let s=this.media,i=this._url,r=this._url=Ln.buildAbsoluteURL(self.location.href,e,{alwaysNormalize:!0});this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.logger.log(`loadSource:${r}`),s&&i&&(i!==r||(t=this.bufferController)!=null&&t.hasSourceTypes())&&(this.detachMedia(),this.attachMedia(s)),this.trigger(p.MANIFEST_LOADING,{url:e})}get url(){return this._url}get hasEnoughToStart(){return this.streamController.hasEnoughToStart}get startPosition(){return this.streamController.startPositionValue}startLoad(e=-1,t){this.logger.log(`startLoad(${e+(t?", <skip seek to start>":"")})`),this.started=!0,this.resumeBuffering();for(let s=0;s<this.networkControllers.length&&(this.networkControllers[s].startLoad(e,t),!(!this.started||!this.networkControllers));s++);}stopLoad(){this.logger.log("stopLoad"),this.started=!1;for(let e=0;e<this.networkControllers.length&&(this.networkControllers[e].stopLoad(),!(this.started||!this.networkControllers));e++);}get loadingEnabled(){return this.started&&this.streamController.state!==C.STOPPED}get bufferingEnabled(){return this.streamController.bufferingEnabled}resumeBuffering(){this.bufferingEnabled||(this.logger.log("resume buffering"),this.networkControllers.forEach(e=>{e.resumeBuffering&&e.resumeBuffering()}))}pauseBuffering(){this.bufferingEnabled&&(this.logger.log("pause buffering"),this.networkControllers.forEach(e=>{e.pauseBuffering&&e.pauseBuffering()}))}get inFlightFragments(){let e={[K.MAIN]:this.streamController.inFlightFrag};return this.audioStreamController&&(e[K.AUDIO]=this.audioStreamController.inFlightFrag),this.subtititleStreamController&&(e[K.SUBTITLE]=this.subtititleStreamController.inFlightFrag),e}swapAudioCodec(){this.logger.log("swapAudioCodec"),this.streamController.swapAudioCodec()}recoverMediaError(){this.logger.log("recoverMediaError");let e=this._media,t=this.started,s=e?.currentTime;this.detachMedia(),e&&(this.attachMedia(e),t&&(s?this.startLoad(s):this.config.autoStartLoad||this.startLoad()))}removeLevel(e){this.levelController.removeLevel(e)}get sessionId(){let e=this._sessionId;return e||(e=this._sessionId=bo()),e}get levels(){let e=this.levelController.levels;return e||[]}get latestLevelDetails(){return this.streamController.getLevelDetails()||null}get loadLevelObj(){return this.levelController.loadLevelObj}get currentLevel(){return this.streamController.currentLevel}set currentLevel(e){this.logger.log(`set currentLevel:${e}`),this.levelController.manualLevel=e,this.streamController.immediateLevelSwitch()}get nextLevel(){return this.streamController.nextLevel}set nextLevel(e){this.logger.log(`set nextLevel:${e}`),this.levelController.manualLevel=e,this.streamController.nextLevelSwitch()}get loadLevel(){return this.levelController.level}set loadLevel(e){this.logger.log(`set loadLevel:${e}`),this.levelController.manualLevel=e}get nextLoadLevel(){return this.levelController.nextLoadLevel}set nextLoadLevel(e){this.levelController.nextLoadLevel=e}get firstLevel(){return Math.max(this.levelController.firstLevel,this.minAutoLevel)}set firstLevel(e){this.logger.log(`set firstLevel:${e}`),this.levelController.firstLevel=e}get startLevel(){let e=this.levelController.startLevel;return e===-1&&this.abrController.forcedAutoLevel>-1?this.abrController.forcedAutoLevel:e}set startLevel(e){this.logger.log(`set startLevel:${e}`),e!==-1&&(e=Math.max(e,this.minAutoLevel)),this.levelController.startLevel=e}get capLevelToPlayerSize(){return this.config.capLevelToPlayerSize}set capLevelToPlayerSize(e){let t=this.capLevelController,s=!!e;t&&s!==this.config.capLevelToPlayerSize&&(s?t.startCapping():(t.stopCapping(),this.autoLevelCapping=-1,this.streamController.nextLevelSwitch()),this.config.capLevelToPlayerSize=s)}get autoLevelCapping(){return this._autoLevelCapping}get bandwidthEstimate(){let{bwEstimator:e}=this.abrController;return e?e.getEstimate():NaN}set bandwidthEstimate(e){this.abrController.resetEstimator(e)}get abrEwmaDefaultEstimate(){let{bwEstimator:e}=this.abrController;return e?e.defaultEstimate:NaN}get ttfbEstimate(){let{bwEstimator:e}=this.abrController;return e?e.getEstimateTTFB():NaN}set autoLevelCapping(e){this._autoLevelCapping!==e&&(this.logger.log(`set autoLevelCapping:${e}`),this._autoLevelCapping=e,this.levelController.checkMaxAutoUpdated())}get maxHdcpLevel(){return this._maxHdcpLevel}set maxHdcpLevel(e){kh(e)&&this._maxHdcpLevel!==e&&(this._maxHdcpLevel=e,this.levelController.checkMaxAutoUpdated())}get autoLevelEnabled(){return this.levelController.manualLevel===-1}get manualLevel(){return this.levelController.manualLevel}get minAutoLevel(){let{levels:e,config:{minAutoBitrate:t}}=this;if(!e)return 0;let s=e.length;for(let i=0;i<s;i++)if(e[i].maxBitrate>=t)return i;return 0}get maxAutoLevel(){let{levels:e,autoLevelCapping:t,maxHdcpLevel:s}=this,i;if(t===-1&&e!=null&&e.length?i=e.length-1:i=t,s)for(let r=i;r--;){let a=e[r].attrs["HDCP-LEVEL"];if(a&&a<=s)return r}return i}get firstAutoLevel(){return this.abrController.firstAutoLevel}get nextAutoLevel(){return this.abrController.nextAutoLevel}set nextAutoLevel(e){this.abrController.nextAutoLevel=e}get playingDate(){return this.streamController.currentProgramDateTime}get mainForwardBufferInfo(){return this.streamController.getMainFwdBufferInfo()}get audioForwardBufferInfo(){var e;return((e=this.audioStreamController)==null?void 0:e.getFwdBufferInfo())||null}get maxBufferLength(){return this.streamController.maxBufferLength}setAudioOption(e){var t;return((t=this.audioTrackController)==null?void 0:t.setAudioOption(e))||null}setSubtitleOption(e){var t;return((t=this.subtitleTrackController)==null?void 0:t.setSubtitleOption(e))||null}get allAudioTracks(){let e=this.audioTrackController;return e?e.allAudioTracks:[]}get audioTracks(){let e=this.audioTrackController;return e?e.audioTracks:[]}get audioTrack(){let e=this.audioTrackController;return e?e.audioTrack:-1}set audioTrack(e){let t=this.audioTrackController;t&&(t.audioTrack=e)}get nextAudioTrack(){var e,t;return(e=(t=this.audioStreamController)==null?void 0:t.nextAudioTrack)!=null?e:-1}set nextAudioTrack(e){let{audioTrackController:t}=this;t&&(t.nextAudioTrack=e)}get allSubtitleTracks(){let e=this.subtitleTrackController;return e?e.allSubtitleTracks:[]}get subtitleTracks(){let e=this.subtitleTrackController;return e?e.subtitleTracks:[]}get subtitleTrack(){let e=this.subtitleTrackController;return e?e.subtitleTrack:-1}get media(){return this._media}set subtitleTrack(e){let t=this.subtitleTrackController;t&&(t.subtitleTrack=e)}get subtitleDisplay(){let e=this.subtitleTrackController;return e?e.subtitleDisplay:!1}set subtitleDisplay(e){let t=this.subtitleTrackController;t&&(t.subtitleDisplay=e)}get lowLatencyMode(){return this.config.lowLatencyMode}set lowLatencyMode(e){this.config.lowLatencyMode=e}get liveSyncPosition(){var e,t;return(e=(t=this.latencyController)==null?void 0:t.liveSyncPosition)!=null?e:null}get latency(){var e;return((e=this.latencyController)==null?void 0:e.latency)||0}get maxLatency(){var e;return((e=this.latencyController)==null?void 0:e.maxLatency)||0}get targetLatency(){var e;return((e=this.latencyController)==null?void 0:e.targetLatency)||null}set targetLatency(e){this.latencyController&&(this.latencyController.targetLatency=e)}get drift(){var e;return((e=this.latencyController)==null?void 0:e.drift)||null}get forceStartLoad(){return this.streamController.forceStartLoad}get pathways(){return this.levelController.pathways}get pathwayPriority(){return this.levelController.pathwayPriority}set pathwayPriority(e){this.levelController.pathwayPriority=e}get bufferedToEnd(){var e;return!!((e=this.bufferController)!=null&&e.bufferedToEnd)}get interstitialsManager(){return this.interstitialsController?this.interstitialsController.interstitialsManager:null}get iframeVariants(){let e=this.levelController.iframeVariants;return e||[]}createIFramePlayer(e){return this._url&&this.iframeController?this.iframeController.createIFramePlayer(e):null}createImageIFramePlayer(e){return this._url&&this.iframeController?this.iframeController.createImageIFramePlayer(e):null}getMediaDecodingInfo(e,t=this.allAudioTracks){let s=Xo(t);return qo(e,s,navigator.mediaCapabilities)}};ct.defaultConfig=void 0;function uc(n,e,t){let s=e,i=!1,r,a=null,o,l=(h=24e4)=>{!t||i||(r&&clearTimeout(r),r=setTimeout(()=>{c()},h))},c=()=>!t||i?Promise.resolve(!1):a||(a=(async()=>{try{let h=await t();if(i||!h)return!1;let u=new URL(s,document.baseURI);u.searchParams.set("token",h),s=u.toString();let d=n.currentTime,f=!n.paused;return o=()=>{if(o=void 0,!i){if(Number.isFinite(d)&&d>0)try{n.currentTime=d}catch{}f&&n.play().catch(()=>{})}},n.addEventListener("loadedmetadata",o,{once:!0}),n.src=s,n.load(),l(),!0}catch{return l(3e4),!1}finally{a=null}})(),a);return l(),{refreshNow:c,stop:()=>{i=!0,r&&clearTimeout(r),o&&n.removeEventListener("loadedmetadata",o)}}}function pg(n,e){let t=typeof n=="string"?document.querySelector(n):n;if(!t)throw new Error(`Target container not found: ${String(n)}`);let s=e.src??(e.assetId?`${(e.baseUrl||"https://api.vexor.et").replace(/\/+$/,"")}/v1/playback/${encodeURIComponent(e.assetId)}/master.m3u8${e.token?`?token=${encodeURIComponent(e.token)}`:""}`:"");if(!s)throw new Error("Provide either src or assetId to create the Vexor player.");let i=t.classList.contains("vexor-player"),r=t.classList.contains("is-protected");t.classList.add("vexor-player");let a=document.createElement("video");a.className="vexor-video",a.controls=e.controls??!0,a.playsInline=!0,a.preload=e.preload??"metadata",e.poster&&(a.poster=e.poster),e.autoPlay&&(a.autoplay=!0),e.muted&&(a.muted=!0),e.loop&&(a.loop=!0),t.appendChild(a);let o=null,l;if(e.watermark){let D=typeof e.watermark=="string"?{text:e.watermark,position:"dynamic",intervalSeconds:15,opacity:.35}:{position:"dynamic",intervalSeconds:15,opacity:.35,...e.watermark};o=document.createElement("div"),o.className="vexor-watermark",o.textContent=D.text,o.style.opacity=String(Math.max(0,Math.min(1,D.opacity??.35))),o.style.fontSize=typeof D.fontSize=="number"?`${D.fontSize}px`:D.fontSize??"12px",o.style.color=D.color??"#ffffff";let M=()=>{switch(o.style.removeProperty("top"),o.style.removeProperty("right"),o.style.removeProperty("bottom"),o.style.removeProperty("left"),o.style.removeProperty("transform"),D.position){case"top-left":o.style.cssText+=";top:16px;left:16px";break;case"top-right":o.style.cssText+=";top:16px;right:16px";break;case"bottom-left":o.style.cssText+=";bottom:48px;left:16px";break;case"bottom-right":o.style.cssText+=";bottom:48px;right:16px";break;case"center":o.style.cssText+=";top:50%;left:50%;transform:translate(-50%,-50%)";break;default:o.style.top=`${10+Math.floor(Math.random()*70)}%`,o.style.left=`${10+Math.floor(Math.random()*70)}%`}};M(),D.position==="dynamic"&&(l=setInterval(M,Math.max(2,D.intervalSeconds||15)*1e3)),t.appendChild(o)}let c=D=>D.preventDefault(),h=D=>D.preventDefault();e.protect&&(t.classList.add("is-protected"),t.addEventListener("contextmenu",c),a.addEventListener("contextmenu",c),a.addEventListener("dragstart",h));let u=s,d=null,f=null,g,m=!1,y=null,E=null,S=!1,T=new URL(u,document.baseURI).search,v=D=>{e.fallbackSrc?(d&&d.destroy(),d=null,a.src=e.fallbackSrc,a.load()):D&&e.onError?.(D)},x=()=>{S||(S=!0,e.onReady?.())},I=()=>{x();let D=E;E=null,D&&Number.isFinite(D.time)&&(a.currentTime=D.time),(D?.shouldPlay||e.autoPlay)&&!m&&a.play().catch(()=>{})};a.addEventListener("loadedmetadata",I),a.addEventListener("loadeddata",I);let A=()=>e.onPlay?.(),b=()=>e.onPause?.(),_=()=>e.onEnded?.();a.addEventListener("play",A),a.addEventListener("pause",b),a.addEventListener("ended",_);let L=()=>e.onTimeUpdate?.(a.currentTime,a.duration);a.addEventListener("timeupdate",L);let P=u.includes(".m3u8")||u.includes("/playback/");if(P&&ct.isSupported()){class D extends ct.DefaultConfig.loader{load(B,k,w){if(T&&B?.url)try{let O=new URL(u,document.baseURI),F=new URL(B.url,O);F.origin===O.origin&&!F.searchParams.has("token")&&(new URLSearchParams(T).forEach((H,N)=>{F.searchParams.has(N)||F.searchParams.set(N,H)}),B.url=F.toString())}catch{}super.load(B,k,w)}}d=new ct({enableWorker:!0,loader:D,fLoader:D,pLoader:D});let M=d;M.on(ct.Events.MANIFEST_PARSED,()=>{if(d!==M||m)return;let U=E;E=null,x(),U&&Number.isFinite(U.time)&&(a.currentTime=U.time),(U?.shouldPlay||e.autoPlay)&&!m&&a.play().catch(()=>{})}),M.on(ct.Events.ERROR,async(U,B)=>{if(!(d!==M||m)){if((B.response?.code===401||B.response?.code===403)&&e.refreshToken)try{y??=e.refreshToken();let k=await y;if(y=null,k&&d===M&&!m){E={time:a.currentTime,shouldPlay:!a.paused};let w=new URL(u,document.baseURI);w.searchParams.set("token",k),u=w.toString(),T=w.search,M.loadSource(u),M.startLoad();return}}catch{y=null}d!==M||m||B.fatal&&v({code:B.details||"MEDIA_PLAYBACK_ERROR",message:`Failed to stream video: ${B.details||"network error"}`,fatal:!0})}}),M.loadSource(u),M.attachMedia(a)}else P&&a.canPlayType("application/vnd.apple.mpegurl")?(a.src=u,f=uc(a,u,e.refreshToken),g=()=>{f?.refreshNow().then(D=>{D||m||(a.removeEventListener("error",g),v({code:"NATIVE_HLS_ERROR",message:"Failed to play native HLS stream",fatal:!0}))})},a.addEventListener("error",g)):!P||e.fallbackSrc?a.src=P?e.fallbackSrc:u:v({code:"HLS_UNSUPPORTED",message:"This browser does not support HLS playback.",fatal:!0});return{play:()=>a.play(),pause:()=>a.pause(),seek:D=>{a.currentTime=Math.max(0,Math.min(D,a.duration||D))},destroy:()=>{m||(m=!0,f?.stop(),d&&d.destroy(),d=null,l&&clearInterval(l),t.removeEventListener("contextmenu",c),a.removeEventListener("contextmenu",c),a.removeEventListener("dragstart",h),a.removeEventListener("loadedmetadata",I),a.removeEventListener("loadeddata",I),a.removeEventListener("play",A),a.removeEventListener("pause",b),a.removeEventListener("ended",_),a.removeEventListener("timeupdate",L),g&&a.removeEventListener("error",g),a.pause(),a.removeAttribute("src"),a.load(),a.remove(),o?.remove(),i||t.classList.remove("vexor-player"),e.protect&&!r&&t.classList.remove("is-protected"))},getElement:()=>a}}return Ec(yg);})();
45
+ //# sourceMappingURL=vexor-player.global.js.map