@oddin-gg/havik-player 2.23.4 → 2.24.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/havik-player.global.js +15 -15
- package/dist/havik-player.global.js.map +1 -1
- package/dist/index.cjs +3 -3
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +10 -0
- package/dist/index.d.ts +10 -0
- package/dist/index.js +414 -341
- package/dist/index.js.map +1 -1
- package/docs/API.md +1 -0
- package/embed/index.html +1 -1
- package/examples/vanilla.html +1 -1
- package/package.json +1 -1
|
@@ -15,35 +15,35 @@ ${this.list(`video`)}
|
|
|
15
15
|
${this.list(`audio`)}
|
|
16
16
|
${this.list(`audiovideo`)}}`}list(e){var t,n;return(t=this.queues)!=null&&t[e]||(n=this.tracks)!=null&&n[e]?`${e}: (${this.listSbInfo(e)}) ${this.listOps(e)}`:``}listSbInfo(e){let t=this.tracks?.[e],n=t?.buffer;return n?`SourceBuffer${n.updating?` updating`:``}${t.ended?` ended`:``}${t.ending?` ending`:``}`:`none`}listOps(e){return this.queues?.[e].map(e=>e.label).join(`, `)||``}},ea={search:function(e,t){let n=0,r=e.length-1,i=null,a=null;for(;n<=r;){i=(n+r)/2|0,a=e[i];let o=t(a);if(o>0)n=i+1;else if(o<0)r=i-1;else return a}return null}};function ta(e,t,n){if(t===null||!Array.isArray(e)||!e.length||!P(t)||t<(e[0].programDateTime||0)||t>=(e[e.length-1].endProgramDateTime||0))return null;for(let r=0;r<e.length;++r){let i=e[r];if(aa(t,n,i))return i}return null}function na(e,t,n=0,r=0,i=.005){let a=null;if(e){a=t[1+e.sn-t[0].sn]||null;let r=e.endDTS-n;r>0&&r<15e-7&&(n+=15e-7),a&&e.level!==a.level&&a.end<=e.end&&(a=t[2+e.sn-t[0].sn]||null)}else n===0&&t[0].start===0&&(a=t[0]);if(a&&((!e||e.level===a.level)&&ia(n,r,a)===0||ra(a,e,Math.min(i,r))))return a;let o=ea.search(t,ia.bind(null,n,r));return o&&(o!==e||!a)?o:a}function ra(e,t,n){if(t?.start===0&&t.level<e.level&&(t.endPTS||0)>0){let r=t.tagList.reduce((e,t)=>(t[0]===`INF`&&(e+=parseFloat(t[1])),e),n);return e.start<=r}return!1}function ia(e=0,t=0,n){if(n.start<=e&&n.start+n.duration>e)return 0;let r=Math.min(t,n.duration+(n.deltaPTS?n.deltaPTS:0));return n.start+n.duration-r<=e?1:n.start-r>e&&n.start?-1:0}function aa(e,t,n){let r=Math.min(t,n.duration+(n.deltaPTS?n.deltaPTS:0))*1e3;return(n.endProgramDateTime||0)-r>e}function oa(e,t,n){if(e&&e.startCC<=t&&e.endCC>=t){let r=e.fragments,{fragmentHint:i}=e;i&&(r=r.concat(i));let a;return ea.search(r,e=>e.cc<t?1:e.cc>t?-1:(a=e,e.end<=n?1:e.start>n?-1:0)),a||null}return null}function sa(e,t){return t===e.endSN&&e.fragmentHint?e.fragmentHint:e.fragments[1+t-e.startSN]||null}var ca={DoNothing:0,SendEndCallback:1,SendAlternateToPenaltyBox:2,RemoveAlternatePermanently:3,InsertDiscontinuity:4,RetryRequest:5},la={None:0,MoveAllAlternatesMatchingHost:1,MoveAllAlternatesMatchingHDCP:2,MoveAllAlternatesMatchingKey:4,SwitchToSDR:8,ResetMediaSource:16},ua=class extends Xt{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(L.ERROR,this.onError,this),e.on(L.MANIFEST_LOADING,this.onManifestLoading,this),e.on(L.LEVEL_UPDATED,this.onLevelUpdated,this)}unregisterListeners(){let e=this.hls;e&&(e.off(L.ERROR,this.onError,this),e.off(L.ERROR,this.onErrorOut,this),e.off(L.MANIFEST_LOADING,this.onManifestLoading,this),e.off(L.LEVEL_UPDATED,this.onLevelUpdated,this))}destroy(){this.unregisterListeners(),this.hls=null}startLoad(e){}stopLoad(){this.playlistError=0}getVariantLevelIndex(e){return e?.type===z.MAIN?e.level:this.getVariantIndex()}getVariantIndex(){var e;let t=this.hls,n=t.currentLevel;return(e=t.loadLevelObj)!=null&&e.details||n===-1?t.loadLevel:n}variantHasKey(e,t){if(e){var n;if((n=e.details)!=null&&n.hasKey(t))return!0;let r=e.audioGroups;if(r)return this.hls.allAudioTracks.filter(e=>r.indexOf(e.groupId)>=0).some(e=>e.details?.hasKey(t))}return!1}onManifestLoading(){this.playlistError=0}onLevelUpdated(){this.playlistError=0}onError(e,t){var n;if(t.fatal)return;let r=this.hls,i=t.context;switch(t.details){case I.FRAG_LOAD_ERROR:case I.FRAG_LOAD_TIMEOUT:case I.KEY_LOAD_ERROR:case I.KEY_LOAD_TIMEOUT:t.errorAction=this.getFragRetryOrSwitchAction(t);return;case I.FRAG_PARSING_ERROR:if((n=t.frag)!=null&&n.gap){t.errorAction=pa();return}case I.FRAG_GAP:case I.FRAG_DECRYPT_ERROR:t.errorAction=this.getFragRetryOrSwitchAction(t),t.errorAction.action=ca.SendAlternateToPenaltyBox;return;case I.PLAYLIST_UNCHANGED_ERROR:case I.LEVEL_EMPTY_ERROR:case I.LEVEL_PARSING_ERROR:{var a;let e=t.parent===z.MAIN?t.level:r.loadLevel;t.details===I.LEVEL_EMPTY_ERROR&&(a=t.context)!=null&&(a=a.levelDetails)!=null&&a.live?t.errorAction=this.getPlaylistRetryOrSwitchAction(t,e):(t.levelRetry=!1,t.errorAction=this.getLevelSwitchAction(t,e))}return;case I.LEVEL_LOAD_ERROR:case I.LEVEL_LOAD_TIMEOUT:typeof i?.level==`number`&&(t.errorAction=this.getPlaylistRetryOrSwitchAction(t,i.level));return;case I.AUDIO_TRACK_LOAD_ERROR:case I.AUDIO_TRACK_LOAD_TIMEOUT:case I.SUBTITLE_LOAD_ERROR:case I.SUBTITLE_TRACK_LOAD_TIMEOUT:if(i){let e=r.loadLevelObj;if(e&&(i.type===R.AUDIO_TRACK&&e.hasAudioGroup(i.groupId)||i.type===R.SUBTITLE_TRACK&&e.hasSubtitleGroup(i.groupId))){t.errorAction=this.getPlaylistRetryOrSwitchAction(t,r.loadLevel),t.errorAction.action=ca.SendAlternateToPenaltyBox,t.errorAction.flags=la.MoveAllAlternatesMatchingHost;return}}return;case I.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:t.errorAction={action:ca.SendAlternateToPenaltyBox,flags:la.MoveAllAlternatesMatchingHDCP};return;case I.KEY_SYSTEM_SESSION_UPDATE_FAILED:case I.KEY_SYSTEM_STATUS_INTERNAL_ERROR:case I.KEY_SYSTEM_NO_SESSION:t.errorAction={action:ca.SendAlternateToPenaltyBox,flags:la.MoveAllAlternatesMatchingKey};return;case I.BUFFER_ADD_CODEC_ERROR:case I.REMUX_ALLOC_ERROR:case I.BUFFER_APPEND_ERROR:t.errorAction||=this.getLevelSwitchAction(t,t.level);return;case I.MEDIA_SOURCE_REQUIRES_RESET:t.errorAction||=this.getLevelSwitchAction(t,t.level),t.errorAction.flags|=la.ResetMediaSource|la.SwitchToSDR;return;case I.INTERNAL_EXCEPTION:case I.BUFFER_APPENDING_ERROR:case I.BUFFER_APPEND_NO_PROGRESS:case I.BUFFER_FULL_ERROR:case I.LEVEL_SWITCH_ERROR:case I.BUFFER_STALLED_ERROR:case I.BUFFER_SEEK_OVER_HOLE:case I.BUFFER_NUDGE_ON_STALL:t.errorAction=pa();return}t.type===F.KEY_SYSTEM_ERROR&&(t.levelRetry=!1,t.errorAction=pa())}getPlaylistRetryOrSwitchAction(e,t){let n=this.hls,r=Vt(n.config.playlistLoadPolicy,e),i=this.playlistError++;if(Wt(r,i,Rt(e),e.response))return{action:ca.RetryRequest,flags:la.None,retryConfig:r,retryCount:i};let a=this.getLevelSwitchAction(e,t);return r&&(a.retryConfig=r,a.retryCount=i),a}getFragRetryOrSwitchAction(e){let t=this.hls,n=this.getVariantLevelIndex(e.frag),r=t.levels[n],{fragLoadPolicy:i,keyLoadPolicy:a}=t.config,o=Vt(zt(e)?a:i,e),s=t.levels.reduce((e,t)=>e+t.fragmentError,0);if(r&&(e.details!==I.FRAG_GAP&&r.fragmentError++,!Bt(e)&&Wt(o,s,Rt(e),e.response)))return{action:ca.RetryRequest,flags:la.None,retryConfig:o,retryCount:s};let c=this.getLevelSwitchAction(e,n);return o&&(c.retryConfig=o,c.retryCount=s),c}getLevelSwitchAction(e,t){let n=this.hls;t??=n.loadLevel;let r=this.hls.levels[t];if(r){let t=e.details;r.loadError++,r.loadErrorTime=self.performance.now(),t===I.BUFFER_APPEND_ERROR&&r.fragmentError++;let o=-1,{levels:s,loadLevel:c,minAutoLevel:l,maxAutoLevel:u}=n;!n.autoLevelEnabled&&!n.config.preserveManualLevelOnError&&(n.loadLevel=-1);let d=e.frag?.type,f=(d===z.AUDIO&&t===I.FRAG_PARSING_ERROR||e.sourceBufferName===`audio`&&da(e))&&s.some(({audioCodec:e})=>r.audioCodec!==e),p=e.sourceBufferName===`video`&&da(e)&&s.some(({codecSet:e,audioCodec:t})=>r.codecSet!==e&&r.audioCodec===t),{type:m,groupId:h}=e.context??{};for(let g=s.length;g--;){let _=(g+c)%s.length;if(_!==c&&_>=l&&_<=u&&(s[_].loadError===0||qt(s[_],n.config.errorPenaltyExpireMs))){var i,a;let n=s[_];if(t===I.FRAG_GAP&&d===z.MAIN&&e.frag){let t=s[_].details;if(t){let n=na(e.frag,t.fragments,e.frag.start);if(n!=null&&n.gap)continue}}else if(m===R.AUDIO_TRACK&&n.hasAudioGroup(h)||m===R.SUBTITLE_TRACK&&n.hasSubtitleGroup(h))continue;else if(d===z.AUDIO&&(i=r.audioGroups)!=null&&i.some(e=>n.hasAudioGroup(e))||d===z.SUBTITLE&&(a=r.subtitleGroups)!=null&&a.some(e=>n.hasSubtitleGroup(e))||f&&r.audioCodec===n.audioCodec||p&&r.codecSet===n.codecSet||!f&&r.audioCodec!==n.audioCodec)continue;o=_;break}}if(o>-1&&n.loadLevel!==o)return e.levelRetry=!0,this.playlistError=0,{action:ca.SendAlternateToPenaltyBox,flags:la.None,nextAutoLevel:o}}return{action:ca.SendAlternateToPenaltyBox,flags:la.MoveAllAlternatesMatchingHost}}onErrorOut(e,t){switch(t.errorAction?.action){case ca.DoNothing:break;case ca.SendAlternateToPenaltyBox:this.sendAlternateToPenaltyBox(t),!t.errorAction.resolved&&t.details!==I.FRAG_GAP&&t.details!==I.PLAYLIST_UNCHANGED_ERROR&&!fa(t)&&(t.fatal=!0);break;case ca.RetryRequest:}if((t.errorAction?.flags||0)&la.ResetMediaSource&&this.hls.recoverMediaError(),t.fatal){this.hls.stopLoad();return}}sendAlternateToPenaltyBox(e){let t=this.hls,n=e.errorAction;if(!n)return;let r=n.nextAutoLevel;if(n.flags===la.None)this.switchLevel(e,r);else if(n.flags&la.SwitchToSDR){let e=this.hls.levels,t=e.length;for(let n=t;n--;)e[n].videoRange===`SDR`?r===void 0&&(r=n):(e[n].fragmentError++,e[n].loadError++)}else if(n.flags&la.MoveAllAlternatesMatchingHDCP){let r=this.getVariantLevelIndex(e.frag),i=t.levels[r]?.attrs[`HDCP-LEVEL`];n.hdcpLevel=i;let a=i===`NONE`;i&&!a?(t.maxHdcpLevel=Ti[Ti.indexOf(i)-1],n.resolved=!0,this.warn(`Restricting playback to HDCP-LEVEL of "${t.maxHdcpLevel}" or lower`)):(a&&this.warn(`HDCP policy resticted output with HDCP-LEVEL=NONE`),n.flags|=la.MoveAllAlternatesMatchingKey)}if(n.flags&la.MoveAllAlternatesMatchingKey){let t=e.decryptdata;if(t){let r=this.hls.levels,i=r.length;for(let n=i;n--;)this.variantHasKey(r[n],t)&&(this.log(`Banned key found in level ${n} (${r[n].bitrate}bps) or audio group "${r[n].audioGroups?.join(`,`)}" (${e.frag?.type} fragment) ${Hn(t.keyId||[])}`),r[n].fragmentError++,r[n].loadError++,this.log(`Removing level ${n} with key error (${e.error})`),this.hls.removeLevel(n));let a=e.frag;if(this.hls.levels.length<i)n.resolved=!0;else if(a&&a.type!==z.MAIN){let e=a.decryptdata;e&&!t.matches(e)&&(n.resolved=!0)}}}n.resolved||this.switchLevel(e,r)}switchLevel(e,t){if(t!==void 0&&e.errorAction&&(this.warn(`switching to level ${t} after ${e.details}`),this.hls.nextAutoLevel=t,e.errorAction.resolved=!0,this.hls.nextLoadLevel=this.hls.nextAutoLevel,e.details===I.BUFFER_ADD_CODEC_ERROR&&e.mimeType&&e.sourceBufferName!==`audiovideo`)){let t=fi(e.mimeType),n=this.hls.levels;for(let r=n.length;r--;)n[r][`${e.sourceBufferName}Codec`]===t&&(this.log(`Removing level ${r} for ${e.details} ("${t}" not supported)`),this.hls.removeLevel(r))}}};function da(e){let t=e.details;return t===I.BUFFER_ADD_CODEC_ERROR||t===I.MEDIA_SOURCE_REQUIRES_RESET||t===I.BUFFER_APPEND_ERROR&&!fa(e)}function fa(e){return e.details===I.BUFFER_APPEND_ERROR&&(e.error.name===`QuotaExceededError`||e.error.name===`InvalidStateError`)}function pa(e){let t={action:ca.DoNothing,flags:la.None};return e&&(t.resolved=!0),t}var ma=10,ha=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,n=this.lastPartIndex-e.lastPartIndex;this.updated=this.endSN!==e.endSN||!!n||!!t||!this.live,this.advanced=this.endSN>e.endSN||t>0||t===0&&n>0,this.misses=this.updated||this.advanced?0:e.misses+1}hasKey(e){return this.encryptedFragments.some(t=>{let n=t.decryptdata;return n||=(t.setKeyFormat(e.keyFormat),t.decryptdata),!!n&&e.matches(n)})}get hasProgramDateTime(){return this.fragments.length?P(this.fragments[this.fragments.length-1].programDateTime):!1}get levelTargetDuration(){return this.averagetargetduration||this.targetduration||ma}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 n=e.length;n--;)if(e[n].index>t)return e[n].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}},ga={length:0,start:()=>0,end:()=>0},J=class e{static isBuffered(t,n){if(t){let r=e.getBuffered(t);for(let e=r.length;e--;)if(n>=r.start(e)&&n<=r.end(e))return!0}return!1}static bufferedRanges(t){if(t){let n=e.getBuffered(t);return e.timeRangesToArray(n)}return[]}static timeRangesToArray(e){let t=[];for(let n=0;n<e.length;n++)t.push({start:e.start(n),end:e.end(n)});return t}static bufferInfo(t,n,r){if(t){let i=e.bufferedRanges(t);if(i.length)return e.bufferedInfo(i,n,r)}return{len:0,start:n,end:n,bufferedIndex:-1}}static bufferedInfo(e,t,n){t=Math.max(0,t),e.length>1&&e.sort((e,t)=>e.start-t.start||t.end-e.end);let r=-1,i=[];if(n)for(let a=0;a<e.length;a++){t>=e[a].start&&t<=e[a].end&&(r=a);let o=i.length;if(o){let t=i[o-1].end;e[a].start-t<n?e[a].end>t&&(i[o-1].end=e[a].end):i.push(e[a])}else i.push(e[a])}else i=e;let a=0,o,s=t,c=t;for(let e=0;e<i.length;e++){let l=i[e].start,u=i[e].end;if(r===-1&&t>=l&&t<=u&&(r=e),t+n>=l&&t<u)s=l,c=u,a=c-t;else if(t+n<l){o=l;break}}return{len:a,start:s||0,end:c||0,nextStart:o,buffered:e,bufferedIndex:r}}static getBuffered(e){try{return e.buffered||ga}catch(e){return U.log(`failed to get media.buffered`,e),ga}}};function Y(e,t,n){X(e,t,n),e.addEventListener(t,n)}function X(e,t,n){e.removeEventListener(t,n)}function _a(e){let t=``,n=e.length;for(let r=0;r<n;r++)t+=`[${e.start(r).toFixed(3)}-${e.end(r).toFixed(3)}]`;return t}var va=/(avc[1234]|hvc1|hev1|dvh[1e]|vp09|av01)(?:\.[^.,]+)+/,ya=`HlsJsTrackRemovedError`,ba=`HlsJsSourceBufferError`,xa=.25,Sa=.001,Ca=class extends Error{constructor(e){super(e),this.name=ya}},wa=class extends Xt{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=e=>{this.hls&&this.mediaSource?.readyState===`open`&&this.media&&!this.media.seeking&&this.hls.pauseBuffering()},this._onStartStreaming=e=>{this.hls&&this.hls.resumeBuffering()},this._onMediaSourceOpen=e=>{let{media:t,mediaSource:n}=this;e&&this.log(`Media source opened`),t&&n&&(X(n,`sourceopen`,this._onMediaSourceOpen),X(t,`emptied`,this._onMediaEmptied),this.updateDuration(),this.hls.trigger(L.MEDIA_ATTACHED,{media:t,mediaSource:n}),this.mediaSource!==null&&this.checkPendingTracks())},this._onMediaSourceClose=()=>{if(this.log(`Media source closed`),this.media){if(this.isMediaSourceReplaced()){let{currentSrc:e}=this.media,t=e&&e!==this._objectUrl?e:this.mediaSrc;this.warn(`MediaSource closed after media element switched to another source (${this._objectUrl} > ${t}) - detaching media`),this.hls.detachMedia();return}let e=this.media.error,{appendError:t,appendErrors:n}=this,r=!1;!t&&e&&(r=Math.max(++n.audio,++n.video,++n.audiovideo)>=this.hls.config.appendErrorMaxRetry);let i=Error(`MediaSource closed while media attached${Oa(r,e)}`);this.warn(i),this.hls.trigger(L.ERROR,V({fatal:r},t,{type:F.MEDIA_ERROR,details:I.MEDIA_SOURCE_REQUIRES_RESET,error:i}))}},this._onMediaSourceEnded=()=>{this.log(`Media source ended`)},this._onMediaEmptied=()=>{let{mediaSrc:e,_objectUrl:t}=this;e!==t&&this.error(`Media element src was set while attaching MediaSource (${t} > ${e})`)},this._onMediaError=()=>{let{media:e}=this;e&&this.log(`Media error (code: ${e.error?.code}): ${e.error?.message}`)},this.hls=e,this.fragmentTracker=t,this.appendSource=on(an(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(),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(L.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(L.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(L.MANIFEST_LOADING,this.onManifestLoading,this),e.on(L.MANIFEST_PARSED,this.onManifestParsed,this),e.on(L.BUFFER_RESET,this.onBufferReset,this),e.on(L.BUFFER_APPENDING,this.onBufferAppending,this),e.on(L.BUFFER_CODECS,this.onBufferCodecs,this),e.on(L.BUFFER_EOS,this.onBufferEos,this),e.on(L.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(L.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(L.FRAG_PARSED,this.onFragParsed,this),e.on(L.FRAG_CHANGED,this.onFragChanged,this),e.on(L.ERROR,this.onError,this)}unregisterListeners(){let{hls:e}=this;e.off(L.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(L.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(L.MANIFEST_LOADING,this.onManifestLoading,this),e.off(L.MANIFEST_PARSED,this.onManifestParsed,this),e.off(L.BUFFER_RESET,this.onBufferReset,this),e.off(L.BUFFER_APPENDING,this.onBufferAppending,this),e.off(L.BUFFER_CODECS,this.onBufferCodecs,this),e.off(L.BUFFER_EOS,this.onBufferEos,this),e.off(L.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(L.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(L.FRAG_PARSED,this.onFragParsed,this),e.off(L.FRAG_CHANGED,this.onFragChanged,this),e.off(L.ERROR,this.onError,this)}transferMedia(){let{media:e,mediaSource:t}=this;if(!e)return null;let n={};if(this.operationQueue){let e=this.isUpdating();e||this.operationQueue.removeBlockers();let t=this.isQueued();(e||t)&&this.warn(`Transfering MediaSource with${t?` operations in queue`:``}${e?` updating SourceBuffer(s)`:``} ${this.operationQueue}`),this.operationQueue.destroy()}let r=this.transferData;return r&&!this.sourceBufferCount&&r.mediaSource===t?V(n,r.tracks):this.sourceBuffers.forEach(e=>{let[t]=e;t&&(n[t]=V({},this.tracks[t]),this.removeBuffer(t)),e[0]=e[1]=null}),{media:e,mediaSource:t,tracks:n}}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 n;let r=2;(t.audio&&!t.video||!t.altAudio)&&(r=1),this.bufferCodecEventsTotal=r,this.log(`${r} bufferCodec event(s) expected.`),(n=this.transferData)!=null&&n.mediaSource&&this.sourceBufferCount&&r&&this.bufferCreated()}onMediaAttaching(e,t){let n=this.media=t.media;this.transferData=this.overrides=void 0;let r=an(this.appendSource);if(r){let e=!!t.mediaSource;(e||t.overrides)&&(this.transferData=t,this.overrides=t.overrides);let i=this.mediaSource=t.mediaSource||new r;if(this.assignMediaSource(i),e)this._objectUrl=n.src,this.attachTransferred();else{let e=this._objectUrl=self.URL.createObjectURL(i),t=this.hls.config,r=t.emeEnabled&&n.mediaKeys?t.emeController?.CDMCleanupPromise:null;r?r.then(()=>{this.hls&&this.setSource(n,i,e)}).catch(()=>{}):this.setSource(n,i,e)}Y(n,`emptied`,this._onMediaEmptied),Y(n,`error`,this._onMediaError),this.appendSource&&Y(n,`seeking`,this._onStartStreaming)}}setSource(e,t,n){if(this.appendSource)try{e.removeAttribute(`src`);let r=self.ManagedMediaSource;e.disableRemotePlayback=e.disableRemotePlayback||r&&t instanceof r,Ta(e),Ea(e,n),e.load()}catch{e.src=n}else e.src=n}assignMediaSource(e){this.log(`${this.transferData?.mediaSource===e?`transferred`:`created`} media source: ${e.constructor?.name}`),Y(e,`sourceopen`,this._onMediaSourceOpen),Y(e,`sourceended`,this._onMediaSourceEnded),Y(e,`sourceclose`,this._onMediaSourceClose),this.appendSource&&(Y(e,`startstreaming`,this._onStartStreaming),Y(e,`endstreaming`,this._onEndStreaming))}attachTransferred(){let e=this.media,t=this.transferData;if(!t||!e)return;let n=this.tracks,r=t.tracks,i=r?Object.keys(r):null,a=i?i.length:0,o=()=>{Promise.resolve().then(()=>{this.media&&this.mediaSourceOpenOrEnded&&this._onMediaSourceOpen()})};if(r&&i&&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})
|
|
17
17
|
required tracks: ${q(n,(e,t)=>e===`initSegment`?void 0:t)};
|
|
18
|
-
transfer tracks: ${q(r,(e,t)=>e===`initSegment`?void 0:t)}}`),!sn(r,n)){t.mediaSource=null,t.tracks=void 0;let i=e.currentTime,a=this.details,o=Math.max(i,a?.fragments[0].start||0);if(o-i>1){this.log(`attachTransferred: waiting for playback to reach new tracks start time ${i} -> ${o}`);return}this.warn(`attachTransferred: resetting MediaSource for incompatible tracks ("${Object.keys(r)}"->"${Object.keys(n)}") start time: ${o} currentTime: ${i}`),this.onMediaDetaching(L.MEDIA_DETACHING,{}),this.onMediaAttaching(L.MEDIA_ATTACHING,t),e.currentTime=o;return}this.transferData=void 0,i.forEach(e=>{let t=e,n=r[t];if(n){let e=n.buffer;if(e){let r=this.fragmentTracker,i=n.id;if(r.hasFragments(i)||r.hasParts(i)){let n=J.getBuffered(e);r.detectEvictedFragments(t,n,i,null,null,!0)}let a=Da(t),o=[t,e];this.sourceBuffers[a]=o,e.updating&&this.operationQueue&&this.operationQueue.prependBlocker(t),this.trackSourceBuffer(t,n)}}}),o(),this.bufferCreated()}else this.log(`attachTransferred: MediaSource w/o SourceBuffers`),o()}get mediaSourceOpenOrEnded(){let e=this.mediaSource?.readyState;return e===`open`||e===`ended`}onMediaDetaching(e,t){let n=!!t.transferMedia;this.transferData=this.overrides=void 0;let{media:r,mediaSource:i,_objectUrl:a}=this;if(i){if(this.log(`media source ${n?`transferring`:`detaching`}`),n)this.sourceBuffers.forEach(([e])=>{e&&this.removeBuffer(e)}),this.resetQueue();else{if(this.mediaSourceOpenOrEnded){let e=i.readyState===`open`;try{let t=i.sourceBuffers;for(let n=t.length;n--;)e&&t[n].abort(),i.removeSourceBuffer(t[n]);e&&i.endOfStream()}catch(e){this.warn(`onMediaDetaching: ${e.message} while calling endOfStream`)}}this.sourceBufferCount&&this.onBufferReset()}X(i,`sourceopen`,this._onMediaSourceOpen),X(i,`sourceended`,this._onMediaSourceEnded),X(i,`sourceclose`,this._onMediaSourceClose),this.appendSource&&(X(i,`startstreaming`,this._onStartStreaming),X(i,`endstreaming`,this._onEndStreaming)),this.mediaSource=null,this._objectUrl=null}r&&(X(r,`emptied`,this._onMediaEmptied),X(r,`error`,this._onMediaError),X(r,`seeking`,this._onStartStreaming),n||(a&&self.URL.revokeObjectURL(a),this.mediaSrc===a&&!this.isMediaSourceReplaced(a)?(r.removeAttribute(`src`),this.appendSource&&Ta(r),r.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){let t=this.tracks[e]?.buffer;if(this.removeBuffer(e),t)try{var n;(n=this.mediaSource)!=null&&n.sourceBuffers.length&&this.mediaSource.removeSourceBuffer(t)}catch(t){this.warn(`onBufferReset ${e}`,t)}delete this.tracks[e]}removeBuffer(e){this.removeBufferListeners(e),this.sourceBuffers[Da(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 $i(this.tracks)}onBufferCodecs(e,t){let n=this.tracks,r=Object.keys(t);this.log(`BUFFER_CODECS: "${r}" (current SB count ${this.sourceBufferCount})`);let i=`audiovideo`in t&&(n.audio||n.video)||n.audiovideo&&(`audio`in t||`video`in t),a=!i&&this.sourceBufferCount&&this.media&&r.some(e=>!n[e]);if(i||a){this.warn(`Unsupported transition between "${Object.keys(n)}" and "${r}" SourceBuffers`);return}r.forEach(e=>{var r;let{id:i,codec:a,levelCodec:o,container:s,metadata:c,supplemental:l}=t[e],u=n[e],d=(r=this.transferData)==null||(r=r.tracks)==null?void 0:r[e],f=d!=null&&d.buffer?d:u,p=f?.pendingCodec||f?.codec,m=f?.levelCodec;u||=n[e]={buffer:void 0,listeners:[],codec:a,supplemental:l,container:s,levelCodec:o,metadata:c,id:i};let h=si(p,m),g=h?.replace(va,`$1`),_=si(a,o),v=_?.replace(va,`$1`);_&&h&&g!==v&&(e.slice(0,5)===`audio`&&(_=ai(_,this.appendSource)),this.log(`switching codec ${p} to ${_}`),_!==(u.pendingCodec||u.codec)&&(u.pendingCodec=_),u.container=s,this.appendChangeType(e,s,_))}),(this.tracksReady||this.sourceBufferCount)&&(t.tracks=this.sourceBufferTracks),!this.sourceBufferCount&&(this.bufferCodecEventsTotal>1&&!this.tracks.video&&!t.video&&t.audio?.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 n=this.tracks[t];return e[t]={id:n.id,container:n.container,codec:n.codec,levelCodec:n.levelCodec},e},{})}appendChangeType(e,t,n){let r=`${t};codecs=${n}`,i={label:`change-type=${r}`,execute:()=>{let i=this.tracks[e];if(i){let a=i.buffer;a!=null&&a.changeType&&(this.log(`changing ${e} sourceBuffer type to ${r}`),a.changeType(r),i.codec=n,i.container=t)}this.shiftAndExecuteNext(e)},onStart:()=>{},onComplete:()=>{},onError:t=>{this.warn(`Failed to change ${e} SourceBuffer type`,t)}};this.append(i,e,this.isPending(this.tracks[e]))}blockAudio(e){let t=e.start,n=t+e.duration*.05;this.fragmentTracker.getAppendedFrag(t,z.MAIN)?.gap!==!0&&this.append({label:`block-audio`,execute:()=>{(this.lastVideoAppendEnd>n||J.isBuffered(this.tracks.video?.buffer,n)||this.fragmentTracker.getAppendedFrag(n,z.MAIN)?.gap===!0)&&this.unblockAudio()},onStart:()=>{},onComplete:()=>{},onError:e=>{this.warn(`Error executing block-audio operation`,e)}},`audio`,!0)}unblockAudio(){this.operationQueue&&this.operationQueue.unblockAudio()}onBufferAppending(e,t){let{tracks:n}=this,{data:r,type:i,parent:a,frag:o,part:s,chunkMeta:c,offset:l}=t,u=c.buffering[i],d=Tt(o)&&!s&&!o.gap&&!c.partial&&!c.iframe,f=null,p=!1,{sn:m,cc:h}=o,g=self.performance.now();u.start=g;let _=o.stats.buffering,v=s?s.stats.buffering:null;_.start===0&&(_.start=g),v?.start===0&&(v.start=g);let y=n.audio,b=!1;i===`audio`&&y?.container===`audio/mpeg`&&(b=!this.lastMpegAudioChunk||c.id===1||this.lastMpegAudioChunk.sn!==c.sn,this.lastMpegAudioChunk=c);let x=n.video,S=x?.buffer;if(S&&m!==`initSegment`&&l!==void 0){let e=y?.buffer,t=s||o;if(i===`audio`&&a!==`main`&&!(x.ending||x.ended)&&e&&J.getBuffered(e).length){let e=t.start+t.duration*.05,n=J.getBuffered(S),r=this.currentOp(`video`);(!n.length&&!r||!J.isBuffered(S,e)&&this.lastVideoAppendEnd<e)&&this.blockAudio(t)}else if(i===`video`){let e=t.end,n=this.lastVideoAppendEnd-e;this.lastVideoAppendEnd=e,n<0||n>t.duration?this.unblockAudio():this.isAudioBlocked()&&this.executeNext(`audio`)}}let C=(s||o).start,w={label:`append-${i}`,execute:()=>{u.executeStart=self.performance.now();let e=this.tracks[i]?.buffer;e&&(d&&(f=J.timeRangesToArray(J.getBuffered(e)),p=ja(Aa(f,o),o)),b?this.updateTimestampOffset(e,C,.1,i,m,h):l!==void 0&&P(l)&&this.updateTimestampOffset(e,l,1e-6,i,m,h)),this.appendExecutor(r,i)},onStart:()=>{},onComplete:()=>{this.clearBufferAppendTimeoutId(this.tracks[i]);let e=self.performance.now();u.executeEnd=u.end=e,_.first===0&&(_.first=e),v?.first===0&&(v.first=e);let t={};if(this.sourceBuffers.forEach(([e,n])=>{e&&(t[e]=J.getBuffered(n))}),d){let e=this.getFragmentAppendProgress(o),n=t[i];if(n&&f){let t=Aa(J.timeRangesToArray(n),o);e.progressed||=t-Aa(f,o)>Sa;let r=p&&ja(t,o);e.fullyBuffered[i]=(e.fullyBuffered[i]===void 0||e.fullyBuffered[i])&&r}}this.hls.trigger(L.BUFFER_APPENDED,{type:i,frag:o,part:s,chunkMeta:c,parent:a,timeRanges:t})},onError:e=>{this.clearBufferAppendTimeoutId(this.tracks[i]);let t=e.code===DOMException.QUOTA_EXCEEDED_ERR||e.name==`QuotaExceededError`||`quota`in e;if(t&&!this._quotaEvictionPending[i]){let e=this.getBackBufferEvictionTarget(i,r.byteLength,o.type);if(e>0){this._quotaEvictionPending[i]=!0,this.log(`QuotaExceededError on "${i}" append sn: ${m} - evicting back buffer to ${e.toFixed(3)}s and retrying`);let t=this.getFlushOp(i,0,e),n=this.getClearEvictionPendingOp(i);this.insertNext([t,w,n],i);return}this.warn(`QuotaExceededError on "${i}" sn: ${m} - no back buffer available to evict`)}d&&(this.getFragmentAppendProgress(o).errored=!0);let n={type:F.MEDIA_ERROR,parent:a,details:I.BUFFER_APPEND_ERROR,sourceBufferName:i,frag:o,part:s,chunkMeta:c,error:e,err:e,fatal:!1},l=this.media?.error;if(e.name===ya&&this.sourceBufferCount===0&&(!this.media||this.pendingTrackCount===0))n.errorAction=pa(!0);else{t&&(n.details=I.BUFFER_FULL_ERROR);let r=++this.appendErrors[i],a=this.hls.config.appendErrorMaxRetry;this.warn(`Failed ${r}/${a+1} times to append segment in "${i}" sourceBuffer with error: ${e.message}`),r>=a&&(n.fatal=!t);let o=this.mediaSource?.readyState;(o===`ended`||o===`closed`||l)&&!this.isMediaSourceReplaced()&&(this.warn(`MediaSource readyState "${o}" during SourceBuffer${Oa(n.fatal,l)}`),n.details=I.MEDIA_SOURCE_REQUIRES_RESET)}this.appendError=n,this.hls.trigger(L.ERROR,n),t&&this.hls&&this.trimBuffers(o.start,1)}};this.log(`queuing "${i}" append sn: ${m}${s?` p: `+s.index:``} of ${a} playlist ${o.level} cc: ${h} offset: ${l} bytes: ${r.byteLength}`),this.append(w,i,this.isPending(this.tracks[i]))}getClearEvictionPendingOp(e){return{label:`clear`,execute:()=>{this._quotaEvictionPending[e]=!1,this.shiftAndExecuteNext(e)},onStart:()=>{},onComplete:()=>{},onError:()=>{}}}getFlushOp(e,t,n){return this.log(`queuing "${e}" remove ${t}-${n}`),{label:`remove`,execute:()=>{this.removeExecutor(e,t,n)},onStart:()=>{},onComplete:()=>{let r=this.tracks[e]?.buffer;this.log(`Remove request ${t}-${n} from ${e} Source Buffer complete > buffer: ${r?_a(J.getBuffered(r)):`(detached)`}`),this.hls.trigger(L.BUFFER_FLUSHED,{type:e,start:t,end:n})},onError:r=>{this.warn(`Failed to remove ${t}-${n} from "${e}" SourceBuffer`,r),this.hls.trigger(L.BUFFER_FLUSHED,{type:e,start:0,end:0,error:r})}}}onBufferFlushing(e,t){let{type:n,startOffset:r,endOffset:i}=t;(!n||n===`audio`)&&this.unblockAudio(),n?this.append(this.getFlushOp(n,r,i),n):this.sourceBuffers.forEach(([e])=>{e&&this.append(this.getFlushOp(e,r,i),e)})}onFragParsed(e,t){let{frag:n,part:r,chunkMeta:i}=t,a=[],o=r?r.elementaryStreams:n.elementaryStreams;o[B.AUDIOVIDEO]?a.push(`audiovideo`):(o[B.AUDIO]&&a.push(`audio`),o[B.VIDEO]&&a.push(`video`)),a.length===0&&this.log(`Fragments must have at least one ElementaryStreamType set. ${n.type} ${n.level} ${r?`part: ${r.index} of `:``}sn: ${n.sn}`),this.blockBuffers(()=>{let e=self.performance.now();n.stats.buffering.end=e,r&&(r.stats.buffering.end=e);let t=r?r.stats:n.stats;this.checkAppendProgress(n,r,i,a),this.hls&&(this.hls.trigger(L.FRAG_BUFFERED,{frag:n,part:r,stats:t,id:n.type,chunkMeta:i}),!r&&n.gap&&t.retry&&this.log(`Nothing buffered for ${n.type} level: ${n.level} sn: ${n.sn} retries ${t.retry}`))},a).catch(e=>{this.warn(`Fragment buffered callback ${e.message}`),this.stepOperationQueue(this.sourceBufferTypes)})}onFragChanged(e,t){let n=this.hls?.config;if(!n)return;let{backBufferLength:r,frontBufferFlushThreshold:i}=n;this.trimBuffers(i,r,t.frag,t.previousFrag);let a=t.frag.elementaryStreams,{appendErrors:o}=this,s=this.appendError?.sourceBufferName;Object.keys(a).forEach(e=>{a[e]&&(o[e]=0,e===s&&(this.appendError=void 0),e===`audio`||e===`video`?(o.audiovideo=0,s===`audiovideo`&&(this.appendError=void 0)):(o.audio=0,o.video=0,s!==`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){this.sourceBuffers.forEach(([e])=>{if(e){let n=this.tracks[e];(!t.type||t.type===e)&&(n.ending=!0,n.ended||(n.ended=!0,this.log(`${e} buffer reached EOS`)))}});let n=this.overrides?.endOfStream!==!1;this.allTracksEnding?(this.unblockAudio(),n?(this.log(`Queueing EOS`),this.blockUntilOpen(()=>{if(this.tracksEnded(),!this.allTracksEnding){this.log(`EOS cancelled`);return}let{mediaSource:e}=this;if(e?.readyState!==`open`){e&&this.log(`Could not call mediaSource.endOfStream(). mediaSource.readyState: ${e.readyState}`);return}this.log(`Calling mediaSource.endOfStream()`),e.endOfStream(),this.hls.trigger(L.BUFFERED_TO_END,void 0)})):(this.tracksEnded(),this.hls.trigger(L.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===I.BUFFER_APPEND_ERROR&&t.frag){let e=t.errorAction?.nextAutoLevel;P(e)&&e!==t.frag.level&&this.resetAppendErrors()}}getBackBufferEvictionTarget(e,t,n){let{media:r}=this;return r?this.fragmentTracker.getBackBufferEvictionEnd(r.currentTime,n,t):0}getFragmentAppendProgress(e){let t=ka(e),n=this.fragmentAppendProgress[t];return n?.stats!==e.stats&&(n={stats:e.stats,progressed:!1,errored:!1,fullyBuffered:Object.create(null)},this.fragmentAppendProgress[t]=n),n}checkAppendProgress(e,t,n,r){if(t||!Tt(e)||e.gap||n.iframe||n.partial)return;let i=ka(e),a=this.fragmentAppendProgress[i];delete this.fragmentAppendProgress[i];let o=e.stats.buffering;if(o.start&&!o.first)return;let s=a?.stats===e.stats?a:void 0;if(s!=null&&s.errored)return;let c=r.length>0&&r.every(e=>s?.fullyBuffered[e]===!0);if(s!=null&&s.progressed||c){delete this.appendsWithoutProgress[i];return}if(!s&&r.length===0)return;let l=(this.appendsWithoutProgress[i]||0)+1,u=this.hls;l>=u.config.appendErrorMaxRetry?delete this.appendsWithoutProgress[i]:this.appendsWithoutProgress[i]=l,this.warn(`Fragment ${e.sn} of ${e.type} playlist ${e.level} appended ${l} time${l>1?`s`:``} without buffered range growth`),u.trigger(L.ERROR,{type:F.MEDIA_ERROR,details:I.BUFFER_APPEND_NO_PROGRESS,fatal:!1,frag:e,chunkMeta:n,parent:e.type,appendsWithoutProgress:l,error:Error(`Fragment append did not increase buffered coverage (${l})`)})}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,n,r){let{hls:i,details:a,media:o}=this;if(!o||a===null||!this.sourceBufferCount)return;let s=i.config,c=o.currentTime,l=a.levelTargetDuration;t=a.live&&s.liveBackBufferLength!==null?s.liveBackBufferLength:t;let u=-1/0;if(P(t)&&t>=0){let e=Math.max(t,l);u=Math.floor(c/l)*l-e}if(n){let e=this.getLoopBackBufferFlushEnd(n,r??null);e>0&&(u=Math.max(u,e))}if(u>0&&this.flushBackBuffer(c,l,u),P(e)&&e>0){let t=Math.max(s.maxBufferLength,e),n=Math.max(t,l),r=Math.floor(c/l)*l+n;this.flushFrontBuffer(c,l,r)}}getLoopBackBufferFlushEnd(e,t){let{media:n}=this;if(this.hls?.config.loopBackBufferFlush===!1||!(n!=null&&n.loop)||!t||e.level<=t.level)return 0;let{video:r,audiovideo:i}=e.elementaryStreams;if(r!=null&&r.partial||i!=null&&i.partial)return 0;let a=this.getEarliestElementaryStreamStart(e)-xa;return a<=0?0:(this.log(`Flushing lower quality back buffer for loop: level ${e.level}, range [0-${a.toFixed(3)}]`),a)}getEarliestElementaryStreamStart(e){let{audio:t,video:n,audiovideo:r}=e.elementaryStreams,i=e.start;return r?i=Math.min(i,r.startDTS):(t&&(i=Math.min(i,t.startDTS)),n&&(i=Math.min(i,n.startDTS))),i}flushBackBuffer(e,t,n){this.sourceBuffers.forEach(([e,t])=>{if(t){let a=J.getBuffered(t);if(a.length>0&&n>a.start(0)){var r,i;this.hls.trigger(L.BACK_BUFFER_REACHED,{bufferEnd:n});let t=this.tracks[e];if((r=this.details)!=null&&r.live)this.hls.trigger(L.LIVE_BACK_BUFFER_REACHED,{bufferEnd:n});else if(t!=null&&t.ended&&!((i=this.media)!=null&&i.loop&&this.hls?.config.loopBackBufferFlush!==!1)){this.log(`Cannot flush ${e} back buffer while SourceBuffer is in ended state`);return}this.hls.trigger(L.BUFFER_FLUSHING,{startOffset:0,endOffset:n,type:e})}}})}flushFrontBuffer(e,t,n){this.sourceBuffers.forEach(([t,r])=>{if(r){let i=J.getBuffered(r),a=i.length;if(a<2)return;let o=i.start(a-1),s=i.end(a-1);if(n>o||e>=o&&e<=s)return;this.hls.trigger(L.BUFFER_FLUSHING,{startOffset:o,endOffset:1/0,type:t})}})}getDurationAndRange(){let{details:e,mediaSource:t}=this;if(!e||!this.media||t?.readyState!==`open`)return null;let n=e.edge;if(e.live&&this.hls.config.liveDurationInfinity){if(e.fragments.length&&t.setLiveSeekableRange){let t=Math.max(0,e.fragmentStart);return{duration:1/0,start:t,end:Math.max(t,n)}}return{duration:1/0}}let r=this.overrides?.duration;if(r)return P(r)?{duration:r}:null;let i=this.media.duration;return n>(P(t.duration)?t.duration:0)&&n>i||!P(i)?{duration:n}:null}updateMediaSource({duration:e,start:t,end:n}){let r=this.mediaSource;r&&this.media&&r.readyState===`open`&&(r.duration!==e&&(P(e)&&this.log(`Updating MediaSource duration to ${e.toFixed(3)}`),r.duration=e),t!==void 0&&n!==void 0&&(this.log(`MediaSource duration is set to ${r.duration}. Setting seekable range to ${t}-${n}.`),r.setLiveSeekableRange(t,n)))}get tracksReady(){let e=this.pendingTrackCount;return e>0&&(e>=this.bufferCodecEventsTotal||this.isPending(this.tracks.audiovideo))}checkPendingTracks(){let{bufferCodecEventsTotal:e,pendingTrackCount:t,tracks:n}=this;if(this.log(`checkPendingTracks (pending: ${t} codec events expected: ${e}) ${q(n)}`),this.tracksReady){let e=this.transferData?.tracks;e&&Object.keys(e).length?this.attachTransferred():this.createSourceBuffers()}}bufferCreated(){if(this.sourceBufferCount){let e={};this.sourceBuffers.forEach(([t,n])=>{if(t){let r=this.tracks[t];e[t]={buffer:n,container:r.container,codec:r.codec,supplemental:r.supplemental,levelCodec:r.levelCodec,id:r.id,metadata:r.metadata}}}),this.hls.trigger(L.BUFFER_CREATED,{tracks:e}),this.log(`SourceBuffers created. Running queue: ${this.operationQueue}`),this.sourceBuffers.forEach(([e])=>{this.executeNext(e)})}else{let e=Error(`could not create source buffer for media codec(s)`);this.hls.trigger(L.ERROR,{type:F.MEDIA_ERROR,details:I.BUFFER_INCOMPATIBLE_CODECS_ERROR,fatal:!0,error:e,reason:e.message})}}createSourceBuffers(){let{tracks:e,sourceBuffers:t,mediaSource:n}=this;if(!n)throw Error(`createSourceBuffers called when mediaSource was null`);for(let i in e){let a=i,o=e[a];if(this.isPending(o)){let e=this.getTrackCodec(o,a),i=`${o.container};codecs=${e}`;o.codec=e,this.log(`creating sourceBuffer(${i})${this.currentOp(a)?` Queued`:``} ${q(o)}`);try{let e=n.addSourceBuffer(i),r=Da(a);t[r]=[a,e],o.buffer=e}catch(e){var r;this.error(`error while trying to add sourceBuffer: ${e.message}`),this.shiftAndExecuteNext(a),(r=this.operationQueue)==null||r.removeBlockers(),delete this.tracks[a],this.hls.trigger(L.ERROR,{type:F.MEDIA_ERROR,details:I.BUFFER_ADD_CODEC_ERROR,fatal:!1,error:e,sourceBufferName:a,mimeType:i,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 n=e.supplemental,r=e.codec;n&&(t===`video`||t===`audiovideo`)&&Zr(n,`video`)&&(r=oi(r,n));let i=si(r,e.levelCodec);return i?t.slice(0,5)===`audio`?ai(i,this.appendSource):i:``}trackSourceBuffer(e,t){let n=t.buffer;if(!n)return;let r=this.getTrackCodec(t,e);this.tracks[e]={buffer:n,codec:r,container:t.container,levelCodec:t.levelCodec,supplemental:t.supplemental,metadata:t.metadata,id:t.id,listeners:[]},this.removeBufferListeners(e),this.addBufferListener(e,`updatestart`,this.onSBUpdateStart),this.addBufferListener(e,`updateend`,this.onSBUpdateEnd),this.addBufferListener(e,`error`,this.onSBUpdateError),this.appendSource&&this.addBufferListener(e,`bufferedchange`,(e,t)=>{let n=t.removedRanges;n!=null&&n.length&&(this.log(`${e} buffer removed ${_a(n)}`),this.hls.trigger(L.BUFFER_FLUSHED,{type:e,start:n.start(0),end:n.end(n.length-1)}))})}get mediaSrc(){let e=this.media;if(e)return(e.src?e:e.querySelector?.call(e,`source`)||e).src}isMediaSourceReplaced(e=this._objectUrl){if(!e)return!1;let t=this.media?.currentSrc,n=this.mediaSrc;return!!t&&t!==e||!!n&&n!==e}onSBUpdateStart(e){let t=this.currentOp(e);t&&t.onStart()}onSBUpdateEnd(e){var t;if(this.mediaSource?.readyState===`closed`){this.resetBuffer(e);return}let n=this.currentOp(e);if(n){if(n.onComplete(),(t=this.tracks[e])!=null&&(t=t.buffer)!=null&&t.updating){this.log(`${e} SourceBuffer updating on "updateend"`),this.blockUntilOpen(()=>{this.shiftAndExecuteNext(e)});return}this.shiftAndExecuteNext(e)}}onSBUpdateError(e,t){let n=this.mediaSource?.readyState,r=Error(`${e} SourceBuffer error. MediaSource readyState: ${n}`);r.name=ba,this.error(`${r.message}`,t),this.hls.trigger(L.ERROR,{type:F.MEDIA_ERROR,details:I.BUFFER_APPENDING_ERROR,sourceBufferName:e,error:r,fatal:!1});let i=this.currentOp(e);i&&i.onError(r)}updateTimestampOffset(e,t,n,r,i,a){let o=t-e.timestampOffset;Math.abs(o)>=n&&(this.log(`Updating ${r} SourceBuffer timestampOffset to ${t} (sn: ${i} cc: ${a})`),e.timestampOffset=t)}removeExecutor(e,t,n){let{media:r,mediaSource:i}=this,a=this.tracks[e],o=a?.buffer;if(!r||!i||!o)throw Error(`Attempting to remove from the ${e} SourceBuffer, but it does not exist`);let s=P(r.duration)?r.duration:1/0,c=P(i.duration)?i.duration:1/0,l=Math.max(0,t);if(l>=c){var u;(u=this.currentOp(e))==null||u.onComplete(),this.shiftAndExecuteNext(e);return}let d=Math.min(n,s,c);if(d>l&&(!a.ending||a.ended))a.ended=!1,this.log(`Removing [${l},${d}] from the ${e} SourceBuffer`),o.remove(l,d);else throw Error(`Cannot remove ${d<=l?`invalid range (${l} >= ${d}) `:``}from the ${e} SourceBuffer${a.ending?` while track ending`:``}`)}appendExecutor(e,t){let n=this.tracks[t],r=n?.buffer;if(!r)throw new Ca(`Attempting to append to the ${t} SourceBuffer, but it does not exist`);if(n.ending=!1,n.ended=!1,this.hls.config.appendTimeout!==1/0){let e=this.calculateAppendTimeoutTime(r);n.bufferAppendTimeoutId=self.setTimeout(()=>this.appendTimeoutHandler(t,r,e),e)}r.appendBuffer(e)}appendTimeoutHandler(e,t,n){this.log(`Received timeout after ${n}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 r=this.currentOp(e);r&&r.onError(Error(`${e}-append-timeout`))}calculateAppendTimeoutTime(e){let t=ma;this.details&&(t=this.details.levelTargetDuration);let n=2*t*1e3;if(this.media===null)return n;let r=J.bufferInfo(e,this.media.currentTime,0);return r.len?(n=Math.max(r.len*1e3,n),Math.max(this.hls.config.appendTimeout,n)):n}blockUntilOpen(e){if(this.isUpdating()||this.isQueued())this.blockBuffers(e).catch(e=>{this.warn(`SourceBuffer blocked callback ${e}`),this.stepOperationQueue(this.sourceBufferTypes)});else try{e()}catch(e){this.warn(`Callback run without blocking ${this.operationQueue} ${e}`)}}isUpdating(){return this.sourceBuffers.some(([e,t])=>e&&t.updating)}isQueued(){return this.sourceBuffers.some(([e])=>e&&!!this.currentOp(e))}isPending(e){return!!e&&!e.buffer}isAudioBlocked(){return this.currentOp(`audio`)?.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:n}=this,r=t.length===2&&this.isAudioBlocking()?[this.appendBlocker(`video`)]:t.map(e=>this.appendBlocker(e));return Promise.all(r).then(t=>{n===this.operationQueue&&(e(),this.stepOperationQueue(this.sourceBufferTypes))})}stepOperationQueue(e){e.forEach(e=>{let t=this.tracks[e]?.buffer;!t||t.updating||e===`audio`&&this.isAudioBlocked()||this.shiftAndExecuteNext(e)})}append(e,t,n){this.operationQueue&&this.operationQueue.append(e,t,n)}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]),0)}get sourceBufferCount(){return this.sourceBuffers.reduce((e,[t])=>e+ +!!t,0)}get sourceBufferTypes(){return this.sourceBuffers.map(([e])=>e).filter(e=>!!e)}addBufferListener(e,t,n){let r=this.tracks[e];if(!r)return;let i=r.buffer;if(!i)return;let a=n.bind(this,e);r.listeners.push({event:t,listener:a}),Y(i,t,a)}removeBufferListeners(e){let t=this.tracks[e];if(!t)return;let n=t.buffer;n&&(t.listeners.forEach(e=>{X(n,e.event,e.listener)}),t.listeners.length=0)}};function Ta(e){let t=e.querySelectorAll(`source`);[].slice.call(t).forEach(t=>{e.removeChild(t)})}function Ea(e,t){let n=self.document.createElement(`source`);n.type=`video/mp4`,n.src=t,e.appendChild(n)}function Da(e){return+(e===`audio`)}function Oa(e,t){return`${e?``:` - triggering recovery`}${t?` with HTMLMediaElement Error: `+t.message:``}`}function ka(e){return`${e.type}_${e.sn}_${e.level}`}function Aa(e,t){let{start:n,end:r}=t,i=0;for(let t=0;t<e.length;t++){let a=e[t];if(a.start>=r)break;let o=Math.max(n,a.start),s=Math.min(r,a.end);s>o&&(i+=s-o)}return i}function ja(e,t){return t.duration-e<=.05}var Z={NOT_LOADED:`NOT_LOADED`,APPENDING:`APPENDING`,PARTIAL:`PARTIAL`,OK:`OK`},Ma=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(L.MANIFEST_LOADING,this.onManifestLoading,this),e.on(L.BUFFER_APPENDED,this.onBufferAppended,this),e.on(L.FRAG_BUFFERED,this.onFragBuffered,this),e.on(L.FRAG_LOADED,this.onFragLoaded,this))}_unregisterListeners(){let{hls:e}=this;e&&(e.off(L.MANIFEST_LOADING,this.onManifestLoading,this),e.off(L.BUFFER_APPENDED,this.onBufferAppended,this),e.off(L.FRAG_BUFFERED,this.onFragBuffered,this),e.off(L.FRAG_LOADED,this.onFragLoaded,this))}destroy(){this._unregisterListeners(),this.hls=this.fragments=this.activePartLists=this.endListFragments=this.timeRanges=null}getAppendedFrag(e,t){let n=this.activePartLists[t];if(n)for(let t=n.length;t--;){let r=n[t];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,n){let{fragments:r}=this,i=Object.keys(r);for(let a=i.length;a--;){let o=r[i[a]];if(o?.body.type===t&&(!n||o.buffered)){let t=o.body;if(t.start<=e&&e<=t.end)return t}}return null}detectEvictedFragments(e,t,n,r,i,a){this.timeRanges&&(this.timeRanges[e]=t);let o=i?.fragment.sn||-1;Object.keys(this.fragments).forEach(i=>{let s=this.fragments[i];if(!s||!this.hls)return;let c=s.body;if(o>=c.sn)return;if(!s.buffered&&(!s.loaded||a)){c.type===n&&this.removeFragment(c);return}let l=s.range[e];if(l){if(l.time.length===0){this.removeFragment(c);return}if(l.time.some(e=>{let n=!this.isTimeBuffered(e.startPTS,e.endPTS,t);return n&&this.removeFragment(c),n}),r&&r!==c&&Wr()){let e=r.endPTS,t=c.startPTS;if(e&&t&&s.range.video){let n=t-e;n<0&&n>-.1&&(this.removeFragment(c),this.hls.trigger(L.BUFFER_FLUSHING,{startOffset:e+.004,endOffset:1/0,type:`video`}))}}}})}detectPartialFragments(e){let t=this.timeRanges,{frag:n,part:r,id:i}=e;if(!t||!Tt(n))return;let a=Pa(n),o=this.fragments[a];if(!o||o.buffered&&n.gap)return;let s=!n.relurl;Object.keys(t).forEach(e=>{let a=n.elementaryStreams[e];if(!a)return;let c=t[e],l=s||a.partial===!0;o.range[e]=this.getBufferedTimes(n,r,l,c),this.detectEvictedFragments(e,c,i,n,r)}),o.loaded=null;let c=Object.keys(o.range);if(c.length){if(this.bufferedEnd(o,n),Na(o)||this.removeParts(n.sn-1,n.type),!r){let e=Math.min(.004,n.duration);c.some(t=>{let r=o.range[t]?.time,i=r.length===0||r.length===1&&r[0].endPTS-r[0].startPTS<e;return i&&this.addAsGap(n),i})}}else this.removeFragment(n)}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 n=this.activePartLists[t];n&&(this.activePartLists[t]=Fa(n,t=>t.fragment.sn>=e))}fragBuffered(e,t){let n=Pa(e),r=this.fragments[n];return!r&&t&&(r=this.fragments[n]={body:e,appendedPTS:null,loaded:null,buffered:!1,range:Object.create(null)},e.gap&&(this.hasGaps=!0)),r&&(r.loaded=null,this.bufferedEnd(r,e)),r}getBufferedTimes(e,t,n,r){let i={time:[],partial:n},a=e.start,o=e.end,s=e.minEndPTS||o,c=e.maxStartPTS||a;for(let e=0;e<r.length;e++){let t=r.start(e)-this.bufferPadding,n=r.end(e)+this.bufferPadding;if(c>=t&&s<=n){i.time.push({startPTS:Math.max(a,r.start(e)),endPTS:Math.min(o,r.end(e))});break}if(a<n&&o>t){let t=Math.max(a,r.start(e)),n=Math.min(o,r.end(e));n>t&&(i.partial=!0,i.time.push({startPTS:t,endPTS:n}))}else if(o<=t)break}return i}getPartialFragment(e){let t=null,n,r,i,a=0,{bufferPadding:o,fragments:s}=this;return Object.keys(s).forEach(c=>{let l=s[c];l&&Na(l)&&(r=l.body.start-o,i=l.body.end+o,e>=r&&e<=i&&(n=Math.min(e-r,i-e),a<=n&&(t=l.body,a=n)))}),t}isEndListAppended(e){let t=this.endListFragments[e];return t!==void 0&&(t.buffered||Na(t))}getState(e){let t=Pa(e),n=this.fragments[t];return n?n.buffered?Na(n)?Z.PARTIAL:Z.OK:Z.APPENDING:Z.NOT_LOADED}isTimeBuffered(e,t,n){let r,i;for(let a=0;a<n.length;a++){if(r=n.start(a)-this.bufferPadding,i=n.end(a)+this.bufferPadding,e>=r&&t<=i)return!0;if(t<=r)return!1}return!1}onManifestLoading(){this.removeAllFragments()}onFragLoaded(e,t){if(!Tt(t.frag)||t.frag.bitrateTest)return;let n=t.frag,r=t.part?null:t,i=Pa(n);this.fragments[i]={body:n,appendedPTS:null,loaded:r,buffered:!1,range:Object.create(null)}}onBufferAppended(e,t){let{frag:n,part:r,timeRanges:i}=t;if(!Tt(n))return;let a=n.type;if(r){let e=this.activePartLists[a];e||(this.activePartLists[a]=e=[]),e.push(r)}this.timeRanges=i}onFragBuffered(e,t){this.detectPartialFragments(t)}hasFragment(e){let t=Pa(e);return!!this.fragments[t]}hasFragments(e){let{fragments:t}=this,n=Object.keys(t);if(!e)return n.length>0;for(let r=n.length;r--;)if(t[n[r]]?.body.type===e)return!0;return!1}hasParts(e){var t;return!!((t=this.activePartLists[e])!=null&&t.length)}getBackBufferEvictionEnd(e,t,n){let{fragments:r}=this,i=0,a=0,o=Object.keys(r);for(let s=0;s<o.length;s++){let c=r[o[s]];if(!c||!c.buffered||c.body.type!==t)continue;let l=c.body;if(l.gap)return 0;let u=l.hasStats&&l.stats.loaded||l.byteLength||l.bitrate&&l.bitrate*8*l.duration;if(l.end<=e&&u&&(i+=u,a=Math.max(a,l.end),i>=n))return a}return a>0?a:0}removeFragmentsInRange(e,t,n,r,i){(!r||this.hasGaps)&&Object.keys(this.fragments).forEach(a=>{let o=this.fragments[a];if(!o)return;let s=o.body;s.type!==n||r&&!s.gap||s.start<t&&s.end>e&&(o.buffered||i)&&this.removeFragment(s)})}removeFragment(e){let t=Pa(e);e.clearElementaryStreamInfo();let n=this.activePartLists[e.type];if(n){let t=e.sn;this.activePartLists[e.type]=Fa(n,e=>e.fragment.sn!==t)}delete this.fragments[t],e.endList&&delete this.endListFragments[e.type]}gapFragments(){return this.hasGaps?Object.keys(this.fragments).map(e=>this.fragments[e]?.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(e=>e.clearElementaryStreamInfo())}};function Na(e){var t,n,r,i;return e.buffered&&!!(e.body.gap||(t=e.range.video)!=null&&t.partial||(n=e.range.audio)!=null&&n.partial||(r=e.range.audiovideo)!=null&&r.partial||(i=e.range.subs)!=null&&i.partial)}function Pa(e){return`${e.type}_${e.level}_${e.sn}`}function Fa(e,t){return e.filter(e=>{let n=t(e);return n||e.clearElementaryStreamInfo(),n})}var Ia={cbc:0,ctr:1},La=class{constructor(e,t,n){this.subtle=void 0,this.aesIV=void 0,this.aesMode=void 0,this.subtle=e,this.aesIV=t,this.aesMode=n}decrypt(e,t){switch(this.aesMode){case Ia.cbc:return this.subtle.decrypt({name:`AES-CBC`,iv:this.aesIV},t,e);case Ia.ctr:return this.subtle.decrypt({name:`AES-CTR`,counter:this.aesIV,length:64},t,e);default:throw Error(`[AESCrypto] invalid aes mode ${this.aesMode}`)}}};function Ra(e){let t=e.byteLength,n=t&&new DataView(e.buffer).getUint8(t-1);return n?e.slice(0,t-n):e}var za=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,this.ksRows=0,this.keySize=0,this.keySchedule=void 0,this.invKeySchedule=void 0,this.initTable()}uint8ArrayToUint32Array_(e){let t=new DataView(e),n=new Uint32Array(4);for(let e=0;e<4;e++)n[e]=t.getUint32(e*4);return n}initTable(){let e=this.sBox,t=this.invSBox,n=this.subMix,r=n[0],i=n[1],a=n[2],o=n[3],s=this.invSubMix,c=s[0],l=s[1],u=s[2],d=s[3],f=new Uint32Array(256),p=0,m=0,h=0;for(h=0;h<256;h++)h<128?f[h]=h<<1:f[h]=h<<1^283;for(h=0;h<256;h++){let n=m^m<<1^m<<2^m<<3^m<<4;n=n>>>8^n&255^99,e[p]=n,t[n]=p;let s=f[p],h=f[s],g=f[h],_=f[n]*257^n*16843008;r[p]=_<<24|_>>>8,i[p]=_<<16|_>>>16,a[p]=_<<8|_>>>24,o[p]=_,_=g*16843009^h*65537^s*257^p*16843008,c[n]=_<<24|_>>>8,l[n]=_<<16|_>>>16,u[n]=_<<8|_>>>24,d[n]=_,p?(p=s^f[f[f[g^s]]],m^=f[f[m]]):p=m=1}}expandKey(e){let t=this.uint8ArrayToUint32Array_(e),n=!0,r=0;for(;r<t.length&&n;)n=t[r]===this.key[r],r++;if(n)return;this.key=t;let i=this.keySize=t.length;if(i!==4&&i!==6&&i!==8)throw Error(`Invalid aes key size=`+i);let a=this.ksRows=(i+6+1)*4,o,s,c=this.keySchedule=new Uint32Array(a),l=this.invKeySchedule=new Uint32Array(a),u=this.sBox,d=this.rcon,f=this.invSubMix,p=f[0],m=f[1],h=f[2],g=f[3],_,v;for(o=0;o<a;o++){if(o<i){_=c[o]=t[o];continue}v=_,o%i===0?(v=v<<8|v>>>24,v=u[v>>>24]<<24|u[v>>>16&255]<<16|u[v>>>8&255]<<8|u[v&255],v^=d[o/i|0]<<24):i>6&&o%i===4&&(v=u[v>>>24]<<24|u[v>>>16&255]<<16|u[v>>>8&255]<<8|u[v&255]),c[o]=_=(c[o-i]^v)>>>0}for(s=0;s<a;s++)o=a-s,v=s&3?c[o]:c[o-4],s<4||o<=4?l[s]=v:l[s]=p[u[v>>>24]]^m[u[v>>>16&255]]^h[u[v>>>8&255]]^g[u[v&255]],l[s]=l[s]>>>0}networkToHostOrderSwap(e){return e<<24|(e&65280)<<8|(e&16711680)>>8|e>>>24}decrypt(e,t,n){let r=this.keySize+6,i=this.invKeySchedule,a=this.invSBox,o=this.invSubMix,s=o[0],c=o[1],l=o[2],u=o[3],d=this.uint8ArrayToUint32Array_(n),f=d[0],p=d[1],m=d[2],h=d[3],g=new Int32Array(e),_=new Int32Array(g.length),v,y,b,x,S,C,w,T,E,D,O,k,A,j,M=this.networkToHostOrderSwap;for(;t<g.length;){for(E=M(g[t]),D=M(g[t+1]),O=M(g[t+2]),k=M(g[t+3]),S=E^i[0],C=k^i[1],w=O^i[2],T=D^i[3],A=4,j=1;j<r;j++)v=s[S>>>24]^c[C>>16&255]^l[w>>8&255]^u[T&255]^i[A],y=s[C>>>24]^c[w>>16&255]^l[T>>8&255]^u[S&255]^i[A+1],b=s[w>>>24]^c[T>>16&255]^l[S>>8&255]^u[C&255]^i[A+2],x=s[T>>>24]^c[S>>16&255]^l[C>>8&255]^u[w&255]^i[A+3],S=v,C=y,w=b,T=x,A+=4;v=a[S>>>24]<<24^a[C>>16&255]<<16^a[w>>8&255]<<8^a[T&255]^i[A],y=a[C>>>24]<<24^a[w>>16&255]<<16^a[T>>8&255]<<8^a[S&255]^i[A+1],b=a[w>>>24]<<24^a[T>>16&255]<<16^a[S>>8&255]<<8^a[C&255]^i[A+2],x=a[T>>>24]<<24^a[S>>16&255]<<16^a[C>>8&255]<<8^a[w&255]^i[A+3],_[t]=M(v^f),_[t+1]=M(x^p),_[t+2]=M(b^m),_[t+3]=M(y^h),f=E,p=D,m=O,h=k,t+=4}return _.buffer}},Ba=class{constructor(e,t,n){this.subtle=void 0,this.key=void 0,this.aesMode=void 0,this.subtle=e,this.key=t,this.aesMode=n}expandKey(){let e=Va(this.aesMode);return this.subtle.importKey(`raw`,this.key,{name:e},!1,[`encrypt`,`decrypt`])}};function Va(e){switch(e){case Ia.cbc:return`AES-CBC`;case Ia.ctr:return`AES-CTR`;default:throw Error(`[FastAESKey] invalid aes mode ${e}`)}}var Ha=16,Ua=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 e=self.crypto;e&&(this.subtle=e.subtle||e.webkitSubtle)}catch{}this.useSoftware=!this.subtle}destroy(){this.subtle=null,this.softwareDecrypter=null,this.key=null,this.fastAesKey=null,this.remainderData=null,this.currentIV=null,this.currentResult=null}isSync(){return this.useSoftware}flush(){let{currentResult:e,remainderData:t}=this;if(!e||t)return this.reset(),null;let n=new Uint8Array(e);this.reset();let r=this.decryptRange;return r?r.start===0&&r.end>=n.length?n:n.slice(r.start,r.end):Ra(n)}reset(){this.currentResult=null,this.currentIV=null,this.remainderData=null,this.softwareDecrypter&&=null}decrypt(e,t,n,r,i){return this.decryptRange=i,this.useSoftware||i?new Promise((i,a)=>{let o=ArrayBuffer.isView(e)?e:new Uint8Array(e);this.softwareDecrypt(o,t,n,r);let s=this.flush();s?i(s.buffer):a(Error(`[softwareDecrypt] Failed to decrypt data`))}):this.webCryptoDecrypt(new Uint8Array(e),t,n,r)}softwareDecrypt(e,t,n,r){let{currentIV:i,currentResult:a,remainderData:o}=this;if(r!==Ia.cbc||t.byteLength!==16)return U.warn(`SoftwareDecrypt: can only handle AES-128-CBC`),null;this.logOnce(`JS AES decrypt`),o&&(e=Tr(o,e),this.remainderData=null);let s=this.getValidChunk(e);if(!s.length)return null;i&&(n=i);let c=this.softwareDecrypter;c||=this.softwareDecrypter=new za,c.expandKey(t);let l=a;return this.currentResult=c.decrypt(s.buffer,0,n),this.currentIV=s.slice(-16).buffer,l||null}webCryptoDecrypt(e,t,n,r){if(this.key!==t||!this.fastAesKey){if(!this.subtle)return Promise.resolve(this.onWebCryptoError(e,t,n,r));this.key=t,this.fastAesKey=new Ba(this.subtle,t,r)}return this.fastAesKey.expandKey().then(t=>this.subtle?(this.logOnce(`WebCrypto AES decrypt`),new La(this.subtle,new Uint8Array(n),r).decrypt(e.buffer,t)):Promise.reject(Error(`web crypto not initialized`))).catch(i=>(U.warn(`[decrypter]: WebCrypto Error, disable WebCrypto API, ${i.name}: ${i.message}`),this.onWebCryptoError(e,t,n,r)))}onWebCryptoError(e,t,n,r){let i=this.enableSoftwareAES;if(i){this.useSoftware=!0,this.logEnabled=!0,this.softwareDecrypt(e,t,n,r);let i=this.flush();if(i)return i.buffer}throw Error(`WebCrypto`+(i?` and softwareDecrypt`:``)+`: failed to decrypt data`)}getValidChunk(e){let t=e,n=e.length-e.length%Ha;return n!==e.length&&(t=e.slice(0,n),this.remainderData=e.slice(n)),t}logOnce(e){this.logEnabled&&=(U.log(`[decrypter]: ${e}`),!1)}},Wa=2**17,Ga=class{constructor(e){this.config=void 0,this.loader=null,this.partLoadTimeout=-1,this.config=e}destroy(){this.loader&&=(this.loader.destroy(),null)}abort(){this.loader&&this.loader.abort()}load(e,t,n,r){let i=e.url;if(!i)return Promise.reject(new Xa({type:F.NETWORK_ERROR,details:I.FRAG_LOAD_ERROR,fatal:!1,frag:e,error:Error(`Fragment does not have a ${i?`part list`:`url`}`),networkDetails:null}));this.abort();let a=this.config,o=a.fLoader,s=a.loader;return new Promise((c,l)=>{if(this.loader&&this.loader.destroy(),e.gap){if(e.tagList.some(e=>e[0]===`GAP`)){l(Ja(e));return}e.gap=!1}let u=this.loader=o?new o(a):new s(a),d=Ka(e,null,t);e.loader=u;let f=Ut(a.fragLoadPolicy.default),p={loadPolicy:f,timeout:f.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:e.sn===`initSegment`?1/0:Wa};u.stats.retry=e.stats.retry,e.stats=u.stats;let m={onSuccess:(t,n,r,i)=>{this.resetLoader(e,u);let a=t.data;r.resetIV&&e.decryptdata&&(e.decryptdata.iv=new Uint8Array(a.slice(0,16)),a=a.slice(16)),c({frag:e,part:null,payload:a,networkDetails:i})},onError:(t,n,r,a)=>{this.resetLoader(e,u),l(new Xa({type:F.NETWORK_ERROR,details:I.FRAG_LOAD_ERROR,fatal:!1,frag:e,response:H({url:i,data:void 0},t),error:Error(`HTTP Error ${t.code} ${t.text}`),networkDetails:r,stats:a}))},onAbort:(t,n,r)=>{this.resetLoader(e,u),l(new Xa({type:F.NETWORK_ERROR,details:I.INTERNAL_ABORTED,fatal:!1,frag:e,error:Error(`Aborted`),networkDetails:r,stats:t}))},onTimeout:(t,n,r)=>{this.resetLoader(e,u),l(new Xa({type:F.NETWORK_ERROR,details:I.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,error:Error(`Timeout after ${p.timeout}ms`),networkDetails:r,stats:t}))}};if(n){let t=this.gateProgress(n,r);m.onProgress=(n,r,i,a)=>t({frag:e,part:null,payload:i,networkDetails:a})}u.load(d,p,m)})}gateProgress(e,t){let n=e;if(t){let r=[],i=!1;t.then(()=>{i=!0,r.forEach(t=>e(t)),r.length=0}).catch(()=>{}),n=t=>{i?e(t):r.push(t)}}return n}loadPart(e,t,n){this.abort();let r=this.config,i=r.fLoader,a=r.loader;return new Promise((o,s)=>{if(this.loader&&this.loader.destroy(),e.gap||t.gap){s(Ja(e,t));return}let c=this.loader=i?new i(r):new a(r),l=Ka(e,t);e.loader=c;let u=Ut(r.fragLoadPolicy.default),d={loadPolicy:u,timeout:u.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:Wa};t.stats=c.stats,c.load(l,d,{onSuccess:(r,i,a,s)=>{this.resetLoader(e,c),this.updateStatsFromPart(e,t);let l={frag:e,part:t,payload:r.data,networkDetails:s};n(l),o(l)},onError:(n,r,i,a)=>{this.resetLoader(e,c),s(new Xa({type:F.NETWORK_ERROR,details:I.FRAG_LOAD_ERROR,fatal:!1,frag:e,part:t,response:H({url:l.url,data:void 0},n),error:Error(`HTTP Error ${n.code} ${n.text}`),networkDetails:i,stats:a}))},onAbort:(n,r,i)=>{e.stats.aborted=t.stats.aborted,this.resetLoader(e,c),s(new Xa({type:F.NETWORK_ERROR,details:I.INTERNAL_ABORTED,fatal:!1,frag:e,part:t,error:Error(`Aborted`),networkDetails:i,stats:n}))},onTimeout:(n,r,i)=>{this.resetLoader(e,c),s(new Xa({type:F.NETWORK_ERROR,details:I.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,part:t,error:Error(`Timeout after ${d.timeout}ms`),networkDetails:i,stats:n}))}})})}updateStatsFromPart(e,t){let n=e.stats,r=t.stats,i=r.total;if(n.loaded+=r.loaded,i){let r=Math.round(e.duration/t.duration),a=Math.min(Math.round(n.loaded/i),r),o=(r-a)*Math.round(n.loaded/a);n.total=n.loaded+o}else n.total=Math.max(n.loaded,n.total);let a=n.loading,o=r.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 Ka(e,t=null,n){let r=t||e,i={type:R.MEDIA_FRAGMENT,frag:e,part:t,responseType:`arraybuffer`,url:r.url,headers:{},rangeStart:0,rangeEnd:0},a=qa(e,t,n);return a.resetIV&&(i.resetIV=!0),a.byteRange&&(i.rangeStart=a.byteRange.start,i.rangeEnd=a.byteRange.end),i}function qa(e,t=null,n){let r={},i=t||e,a=i.byteRangeStartOffset,o=i.byteRangeEndOffset;if(P(a)&&P(o)){if((e.sn===`initSegment`||n)&&Ya(e.decryptdata?.method)){let e=Math.floor(a/16)*16,t=Math.ceil(o/16)*16;r.decryptRange={start:a-e,end:o-e},e>=16&&(r.resetIV=!0,e-=16),r.byteRange={start:e,end:t}}else r.byteRange={start:a,end:o}}return r}function Ja(e,t){let n=Error(`GAP ${e.gap?`tag`:`attribute`} found`),r={type:F.MEDIA_ERROR,details:I.FRAG_GAP,fatal:!1,frag:e,error:n,networkDetails:null};return t&&(r.part=t),(t||e).stats.aborted=!0,new Xa(r)}function Ya(e){return e===`AES-128`||e===`AES-256`}var Xa=class extends Error{constructor(e){super(e.error.message),this.data=void 0,this.data=e}},Za=class extends Xt{constructor(e,t){super(e,t),this._boundTick=void 0,this._tickTimer=null,this._tickInterval=null,this._tickCallCount=0,this._boundTick=this.tick.bind(this)}destroy(){this.onHandlerDestroying(),this.onHandlerDestroyed()}onHandlerDestroying(){this.clearNextTick(),this.clearInterval()}onHandlerDestroyed(){}hasInterval(){return!!this._tickInterval}hasNextTick(){return!!this._tickTimer}setInterval(e){return!this._tickInterval&&(this._tickCallCount=0,this._tickInterval=self.setInterval(this._boundTick,e),!0)}clearInterval(){return this._tickInterval?(self.clearInterval(this._tickInterval),this._tickInterval=null,!0):!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(){}},Qa=class{constructor(e,t,n,r=0,i=-1,a=!1,o,s,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=$a(),this.buffering={audio:$a(),video:$a(),audiovideo:$a()},this.level=e,this.sn=t,this.id=n,this.size=r,this.part=i,this.partial=a,this.duration=o||0,this.decryptRange=c,this.iframe=s||!1}};function $a(){return{start:0,executeStart:0,executeEnd:0,end:0}}var eo=/\{\$([a-zA-Z0-9-_]+)\}/g;function to(e){return eo.lastIndex=0,eo.test(e)}function no(e,t){if(e.variableList!==null||e.hasVariableRefs){let n=e.variableList;return t.replace(eo,t=>{let r=t.substring(2,t.length-1),i=n?.[r];return i===void 0?(e.playlistParsingError||=Error(`Missing preceding EXT-X-DEFINE tag for Variable Reference: "${r}"`),t):i})}return t}function ro(e,t,n){let r=e.variableList;r||(e.variableList=r={});let i,a;if(`QUERYPARAM`in t){i=t.QUERYPARAM;try{let e=new self.URL(n).searchParams;if(e.has(i))a=e.get(i);else throw Error(`"${i}" does not match any query parameter in URI: "${n}"`)}catch(t){e.playlistParsingError||=Error(`EXT-X-DEFINE QUERYPARAM: ${t.message}`)}}else i=t.NAME,a=t.VALUE;i in r?e.playlistParsingError||=Error(`EXT-X-DEFINE duplicate Variable Name declarations: "${i}"`):r[i]=a||``}function io(e,t,n){let r=t.IMPORT;if(n&&r in n){let t=e.variableList;t||(e.variableList=t={}),t[r]=n[r]}else e.playlistParsingError||=Error(`EXT-X-DEFINE IMPORT attribute not found in Multivariant Playlist: "${r}"`)}var ao=/^(\d+)x(\d+)$/,oo=/(.+?)=(".*?"|.*?)(?:,|$)/g,so=class e{constructor(t,n){typeof t==`string`&&(t=e.parseAttrList(t,n)),V(this,t)}get clientAttrs(){return Object.keys(this).filter(e=>e.substring(0,2)===`X-`)}decimalInteger(e){let t=parseInt(this[e],10);return t>2**53-1?1/0:t}hexadecimalInteger(e){if(this[e]){let t=(this[e]||`0x`).slice(2);t=(t.length&1?`0`:``)+t;let n=new Uint8Array(t.length/2);for(let e=0;e<t.length/2;e++)n[e]=parseInt(t.slice(e*2,e*2+2),16);return n}return null}hexadecimalIntegerAsNumber(e){let t=parseInt(this[e],16);return t>2**53-1?1/0:t}decimalFloatingPoint(e){return parseFloat(this[e])}optionalFloat(e,t){let n=this[e];return n?parseFloat(n):t}enumeratedString(e){return this[e]}enumeratedStringList(e,t){let n=this[e];return(n?n.split(/[ ,]+/):[]).reduce((e,t)=>(e[t.toLowerCase()]=!0,e),t)}bool(e){return this[e]===`YES`}decimalResolution(e){let t=ao.exec(this[e]);if(t!==null)return{width:parseInt(t[1],10),height:parseInt(t[2],10)}}static parseAttrList(e,t){let n,r={};for(oo.lastIndex=0;(n=oo.exec(e))!==null;){let i=n[1].trim(),a=n[2],o=a.indexOf(`"`)===0&&a.lastIndexOf(`"`)===a.length-1,s=!1;if(o)a=a.slice(1,-1);else switch(i){case`IV`:case`SCTE35-CMD`:case`SCTE35-IN`:case`SCTE35-OUT`:s=!0}if(t&&(o||s))a=no(t,a);else if(!s&&!o)switch(i){case`CLOSED-CAPTIONS`:if(a===`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`:U.warn(`${e}: attribute ${i} is missing quotes`)}r[i]=a}return r}},co=`com.apple.hls.interstitial`;function lo(e){return e!==`ID`&&e!==`CLASS`&&e!==`CUE`&&e!==`START-DATE`&&e!==`DURATION`&&e!==`END-DATE`&&e!==`END-ON-NEXT`}function uo(e){return e===`SCTE35-OUT`||e===`SCTE35-IN`||e===`SCTE35-CMD`}var fo=class{constructor(e,t,n=0){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=t?.tagOrder??n,t){let n=t.attr;for(let t in n)if(Object.prototype.hasOwnProperty.call(e,t)&&e[t]!==n[t]){U.warn(`DATERANGE tag attribute: "${t}" does not match for tags with ID: "${e.ID}"`),this._badValueForSameId=t;break}e=V(new so({}),n,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 n=t?.endDate||new Date(e[`END-DATE`]);P(n.getTime())&&(this._endDate=n)}}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?(U.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?null:this._dateAtEnd=new Date(this._startDate.getTime()+t*1e3)}get duration(){if(`DURATION`in this.attr){let e=this.attr.decimalFloatingPoint(`DURATION`);if(P(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===co}get isValid(){return!!this.id&&!this._badValueForSameId&&P(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`:P(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 po(e,t){return e.length===t.length&&!e.some((e,n)=>e!==t[n])}function mo(e,t){return!e&&!t?!0:!e||!t?!1:po(e,t)}function ho(e){return e===`AES-128`||e===`AES-256`||e===`AES-256-CTR`}function go(e){switch(e){case`AES-128`:case`AES-256`:return Ia.cbc;case`AES-256-CTR`:return Ia.ctr;default:throw Error(`invalid full segment method ${e}`)}}function _o(e){return Uint8Array.from(unescape(encodeURIComponent(e)),e=>e.charCodeAt(0))}function vo(e){let t=_o(e).subarray(0,16),n=new Uint8Array(16);return n.set(t,16-t.length),n}function yo(e){let t=function(e,t,n){let r=e[t];e[t]=e[n],e[n]=r};t(e,0,3),t(e,1,2),t(e,4,5),t(e,6,7)}function bo(e){let t=e.split(`:`),n=null;if(t[0]===`data`&&t.length===2){let e=t[1].split(`;`),r=e[e.length-1].split(`,`);if(r.length===2){let t=r[0]===`base64`,i=r[1];t?(e.splice(-1,1),n=Wn(i)):n=vo(i)}}return n}var xo=typeof self<`u`?self:void 0,Q={CLEARKEY:`org.w3.clearkey`,FAIRPLAY:`com.apple.fps`,PLAYREADY:`com.microsoft.playready`,WIDEVINE:`com.widevine.alpha`},So={CLEARKEY:`org.w3.clearkey`,FAIRPLAY:`com.apple.streamingkeydelivery`,PLAYREADY:`com.microsoft.playready`,WIDEVINE:`urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed`};function Co(e){switch(e){case So.FAIRPLAY:return Q.FAIRPLAY;case So.PLAYREADY:return Q.PLAYREADY;case So.WIDEVINE:return Q.WIDEVINE;case So.CLEARKEY:return Q.CLEARKEY}}var wo={WIDEVINE:`edef8ba979d64acea3c827dcd51d21ed`};function To(e){switch(e){case Q.FAIRPLAY:return So.FAIRPLAY;case Q.PLAYREADY:return So.PLAYREADY;case Q.WIDEVINE:return So.WIDEVINE;case Q.CLEARKEY:return So.CLEARKEY}}function Eo(e){let{drmSystems:t,widevineLicenseUrl:n}=e,r=t?[Q.FAIRPLAY,Q.WIDEVINE,Q.PLAYREADY,Q.CLEARKEY].filter(e=>!!t[e]):[];return!r[Q.WIDEVINE]&&n&&r.push(Q.WIDEVINE),r}var Do=function(e){return xo!=null&&(e=xo.navigator)!=null&&e.requestMediaKeySystemAccess?self.navigator.requestMediaKeySystemAccess.bind(self.navigator):null}();function Oo(e,t,n,r){let i;switch(e){case Q.FAIRPLAY:i=[`cenc`,`sinf`];break;case Q.WIDEVINE:case Q.PLAYREADY:i=[`cenc`];break;case Q.CLEARKEY:i=[`cenc`,`keyids`];break;default:throw Error(`Unknown key-system: ${e}`)}return ko(i,t,n,r)}function ko(e,t,n,r){return[{initDataTypes:e,persistentState:r.persistentState||`optional`,distinctiveIdentifier:r.distinctiveIdentifier||`optional`,sessionTypes:r.sessionTypes||[r.sessionType||`temporary`],audioCapabilities:t.map(e=>({contentType:`audio/mp4; codecs=${e}`,robustness:r.audioRobustness||``,encryptionScheme:r.audioEncryptionScheme||null})),videoCapabilities:n.map(e=>({contentType:`video/mp4; codecs=${e}`,robustness:r.videoRobustness||``,encryptionScheme:r.videoEncryptionScheme||null}))}]}function Ao(e){var t;return!!e&&(e.sessionType===`persistent-license`||!!((t=e.sessionTypes)!=null&&t.some(e=>e===`persistent-license`)))}function jo(e){let t=Gn(new Uint16Array(e.buffer,e.byteOffset,e.byteLength/2)),n=t.substring(t.indexOf(`<`),t.length),r=new DOMParser().parseFromString(n,`text/xml`).getElementsByTagName(`KID`)[0];if(r){let e=r.childNodes[0]?r.childNodes[0].nodeValue:r.getAttribute(`VALUE`);if(e){let t=Wn(e).subarray(0,16);return yo(t),t}}return null}var Mo={},No=class e{static clearKeyUriToKeyIdMap(){Mo={}}static setKeyIdForUri(e,t){Mo[e]=t}static addKeyIdForUri(e){let t=Object.keys(Mo).length%(2**53-1),n=new Uint8Array(16);return new DataView(n.buffer,12,4).setUint32(0,t),Mo[e]=n,n}constructor(e,t,n,r=[1],i=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=n,this.keyFormatVersions=r,this.iv=i,this.encrypted=e?e!==`NONE`:!1,this.isCommonEncryption=this.encrypted&&!ho(e),a!=null&&a.startsWith(`0x`)&&(this.keyId=new Uint8Array(Un(a)))}matches(e){return e.uri===this.uri&&e.method===this.method&&e.encrypted===this.encrypted&&e.keyFormat===this.keyFormat&&po(e.keyFormatVersions,this.keyFormatVersions)&&mo(e.iv,this.iv)&&mo(e.keyId,this.keyId)}isSupported(){if(this.method){if(ho(this.method)||this.method===`NONE`)return!0;if(this.keyFormat===`identity`)return this.method===`SAMPLE-AES`;switch(this.keyFormat){case So.FAIRPLAY:case So.WIDEVINE:case So.PLAYREADY:case So.CLEARKEY:return[`SAMPLE-AES`,`SAMPLE-AES-CENC`,`SAMPLE-AES-CTR`].indexOf(this.method)!==-1}}return!1}getDecryptData(t,n){if(!this.encrypted||!this.uri)return null;if(ho(this.method)){let n=this.iv;return n||=(typeof t!=`number`&&(U.warn(`missing IV for initialization segment with method="${this.method}" - compliance issue`),t=0),Io(t)),new e(this.method,this.uri,`identity`,this.keyFormatVersions,n)}if(this.keyId){let t=Mo[this.uri];if(t&&!po(this.keyId,t)&&e.setKeyIdForUri(this.uri,this.keyId),this.pssh)return this}let r=bo(this.uri);if(r)switch(this.keyFormat){case So.WIDEVINE:if(this.pssh=r,!this.keyId){let e=Pr(r.buffer).filter(e=>e.systemId===wo.WIDEVINE);if(e.length){var i;let t=e[0];this.keyId=(i=t.kids)!=null&&i.length?t.kids[0]:null}}this.keyId||=Fo(n);break;case So.PLAYREADY:{let e=new Uint8Array([154,4,240,121,152,64,66,134,171,146,230,91,224,136,95,149]);this.pssh=Nr(e,null,r),this.keyId=jo(r);break}default:{let e=r.subarray(0,16);if(e.length!==16){let t=new Uint8Array(16);t.set(e,16-e.length),e=t}this.keyId=e;break}}if(this.keyId?.byteLength!==16){let t;t=Po(n),t||(t=Fo(n),t||=Mo[this.uri]),t&&(this.keyId=t,e.setKeyIdForUri(this.uri,t))}return this}};function Po(e){let t=e?.[So.WIDEVINE];return t?t.keyId:null}function Fo(e){let t=e?.[So.PLAYREADY];if(t){let e=bo(t.uri);if(e)return jo(e)}return null}function Io(e){let t=new Uint8Array(16);for(let n=12;n<16;n++)t[n]=e>>8*(15-n)&255;return t}var Lo=/#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,Ro=/#EXT-X-MEDIA:(.*)/g,zo=/^#EXT(?:INF|-X-TARGETDURATION):/m,Bo=new RegExp([`#EXTINF:\\s*(\\d+(?:\\.\\d*)?|\\.\\d+)?(?:,(.*)\\s+)?`,`(?!#) *(\\S[^\\r\\n]*)`,`#.*`].join(`|`),`g`),Vo=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):(.+)`,`#EXT-X-(BITRATE|DISCONTINUITY-SEQUENCE|MEDIA-SEQUENCE|TARGETDURATION|VERSION): *(\\d+)`,`#EXT-X-(DISCONTINUITY|ENDLIST|GAP|INDEPENDENT-SEGMENTS|I-FRAMES-ONLY)`,`(#)([^:]*):(.*)`,`(#)(.*)(?:.*)\\r?\\n?`].join(`|`)),Ho=class e{static findGroup(e,t){for(let n=0;n<e.length;n++){let r=e[n];if(r.id===t)return r}}static resolve(e,t){return St.buildAbsoluteURL(t,e,{alwaysNormalize:!0})}static isMediaPlaylist(e){return zo.test(e)}static parseMasterPlaylist(t,n){let r={contentSteering:null,levels:[],iframeVariants:[],playlistParsingError:null,sessionData:null,sessionKeys:null,startTimeOffset:null,variableList:null,hasVariableRefs:to(t)},i=[];if(Lo.lastIndex=0,!t.startsWith(`#EXTM3U`))return r.playlistParsingError=Error(`no EXTM3U delimiter`),r;let a;for(;(a=Lo.exec(t))!=null;)if(a[1]){let e=Uo(new so(a[1],r),a[2],n,r,i);e&&r.levels.push(e)}else if(a[3]){let t=a[3],o=a[4];switch(t){case`I-FRAME-STREAM-INF`:{let e=new so(o,r),t=Uo(e,e.URI,n,r,i,!0);t&&r.iframeVariants.push(t)}break;case`SESSION-DATA`:{let e=new so(o,r),t=e[`DATA-ID`];t&&(r.sessionData===null&&(r.sessionData={}),r.sessionData[t]=e);break}case`SESSION-KEY`:{let e=Ko(o,n,r);e.encrypted&&e.isSupported()?(r.sessionKeys===null&&(r.sessionKeys=[]),r.sessionKeys.push(e)):U.warn(`[Keys] Ignoring invalid EXT-X-SESSION-KEY tag: "${o}"`);break}case`DEFINE`:ro(r,new so(o,r),n);break;case`CONTENT-STEERING`:{let t=new so(o,r);r.contentSteering={uri:e.resolve(t[`SERVER-URI`],n),pathwayId:t[`PATHWAY-ID`]||`.`};break}case`START`:r.startTimeOffset=qo(o)}}return r.levels=i.length>0&&i.length<r.levels.length?i:r.levels,r.levels.length===0&&(r.playlistParsingError=Error(`no levels found in manifest`)),r}static parseMasterPlaylistMedia(t,n,r){let i,a={},o=r.levels,s={AUDIO:o.map(e=>({id:e.attrs.AUDIO,audioCodec:e.audioCodec})),SUBTITLES:o.map(e=>({id:e.attrs.SUBTITLES,textCodec:e.textCodec})),"CLOSED-CAPTIONS":[]},c=0;for(Ro.lastIndex=0;(i=Ro.exec(t))!==null;){let t=new so(i[1],r),o=t.TYPE;if(o){let r=s[o],i=a[o]||[];a[o]=i;let l=t.LANGUAGE,u=t[`ASSOC-LANGUAGE`],d=t.CHANNELS,f=t.CHARACTERISTICS,p=t[`INSTREAM-ID`],m={attrs:t,bitrate:0,id:c++,groupId:t[`GROUP-ID`]||``,name:t.NAME||l||``,type:o,default:t.bool(`DEFAULT`),autoselect:t.bool(`AUTOSELECT`),forced:t.bool(`FORCED`),lang:l,url:t.URI?e.resolve(t.URI,n):``};if(u&&(m.assocLang=u),d&&(m.channels=d),f&&(m.characteristics=f),p&&(m.instreamId=p),r!=null&&r.length){let t=e.findGroup(r,m.groupId)||r[0];Yo(m,t,`audioCodec`),Yo(m,t,`textCodec`)}i.push(m)}}return a}static parseLevelPlaylist(e,t,n,r,i,a){let o={url:t},s=new ha(t),c=s.fragments,l=[],u=null,d=0,f=0,p=0,m=0,h=0,g=null,_=new Ot(r,o),v,y,b,x=-1,S=!1,C=null,w;if(Bo.lastIndex=0,s.m3u8=e,s.hasVariableRefs=to(e),Bo.exec(e)?.[0]!==`#EXTM3U`)return s.playlistParsingError=Error(`Missing format identifier #EXTM3U`),s;for(;(v=Bo.exec(e))!==null;){S&&(S=!1,_=new Ot(r,o),_.playlistOffset=p,_.setStart(p),_.sn=d,_.cc=m,h&&(_.bitrate=h),_.level=n,u&&(_.initSegment=u,u.rawProgramDateTime&&(_.rawProgramDateTime=u.rawProgramDateTime,u.rawProgramDateTime=null),C&&=(_.setByteRange(C),null)));let e=v[1];if(e){_.duration=parseFloat(e);let t=(` `+v[2]).slice(1);_.title=t||null,_.tagList.push(t?[`INF`,e,t]:[`INF`,e])}else if(v[3]){if(P(_.duration)){_.playlistOffset=p,_.setStart(p),b&&$o(_,b,s),_.sn=d,_.level=n,_.cc=m;let e=(` `+v[3]).slice(1);_.relurl=no(s,e),Zo(_,g,l),g=_,p+=_.duration,d++,f=0;let t=_.byteRange;if(t.length===2&&(_.bitrate=(t[1]-t[0])*8/_.duration|0),s.iframesOnly&&t[0]&&u?.cc!==m){let e=new Ot(r,o);e.relurl=_.relurl,e.setByteRange(`${Math.min(t[0],1316)}@0`),e.level=n,e.sn=`initSegment`,b&&(e.levelkeys=b,b.identity&&(e._decryptdata=b.identity.getDecryptData(0))),u=e,_.initSegment=u}c.push(_),S=!0}}else{if(v=v[0].match(Vo),!v){U.warn(`No matches on slow regex match for level playlist!`);continue}for(y=1;y<v.length&&v[y]===void 0;y++);let e=(` `+v[y]).slice(1),i=(` `+v[y+1]).slice(1),l=v[y+2]?(` `+v[y+2]).slice(1):null;switch(e){case`BYTERANGE`:g?_.setByteRange(i,g):_.setByteRange(i);break;case`PROGRAM-DATE-TIME`:_.rawProgramDateTime=i,_.tagList.push([`PROGRAM-DATE-TIME`,i]),x===-1&&(x=c.length);break;case`PLAYLIST-TYPE`:s.type&&es(s,e,v),s.type=i.toUpperCase();break;case`MEDIA-SEQUENCE`:s.startSN===0?g!==null&&ts(s,e,v):es(s,e,v),s.startSN=parseInt(i),d=s.startSN+s.skippedSegments;break;case`SKIP`:{s.skippedSegments&&es(s,e,v);let t=new so(i,s),n=t.decimalInteger(`SKIPPED-SEGMENTS`);if(P(n)){s.skippedSegments+=n;for(let e=n;e--;)c.push(null);d+=n}let r=t.enumeratedString(`RECENTLY-REMOVED-DATERANGES`);r&&(s.recentlyRemovedDateranges=(s.recentlyRemovedDateranges||[]).concat(r.split(` `)));break}case`TARGETDURATION`:s.targetduration!==0&&es(s,e,v),s.targetduration=Math.max(parseInt(i),1);break;case`VERSION`:s.version!==null&&es(s,e,v),s.version=parseInt(i);break;case`INDEPENDENT-SEGMENTS`:break;case`I-FRAMES-ONLY`:s.iframesOnly=!0;break;case`ENDLIST`:s.live||es(s,e,v),s.live=!1;break;case`#`:(i||l)&&_.tagList.push(l?[i,l]:[i]);break;case`DISCONTINUITY`:m++,_.tagList.push([`DIS`]);break;case`GAP`:_.gap=!0,_.tagList.push([e]);break;case`BITRATE`:_.tagList.push([e,i]),h=parseInt(i)*1e3,P(h)?_.bitrate=h:h=0;break;case`DATERANGE`:{let e=new so(i,s),t=new fo(e,s.dateRanges[e.ID],s.dateRangeTagCount);s.dateRangeTagCount++,t.isValid||s.skippedSegments?s.dateRanges[t.id]=t:U.log(`Ignoring invalid DATERANGE tag: ${t.invalidReason}: ${i}`),_.tagList.push([`EXT-X-DATERANGE`,i]);break}case`DEFINE`:{let e=new so(i,s);`IMPORT`in e?io(s,e,a):ro(s,e,t)}break;case`DISCONTINUITY-SEQUENCE`:s.startCC!==0&&es(s,e,v),s.startCC=m=parseInt(i),c.forEach(e=>e&&(e.cc=m));break;case`KEY`:{let e=Ko(i,t,s);if(e.isSupported()){if(e.method===`NONE`){b=void 0;break}b||={};let t=b[e.keyFormat];t!=null&&t.matches(e)||(t&&(b=V({},b)),b[e.keyFormat]=e)}else U.warn(`[Keys] Ignoring unsupported EXT-X-KEY tag: "${i}"`);break}case`START`:s.startTimeOffset=qo(i);break;case`MAP`:{let e=new so(i,s);if(_.duration){let t=new Ot(r,o);Qo(t,e,n,b),u=t,_.initSegment=u,u.rawProgramDateTime&&!_.rawProgramDateTime&&(_.rawProgramDateTime=u.rawProgramDateTime)}else{let t=_.byteRangeEndOffset;if(t){let e=_.byteRangeStartOffset;C=`${t-e}@${e}`}else C=null;Qo(_,e,n,b),u=_,S=!0}u.cc=m;break}case`SERVER-CONTROL`:w&&es(s,e,v),w=new so(i),s.canBlockReload=w.bool(`CAN-BLOCK-RELOAD`),s.canSkipUntil=w.optionalFloat(`CAN-SKIP-UNTIL`,0),s.canSkipDateRanges=s.canSkipUntil>0&&w.bool(`CAN-SKIP-DATERANGES`),s.partHoldBack=w.optionalFloat(`PART-HOLD-BACK`,0),s.holdBack=w.optionalFloat(`HOLD-BACK`,0);break;case`PART-INF`:s.partTarget&&es(s,e,v),s.partTarget=new so(i).decimalFloatingPoint(`PART-TARGET`);break;case`PART`:{let e=s.partList;e||=s.partList=[];let t=f>0?e[e.length-1]:void 0,n=f++,r=new kt(new so(i,s),_,o,n,t);e.push(r),_.duration+=r.duration;break}case`PRELOAD-HINT`:s.preloadHint=new so(i,s);break;case`RENDITION-REPORT`:{let e=new so(i,s);s.renditionReports=s.renditionReports||[],s.renditionReports.push(e);break}default:U.warn(`line parsed but not handled: ${v}`)}}}g&&!g.relurl?(c.pop(),p-=g.duration,s.partList&&(s.fragmentHint=g)):s.partList&&(Zo(_,g,l),_.cc=m,s.fragmentHint=_,b&&$o(_,b,s)),s.targetduration||(s.playlistParsingError=Error(`Missing Target Duration`));let T=c.length,E=c[0],D=c[T-1];if(p+=s.skippedSegments*s.targetduration,p>0&&T&&D){s.averagetargetduration=p/T;let e=D.sn;s.endSN=e===`initSegment`?0:e,s.live||(D.endList=!0),x>0&&(Xo(c,x,x>T-1?_:null),E&&l.unshift(E))}return s.fragmentHint&&(p+=s.fragmentHint.duration),s.totalduration=p,l.length&&s.dateRangeTagCount&&E&&Wo(l,s),s.endCC=m,s}};function Uo(e,t,n,r,i,a){var o;if(t===void 0)return null;let s=no(r,t),c={attrs:e,bitrate:e.decimalInteger(`BANDWIDTH`)||e.decimalInteger(`AVERAGE-BANDWIDTH`),name:e.NAME,url:Ho.resolve(s,n)},l=e.decimalResolution(`RESOLUTION`);l&&(c.width=l.width,c.height=l.height),Jo(e.CODECS,c);let u=e[`SUPPLEMENTAL-CODECS`];return u&&(c.supplemental={},Jo(u,c.supplemental)),(o=c.unknownCodecs)!=null&&o.length||i.push(c),a&&(c.iframes=!0),c}function Wo(e,t){let n=e.length;if(!n){if(t.hasProgramDateTime){let r=t.fragments[t.fragments.length-1];e.push(r),n++}else return}let r=e[n-1],i=t.live?1/0:t.totalduration,a=Object.keys(t.dateRanges);for(let o=a.length;o--;){let s=t.dateRanges[a[o]],c=s.startDate.getTime();s.tagAnchor=r.ref;for(let r=n;r--&&!(e[r]?.sn<t.startSN);){let n=Go(t,c,e,r,i);if(n){s.tagAnchor=n.ref;break}}}}function Go(e,t,n,r,i){let a=n[r];if(a){let o=a.programDateTime;if((t>=o||r===0)&&t<=o+((n[r+1]?.start||i)-a.start)*1e3){let i=a.sn-e.startSN,o=e.fragments;if(i>=0&&i<o.length){if(o.length>n.length){let a=n[r+1]||o[o.length-1],s=Math.min(a.sn-e.startSN,o.length-1);for(let e=s;e>i;e--){let n=o[e].programDateTime;if(t>=n&&t<n+o[e].duration*1e3)return o[e]}}return o[i]}}}return null}function Ko(e,t,n){let r=new so(e,n),i=r.METHOD??``,a=r.URI,o=r.hexadecimalInteger(`IV`),s=r.KEYFORMATVERSIONS,c=r.KEYFORMAT??`identity`;return a&&r.IV&&!o&&U.error(`Invalid IV: ${r.IV}`),new No(i,a?Ho.resolve(a,t):``,c,(s||`1`).split(`/`).map(Number).filter(Number.isFinite),o,r.KEYID)}function qo(e){let t=new so(e).decimalFloatingPoint(`TIME-OFFSET`);return P(t)?t:null}function Jo(e,t){let n=(e||``).split(/[ ,]+/).filter(e=>e);[`video`,`audio`,`text`,`image`].forEach(e=>{let r=n.filter(t=>Xr(t,e));r.length&&(t[`${e}Codec`]=r.map(e=>e.split(`/`)[0]).join(`,`),n=n.filter(e=>r.indexOf(e)===-1))}),t.unknownCodecs=n}function Yo(e,t,n){let r=t[n];r&&(e[n]=r)}function Xo(e,t,n){if(n||=e[t],n)for(let r=t;r--;){let t=e[r];if(!t)return;t.programDateTime=n.programDateTime-t.duration*1e3,n=t}}function Zo(e,t,n){e.rawProgramDateTime?n.push(e):t!=null&&t.programDateTime&&(e.programDateTime=t.endProgramDateTime)}function Qo(e,t,n,r){e.relurl=t.URI,t.BYTERANGE&&e.setByteRange(t.BYTERANGE),e.level=n,e.sn=`initSegment`,r&&(e.levelkeys=r),e.initSegment=null}function $o(e,t,n){e.levelkeys=t;let{encryptedFragments:r}=n;(!r.length||r[r.length-1].levelkeys!==t)&&Object.keys(t).some(e=>t[e].isCommonEncryption)&&r.push(e)}function es(e,t,n){e.playlistParsingError=Error(`#EXT-X-${t} must not appear more than once (${n[0]})`)}function ts(e,t,n){e.playlistParsingError=Error(`#EXT-X-${t} must appear before the first Media Segment (${n[0]})`)}function ns(e,t){let n=t.startPTS;if(P(n)){let r=0,i;t.sn>e.sn?(r=n-e.start,i=e):(r=e.start-n,i=t),i.duration!==r&&i.setDuration(r)}else t.sn>e.sn?e.cc===t.cc&&e.minEndPTS?t.setStart(e.start+(e.minEndPTS-e.start)):t.setStart(e.start+e.duration):t.setStart(Math.max(e.start-t.duration,0))}function rs(e,t,n,r,i,a,o,s){r-n<=0&&(s.warn(`Fragment should have a positive duration`,t),r=n+t.duration,a=i+t.duration);let c=n,l=r,u=t.startPTS,d=t.endPTS;if(P(u)){let o=Math.abs(u-n);e&&o>e.totalduration?s.warn(`media timestamps and playlist times differ by ${o}s for level ${t.level} ${e.url}`):t.deltaPTS=P(t.deltaPTS)?Math.max(o,t.deltaPTS):o,c=Math.max(n,u),n=Math.min(n,u),i=t.startDTS===void 0?i:Math.min(i,t.startDTS),l=Math.min(r,d),r=Math.max(r,d),a=t.endDTS===void 0?a:Math.max(a,t.endDTS)}let f=n-t.start;return t.start!==0&&t.setStart(n),t.setDuration(r-t.start),t.startPTS=n,t.maxStartPTS=c,t.startDTS=i,t.endPTS=r,t.minEndPTS=l,t.endDTS=a,is(e,t,f)}function is(e,t,n){let r=t.sn;if(!e||r<e.startSN||r>(e.fragmentHint?.sn||e.endSN))return 0;let i,a=r-e.startSN,o=e.fragments;for(o[a]=t,i=a;i>0;i--)ns(o[i],o[i-1]);for(i=a;i<o.length-1;i++)ns(o[i],o[i+1]);return e.fragmentHint&&ns(o[o.length-1],e.fragmentHint),e.PTSKnown=e.alignedSliding=!0,n}function as(e,t,n){if(e===t)return;let r=null,i=e.fragments;for(let e=i.length-1;e>=0;e--){let t=i[e].initSegment;if(t){r=t;break}}e.fragmentHint&&delete e.fragmentHint.endPTS;let a;cs(e,t,(e,n,i,o)=>{if(n.cc!==e.cc&&(e.cc>n.cc||t.skippedSegments)){let r=e.cc-n.cc;for(let e=i;e<o.length;e++)o[e].cc+=r;t.endCC=o[o.length-1].cc}P(e.startPTS)&&P(e.endPTS)&&(n.setStart(n.startPTS=e.startPTS),n.startDTS=e.startDTS,n.maxStartPTS=e.maxStartPTS,n.endPTS=e.endPTS,n.endDTS=e.endDTS,n.minEndPTS=e.minEndPTS,n.setDuration(e.endPTS-e.startPTS),n.duration&&(a=n),t.PTSKnown=t.alignedSliding=!0),e.hasStreams&&(n.elementaryStreams=e.elementaryStreams),n.loader=e.loader,n.gap=e.gap||n.gap,e.hasStats&&(n.stats=e.stats),e.initSegment&&(n.initSegment=e.initSegment,r=e.initSegment)});let o=t.fragments,s=t.fragmentHint?o.concat(t.fragmentHint):o;if(r&&s.forEach(e=>{e&&(!e.initSegment||e.initSegment.relurl===r?.relurl)&&(e.initSegment=r)}),t.skippedSegments){if(t.deltaUpdateFailed=o.some(e=>!e),t.deltaUpdateFailed){n.warn(`[level-helper] Previous playlist missing segments skipped in delta playlist`);for(let e=t.skippedSegments;e--;)o.shift();t.startSN=o[0].sn}else{t.canSkipDateRanges&&(t.dateRanges=os(e.dateRanges,t,n));let r=e.fragments.filter(e=>e.rawProgramDateTime);if(e.hasProgramDateTime&&!t.hasProgramDateTime)for(let e=1;e<s.length;e++)s[e].programDateTime===null&&Zo(s[e],s[e-1],r);Wo(r,t)}t.endCC=o[o.length-1].cc}else if(t.startSN>e.endSN&&o[0].cc<e.endCC){let n=e.endCC-o[0].cc;s.forEach(e=>{e.cc+=n}),t.endCC+=n}if(t.startCC||=ps(e,t.startSN-1)?.cc??o[0].cc,ss(e.partList,t.partList,(e,t)=>{t.elementaryStreams=e.elementaryStreams,t.stats=e.stats,t.gap=e.gap||t.gap}),a){let e=t.iframesOnly&&a.type===z.MAIN;rs(t,a,a.startPTS,a.endPTS,a.startDTS,a.endDTS,e,n)}else us(e,t);o.length&&(t.totalduration=t.edge-o[0].start),t.driftStartTime=e.driftStartTime,t.driftStart=e.driftStart;let c=t.advancedDateTime;if(t.advanced&&c){let e=t.edge;t.driftStart||=(t.driftStartTime=c,e),t.driftEndTime=c,t.driftEnd=e}else t.driftEndTime=e.driftEndTime,t.driftEnd=e.driftEnd,t.advancedDateTime=e.advancedDateTime;t.requestScheduled===-1&&(t.requestScheduled=e.requestScheduled)}function os(e,t,n){let{dateRanges:r,recentlyRemovedDateranges:i}=t,a=V({},e);i&&i.forEach(e=>{delete a[e]});let o=Object.keys(a).length;return o?(Object.keys(r).forEach(e=>{let t=a[e],i=new fo(r[e].attr,t);i.isValid?(a[e]=i,t||(i.tagOrder+=o)):n.warn(`Ignoring invalid Playlist Delta Update DATERANGE tag: "${q(r[e].attr)}"`)}),a):r}function ss(e,t,n){if(e&&t){let r=0;for(let i=0,a=e.length;i<a;i++){let a=e[i],o=t[i+r];a&&o&&a.index===o.index&&a.fragment.sn===o.fragment.sn?n(a,o):r--}}}function cs(e,t,n){var r;let i=t.skippedSegments,a=Math.max(e.startSN,t.startSN)-t.startSN,o=+!!e.fragmentHint+(i?t.endSN:Math.min(e.endSN,t.endSN))-t.startSN,s=t.startSN-e.startSN,c=t.fragmentHint?t.fragments.concat(t.fragmentHint):t.fragments,l=(r=e.fragmentHint)!=null&&r.duration?e.fragments.concat(e.fragmentHint):e.fragments;for(let r=a;r<=o;r++){let a=l[s+r],o=c[r];if(i&&!o&&a&&(o=t.fragments[r]=a),a&&o){n(a,o,r,c);let i=a.relurl,s=o.relurl;if(i&&_s(i,s)){t.playlistParsingError=ls(`media sequence mismatch ${o.sn}:`,e,t,a,o);return}if(a.cc!==o.cc){t.playlistParsingError=ls(`discontinuity sequence mismatch (${a.cc}!=${o.cc})`,e,t,a,o);return}}}}function ls(e,t,n,r,i){return Error(`${e} ${i.url}
|
|
18
|
+
transfer tracks: ${q(r,(e,t)=>e===`initSegment`?void 0:t)}}`),!sn(r,n)){t.mediaSource=null,t.tracks=void 0;let i=e.currentTime,a=this.details,o=Math.max(i,a?.fragments[0].start||0);if(o-i>1){this.log(`attachTransferred: waiting for playback to reach new tracks start time ${i} -> ${o}`);return}this.warn(`attachTransferred: resetting MediaSource for incompatible tracks ("${Object.keys(r)}"->"${Object.keys(n)}") start time: ${o} currentTime: ${i}`),this.onMediaDetaching(L.MEDIA_DETACHING,{}),this.onMediaAttaching(L.MEDIA_ATTACHING,t),e.currentTime=o;return}this.transferData=void 0,i.forEach(e=>{let t=e,n=r[t];if(n){let e=n.buffer;if(e){let r=this.fragmentTracker,i=n.id;if(r.hasFragments(i)||r.hasParts(i)){let n=J.getBuffered(e);r.detectEvictedFragments(t,n,i,null,null,!0)}let a=Da(t),o=[t,e];this.sourceBuffers[a]=o,e.updating&&this.operationQueue&&this.operationQueue.prependBlocker(t),this.trackSourceBuffer(t,n)}}}),o(),this.bufferCreated()}else this.log(`attachTransferred: MediaSource w/o SourceBuffers`),o()}get mediaSourceOpenOrEnded(){let e=this.mediaSource?.readyState;return e===`open`||e===`ended`}onMediaDetaching(e,t){let n=!!t.transferMedia;this.transferData=this.overrides=void 0;let{media:r,mediaSource:i,_objectUrl:a}=this;if(i){if(this.log(`media source ${n?`transferring`:`detaching`}`),n)this.sourceBuffers.forEach(([e])=>{e&&this.removeBuffer(e)}),this.resetQueue();else{if(this.mediaSourceOpenOrEnded){let e=i.readyState===`open`;try{let t=i.sourceBuffers;for(let n=t.length;n--;)e&&t[n].abort(),i.removeSourceBuffer(t[n]);e&&i.endOfStream()}catch(e){this.warn(`onMediaDetaching: ${e.message} while calling endOfStream`)}}this.sourceBufferCount&&this.onBufferReset()}X(i,`sourceopen`,this._onMediaSourceOpen),X(i,`sourceended`,this._onMediaSourceEnded),X(i,`sourceclose`,this._onMediaSourceClose),this.appendSource&&(X(i,`startstreaming`,this._onStartStreaming),X(i,`endstreaming`,this._onEndStreaming)),this.mediaSource=null,this._objectUrl=null}r&&(X(r,`emptied`,this._onMediaEmptied),X(r,`error`,this._onMediaError),X(r,`seeking`,this._onStartStreaming),n||(a&&self.URL.revokeObjectURL(a),this.mediaSrc===a&&!this.isMediaSourceReplaced(a)?(r.removeAttribute(`src`),this.appendSource&&Ta(r),r.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){let t=this.tracks[e]?.buffer;if(this.removeBuffer(e),t)try{var n;(n=this.mediaSource)!=null&&n.sourceBuffers.length&&this.mediaSource.removeSourceBuffer(t)}catch(t){this.warn(`onBufferReset ${e}`,t)}delete this.tracks[e]}removeBuffer(e){this.removeBufferListeners(e),this.sourceBuffers[Da(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 $i(this.tracks)}onBufferCodecs(e,t){let n=this.tracks,r=Object.keys(t);this.log(`BUFFER_CODECS: "${r}" (current SB count ${this.sourceBufferCount})`);let i=`audiovideo`in t&&(n.audio||n.video)||n.audiovideo&&(`audio`in t||`video`in t),a=!i&&this.sourceBufferCount&&this.media&&r.some(e=>!n[e]);if(i||a){this.warn(`Unsupported transition between "${Object.keys(n)}" and "${r}" SourceBuffers`);return}r.forEach(e=>{var r;let{id:i,codec:a,levelCodec:o,container:s,metadata:c,supplemental:l}=t[e],u=n[e],d=(r=this.transferData)==null||(r=r.tracks)==null?void 0:r[e],f=d!=null&&d.buffer?d:u,p=f?.pendingCodec||f?.codec,m=f?.levelCodec;u||=n[e]={buffer:void 0,listeners:[],codec:a,supplemental:l,container:s,levelCodec:o,metadata:c,id:i};let h=si(p,m),g=h?.replace(va,`$1`),_=si(a,o),v=_?.replace(va,`$1`);_&&h&&g!==v&&(e.slice(0,5)===`audio`&&(_=ai(_,this.appendSource)),this.log(`switching codec ${p} to ${_}`),_!==(u.pendingCodec||u.codec)&&(u.pendingCodec=_),u.container=s,this.appendChangeType(e,s,_))}),(this.tracksReady||this.sourceBufferCount)&&(t.tracks=this.sourceBufferTracks),!this.sourceBufferCount&&(this.bufferCodecEventsTotal>1&&!this.tracks.video&&!t.video&&t.audio?.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 n=this.tracks[t];return e[t]={id:n.id,container:n.container,codec:n.codec,levelCodec:n.levelCodec},e},{})}appendChangeType(e,t,n){let r=`${t};codecs=${n}`,i={label:`change-type=${r}`,execute:()=>{let i=this.tracks[e];if(i){let a=i.buffer;a!=null&&a.changeType&&(this.log(`changing ${e} sourceBuffer type to ${r}`),a.changeType(r),i.codec=n,i.container=t)}this.shiftAndExecuteNext(e)},onStart:()=>{},onComplete:()=>{},onError:t=>{this.warn(`Failed to change ${e} SourceBuffer type`,t)}};this.append(i,e,this.isPending(this.tracks[e]))}blockAudio(e){let t=e.start,n=t+e.duration*.05;this.fragmentTracker.getAppendedFrag(t,z.MAIN)?.gap!==!0&&this.append({label:`block-audio`,execute:()=>{(this.lastVideoAppendEnd>n||J.isBuffered(this.tracks.video?.buffer,n)||this.fragmentTracker.getAppendedFrag(n,z.MAIN)?.gap===!0)&&this.unblockAudio()},onStart:()=>{},onComplete:()=>{},onError:e=>{this.warn(`Error executing block-audio operation`,e)}},`audio`,!0)}unblockAudio(){this.operationQueue&&this.operationQueue.unblockAudio()}onBufferAppending(e,t){let{tracks:n}=this,{data:r,type:i,parent:a,frag:o,part:s,chunkMeta:c,offset:l}=t,u=c.buffering[i],d=Tt(o)&&!s&&!o.gap&&!c.partial&&!c.iframe,f=null,p=!1,{sn:m,cc:h}=o,g=self.performance.now();u.start=g;let _=o.stats.buffering,v=s?s.stats.buffering:null;_.start===0&&(_.start=g),v?.start===0&&(v.start=g);let y=n.audio,b=!1;i===`audio`&&y?.container===`audio/mpeg`&&(b=!this.lastMpegAudioChunk||c.id===1||this.lastMpegAudioChunk.sn!==c.sn,this.lastMpegAudioChunk=c);let x=n.video,S=x?.buffer;if(S&&m!==`initSegment`&&l!==void 0){let e=y?.buffer,t=s||o;if(i===`audio`&&a!==`main`&&!(x.ending||x.ended)&&e&&J.getBuffered(e).length){let e=t.start+t.duration*.05,n=J.getBuffered(S),r=this.currentOp(`video`);(!n.length&&!r||!J.isBuffered(S,e)&&this.lastVideoAppendEnd<e)&&this.blockAudio(t)}else if(i===`video`){let e=t.end,n=this.lastVideoAppendEnd-e;this.lastVideoAppendEnd=e,n<0||n>t.duration?this.unblockAudio():this.isAudioBlocked()&&this.executeNext(`audio`)}}let C=(s||o).start,w={label:`append-${i}`,execute:()=>{u.executeStart=self.performance.now();let e=this.tracks[i]?.buffer;e&&(d&&(f=J.timeRangesToArray(J.getBuffered(e)),p=ja(Aa(f,o),o)),b?this.updateTimestampOffset(e,C,.1,i,m,h):l!==void 0&&P(l)&&this.updateTimestampOffset(e,l,1e-6,i,m,h)),this.appendExecutor(r,i)},onStart:()=>{},onComplete:()=>{this.clearBufferAppendTimeoutId(this.tracks[i]);let e=self.performance.now();u.executeEnd=u.end=e,_.first===0&&(_.first=e),v?.first===0&&(v.first=e);let t={};if(this.sourceBuffers.forEach(([e,n])=>{e&&(t[e]=J.getBuffered(n))}),d){let e=this.getFragmentAppendProgress(o),n=t[i];if(n&&f){let t=Aa(J.timeRangesToArray(n),o);e.progressed||=t-Aa(f,o)>Sa;let r=p&&ja(t,o);e.fullyBuffered[i]=(e.fullyBuffered[i]===void 0||e.fullyBuffered[i])&&r}}this.hls.trigger(L.BUFFER_APPENDED,{type:i,frag:o,part:s,chunkMeta:c,parent:a,timeRanges:t})},onError:e=>{this.clearBufferAppendTimeoutId(this.tracks[i]);let t=e.code===DOMException.QUOTA_EXCEEDED_ERR||e.name==`QuotaExceededError`||`quota`in e;if(t&&!this._quotaEvictionPending[i]){let e=this.getBackBufferEvictionTarget(i,r.byteLength,o.type);if(e>0){this._quotaEvictionPending[i]=!0,this.log(`QuotaExceededError on "${i}" append sn: ${m} - evicting back buffer to ${e.toFixed(3)}s and retrying`);let t=this.getFlushOp(i,0,e),n=this.getClearEvictionPendingOp(i);this.insertNext([t,w,n],i);return}this.warn(`QuotaExceededError on "${i}" sn: ${m} - no back buffer available to evict`)}d&&(this.getFragmentAppendProgress(o).errored=!0);let n={type:F.MEDIA_ERROR,parent:a,details:I.BUFFER_APPEND_ERROR,sourceBufferName:i,frag:o,part:s,chunkMeta:c,error:e,err:e,fatal:!1},l=this.media?.error;if(e.name===ya&&this.sourceBufferCount===0&&(!this.media||this.pendingTrackCount===0))n.errorAction=pa(!0);else{t&&(n.details=I.BUFFER_FULL_ERROR);let r=++this.appendErrors[i],a=this.hls.config.appendErrorMaxRetry;this.warn(`Failed ${r}/${a+1} times to append segment in "${i}" sourceBuffer with error: ${e.message}`),r>=a&&(n.fatal=!t);let o=this.mediaSource?.readyState;(o===`ended`||o===`closed`||l)&&!this.isMediaSourceReplaced()&&(this.warn(`MediaSource readyState "${o}" during SourceBuffer${Oa(n.fatal,l)}`),n.details=I.MEDIA_SOURCE_REQUIRES_RESET)}this.appendError=n,this.hls.trigger(L.ERROR,n),t&&this.hls&&this.trimBuffers(o.start,1)}};this.log(`queuing "${i}" append sn: ${m}${s?` p: `+s.index:``} of ${a} playlist ${o.level} cc: ${h} offset: ${l} bytes: ${r.byteLength}`),this.append(w,i,this.isPending(this.tracks[i]))}getClearEvictionPendingOp(e){return{label:`clear`,execute:()=>{this._quotaEvictionPending[e]=!1,this.shiftAndExecuteNext(e)},onStart:()=>{},onComplete:()=>{},onError:()=>{}}}getFlushOp(e,t,n){return this.log(`queuing "${e}" remove ${t}-${n}`),{label:`remove`,execute:()=>{this.removeExecutor(e,t,n)},onStart:()=>{},onComplete:()=>{let r=this.tracks[e]?.buffer;this.log(`Remove request ${t}-${n} from ${e} Source Buffer complete > buffer: ${r?_a(J.getBuffered(r)):`(detached)`}`),this.hls.trigger(L.BUFFER_FLUSHED,{type:e,start:t,end:n})},onError:r=>{this.warn(`Failed to remove ${t}-${n} from "${e}" SourceBuffer`,r),this.hls.trigger(L.BUFFER_FLUSHED,{type:e,start:0,end:0,error:r})}}}onBufferFlushing(e,t){let{type:n,startOffset:r,endOffset:i}=t;(!n||n===`audio`)&&this.unblockAudio(),n?this.append(this.getFlushOp(n,r,i),n):this.sourceBuffers.forEach(([e])=>{e&&this.append(this.getFlushOp(e,r,i),e)})}onFragParsed(e,t){let{frag:n,part:r,chunkMeta:i}=t,a=[],o=r?r.elementaryStreams:n.elementaryStreams;o[B.AUDIOVIDEO]?a.push(`audiovideo`):(o[B.AUDIO]&&a.push(`audio`),o[B.VIDEO]&&a.push(`video`)),a.length===0&&this.log(`Fragments must have at least one ElementaryStreamType set. ${n.type} ${n.level} ${r?`part: ${r.index} of `:``}sn: ${n.sn}`),this.blockBuffers(()=>{let e=self.performance.now();n.stats.buffering.end=e,r&&(r.stats.buffering.end=e);let t=r?r.stats:n.stats;this.checkAppendProgress(n,r,i,a),this.hls&&(this.hls.trigger(L.FRAG_BUFFERED,{frag:n,part:r,stats:t,id:n.type,chunkMeta:i}),!r&&n.gap&&t.retry&&this.log(`Nothing buffered for ${n.type} level: ${n.level} sn: ${n.sn} retries ${t.retry}`))},a).catch(e=>{this.warn(`Fragment buffered callback ${e.message}`),this.stepOperationQueue(this.sourceBufferTypes)})}onFragChanged(e,t){let n=this.hls?.config;if(!n)return;let{backBufferLength:r,frontBufferFlushThreshold:i}=n;this.trimBuffers(i,r,t.frag,t.previousFrag);let a=t.frag.elementaryStreams,{appendErrors:o}=this,s=this.appendError?.sourceBufferName;Object.keys(a).forEach(e=>{a[e]&&(o[e]=0,e===s&&(this.appendError=void 0),e===`audio`||e===`video`?(o.audiovideo=0,s===`audiovideo`&&(this.appendError=void 0)):(o.audio=0,o.video=0,s!==`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){this.sourceBuffers.forEach(([e])=>{if(e){let n=this.tracks[e];(!t.type||t.type===e)&&(n.ending=!0,n.ended||(n.ended=!0,this.log(`${e} buffer reached EOS`)))}});let n=this.overrides?.endOfStream!==!1;this.allTracksEnding?(this.unblockAudio(),n?(this.log(`Queueing EOS`),this.blockUntilOpen(()=>{if(this.tracksEnded(),!this.allTracksEnding){this.log(`EOS cancelled`);return}let{mediaSource:e}=this;if(e?.readyState!==`open`){e&&this.log(`Could not call mediaSource.endOfStream(). mediaSource.readyState: ${e.readyState}`);return}this.log(`Calling mediaSource.endOfStream()`),e.endOfStream(),this.hls.trigger(L.BUFFERED_TO_END,void 0)})):(this.tracksEnded(),this.hls.trigger(L.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===I.BUFFER_APPEND_ERROR&&t.frag){let e=t.errorAction?.nextAutoLevel;P(e)&&e!==t.frag.level&&this.resetAppendErrors()}}getBackBufferEvictionTarget(e,t,n){let{media:r}=this;return r?this.fragmentTracker.getBackBufferEvictionEnd(r.currentTime,n,t):0}getFragmentAppendProgress(e){let t=ka(e),n=this.fragmentAppendProgress[t];return n?.stats!==e.stats&&(n={stats:e.stats,progressed:!1,errored:!1,fullyBuffered:Object.create(null)},this.fragmentAppendProgress[t]=n),n}checkAppendProgress(e,t,n,r){if(t||!Tt(e)||e.gap||n.iframe||n.partial)return;let i=ka(e),a=this.fragmentAppendProgress[i];delete this.fragmentAppendProgress[i];let o=e.stats.buffering;if(o.start&&!o.first)return;let s=a?.stats===e.stats?a:void 0;if(s!=null&&s.errored)return;let c=r.length>0&&r.every(e=>s?.fullyBuffered[e]===!0);if(s!=null&&s.progressed||c){delete this.appendsWithoutProgress[i];return}if(!s&&r.length===0)return;let l=(this.appendsWithoutProgress[i]||0)+1,u=this.hls;l>=u.config.appendErrorMaxRetry?delete this.appendsWithoutProgress[i]:this.appendsWithoutProgress[i]=l,this.warn(`Fragment ${e.sn} of ${e.type} playlist ${e.level} appended ${l} time${l>1?`s`:``} without buffered range growth`),u.trigger(L.ERROR,{type:F.MEDIA_ERROR,details:I.BUFFER_APPEND_NO_PROGRESS,fatal:!1,frag:e,chunkMeta:n,parent:e.type,appendsWithoutProgress:l,error:Error(`Fragment append did not increase buffered coverage (${l})`)})}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,n,r){let{hls:i,details:a,media:o}=this;if(!o||a===null||!this.sourceBufferCount)return;let s=i.config,c=o.currentTime,l=a.levelTargetDuration;t=a.live&&s.liveBackBufferLength!==null?s.liveBackBufferLength:t;let u=-1/0;if(P(t)&&t>=0){let e=Math.max(t,l);u=Math.floor(c/l)*l-e}if(n){let e=this.getLoopBackBufferFlushEnd(n,r??null);e>0&&(u=Math.max(u,e))}if(u>0&&this.flushBackBuffer(c,l,u),P(e)&&e>0){let t=Math.max(s.maxBufferLength,e),n=Math.max(t,l),r=Math.floor(c/l)*l+n;this.flushFrontBuffer(c,l,r)}}getLoopBackBufferFlushEnd(e,t){let{media:n}=this;if(this.hls?.config.loopBackBufferFlush===!1||!(n!=null&&n.loop)||!t||e.level<=t.level)return 0;let{video:r,audiovideo:i}=e.elementaryStreams;if(r!=null&&r.partial||i!=null&&i.partial)return 0;let a=this.getEarliestElementaryStreamStart(e)-xa;return a<=0?0:(this.log(`Flushing lower quality back buffer for loop: level ${e.level}, range [0-${a.toFixed(3)}]`),a)}getEarliestElementaryStreamStart(e){let{audio:t,video:n,audiovideo:r}=e.elementaryStreams,i=e.start;return r?i=Math.min(i,r.startDTS):(t&&(i=Math.min(i,t.startDTS)),n&&(i=Math.min(i,n.startDTS))),i}flushBackBuffer(e,t,n){this.sourceBuffers.forEach(([e,t])=>{if(t){let a=J.getBuffered(t);if(a.length>0&&n>a.start(0)){var r,i;this.hls.trigger(L.BACK_BUFFER_REACHED,{bufferEnd:n});let t=this.tracks[e];if((r=this.details)!=null&&r.live)this.hls.trigger(L.LIVE_BACK_BUFFER_REACHED,{bufferEnd:n});else if(t!=null&&t.ended&&!((i=this.media)!=null&&i.loop&&this.hls?.config.loopBackBufferFlush!==!1)){this.log(`Cannot flush ${e} back buffer while SourceBuffer is in ended state`);return}this.hls.trigger(L.BUFFER_FLUSHING,{startOffset:0,endOffset:n,type:e})}}})}flushFrontBuffer(e,t,n){this.sourceBuffers.forEach(([t,r])=>{if(r){let i=J.getBuffered(r),a=i.length;if(a<2)return;let o=i.start(a-1),s=i.end(a-1);if(n>o||e>=o&&e<=s)return;this.hls.trigger(L.BUFFER_FLUSHING,{startOffset:o,endOffset:1/0,type:t})}})}getDurationAndRange(){let{details:e,mediaSource:t}=this;if(!e||!this.media||t?.readyState!==`open`)return null;let n=e.edge;if(e.live&&this.hls.config.liveDurationInfinity){if(e.fragments.length&&t.setLiveSeekableRange){let t=Math.max(0,e.fragmentStart);return{duration:1/0,start:t,end:Math.max(t,n)}}return{duration:1/0}}let r=this.overrides?.duration;if(r)return P(r)?{duration:r}:null;let i=this.media.duration;return n>(P(t.duration)?t.duration:0)&&n>i||!P(i)?{duration:n}:null}updateMediaSource({duration:e,start:t,end:n}){let r=this.mediaSource;r&&this.media&&r.readyState===`open`&&(r.duration!==e&&(P(e)&&this.log(`Updating MediaSource duration to ${e.toFixed(3)}`),r.duration=e),t!==void 0&&n!==void 0&&(this.log(`MediaSource duration is set to ${r.duration}. Setting seekable range to ${t}-${n}.`),r.setLiveSeekableRange(t,n)))}get tracksReady(){let e=this.pendingTrackCount;return e>0&&(e>=this.bufferCodecEventsTotal||this.isPending(this.tracks.audiovideo))}checkPendingTracks(){let{bufferCodecEventsTotal:e,pendingTrackCount:t,tracks:n}=this;if(this.log(`checkPendingTracks (pending: ${t} codec events expected: ${e}) ${q(n)}`),this.tracksReady){let e=this.transferData?.tracks;e&&Object.keys(e).length?this.attachTransferred():this.createSourceBuffers()}}bufferCreated(){if(this.sourceBufferCount){let e={};this.sourceBuffers.forEach(([t,n])=>{if(t){let r=this.tracks[t];e[t]={buffer:n,container:r.container,codec:r.codec,supplemental:r.supplemental,levelCodec:r.levelCodec,id:r.id,metadata:r.metadata}}}),this.hls.trigger(L.BUFFER_CREATED,{tracks:e}),this.log(`SourceBuffers created. Running queue: ${this.operationQueue}`),this.sourceBuffers.forEach(([e])=>{this.executeNext(e)})}else{let e=Error(`could not create source buffer for media codec(s)`);this.hls.trigger(L.ERROR,{type:F.MEDIA_ERROR,details:I.BUFFER_INCOMPATIBLE_CODECS_ERROR,fatal:!0,error:e,reason:e.message})}}createSourceBuffers(){let{tracks:e,sourceBuffers:t,mediaSource:n}=this;if(!n)throw Error(`createSourceBuffers called when mediaSource was null`);for(let i in e){let a=i,o=e[a];if(this.isPending(o)){let e=this.getTrackCodec(o,a),i=`${o.container};codecs=${e}`;o.codec=e,this.log(`creating sourceBuffer(${i})${this.currentOp(a)?` Queued`:``} ${q(o)}`);try{let e=n.addSourceBuffer(i),r=Da(a);t[r]=[a,e],o.buffer=e}catch(e){var r;this.error(`error while trying to add sourceBuffer: ${e.message}`),this.shiftAndExecuteNext(a),(r=this.operationQueue)==null||r.removeBlockers(),delete this.tracks[a],this.hls.trigger(L.ERROR,{type:F.MEDIA_ERROR,details:I.BUFFER_ADD_CODEC_ERROR,fatal:!1,error:e,sourceBufferName:a,mimeType:i,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 n=e.supplemental,r=e.codec;n&&(t===`video`||t===`audiovideo`)&&Zr(n,`video`)&&(r=oi(r,n));let i=si(r,e.levelCodec);return i?t.slice(0,5)===`audio`?ai(i,this.appendSource):i:``}trackSourceBuffer(e,t){let n=t.buffer;if(!n)return;let r=this.getTrackCodec(t,e);this.tracks[e]={buffer:n,codec:r,container:t.container,levelCodec:t.levelCodec,supplemental:t.supplemental,metadata:t.metadata,id:t.id,listeners:[]},this.removeBufferListeners(e),this.addBufferListener(e,`updatestart`,this.onSBUpdateStart),this.addBufferListener(e,`updateend`,this.onSBUpdateEnd),this.addBufferListener(e,`error`,this.onSBUpdateError),this.appendSource&&this.addBufferListener(e,`bufferedchange`,(e,t)=>{let n=t.removedRanges;n!=null&&n.length&&(this.log(`${e} buffer removed ${_a(n)}`),this.hls.trigger(L.BUFFER_FLUSHED,{type:e,start:n.start(0),end:n.end(n.length-1)}))})}get mediaSrc(){let e=this.media;if(e)return(e.src?e:e.querySelector?.call(e,`source`)||e).src}isMediaSourceReplaced(e=this._objectUrl){if(!e)return!1;let t=this.media?.currentSrc,n=this.mediaSrc;return!!t&&t!==e||!!n&&n!==e}onSBUpdateStart(e){let t=this.currentOp(e);t&&t.onStart()}onSBUpdateEnd(e){var t;if(this.mediaSource?.readyState===`closed`){this.resetBuffer(e);return}let n=this.currentOp(e);if(n){if(n.onComplete(),(t=this.tracks[e])!=null&&(t=t.buffer)!=null&&t.updating){this.log(`${e} SourceBuffer updating on "updateend"`),this.blockUntilOpen(()=>{this.shiftAndExecuteNext(e)});return}this.shiftAndExecuteNext(e)}}onSBUpdateError(e,t){let n=this.mediaSource?.readyState,r=Error(`${e} SourceBuffer error. MediaSource readyState: ${n}`);r.name=ba,this.error(`${r.message}`,t),this.hls.trigger(L.ERROR,{type:F.MEDIA_ERROR,details:I.BUFFER_APPENDING_ERROR,sourceBufferName:e,error:r,fatal:!1});let i=this.currentOp(e);i&&i.onError(r)}updateTimestampOffset(e,t,n,r,i,a){let o=t-e.timestampOffset;Math.abs(o)>=n&&(this.log(`Updating ${r} SourceBuffer timestampOffset to ${t} (sn: ${i} cc: ${a})`),e.timestampOffset=t)}removeExecutor(e,t,n){let{media:r,mediaSource:i}=this,a=this.tracks[e],o=a?.buffer;if(!r||!i||!o)throw Error(`Attempting to remove from the ${e} SourceBuffer, but it does not exist`);let s=P(r.duration)?r.duration:1/0,c=P(i.duration)?i.duration:1/0,l=Math.max(0,t);if(l>=c){var u;(u=this.currentOp(e))==null||u.onComplete(),this.shiftAndExecuteNext(e);return}let d=Math.min(n,s,c);if(d>l&&(!a.ending||a.ended))a.ended=!1,this.log(`Removing [${l},${d}] from the ${e} SourceBuffer`),o.remove(l,d);else throw Error(`Cannot remove ${d<=l?`invalid range (${l} >= ${d}) `:``}from the ${e} SourceBuffer${a.ending?` while track ending`:``}`)}appendExecutor(e,t){let n=this.tracks[t],r=n?.buffer;if(!r)throw new Ca(`Attempting to append to the ${t} SourceBuffer, but it does not exist`);if(n.ending=!1,n.ended=!1,this.hls.config.appendTimeout!==1/0){let e=this.calculateAppendTimeoutTime(r);n.bufferAppendTimeoutId=self.setTimeout(()=>this.appendTimeoutHandler(t,r,e),e)}r.appendBuffer(e)}appendTimeoutHandler(e,t,n){this.log(`Received timeout after ${n}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 r=this.currentOp(e);r&&r.onError(Error(`${e}-append-timeout`))}calculateAppendTimeoutTime(e){let t=ma;this.details&&(t=this.details.levelTargetDuration);let n=2*t*1e3;if(this.media===null)return n;let r=J.bufferInfo(e,this.media.currentTime,0);return r.len?(n=Math.max(r.len*1e3,n),Math.max(this.hls.config.appendTimeout,n)):n}blockUntilOpen(e){if(this.isUpdating()||this.isQueued())this.blockBuffers(e).catch(e=>{this.warn(`SourceBuffer blocked callback ${e}`),this.stepOperationQueue(this.sourceBufferTypes)});else try{e()}catch(e){this.warn(`Callback run without blocking ${this.operationQueue} ${e}`)}}isUpdating(){return this.sourceBuffers.some(([e,t])=>e&&t.updating)}isQueued(){return this.sourceBuffers.some(([e])=>e&&!!this.currentOp(e))}isPending(e){return!!e&&!e.buffer}isAudioBlocked(){return this.currentOp(`audio`)?.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:n}=this,r=t.length===2&&this.isAudioBlocking()?[this.appendBlocker(`video`)]:t.map(e=>this.appendBlocker(e));return Promise.all(r).then(t=>{n===this.operationQueue&&(e(),this.stepOperationQueue(this.sourceBufferTypes))})}stepOperationQueue(e){e.forEach(e=>{let t=this.tracks[e]?.buffer;!t||t.updating||e===`audio`&&this.isAudioBlocked()||this.shiftAndExecuteNext(e)})}append(e,t,n){this.operationQueue&&this.operationQueue.append(e,t,n)}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]),0)}get sourceBufferCount(){return this.sourceBuffers.reduce((e,[t])=>e+ +!!t,0)}get sourceBufferTypes(){return this.sourceBuffers.map(([e])=>e).filter(e=>!!e)}addBufferListener(e,t,n){let r=this.tracks[e];if(!r)return;let i=r.buffer;if(!i)return;let a=n.bind(this,e);r.listeners.push({event:t,listener:a}),Y(i,t,a)}removeBufferListeners(e){let t=this.tracks[e];if(!t)return;let n=t.buffer;n&&(t.listeners.forEach(e=>{X(n,e.event,e.listener)}),t.listeners.length=0)}};function Ta(e){let t=e.querySelectorAll(`source`);[].slice.call(t).forEach(t=>{e.removeChild(t)})}function Ea(e,t){let n=self.document.createElement(`source`);n.type=`video/mp4`,n.src=t,e.appendChild(n)}function Da(e){return+(e===`audio`)}function Oa(e,t){return`${e?``:` - triggering recovery`}${t?` with HTMLMediaElement Error: `+t.message:``}`}function ka(e){return`${e.type}_${e.sn}_${e.level}`}function Aa(e,t){let{start:n,end:r}=t,i=0;for(let t=0;t<e.length;t++){let a=e[t];if(a.start>=r)break;let o=Math.max(n,a.start),s=Math.min(r,a.end);s>o&&(i+=s-o)}return i}function ja(e,t){return t.duration-e<=.05}var Z={NOT_LOADED:`NOT_LOADED`,APPENDING:`APPENDING`,PARTIAL:`PARTIAL`,OK:`OK`},Ma=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(L.MANIFEST_LOADING,this.onManifestLoading,this),e.on(L.BUFFER_APPENDED,this.onBufferAppended,this),e.on(L.FRAG_BUFFERED,this.onFragBuffered,this),e.on(L.FRAG_LOADED,this.onFragLoaded,this))}_unregisterListeners(){let{hls:e}=this;e&&(e.off(L.MANIFEST_LOADING,this.onManifestLoading,this),e.off(L.BUFFER_APPENDED,this.onBufferAppended,this),e.off(L.FRAG_BUFFERED,this.onFragBuffered,this),e.off(L.FRAG_LOADED,this.onFragLoaded,this))}destroy(){this._unregisterListeners(),this.hls=this.fragments=this.activePartLists=this.endListFragments=this.timeRanges=null}getAppendedFrag(e,t){let n=this.activePartLists[t];if(n)for(let t=n.length;t--;){let r=n[t];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,n){let{fragments:r}=this,i=Object.keys(r);for(let a=i.length;a--;){let o=r[i[a]];if(o?.body.type===t&&(!n||o.buffered)){let t=o.body;if(t.start<=e&&e<=t.end)return t}}return null}detectEvictedFragments(e,t,n,r,i,a){this.timeRanges&&(this.timeRanges[e]=t);let o=i?.fragment.sn||-1;Object.keys(this.fragments).forEach(i=>{let s=this.fragments[i];if(!s||!this.hls)return;let c=s.body;if(o>=c.sn)return;if(!s.buffered&&(!s.loaded||a)){c.type===n&&this.removeFragment(c);return}let l=s.range[e];if(l){if(l.time.length===0){this.removeFragment(c);return}if(l.time.some(e=>{let n=!this.isTimeBuffered(e.startPTS,e.endPTS,t);return n&&this.removeFragment(c),n}),r&&r!==c&&Wr()){let e=r.endPTS,t=c.startPTS;if(e&&t&&s.range.video){let n=t-e;n<0&&n>-.1&&(this.removeFragment(c),this.hls.trigger(L.BUFFER_FLUSHING,{startOffset:e+.004,endOffset:1/0,type:`video`}))}}}})}detectPartialFragments(e){let t=this.timeRanges,{frag:n,part:r,id:i}=e;if(!t||!Tt(n))return;let a=Pa(n),o=this.fragments[a];if(!o||o.buffered&&n.gap)return;let s=!n.relurl;Object.keys(t).forEach(e=>{let a=n.elementaryStreams[e];if(!a)return;let c=t[e],l=s||a.partial===!0;o.range[e]=this.getBufferedTimes(n,r,l,c),this.detectEvictedFragments(e,c,i,n,r)}),o.loaded=null;let c=Object.keys(o.range);if(c.length){if(this.bufferedEnd(o,n),Na(o)||this.removeParts(n.sn-1,n.type),!r){let e=Math.min(.004,n.duration);c.some(t=>{let r=o.range[t]?.time,i=r.length===0||r.length===1&&r[0].endPTS-r[0].startPTS<e;return i&&this.addAsGap(n),i})}}else this.removeFragment(n)}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 n=this.activePartLists[t];n&&(this.activePartLists[t]=Fa(n,t=>t.fragment.sn>=e))}fragBuffered(e,t){let n=Pa(e),r=this.fragments[n];return!r&&t&&(r=this.fragments[n]={body:e,appendedPTS:null,loaded:null,buffered:!1,range:Object.create(null)},e.gap&&(this.hasGaps=!0)),r&&(r.loaded=null,this.bufferedEnd(r,e)),r}getBufferedTimes(e,t,n,r){let i={time:[],partial:n},a=e.start,o=e.end,s=e.minEndPTS||o,c=e.maxStartPTS||a;for(let e=0;e<r.length;e++){let t=r.start(e)-this.bufferPadding,n=r.end(e)+this.bufferPadding;if(c>=t&&s<=n){i.time.push({startPTS:Math.max(a,r.start(e)),endPTS:Math.min(o,r.end(e))});break}if(a<n&&o>t){let t=Math.max(a,r.start(e)),n=Math.min(o,r.end(e));n>t&&(i.partial=!0,i.time.push({startPTS:t,endPTS:n}))}else if(o<=t)break}return i}getPartialFragment(e){let t=null,n,r,i,a=0,{bufferPadding:o,fragments:s}=this;return Object.keys(s).forEach(c=>{let l=s[c];l&&Na(l)&&(r=l.body.start-o,i=l.body.end+o,e>=r&&e<=i&&(n=Math.min(e-r,i-e),a<=n&&(t=l.body,a=n)))}),t}isEndListAppended(e){let t=this.endListFragments[e];return t!==void 0&&(t.buffered||Na(t))}getState(e){let t=Pa(e),n=this.fragments[t];return n?n.buffered?Na(n)?Z.PARTIAL:Z.OK:Z.APPENDING:Z.NOT_LOADED}isTimeBuffered(e,t,n){let r,i;for(let a=0;a<n.length;a++){if(r=n.start(a)-this.bufferPadding,i=n.end(a)+this.bufferPadding,e>=r&&t<=i)return!0;if(t<=r)return!1}return!1}onManifestLoading(){this.removeAllFragments()}onFragLoaded(e,t){if(!Tt(t.frag)||t.frag.bitrateTest)return;let n=t.frag,r=t.part?null:t,i=Pa(n);this.fragments[i]={body:n,appendedPTS:null,loaded:r,buffered:!1,range:Object.create(null)}}onBufferAppended(e,t){let{frag:n,part:r,timeRanges:i}=t;if(!Tt(n))return;let a=n.type;if(r){let e=this.activePartLists[a];e||(this.activePartLists[a]=e=[]),e.push(r)}this.timeRanges=i}onFragBuffered(e,t){this.detectPartialFragments(t)}hasFragment(e){let t=Pa(e);return!!this.fragments[t]}hasFragments(e){let{fragments:t}=this,n=Object.keys(t);if(!e)return n.length>0;for(let r=n.length;r--;)if(t[n[r]]?.body.type===e)return!0;return!1}hasParts(e){var t;return!!((t=this.activePartLists[e])!=null&&t.length)}getBackBufferEvictionEnd(e,t,n){let{fragments:r}=this,i=0,a=0,o=Object.keys(r);for(let s=0;s<o.length;s++){let c=r[o[s]];if(!c||!c.buffered||c.body.type!==t)continue;let l=c.body;if(l.gap)return 0;let u=l.hasStats&&l.stats.loaded||l.byteLength||l.bitrate&&l.bitrate*8*l.duration;if(l.end<=e&&u&&(i+=u,a=Math.max(a,l.end),i>=n))return a}return a>0?a:0}removeFragmentsInRange(e,t,n,r,i){(!r||this.hasGaps)&&Object.keys(this.fragments).forEach(a=>{let o=this.fragments[a];if(!o)return;let s=o.body;s.type!==n||r&&!s.gap||s.start<t&&s.end>e&&(o.buffered||i)&&this.removeFragment(s)})}removeFragment(e){let t=Pa(e);e.clearElementaryStreamInfo();let n=this.activePartLists[e.type];if(n){let t=e.sn;this.activePartLists[e.type]=Fa(n,e=>e.fragment.sn!==t)}delete this.fragments[t],e.endList&&delete this.endListFragments[e.type]}gapFragments(){return this.hasGaps?Object.keys(this.fragments).map(e=>this.fragments[e]?.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(e=>e.clearElementaryStreamInfo())}};function Na(e){var t,n,r,i;return e.buffered&&!!(e.body.gap||(t=e.range.video)!=null&&t.partial||(n=e.range.audio)!=null&&n.partial||(r=e.range.audiovideo)!=null&&r.partial||(i=e.range.subs)!=null&&i.partial)}function Pa(e){return`${e.type}_${e.level}_${e.sn}`}function Fa(e,t){return e.filter(e=>{let n=t(e);return n||e.clearElementaryStreamInfo(),n})}var Ia={cbc:0,ctr:1},La=class{constructor(e,t,n){this.subtle=void 0,this.aesIV=void 0,this.aesMode=void 0,this.subtle=e,this.aesIV=t,this.aesMode=n}decrypt(e,t){switch(this.aesMode){case Ia.cbc:return this.subtle.decrypt({name:`AES-CBC`,iv:this.aesIV},t,e);case Ia.ctr:return this.subtle.decrypt({name:`AES-CTR`,counter:this.aesIV,length:64},t,e);default:throw Error(`[AESCrypto] invalid aes mode ${this.aesMode}`)}}};function Ra(e){let t=e.byteLength,n=t&&new DataView(e.buffer).getUint8(t-1);return n?e.slice(0,t-n):e}var za=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,this.ksRows=0,this.keySize=0,this.keySchedule=void 0,this.invKeySchedule=void 0,this.initTable()}uint8ArrayToUint32Array_(e){let t=new DataView(e),n=new Uint32Array(4);for(let e=0;e<4;e++)n[e]=t.getUint32(e*4);return n}initTable(){let e=this.sBox,t=this.invSBox,n=this.subMix,r=n[0],i=n[1],a=n[2],o=n[3],s=this.invSubMix,c=s[0],l=s[1],u=s[2],d=s[3],f=new Uint32Array(256),p=0,m=0,h=0;for(h=0;h<256;h++)h<128?f[h]=h<<1:f[h]=h<<1^283;for(h=0;h<256;h++){let n=m^m<<1^m<<2^m<<3^m<<4;n=n>>>8^n&255^99,e[p]=n,t[n]=p;let s=f[p],h=f[s],g=f[h],_=f[n]*257^n*16843008;r[p]=_<<24|_>>>8,i[p]=_<<16|_>>>16,a[p]=_<<8|_>>>24,o[p]=_,_=g*16843009^h*65537^s*257^p*16843008,c[n]=_<<24|_>>>8,l[n]=_<<16|_>>>16,u[n]=_<<8|_>>>24,d[n]=_,p?(p=s^f[f[f[g^s]]],m^=f[f[m]]):p=m=1}}expandKey(e){let t=this.uint8ArrayToUint32Array_(e),n=!0,r=0;for(;r<t.length&&n;)n=t[r]===this.key[r],r++;if(n)return;this.key=t;let i=this.keySize=t.length;if(i!==4&&i!==6&&i!==8)throw Error(`Invalid aes key size=`+i);let a=this.ksRows=(i+6+1)*4,o,s,c=this.keySchedule=new Uint32Array(a),l=this.invKeySchedule=new Uint32Array(a),u=this.sBox,d=this.rcon,f=this.invSubMix,p=f[0],m=f[1],h=f[2],g=f[3],_,v;for(o=0;o<a;o++){if(o<i){_=c[o]=t[o];continue}v=_,o%i===0?(v=v<<8|v>>>24,v=u[v>>>24]<<24|u[v>>>16&255]<<16|u[v>>>8&255]<<8|u[v&255],v^=d[o/i|0]<<24):i>6&&o%i===4&&(v=u[v>>>24]<<24|u[v>>>16&255]<<16|u[v>>>8&255]<<8|u[v&255]),c[o]=_=(c[o-i]^v)>>>0}for(s=0;s<a;s++)o=a-s,v=s&3?c[o]:c[o-4],s<4||o<=4?l[s]=v:l[s]=p[u[v>>>24]]^m[u[v>>>16&255]]^h[u[v>>>8&255]]^g[u[v&255]],l[s]=l[s]>>>0}networkToHostOrderSwap(e){return e<<24|(e&65280)<<8|(e&16711680)>>8|e>>>24}decrypt(e,t,n){let r=this.keySize+6,i=this.invKeySchedule,a=this.invSBox,o=this.invSubMix,s=o[0],c=o[1],l=o[2],u=o[3],d=this.uint8ArrayToUint32Array_(n),f=d[0],p=d[1],m=d[2],h=d[3],g=new Int32Array(e),_=new Int32Array(g.length),v,y,b,x,S,C,w,T,E,D,O,k,A,j,M=this.networkToHostOrderSwap;for(;t<g.length;){for(E=M(g[t]),D=M(g[t+1]),O=M(g[t+2]),k=M(g[t+3]),S=E^i[0],C=k^i[1],w=O^i[2],T=D^i[3],A=4,j=1;j<r;j++)v=s[S>>>24]^c[C>>16&255]^l[w>>8&255]^u[T&255]^i[A],y=s[C>>>24]^c[w>>16&255]^l[T>>8&255]^u[S&255]^i[A+1],b=s[w>>>24]^c[T>>16&255]^l[S>>8&255]^u[C&255]^i[A+2],x=s[T>>>24]^c[S>>16&255]^l[C>>8&255]^u[w&255]^i[A+3],S=v,C=y,w=b,T=x,A+=4;v=a[S>>>24]<<24^a[C>>16&255]<<16^a[w>>8&255]<<8^a[T&255]^i[A],y=a[C>>>24]<<24^a[w>>16&255]<<16^a[T>>8&255]<<8^a[S&255]^i[A+1],b=a[w>>>24]<<24^a[T>>16&255]<<16^a[S>>8&255]<<8^a[C&255]^i[A+2],x=a[T>>>24]<<24^a[S>>16&255]<<16^a[C>>8&255]<<8^a[w&255]^i[A+3],_[t]=M(v^f),_[t+1]=M(x^p),_[t+2]=M(b^m),_[t+3]=M(y^h),f=E,p=D,m=O,h=k,t+=4}return _.buffer}},Ba=class{constructor(e,t,n){this.subtle=void 0,this.key=void 0,this.aesMode=void 0,this.subtle=e,this.key=t,this.aesMode=n}expandKey(){let e=Va(this.aesMode);return this.subtle.importKey(`raw`,this.key,{name:e},!1,[`encrypt`,`decrypt`])}};function Va(e){switch(e){case Ia.cbc:return`AES-CBC`;case Ia.ctr:return`AES-CTR`;default:throw Error(`[FastAESKey] invalid aes mode ${e}`)}}var Ha=16,Ua=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 e=self.crypto;e&&(this.subtle=e.subtle||e.webkitSubtle)}catch{}this.useSoftware=!this.subtle}destroy(){this.subtle=null,this.softwareDecrypter=null,this.key=null,this.fastAesKey=null,this.remainderData=null,this.currentIV=null,this.currentResult=null}isSync(){return this.useSoftware}flush(){let{currentResult:e,remainderData:t}=this;if(!e||t)return this.reset(),null;let n=new Uint8Array(e);this.reset();let r=this.decryptRange;return r?r.start===0&&r.end>=n.length?n:n.slice(r.start,r.end):Ra(n)}reset(){this.currentResult=null,this.currentIV=null,this.remainderData=null,this.softwareDecrypter&&=null}decrypt(e,t,n,r,i){return this.decryptRange=i,this.useSoftware||i?new Promise((i,a)=>{let o=ArrayBuffer.isView(e)?e:new Uint8Array(e);this.softwareDecrypt(o,t,n,r);let s=this.flush();s?i(s.buffer):a(Error(`[softwareDecrypt] Failed to decrypt data`))}):this.webCryptoDecrypt(new Uint8Array(e),t,n,r)}softwareDecrypt(e,t,n,r){let{currentIV:i,currentResult:a,remainderData:o}=this;if(r!==Ia.cbc||t.byteLength!==16)return U.warn(`SoftwareDecrypt: can only handle AES-128-CBC`),null;this.logOnce(`JS AES decrypt`),o&&(e=Tr(o,e),this.remainderData=null);let s=this.getValidChunk(e);if(!s.length)return null;i&&(n=i);let c=this.softwareDecrypter;c||=this.softwareDecrypter=new za,c.expandKey(t);let l=a;return this.currentResult=c.decrypt(s.buffer,0,n),this.currentIV=s.slice(-16).buffer,l||null}webCryptoDecrypt(e,t,n,r){if(this.key!==t||!this.fastAesKey){if(!this.subtle)return Promise.resolve(this.onWebCryptoError(e,t,n,r));this.key=t,this.fastAesKey=new Ba(this.subtle,t,r)}return this.fastAesKey.expandKey().then(t=>this.subtle?(this.logOnce(`WebCrypto AES decrypt`),new La(this.subtle,new Uint8Array(n),r).decrypt(e.buffer,t)):Promise.reject(Error(`web crypto not initialized`))).catch(i=>(U.warn(`[decrypter]: WebCrypto Error, disable WebCrypto API, ${i.name}: ${i.message}`),this.onWebCryptoError(e,t,n,r)))}onWebCryptoError(e,t,n,r){let i=this.enableSoftwareAES;if(i){this.useSoftware=!0,this.logEnabled=!0,this.softwareDecrypt(e,t,n,r);let i=this.flush();if(i)return i.buffer}throw Error(`WebCrypto`+(i?` and softwareDecrypt`:``)+`: failed to decrypt data`)}getValidChunk(e){let t=e,n=e.length-e.length%Ha;return n!==e.length&&(t=e.slice(0,n),this.remainderData=e.slice(n)),t}logOnce(e){this.logEnabled&&=(U.log(`[decrypter]: ${e}`),!1)}},Wa=2**17,Ga=class{constructor(e){this.config=void 0,this.loader=null,this.partLoadTimeout=-1,this.config=e}destroy(){this.loader&&=(this.loader.destroy(),null)}abort(){this.loader&&this.loader.abort()}load(e,t,n,r){let i=e.url;if(!i)return Promise.reject(new Xa({type:F.NETWORK_ERROR,details:I.FRAG_LOAD_ERROR,fatal:!1,frag:e,error:Error(`Fragment does not have a ${i?`part list`:`url`}`),networkDetails:null}));this.abort();let a=this.config,o=a.fLoader,s=a.loader;return new Promise((c,l)=>{if(this.loader&&this.loader.destroy(),e.gap){if(e.tagList.some(e=>e[0]===`GAP`)){l(Ja(e));return}e.gap=!1}let u=this.loader=o?new o(a):new s(a),d=Ka(e,null,t);e.loader=u;let f=Ut(a.fragLoadPolicy.default),p={loadPolicy:f,timeout:f.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:e.sn===`initSegment`?1/0:Wa};u.stats.retry=e.stats.retry,e.stats=u.stats;let m={onSuccess:(t,n,r,i)=>{this.resetLoader(e,u);let a=t.data;r.resetIV&&e.decryptdata&&(e.decryptdata.iv=new Uint8Array(a.slice(0,16)),a=a.slice(16)),c({frag:e,part:null,payload:a,networkDetails:i})},onError:(t,n,r,a)=>{this.resetLoader(e,u),l(new Xa({type:F.NETWORK_ERROR,details:I.FRAG_LOAD_ERROR,fatal:!1,frag:e,response:H({url:i,data:void 0},t),error:Error(`HTTP Error ${t.code} ${t.text}`),networkDetails:r,stats:a}))},onAbort:(t,n,r)=>{this.resetLoader(e,u),l(new Xa({type:F.NETWORK_ERROR,details:I.INTERNAL_ABORTED,fatal:!1,frag:e,error:Error(`Aborted`),networkDetails:r,stats:t}))},onTimeout:(t,n,r)=>{this.resetLoader(e,u),l(new Xa({type:F.NETWORK_ERROR,details:I.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,error:Error(`Timeout after ${p.timeout}ms`),networkDetails:r,stats:t}))}};if(n){let t=this.gateProgress(n,r);m.onProgress=(n,r,i,a)=>t({frag:e,part:null,payload:i,networkDetails:a})}u.load(d,p,m)})}gateProgress(e,t){let n=e;if(t){let r=[],i=!1;t.then(()=>{i=!0,r.forEach(t=>e(t)),r.length=0}).catch(()=>{}),n=t=>{i?e(t):r.push(t)}}return n}loadPart(e,t,n){this.abort();let r=this.config,i=r.fLoader,a=r.loader;return new Promise((o,s)=>{if(this.loader&&this.loader.destroy(),e.gap||t.gap){s(Ja(e,t));return}let c=this.loader=i?new i(r):new a(r),l=Ka(e,t);e.loader=c;let u=Ut(r.fragLoadPolicy.default),d={loadPolicy:u,timeout:u.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:Wa};t.stats=c.stats,c.load(l,d,{onSuccess:(r,i,a,s)=>{this.resetLoader(e,c),this.updateStatsFromPart(e,t);let l={frag:e,part:t,payload:r.data,networkDetails:s};n(l),o(l)},onError:(n,r,i,a)=>{this.resetLoader(e,c),s(new Xa({type:F.NETWORK_ERROR,details:I.FRAG_LOAD_ERROR,fatal:!1,frag:e,part:t,response:H({url:l.url,data:void 0},n),error:Error(`HTTP Error ${n.code} ${n.text}`),networkDetails:i,stats:a}))},onAbort:(n,r,i)=>{e.stats.aborted=t.stats.aborted,this.resetLoader(e,c),s(new Xa({type:F.NETWORK_ERROR,details:I.INTERNAL_ABORTED,fatal:!1,frag:e,part:t,error:Error(`Aborted`),networkDetails:i,stats:n}))},onTimeout:(n,r,i)=>{this.resetLoader(e,c),s(new Xa({type:F.NETWORK_ERROR,details:I.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,part:t,error:Error(`Timeout after ${d.timeout}ms`),networkDetails:i,stats:n}))}})})}updateStatsFromPart(e,t){let n=e.stats,r=t.stats,i=r.total;if(n.loaded+=r.loaded,i){let r=Math.round(e.duration/t.duration),a=Math.min(Math.round(n.loaded/i),r),o=(r-a)*Math.round(n.loaded/a);n.total=n.loaded+o}else n.total=Math.max(n.loaded,n.total);let a=n.loading,o=r.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 Ka(e,t=null,n){let r=t||e,i={type:R.MEDIA_FRAGMENT,frag:e,part:t,responseType:`arraybuffer`,url:r.url,headers:{},rangeStart:0,rangeEnd:0},a=qa(e,t,n);return a.resetIV&&(i.resetIV=!0),a.byteRange&&(i.rangeStart=a.byteRange.start,i.rangeEnd=a.byteRange.end),i}function qa(e,t=null,n){let r={},i=t||e,a=i.byteRangeStartOffset,o=i.byteRangeEndOffset;if(P(a)&&P(o)){if((e.sn===`initSegment`||n)&&Ya(e.decryptdata?.method)){let e=Math.floor(a/16)*16,t=Math.ceil(o/16)*16;r.decryptRange={start:a-e,end:o-e},e>=16&&(r.resetIV=!0,e-=16),r.byteRange={start:e,end:t}}else r.byteRange={start:a,end:o}}return r}function Ja(e,t){let n=Error(`GAP ${e.gap?`tag`:`attribute`} found`),r={type:F.MEDIA_ERROR,details:I.FRAG_GAP,fatal:!1,frag:e,error:n,networkDetails:null};return t&&(r.part=t),(t||e).stats.aborted=!0,new Xa(r)}function Ya(e){return e===`AES-128`||e===`AES-256`}var Xa=class extends Error{constructor(e){super(e.error.message),this.data=void 0,this.data=e}},Za=class extends Xt{constructor(e,t){super(e,t),this._boundTick=void 0,this._tickTimer=null,this._tickInterval=null,this._tickCallCount=0,this._boundTick=this.tick.bind(this)}destroy(){this.onHandlerDestroying(),this.onHandlerDestroyed()}onHandlerDestroying(){this.clearNextTick(),this.clearInterval()}onHandlerDestroyed(){}hasInterval(){return!!this._tickInterval}hasNextTick(){return!!this._tickTimer}setInterval(e){return!this._tickInterval&&(this._tickCallCount=0,this._tickInterval=self.setInterval(this._boundTick,e),!0)}clearInterval(){return this._tickInterval?(self.clearInterval(this._tickInterval),this._tickInterval=null,!0):!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(){}},Qa=class{constructor(e,t,n,r=0,i=-1,a=!1,o,s,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=$a(),this.buffering={audio:$a(),video:$a(),audiovideo:$a()},this.level=e,this.sn=t,this.id=n,this.size=r,this.part=i,this.partial=a,this.duration=o||0,this.decryptRange=c,this.iframe=s||!1}};function $a(){return{start:0,executeStart:0,executeEnd:0,end:0}}var eo=/\{\$([a-zA-Z0-9-_]+)\}/g;function to(e){return eo.lastIndex=0,eo.test(e)}function no(e,t){if(e.variableList!==null||e.hasVariableRefs){let n=e.variableList;return t.replace(eo,t=>{let r=t.substring(2,t.length-1),i=n?.[r];return i===void 0?(e.playlistParsingError||=Error(`Missing preceding EXT-X-DEFINE tag for Variable Reference: "${r}"`),t):i})}return t}function ro(e,t,n){let r=e.variableList;r||(e.variableList=r={});let i,a;if(`QUERYPARAM`in t){i=t.QUERYPARAM;try{let e=new self.URL(n).searchParams;if(e.has(i))a=e.get(i);else throw Error(`"${i}" does not match any query parameter in URI: "${n}"`)}catch(t){e.playlistParsingError||=Error(`EXT-X-DEFINE QUERYPARAM: ${t.message}`)}}else i=t.NAME,a=t.VALUE;i in r?e.playlistParsingError||=Error(`EXT-X-DEFINE duplicate Variable Name declarations: "${i}"`):r[i]=a||``}function io(e,t,n){let r=t.IMPORT;if(n&&r in n){let t=e.variableList;t||(e.variableList=t={}),t[r]=n[r]}else e.playlistParsingError||=Error(`EXT-X-DEFINE IMPORT attribute not found in Multivariant Playlist: "${r}"`)}var ao=/^(\d+)x(\d+)$/,oo=/(.+?)=(".*?"|.*?)(?:,|$)/g,so=class e{constructor(t,n){typeof t==`string`&&(t=e.parseAttrList(t,n)),V(this,t)}get clientAttrs(){return Object.keys(this).filter(e=>e.substring(0,2)===`X-`)}decimalInteger(e){let t=parseInt(this[e],10);return t>2**53-1?1/0:t}hexadecimalInteger(e){if(this[e]){let t=(this[e]||`0x`).slice(2);t=(t.length&1?`0`:``)+t;let n=new Uint8Array(t.length/2);for(let e=0;e<t.length/2;e++)n[e]=parseInt(t.slice(e*2,e*2+2),16);return n}return null}hexadecimalIntegerAsNumber(e){let t=parseInt(this[e],16);return t>2**53-1?1/0:t}decimalFloatingPoint(e){return parseFloat(this[e])}optionalFloat(e,t){let n=this[e];return n?parseFloat(n):t}enumeratedString(e){return this[e]}enumeratedStringList(e,t){let n=this[e];return(n?n.split(/[ ,]+/):[]).reduce((e,t)=>(e[t.toLowerCase()]=!0,e),t)}bool(e){return this[e]===`YES`}decimalResolution(e){let t=ao.exec(this[e]);if(t!==null)return{width:parseInt(t[1],10),height:parseInt(t[2],10)}}static parseAttrList(e,t){let n,r={};for(oo.lastIndex=0;(n=oo.exec(e))!==null;){let i=n[1].trim(),a=n[2],o=a.indexOf(`"`)===0&&a.lastIndexOf(`"`)===a.length-1,s=!1;if(o)a=a.slice(1,-1);else switch(i){case`IV`:case`SCTE35-CMD`:case`SCTE35-IN`:case`SCTE35-OUT`:s=!0}if(t&&(o||s))a=no(t,a);else if(!s&&!o)switch(i){case`CLOSED-CAPTIONS`:if(a===`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`:U.warn(`${e}: attribute ${i} is missing quotes`)}r[i]=a}return r}},co=`com.apple.hls.interstitial`;function lo(e){return e!==`ID`&&e!==`CLASS`&&e!==`CUE`&&e!==`START-DATE`&&e!==`DURATION`&&e!==`END-DATE`&&e!==`END-ON-NEXT`}function uo(e){return e===`SCTE35-OUT`||e===`SCTE35-IN`||e===`SCTE35-CMD`}var fo=class{constructor(e,t,n=0){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=t?.tagOrder??n,t){let n=t.attr;for(let t in n)if(Object.prototype.hasOwnProperty.call(e,t)&&e[t]!==n[t]){U.warn(`DATERANGE tag attribute: "${t}" does not match for tags with ID: "${e.ID}"`),this._badValueForSameId=t;break}e=V(new so({}),n,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 n=t?.endDate||new Date(e[`END-DATE`]);P(n.getTime())&&(this._endDate=n)}}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?(U.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?null:this._dateAtEnd=new Date(this._startDate.getTime()+t*1e3)}get duration(){if(`DURATION`in this.attr){let e=this.attr.decimalFloatingPoint(`DURATION`);if(P(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===co}get isValid(){return!!this.id&&!this._badValueForSameId&&P(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`:P(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 po(e,t){return e.length===t.length&&!e.some((e,n)=>e!==t[n])}function mo(e,t){return!e&&!t?!0:!e||!t?!1:po(e,t)}function ho(e){return e===`AES-128`||e===`AES-256`||e===`AES-256-CTR`}function go(e){switch(e){case`AES-128`:case`AES-256`:return Ia.cbc;case`AES-256-CTR`:return Ia.ctr;default:throw Error(`invalid full segment method ${e}`)}}function _o(e){return Uint8Array.from(unescape(encodeURIComponent(e)),e=>e.charCodeAt(0))}function vo(e){let t=_o(e).subarray(0,16),n=new Uint8Array(16);return n.set(t,16-t.length),n}function yo(e){let t=function(e,t,n){let r=e[t];e[t]=e[n],e[n]=r};t(e,0,3),t(e,1,2),t(e,4,5),t(e,6,7)}function bo(e){let t=e.split(`:`),n=null;if(t[0]===`data`&&t.length===2){let e=t[1].split(`;`),r=e[e.length-1].split(`,`);if(r.length===2){let t=r[0]===`base64`,i=r[1];t?(e.splice(-1,1),n=Wn(i)):n=vo(i)}}return n}var xo=typeof self<`u`?self:void 0,So={CLEARKEY:`org.w3.clearkey`,FAIRPLAY:`com.apple.fps`,PLAYREADY:`com.microsoft.playready`,WIDEVINE:`com.widevine.alpha`},Co={CLEARKEY:`org.w3.clearkey`,FAIRPLAY:`com.apple.streamingkeydelivery`,PLAYREADY:`com.microsoft.playready`,WIDEVINE:`urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed`};function wo(e){switch(e){case Co.FAIRPLAY:return So.FAIRPLAY;case Co.PLAYREADY:return So.PLAYREADY;case Co.WIDEVINE:return So.WIDEVINE;case Co.CLEARKEY:return So.CLEARKEY}}var To={WIDEVINE:`edef8ba979d64acea3c827dcd51d21ed`};function Eo(e){switch(e){case So.FAIRPLAY:return Co.FAIRPLAY;case So.PLAYREADY:return Co.PLAYREADY;case So.WIDEVINE:return Co.WIDEVINE;case So.CLEARKEY:return Co.CLEARKEY}}function Do(e){let{drmSystems:t,widevineLicenseUrl:n}=e,r=t?[So.FAIRPLAY,So.WIDEVINE,So.PLAYREADY,So.CLEARKEY].filter(e=>!!t[e]):[];return!r[So.WIDEVINE]&&n&&r.push(So.WIDEVINE),r}var Oo=function(e){return xo!=null&&(e=xo.navigator)!=null&&e.requestMediaKeySystemAccess?self.navigator.requestMediaKeySystemAccess.bind(self.navigator):null}();function ko(e,t,n,r){let i;switch(e){case So.FAIRPLAY:i=[`cenc`,`sinf`];break;case So.WIDEVINE:case So.PLAYREADY:i=[`cenc`];break;case So.CLEARKEY:i=[`cenc`,`keyids`];break;default:throw Error(`Unknown key-system: ${e}`)}return Ao(i,t,n,r)}function Ao(e,t,n,r){return[{initDataTypes:e,persistentState:r.persistentState||`optional`,distinctiveIdentifier:r.distinctiveIdentifier||`optional`,sessionTypes:r.sessionTypes||[r.sessionType||`temporary`],audioCapabilities:t.map(e=>({contentType:`audio/mp4; codecs=${e}`,robustness:r.audioRobustness||``,encryptionScheme:r.audioEncryptionScheme||null})),videoCapabilities:n.map(e=>({contentType:`video/mp4; codecs=${e}`,robustness:r.videoRobustness||``,encryptionScheme:r.videoEncryptionScheme||null}))}]}function jo(e){var t;return!!e&&(e.sessionType===`persistent-license`||!!((t=e.sessionTypes)!=null&&t.some(e=>e===`persistent-license`)))}function Mo(e){let t=Gn(new Uint16Array(e.buffer,e.byteOffset,e.byteLength/2)),n=t.substring(t.indexOf(`<`),t.length),r=new DOMParser().parseFromString(n,`text/xml`).getElementsByTagName(`KID`)[0];if(r){let e=r.childNodes[0]?r.childNodes[0].nodeValue:r.getAttribute(`VALUE`);if(e){let t=Wn(e).subarray(0,16);return yo(t),t}}return null}var No={},Po=class e{static clearKeyUriToKeyIdMap(){No={}}static setKeyIdForUri(e,t){No[e]=t}static addKeyIdForUri(e){let t=Object.keys(No).length%(2**53-1),n=new Uint8Array(16);return new DataView(n.buffer,12,4).setUint32(0,t),No[e]=n,n}constructor(e,t,n,r=[1],i=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=n,this.keyFormatVersions=r,this.iv=i,this.encrypted=e?e!==`NONE`:!1,this.isCommonEncryption=this.encrypted&&!ho(e),a!=null&&a.startsWith(`0x`)&&(this.keyId=new Uint8Array(Un(a)))}matches(e){return e.uri===this.uri&&e.method===this.method&&e.encrypted===this.encrypted&&e.keyFormat===this.keyFormat&&po(e.keyFormatVersions,this.keyFormatVersions)&&mo(e.iv,this.iv)&&mo(e.keyId,this.keyId)}isSupported(){if(this.method){if(ho(this.method)||this.method===`NONE`)return!0;if(this.keyFormat===`identity`)return this.method===`SAMPLE-AES`;switch(this.keyFormat){case Co.FAIRPLAY:case Co.WIDEVINE:case Co.PLAYREADY:case Co.CLEARKEY:return[`SAMPLE-AES`,`SAMPLE-AES-CENC`,`SAMPLE-AES-CTR`].indexOf(this.method)!==-1}}return!1}getDecryptData(t,n){if(!this.encrypted||!this.uri)return null;if(ho(this.method)){let n=this.iv;return n||=(typeof t!=`number`&&(U.warn(`missing IV for initialization segment with method="${this.method}" - compliance issue`),t=0),Lo(t)),new e(this.method,this.uri,`identity`,this.keyFormatVersions,n)}if(this.keyId){let t=No[this.uri];if(t&&!po(this.keyId,t)&&e.setKeyIdForUri(this.uri,this.keyId),this.pssh)return this}let r=bo(this.uri);if(r)switch(this.keyFormat){case Co.WIDEVINE:if(this.pssh=r,!this.keyId){let e=Pr(r.buffer).filter(e=>e.systemId===To.WIDEVINE);if(e.length){var i;let t=e[0];this.keyId=(i=t.kids)!=null&&i.length?t.kids[0]:null}}this.keyId||=Io(n);break;case Co.PLAYREADY:{let e=new Uint8Array([154,4,240,121,152,64,66,134,171,146,230,91,224,136,95,149]);this.pssh=Nr(e,null,r),this.keyId=Mo(r);break}default:{let e=r.subarray(0,16);if(e.length!==16){let t=new Uint8Array(16);t.set(e,16-e.length),e=t}this.keyId=e;break}}if(this.keyId?.byteLength!==16){let t;t=Fo(n),t||(t=Io(n),t||=No[this.uri]),t&&(this.keyId=t,e.setKeyIdForUri(this.uri,t))}return this}};function Fo(e){let t=e?.[Co.WIDEVINE];return t?t.keyId:null}function Io(e){let t=e?.[Co.PLAYREADY];if(t){let e=bo(t.uri);if(e)return Mo(e)}return null}function Lo(e){let t=new Uint8Array(16);for(let n=12;n<16;n++)t[n]=e>>8*(15-n)&255;return t}var Ro=/#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,zo=/#EXT-X-MEDIA:(.*)/g,Bo=/^#EXT(?:INF|-X-TARGETDURATION):/m,Vo=new RegExp([`#EXTINF:\\s*(\\d+(?:\\.\\d*)?|\\.\\d+)?(?:,(.*)\\s+)?`,`(?!#) *(\\S[^\\r\\n]*)`,`#.*`].join(`|`),`g`),Ho=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):(.+)`,`#EXT-X-(BITRATE|DISCONTINUITY-SEQUENCE|MEDIA-SEQUENCE|TARGETDURATION|VERSION): *(\\d+)`,`#EXT-X-(DISCONTINUITY|ENDLIST|GAP|INDEPENDENT-SEGMENTS|I-FRAMES-ONLY)`,`(#)([^:]*):(.*)`,`(#)(.*)(?:.*)\\r?\\n?`].join(`|`)),Uo=class e{static findGroup(e,t){for(let n=0;n<e.length;n++){let r=e[n];if(r.id===t)return r}}static resolve(e,t){return St.buildAbsoluteURL(t,e,{alwaysNormalize:!0})}static isMediaPlaylist(e){return Bo.test(e)}static parseMasterPlaylist(t,n){let r={contentSteering:null,levels:[],iframeVariants:[],playlistParsingError:null,sessionData:null,sessionKeys:null,startTimeOffset:null,variableList:null,hasVariableRefs:to(t)},i=[];if(Ro.lastIndex=0,!t.startsWith(`#EXTM3U`))return r.playlistParsingError=Error(`no EXTM3U delimiter`),r;let a;for(;(a=Ro.exec(t))!=null;)if(a[1]){let e=Wo(new so(a[1],r),a[2],n,r,i);e&&r.levels.push(e)}else if(a[3]){let t=a[3],o=a[4];switch(t){case`I-FRAME-STREAM-INF`:{let e=new so(o,r),t=Wo(e,e.URI,n,r,i,!0);t&&r.iframeVariants.push(t)}break;case`SESSION-DATA`:{let e=new so(o,r),t=e[`DATA-ID`];t&&(r.sessionData===null&&(r.sessionData={}),r.sessionData[t]=e);break}case`SESSION-KEY`:{let e=qo(o,n,r);e.encrypted&&e.isSupported()?(r.sessionKeys===null&&(r.sessionKeys=[]),r.sessionKeys.push(e)):U.warn(`[Keys] Ignoring invalid EXT-X-SESSION-KEY tag: "${o}"`);break}case`DEFINE`:ro(r,new so(o,r),n);break;case`CONTENT-STEERING`:{let t=new so(o,r);r.contentSteering={uri:e.resolve(t[`SERVER-URI`],n),pathwayId:t[`PATHWAY-ID`]||`.`};break}case`START`:r.startTimeOffset=Jo(o)}}return r.levels=i.length>0&&i.length<r.levels.length?i:r.levels,r.levels.length===0&&(r.playlistParsingError=Error(`no levels found in manifest`)),r}static parseMasterPlaylistMedia(t,n,r){let i,a={},o=r.levels,s={AUDIO:o.map(e=>({id:e.attrs.AUDIO,audioCodec:e.audioCodec})),SUBTITLES:o.map(e=>({id:e.attrs.SUBTITLES,textCodec:e.textCodec})),"CLOSED-CAPTIONS":[]},c=0;for(zo.lastIndex=0;(i=zo.exec(t))!==null;){let t=new so(i[1],r),o=t.TYPE;if(o){let r=s[o],i=a[o]||[];a[o]=i;let l=t.LANGUAGE,u=t[`ASSOC-LANGUAGE`],d=t.CHANNELS,f=t.CHARACTERISTICS,p=t[`INSTREAM-ID`],m={attrs:t,bitrate:0,id:c++,groupId:t[`GROUP-ID`]||``,name:t.NAME||l||``,type:o,default:t.bool(`DEFAULT`),autoselect:t.bool(`AUTOSELECT`),forced:t.bool(`FORCED`),lang:l,url:t.URI?e.resolve(t.URI,n):``};if(u&&(m.assocLang=u),d&&(m.channels=d),f&&(m.characteristics=f),p&&(m.instreamId=p),r!=null&&r.length){let t=e.findGroup(r,m.groupId)||r[0];Xo(m,t,`audioCodec`),Xo(m,t,`textCodec`)}i.push(m)}}return a}static parseLevelPlaylist(e,t,n,r,i,a){let o={url:t},s=new ha(t),c=s.fragments,l=[],u=null,d=0,f=0,p=0,m=0,h=0,g=null,_=new Ot(r,o),v,y,b,x=-1,S=!1,C=null,w;if(Vo.lastIndex=0,s.m3u8=e,s.hasVariableRefs=to(e),Vo.exec(e)?.[0]!==`#EXTM3U`)return s.playlistParsingError=Error(`Missing format identifier #EXTM3U`),s;for(;(v=Vo.exec(e))!==null;){S&&(S=!1,_=new Ot(r,o),_.playlistOffset=p,_.setStart(p),_.sn=d,_.cc=m,h&&(_.bitrate=h),_.level=n,u&&(_.initSegment=u,u.rawProgramDateTime&&(_.rawProgramDateTime=u.rawProgramDateTime,u.rawProgramDateTime=null),C&&=(_.setByteRange(C),null)));let e=v[1];if(e){_.duration=parseFloat(e);let t=(` `+v[2]).slice(1);_.title=t||null,_.tagList.push(t?[`INF`,e,t]:[`INF`,e])}else if(v[3]){if(P(_.duration)){_.playlistOffset=p,_.setStart(p),b&&es(_,b,s),_.sn=d,_.level=n,_.cc=m;let e=(` `+v[3]).slice(1);_.relurl=no(s,e),Qo(_,g,l),g=_,p+=_.duration,d++,f=0;let t=_.byteRange;if(t.length===2&&(_.bitrate=(t[1]-t[0])*8/_.duration|0),s.iframesOnly&&t[0]&&u?.cc!==m){let e=new Ot(r,o);e.relurl=_.relurl,e.setByteRange(`${Math.min(t[0],1316)}@0`),e.level=n,e.sn=`initSegment`,b&&(e.levelkeys=b,b.identity&&(e._decryptdata=b.identity.getDecryptData(0))),u=e,_.initSegment=u}c.push(_),S=!0}}else{if(v=v[0].match(Ho),!v){U.warn(`No matches on slow regex match for level playlist!`);continue}for(y=1;y<v.length&&v[y]===void 0;y++);let e=(` `+v[y]).slice(1),i=(` `+v[y+1]).slice(1),l=v[y+2]?(` `+v[y+2]).slice(1):null;switch(e){case`BYTERANGE`:g?_.setByteRange(i,g):_.setByteRange(i);break;case`PROGRAM-DATE-TIME`:_.rawProgramDateTime=i,_.tagList.push([`PROGRAM-DATE-TIME`,i]),x===-1&&(x=c.length);break;case`PLAYLIST-TYPE`:s.type&&ts(s,e,v),s.type=i.toUpperCase();break;case`MEDIA-SEQUENCE`:s.startSN===0?g!==null&&ns(s,e,v):ts(s,e,v),s.startSN=parseInt(i),d=s.startSN+s.skippedSegments;break;case`SKIP`:{s.skippedSegments&&ts(s,e,v);let t=new so(i,s),n=t.decimalInteger(`SKIPPED-SEGMENTS`);if(P(n)){s.skippedSegments+=n;for(let e=n;e--;)c.push(null);d+=n}let r=t.enumeratedString(`RECENTLY-REMOVED-DATERANGES`);r&&(s.recentlyRemovedDateranges=(s.recentlyRemovedDateranges||[]).concat(r.split(` `)));break}case`TARGETDURATION`:s.targetduration!==0&&ts(s,e,v),s.targetduration=Math.max(parseInt(i),1);break;case`VERSION`:s.version!==null&&ts(s,e,v),s.version=parseInt(i);break;case`INDEPENDENT-SEGMENTS`:break;case`I-FRAMES-ONLY`:s.iframesOnly=!0;break;case`ENDLIST`:s.live||ts(s,e,v),s.live=!1;break;case`#`:(i||l)&&_.tagList.push(l?[i,l]:[i]);break;case`DISCONTINUITY`:m++,_.tagList.push([`DIS`]);break;case`GAP`:_.gap=!0,_.tagList.push([e]);break;case`BITRATE`:_.tagList.push([e,i]),h=parseInt(i)*1e3,P(h)?_.bitrate=h:h=0;break;case`DATERANGE`:{let e=new so(i,s),t=new fo(e,s.dateRanges[e.ID],s.dateRangeTagCount);s.dateRangeTagCount++,t.isValid||s.skippedSegments?s.dateRanges[t.id]=t:U.log(`Ignoring invalid DATERANGE tag: ${t.invalidReason}: ${i}`),_.tagList.push([`EXT-X-DATERANGE`,i]);break}case`DEFINE`:{let e=new so(i,s);`IMPORT`in e?io(s,e,a):ro(s,e,t)}break;case`DISCONTINUITY-SEQUENCE`:s.startCC!==0&&ts(s,e,v),s.startCC=m=parseInt(i),c.forEach(e=>e&&(e.cc=m));break;case`KEY`:{let e=qo(i,t,s);if(e.isSupported()){if(e.method===`NONE`){b=void 0;break}b||={};let t=b[e.keyFormat];t!=null&&t.matches(e)||(t&&(b=V({},b)),b[e.keyFormat]=e)}else U.warn(`[Keys] Ignoring unsupported EXT-X-KEY tag: "${i}"`);break}case`START`:s.startTimeOffset=Jo(i);break;case`MAP`:{let e=new so(i,s);if(_.duration){let t=new Ot(r,o);$o(t,e,n,b),u=t,_.initSegment=u,u.rawProgramDateTime&&!_.rawProgramDateTime&&(_.rawProgramDateTime=u.rawProgramDateTime)}else{let t=_.byteRangeEndOffset;if(t){let e=_.byteRangeStartOffset;C=`${t-e}@${e}`}else C=null;$o(_,e,n,b),u=_,S=!0}u.cc=m;break}case`SERVER-CONTROL`:w&&ts(s,e,v),w=new so(i),s.canBlockReload=w.bool(`CAN-BLOCK-RELOAD`),s.canSkipUntil=w.optionalFloat(`CAN-SKIP-UNTIL`,0),s.canSkipDateRanges=s.canSkipUntil>0&&w.bool(`CAN-SKIP-DATERANGES`),s.partHoldBack=w.optionalFloat(`PART-HOLD-BACK`,0),s.holdBack=w.optionalFloat(`HOLD-BACK`,0);break;case`PART-INF`:s.partTarget&&ts(s,e,v),s.partTarget=new so(i).decimalFloatingPoint(`PART-TARGET`);break;case`PART`:{let e=s.partList;e||=s.partList=[];let t=f>0?e[e.length-1]:void 0,n=f++,r=new kt(new so(i,s),_,o,n,t);e.push(r),_.duration+=r.duration;break}case`PRELOAD-HINT`:s.preloadHint=new so(i,s);break;case`RENDITION-REPORT`:{let e=new so(i,s);s.renditionReports=s.renditionReports||[],s.renditionReports.push(e);break}default:U.warn(`line parsed but not handled: ${v}`)}}}g&&!g.relurl?(c.pop(),p-=g.duration,s.partList&&(s.fragmentHint=g)):s.partList&&(Qo(_,g,l),_.cc=m,s.fragmentHint=_,b&&es(_,b,s)),s.targetduration||(s.playlistParsingError=Error(`Missing Target Duration`));let T=c.length,E=c[0],D=c[T-1];if(p+=s.skippedSegments*s.targetduration,p>0&&T&&D){s.averagetargetduration=p/T;let e=D.sn;s.endSN=e===`initSegment`?0:e,s.live||(D.endList=!0),x>0&&(Zo(c,x,x>T-1?_:null),E&&l.unshift(E))}return s.fragmentHint&&(p+=s.fragmentHint.duration),s.totalduration=p,l.length&&s.dateRangeTagCount&&E&&Go(l,s),s.endCC=m,s}};function Wo(e,t,n,r,i,a){var o;if(t===void 0)return null;let s=no(r,t),c={attrs:e,bitrate:e.decimalInteger(`BANDWIDTH`)||e.decimalInteger(`AVERAGE-BANDWIDTH`),name:e.NAME,url:Uo.resolve(s,n)},l=e.decimalResolution(`RESOLUTION`);l&&(c.width=l.width,c.height=l.height),Yo(e.CODECS,c);let u=e[`SUPPLEMENTAL-CODECS`];return u&&(c.supplemental={},Yo(u,c.supplemental)),(o=c.unknownCodecs)!=null&&o.length||i.push(c),a&&(c.iframes=!0),c}function Go(e,t){let n=e.length;if(!n){if(t.hasProgramDateTime){let r=t.fragments[t.fragments.length-1];e.push(r),n++}else return}let r=e[n-1],i=t.live?1/0:t.totalduration,a=Object.keys(t.dateRanges);for(let o=a.length;o--;){let s=t.dateRanges[a[o]],c=s.startDate.getTime();s.tagAnchor=r.ref;for(let r=n;r--&&!(e[r]?.sn<t.startSN);){let n=Ko(t,c,e,r,i);if(n){s.tagAnchor=n.ref;break}}}}function Ko(e,t,n,r,i){let a=n[r];if(a){let o=a.programDateTime;if((t>=o||r===0)&&t<=o+((n[r+1]?.start||i)-a.start)*1e3){let i=a.sn-e.startSN,o=e.fragments;if(i>=0&&i<o.length){if(o.length>n.length){let a=n[r+1]||o[o.length-1],s=Math.min(a.sn-e.startSN,o.length-1);for(let e=s;e>i;e--){let n=o[e].programDateTime;if(t>=n&&t<n+o[e].duration*1e3)return o[e]}}return o[i]}}}return null}function qo(e,t,n){let r=new so(e,n),i=r.METHOD??``,a=r.URI,o=r.hexadecimalInteger(`IV`),s=r.KEYFORMATVERSIONS,c=r.KEYFORMAT??`identity`;return a&&r.IV&&!o&&U.error(`Invalid IV: ${r.IV}`),new Po(i,a?Uo.resolve(a,t):``,c,(s||`1`).split(`/`).map(Number).filter(Number.isFinite),o,r.KEYID)}function Jo(e){let t=new so(e).decimalFloatingPoint(`TIME-OFFSET`);return P(t)?t:null}function Yo(e,t){let n=(e||``).split(/[ ,]+/).filter(e=>e);[`video`,`audio`,`text`,`image`].forEach(e=>{let r=n.filter(t=>Xr(t,e));r.length&&(t[`${e}Codec`]=r.map(e=>e.split(`/`)[0]).join(`,`),n=n.filter(e=>r.indexOf(e)===-1))}),t.unknownCodecs=n}function Xo(e,t,n){let r=t[n];r&&(e[n]=r)}function Zo(e,t,n){if(n||=e[t],n)for(let r=t;r--;){let t=e[r];if(!t)return;t.programDateTime=n.programDateTime-t.duration*1e3,n=t}}function Qo(e,t,n){e.rawProgramDateTime?n.push(e):t!=null&&t.programDateTime&&(e.programDateTime=t.endProgramDateTime)}function $o(e,t,n,r){e.relurl=t.URI,t.BYTERANGE&&e.setByteRange(t.BYTERANGE),e.level=n,e.sn=`initSegment`,r&&(e.levelkeys=r),e.initSegment=null}function es(e,t,n){e.levelkeys=t;let{encryptedFragments:r}=n;(!r.length||r[r.length-1].levelkeys!==t)&&Object.keys(t).some(e=>t[e].isCommonEncryption)&&r.push(e)}function ts(e,t,n){e.playlistParsingError=Error(`#EXT-X-${t} must not appear more than once (${n[0]})`)}function ns(e,t,n){e.playlistParsingError=Error(`#EXT-X-${t} must appear before the first Media Segment (${n[0]})`)}function rs(e,t){let n=t.startPTS;if(P(n)){let r=0,i;t.sn>e.sn?(r=n-e.start,i=e):(r=e.start-n,i=t),i.duration!==r&&i.setDuration(r)}else t.sn>e.sn?e.cc===t.cc&&e.minEndPTS?t.setStart(e.start+(e.minEndPTS-e.start)):t.setStart(e.start+e.duration):t.setStart(Math.max(e.start-t.duration,0))}function is(e,t,n,r,i,a,o,s){r-n<=0&&(s.warn(`Fragment should have a positive duration`,t),r=n+t.duration,a=i+t.duration);let c=n,l=r,u=t.startPTS,d=t.endPTS;if(P(u)){let o=Math.abs(u-n);e&&o>e.totalduration?s.warn(`media timestamps and playlist times differ by ${o}s for level ${t.level} ${e.url}`):t.deltaPTS=P(t.deltaPTS)?Math.max(o,t.deltaPTS):o,c=Math.max(n,u),n=Math.min(n,u),i=t.startDTS===void 0?i:Math.min(i,t.startDTS),l=Math.min(r,d),r=Math.max(r,d),a=t.endDTS===void 0?a:Math.max(a,t.endDTS)}let f=n-t.start;return t.start!==0&&t.setStart(n),t.setDuration(r-t.start),t.startPTS=n,t.maxStartPTS=c,t.startDTS=i,t.endPTS=r,t.minEndPTS=l,t.endDTS=a,as(e,t,f)}function as(e,t,n){let r=t.sn;if(!e||r<e.startSN||r>(e.fragmentHint?.sn||e.endSN))return 0;let i,a=r-e.startSN,o=e.fragments;for(o[a]=t,i=a;i>0;i--)rs(o[i],o[i-1]);for(i=a;i<o.length-1;i++)rs(o[i],o[i+1]);return e.fragmentHint&&rs(o[o.length-1],e.fragmentHint),e.PTSKnown=e.alignedSliding=!0,n}function os(e,t,n){if(e===t)return;let r=null,i=e.fragments;for(let e=i.length-1;e>=0;e--){let t=i[e].initSegment;if(t){r=t;break}}e.fragmentHint&&delete e.fragmentHint.endPTS;let a;ls(e,t,(e,n,i,o)=>{if(n.cc!==e.cc&&(e.cc>n.cc||t.skippedSegments)){let r=e.cc-n.cc;for(let e=i;e<o.length;e++)o[e].cc+=r;t.endCC=o[o.length-1].cc}P(e.startPTS)&&P(e.endPTS)&&(n.setStart(n.startPTS=e.startPTS),n.startDTS=e.startDTS,n.maxStartPTS=e.maxStartPTS,n.endPTS=e.endPTS,n.endDTS=e.endDTS,n.minEndPTS=e.minEndPTS,n.setDuration(e.endPTS-e.startPTS),n.duration&&(a=n),t.PTSKnown=t.alignedSliding=!0),e.hasStreams&&(n.elementaryStreams=e.elementaryStreams),n.loader=e.loader,n.gap=e.gap||n.gap,e.hasStats&&(n.stats=e.stats),e.initSegment&&(n.initSegment=e.initSegment,r=e.initSegment)});let o=t.fragments,s=t.fragmentHint?o.concat(t.fragmentHint):o;if(r&&s.forEach(e=>{e&&(!e.initSegment||e.initSegment.relurl===r?.relurl)&&(e.initSegment=r)}),t.skippedSegments){if(t.deltaUpdateFailed=o.some(e=>!e),t.deltaUpdateFailed){n.warn(`[level-helper] Previous playlist missing segments skipped in delta playlist`);for(let e=t.skippedSegments;e--;)o.shift();t.startSN=o[0].sn}else{t.canSkipDateRanges&&(t.dateRanges=ss(e.dateRanges,t,n));let r=e.fragments.filter(e=>e.rawProgramDateTime);if(e.hasProgramDateTime&&!t.hasProgramDateTime)for(let e=1;e<s.length;e++)s[e].programDateTime===null&&Qo(s[e],s[e-1],r);Go(r,t)}t.endCC=o[o.length-1].cc}else if(t.startSN>e.endSN&&o[0].cc<e.endCC){let n=e.endCC-o[0].cc;s.forEach(e=>{e.cc+=n}),t.endCC+=n}if(t.startCC||=ms(e,t.startSN-1)?.cc??o[0].cc,cs(e.partList,t.partList,(e,t)=>{t.elementaryStreams=e.elementaryStreams,t.stats=e.stats,t.gap=e.gap||t.gap}),a){let e=t.iframesOnly&&a.type===z.MAIN;is(t,a,a.startPTS,a.endPTS,a.startDTS,a.endDTS,e,n)}else ds(e,t);o.length&&(t.totalduration=t.edge-o[0].start),t.driftStartTime=e.driftStartTime,t.driftStart=e.driftStart;let c=t.advancedDateTime;if(t.advanced&&c){let e=t.edge;t.driftStart||=(t.driftStartTime=c,e),t.driftEndTime=c,t.driftEnd=e}else t.driftEndTime=e.driftEndTime,t.driftEnd=e.driftEnd,t.advancedDateTime=e.advancedDateTime;t.requestScheduled===-1&&(t.requestScheduled=e.requestScheduled)}function ss(e,t,n){let{dateRanges:r,recentlyRemovedDateranges:i}=t,a=V({},e);i&&i.forEach(e=>{delete a[e]});let o=Object.keys(a).length;return o?(Object.keys(r).forEach(e=>{let t=a[e],i=new fo(r[e].attr,t);i.isValid?(a[e]=i,t||(i.tagOrder+=o)):n.warn(`Ignoring invalid Playlist Delta Update DATERANGE tag: "${q(r[e].attr)}"`)}),a):r}function cs(e,t,n){if(e&&t){let r=0;for(let i=0,a=e.length;i<a;i++){let a=e[i],o=t[i+r];a&&o&&a.index===o.index&&a.fragment.sn===o.fragment.sn?n(a,o):r--}}}function ls(e,t,n){var r;let i=t.skippedSegments,a=Math.max(e.startSN,t.startSN)-t.startSN,o=+!!e.fragmentHint+(i?t.endSN:Math.min(e.endSN,t.endSN))-t.startSN,s=t.startSN-e.startSN,c=t.fragmentHint?t.fragments.concat(t.fragmentHint):t.fragments,l=(r=e.fragmentHint)!=null&&r.duration?e.fragments.concat(e.fragmentHint):e.fragments;for(let r=a;r<=o;r++){let a=l[s+r],o=c[r];if(i&&!o&&a&&(o=t.fragments[r]=a),a&&o){n(a,o,r,c);let i=a.relurl,s=o.relurl;if(i&&vs(i,s)){t.playlistParsingError=us(`media sequence mismatch ${o.sn}:`,e,t,a,o);return}if(a.cc!==o.cc){t.playlistParsingError=us(`discontinuity sequence mismatch (${a.cc}!=${o.cc})`,e,t,a,o);return}}}}function us(e,t,n,r,i){return Error(`${e} ${i.url}
|
|
19
19
|
Playlist starting @${t.startSN}
|
|
20
20
|
${t.m3u8}
|
|
21
21
|
|
|
22
22
|
Playlist starting @${n.startSN}
|
|
23
|
-
${n.m3u8}`)}function us(e,t,n=!0,r){let i=t.startSN+t.skippedSegments-e.startSN,a=e.fragments,o=i>=0,s=0;if(o&&i<a.length)s=a[i].start,r?.log(`Aligning playlists based on SN ${t.startSN} (diff: ${s})`);else if(o&&t.startSN===e.endSN+1)s=e.fragmentEnd,r?.log(`Aligning playlists based on first/last SN ${t.startSN} (diff: ${s})`);else if(o&&n)s=e.fragmentStart+i*t.levelTargetDuration;else if(!t.skippedSegments&&t.fragmentStart===0)s=e.fragmentStart,r?.log(`Aligning playlists based on first SN ${t.startSN} (diff: ${s})`);else return s;return ds(t,s),s}function ds(e,t){if(t){let n=e.fragments;for(let r=e.skippedSegments;r<n.length;r++)n[r].addStart(t);e.fragmentHint&&e.fragmentHint.addStart(t)}}function fs(e,t=1/0){let n=1e3*e.targetduration;if(e.updated){let r=e.fragments;if(r.length&&n*4>t){let e=r[r.length-1].duration*1e3;e>0&&e<n&&(n=e)}}else n/=2;return Math.round(n)}function ps(e,t,n){if(!e)return null;let r=e.fragments[t-e.startSN];return r||(r=e.fragmentHint,r?.sn===t)?r:n&&t<e.startSN&&n.sn===t?n:null}function ms(e,t,n){return e?hs(e.partList,t,n):null}function hs(e,t,n){if(e)for(let r=e.length;r--;){let i=e[r];if(i.index===n&&i.fragment.sn===t)return i}return null}function gs(e){e.forEach((e,t)=>{var n;(n=e.details)==null||n.fragments.forEach(e=>{e.level=t,e.initSegment&&(e.initSegment.level=t)})})}function _s(e,t){return e!==t&&t?vs(e)!==vs(t):!1}function vs(e){return e.replace(/\?[^?]*$/,``)}function ys(e,t){for(let n=0,r=e.length;n<r;n++)if(e[n]?.cc===t)return e[n];return null}function bs(e,t){return!!(e&&t.startCC<e.endCC&&t.endCC>e.startCC)}function xs(e,t){let n=e.start+t;e.setStart(n)}function Ss(e,t){let n=t.fragments;for(let t=0,r=n.length;t<r;t++)xs(n[t],e);t.fragmentHint&&xs(t.fragmentHint,e),t.alignedSliding=!0}function Cs(e,t,n){e&&(ws(t,e,n),t.alignedSliding||Ts(t,e,n),!t.alignedSliding&&!t.skippedSegments&&us(e,t,!1,n))}function ws(e,t,n){if(!bs(t,e))return;let r=Math.min(t.endCC,e.endCC),i=ys(t.fragments,r),a=ys(e.fragments,r);if(!i||!a)return;let o=i.start-a.start;n.log(`Aligning playlists using dicontinuity sequence ${r} (diff: ${o})`),Ss(o,e)}function Ts(e,t,n){if(!e.hasProgramDateTime||!t.hasProgramDateTime)return;let r=e.fragments,i=t.fragments;if(!r.length||!i.length)return;let a,o,s=Math.min(t.endCC,e.endCC);t.startCC<s&&e.startCC<s&&(a=ys(i,s),o=ys(r,s)),(!a||!o)&&(a=i[Math.floor(i.length/2)]||i.filter(e=>!!e)[0],o=ys(r,a.cc)||r[Math.floor(r.length/2)]);let c=a.programDateTime,l=o.programDateTime;if(!c||!l)return;let u=(l-c)/1e3;if(Math.abs(u)>Math.max(60,e.totalduration)){n.log(`Cannot align playlists using PDT without overlap (${Math.abs(u)} > ${e.totalduration})`);return}let d=u-(o.start-a.start);n.log(`Aligning playlists using PDT (diff: ${d})`),Ss(d,e)}var $={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`},Es=class extends Za{constructor(e,t,n,r,i){super(r,e.logger),this.hls=void 0,this.fragPrevious=null,this.fragCurrent=null,this.fragPlaying=null,this.fragmentTracker=void 0,this.transmuxer=null,this._state=$.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:e,fragCurrent:t,media:n,mediaBuffer:r,state:i}=this,a=n?n.currentTime:0,o=J.bufferInfo(r||n,a,e.maxBufferHole),s=o.len;if(this.log(`Media seeking to ${a}, state: ${i}, ${s?`in`:`out of`} buffer`),this.state===$.ENDED)this.resetLoadingState();else if(t){let n=e.maxFragLookUpTolerance,r=t.start-n,i=t.start+t.duration+n;if(!s||i<o.start||r>o.end){let e=a<r,n=a>i;(e||n)&&(t.loader&&(n||!this.isFragmentNearlyDownloaded(t))?(this.log(`Cancelling fragment load for seek (sn: ${t.sn}) - ${e?`backward`:`forward`} seek`),t.abortRequests(),this.resetLoadingState()):this.fragPrevious=null)}}if(n){var c;if((c=this.hls)!=null&&c.hasEnoughToStart&&!s&&a!==this.startPosition&&this.fragmentTracker.removeFragmentsInRange(a,1/0,this.playlistType,!0),a>this.lastCurrentTime&&(this.lastCurrentTime=a),!this.loadingParts){let e=Math.max(o.end,a),t=this.shouldLoadParts(this.getLevelDetails(),e);t&&(this.log(`LL-Part loading ON after seeking to ${a} with buffer @${e}`),this.loadingParts=t)}}let l=!J.isBuffered(n,a);(!this.hls.hasEnoughToStart||l)&&(this.log(`Setting ${l?`startPosition`:`nextLoadPosition`} to ${a} for seek without enough to start`),this.nextLoadPosition=a,l?this.startPosition=a:this.lastCurrentTime=a),s<1&&this.state===$.IDLE&&this.tickImmediate()},this.onMediaEnded=()=>{this.log(`setting startPosition to 0 because media ended`),this.startPosition=this.nextLoadPosition=this.lastCurrentTime=0},this.playlistType=i,this.hls=e,this.fragmentLoader=new Ga(e.config),this.initFragmentLoader=new Ga(e.config),this.keyLoader=n,this.fragmentTracker=t,this.config=e.config,this.decrypter=new Ua(e.config)}registerListeners(){let{hls:e}=this;e.on(L.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(L.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(L.MANIFEST_LOADING,this.onManifestLoading,this),e.on(L.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(L.ERROR,this.onError,this)}unregisterListeners(){let{hls:e}=this;e.off(L.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(L.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(L.MANIFEST_LOADING,this.onManifestLoading,this),e.off(L.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(L.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===$.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=$.STOPPED}get startPositionValue(){let{nextLoadPosition:e,startPosition:t}=this;if(t===-1&&e){let t=this.getLevelDetails();return t!=null&&t.live?(this.hls.liveSyncPosition||t.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 n=e.end||0,r=this.config.timelineOffset||0;if(n<=r)return!1;let i=e.buffered;this.config.maxBufferHole&&i&&i.length>1&&(e=J.bufferedInfo(i,e.start,0));let a=e.nextStart;if(a&&a>r&&a<t.edge||this.media.currentTime<e.start)return!1;let o=t.partList;if(o!=null&&o.length){let e=o[o.length-1];return J.isBuffered(this.media,e.start+e.duration/2)}let s=t.fragments[t.fragments.length-1];return this.fragmentTracker.isEndListAppended(s.type)}getLevelDetails(){if(this.levels&&this.levelLastLoaded!==null)return this.levelLastLoaded.details}get timelineOffset(){let e=this.config.timelineOffset;return e?this.getLevelDetails()?.appliedTimelineOffset||e:0}onMediaAttached(e,t){let n=this.media=this.mediaBuffer=t.media;Y(n,`seeking`,this.onMediaSeeking),Y(n,`ended`,this.onMediaEnded);let r=this.config;this.levels&&r.autoStartLoad&&this.state===$.STOPPED&&this.startLoad(r.startPosition)}onMediaDetaching(e,t){this.fragPlaying=null;let n=!!t.transferMedia,r=this.media;if(r===null)return;if(r.ended&&(this.log(`MSE detaching and video ended, reset startPosition`),this.startPosition=this.lastCurrentTime=0),X(r,`seeking`,this.onMediaSeeking),X(r,`ended`,this.onMediaEnded),this.media=this.mediaBuffer=null,this.loopSn=void 0,n){this.resetLoadingState(),this.resetTransmuxer();return}this.loadingParts=!1;let{fragmentTracker:i}=this,a=i.gapFragments();i.removeAllFragments(),a.forEach(e=>i.addAsGap(e)),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(),null),super.onHandlerDestroying(),this.hls=this.onMediaSeeking=this.onMediaEnded=null}onHandlerDestroyed(){this.state=$.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,n){this.startFragRequested=!0,this._loadFragForPlayback(e,t,n)}_loadFragForPlayback(e,t,n){this._doFragLoad(e,t,n,e=>{let t=e.frag;if(this.fragContextChanged(t)){this.warn(`${t.type} sn: ${t.sn}${e.part?` part: `+e.part.index:``} of ${this.fragInfo(t,!1,e.part)} was dropped during download.`),this.fragmentTracker.removeFragment(t);return}let n=++t.stats.chunkCount;this.log(`load progress ${t.type} sn: ${t.sn}${e.part?` part: `+e.part.index:``} of ${this.fragInfo(t,!1,e.part)} chunk: ${n}`),this._handleFragmentLoadProgress(e)}).then(e=>{if(!e)return;let t=this.state,n=e.frag;if(this.fragContextChanged(n)){(t===$.FRAG_LOADING||!this.fragCurrent&&t===$.PARSING)&&(this.fragmentTracker.removeFragment(n),this.state=$.IDLE);return}`payload`in e&&(this.log(`Loaded ${n.type} sn: ${n.sn} of ${this.playlistLabel()} ${n.level} (bytes ${n.stats.loaded})`),this.hls.trigger(L.FRAG_LOADED,e)),this._handleFragmentLoadComplete(e)}).catch(t=>{this.state!==$.STOPPED&&this.state!==$.ERROR&&(this.log(`Frag error ${e.type} sn:${e.sn} cc:${e.cc}: ${t?.message||t}`),this.resetFragmentLoading(e))})}clearTrackerIfNeeded(e){let{fragmentTracker:t}=this;if(t.getState(e)===Z.APPENDING){let n=e.type,r=this.getFwdBufferInfo(this.mediaBuffer,n),i=Math.max(e.duration,r?r.len:this.config.maxBufferLength),a=this.backtrackFragment;((a?e.sn-a.sn:0)===1||this.reduceMaxBufferLength(i,e.duration))&&t.removeFragment(e)}else this.mediaBuffer?.buffered.length===0?t.removeAllFragments():t.hasParts(e.type)&&(t.detectPartialFragments({frag:e,part:null,stats:e.stats,id:e.type}),t.getState(e)===Z.PARTIAL&&t.removeFragment(e))}checkLiveUpdate(e){if(e.updated&&!e.live){let t=this.fragmentTracker,n=e.fragments[e.fragments.length-1];if(n.endList&&!t.isEndListAppended(this.playlistType)){let e=t.getPartialFragment(n.end);e&&(t.removeFragment(e),t.fragBuffered(n,!0))}t.detectPartialFragments({frag:n,part:null,stats:n.stats,id:n.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,n=null){if(!(e-t))return;let r={startOffset:e,endOffset:t,type:n};this.hls.trigger(L.BUFFER_FLUSHING,r)}_loadInitSegment(e){let{hls:t}=this;return this.initFragmentLoader.abort(),t.trigger(L.FRAG_LOADING,{frag:e,targetBufferTime:0}),this.initFragmentLoader.load(e).then(e=>{let t=e.frag;if(!this.levels||!Dt(t,this.fragCurrent?.initSegment))throw new Xa({type:F.NETWORK_ERROR,details:I.INTERNAL_ABORTED,error:Error(`init load aborted`),fatal:!1,frag:t,networkDetails:null});return e}).then(e=>{let{frag:n,payload:r}=e,i=n.decryptdata;if(r&&r.byteLength>0&&i!=null&&i.key&&i.iv&&ho(i.method)){let a=self.performance.now(),{decryptRange:o}=qa(n,null,this.iframesOnly);return this.decrypter.decrypt(new Uint8Array(r),i.key.buffer,i.iv.buffer,go(i.method),o).catch(e=>{throw t.trigger(L.ERROR,{type:F.MEDIA_ERROR,details:I.FRAG_DECRYPT_ERROR,fatal:!1,error:e,reason:e.message,frag:n}),this.fragmentLoader.abort(),e}).then(r=>{let i=self.performance.now();return t.trigger(L.FRAG_DECRYPTED,{frag:n,part:null,payload:r,stats:{tstart:a,tdecrypt:i}}),e.payload=r,this.completeInitSegmentLoad(e)})}return this.completeInitSegmentLoad(e)})}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&&Tt(e)&&t&&!t.data){var n;return(t.encrypted&&!((n=t.decryptdata)!=null&&n.key)?this.keyLoader.load(t).then(()=>this._loadInitSegment(t)):this._loadInitSegment(t)).catch(t=>{throw this.state===$.STOPPED||this.state===$.ERROR?t:(`data`in t&&(this.fragmentLoader.abort(),this.handleFragLoadError(t,e)),this.resetFragmentLoading(e),t)})}}unhandledEncryptionError(e,t){var n,r;let i=e.tracks;if(i&&!t.encrypted&&((n=i.audio)!=null&&n.encrypted||(r=i.video)!=null&&r.encrypted)&&(!this.config.emeEnabled||!this.keyLoader.emeController)){let e=this.media,n=Error(`Encrypted track with no key in ${this.fragInfo(t)} (media ${e?`attached mediaKeys: `+e.mediaKeys:`detached`})`);return this.warn(n.message),!e||e.mediaKeys?!1:(this.hls.trigger(L.ERROR,{type:F.KEY_SYSTEM_ERROR,details:I.KEY_SYSTEM_NO_KEYS,fatal:!1,error:n,frag:t}),this.resetTransmuxer(),!0)}return!1}fragContextChanged(e){let{fragCurrent:t}=this;return!e||!Dt(e,t)}fragBufferedComplete(e,t){let n=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:${n?_a(J.getBuffered(n)):`(detached)`})`),Tt(e)){if(e.type!==z.SUBTITLE){let t=e.elementaryStreams;if(!Object.keys(t).some(e=>!!t[e])){this.state=$.IDLE;return}}let n=this.levels?.[e.level];n!=null&&n.fragmentError&&(t||this.fragmentTracker.getState(e)!==Z.PARTIAL)&&(this.log(`Resetting level fragment error count of ${n.fragmentError} on frag buffered`),n.fragmentError=0,e.stats.retry=0)}this.state=$.IDLE}_handleFragmentLoadComplete(e){let{transmuxer:t}=this;if(!t)return;let n=e.frag,{part:r,partsLoaded:i}=e,a=!i||i.length===0||i.some(e=>!e),{decryptRange:o}=qa(n,r),s=new Qa(n.level,n.sn,n.stats.chunkCount+1,0,r?r.index:-1,!a,n.duration,this.iframesOnly,o);this.log(`load complete ${n.type} sn: ${n.sn}${r?` part: `+r.index:``} of ${this.fragInfo(n,!1,r)}`),t.flush(s)}_handleFragmentLoadProgress(e){}loadKeyFor(e,t,n){var r;let i=null;return e.encrypted&&!((r=e.decryptdata)!=null&&r.key)?(this.log(`Loading key for ${e.sn} of [${t.startSN}-${t.endSN}], ${this.playlistLabel()} ${e.level}`),this.state=$.KEY_LOADING,i=this.keyLoader.load(e,n).then(e=>{if(!this.fragContextChanged(e.frag))return this.hls.trigger(L.KEY_LOADED,e),this.state===$.KEY_LOADING&&(this.state=$.IDLE),e}),this.hls.trigger(L.KEY_LOADING,{frag:e})):e.encrypted||(i=this.keyLoader.loadClear(e,t.encryptedFragments,this.startFragRequested),i&&this.log(`[eme] blocking frag sn: ${e.sn} load until media-keys acquired`)),i}_doFragLoad(e,t,n=null,r){this.fragCurrent=e;let i=t.details;if(!this.levels||!i)throw Error(`frag load aborted, missing level${i?``:` detail`}s`);let a=this.fragPrevious;if(!Et(e,a)){let n=this.shouldLoadParts(t.details,e.end);n!==this.loadingParts&&(this.log(`LL-Part loading ${n?`ON`:`OFF`} loading sn ${a?.sn}->${e.sn}`),this.loadingParts=n)}if(n=Math.max(e.start,n||0),this.loadingParts){let o=i.partList;if(o&&r){n>i.fragmentEnd&&i.fragmentHint&&(e=i.fragmentHint);let s=this.getNextPart(o,e,n);if(s>-1){let c=o[s];if(e=this.fragCurrent=c.fragment,!Et(e,a)&&!this.shouldLoadParts(t.details,e.end))return this.log(`LL-Part loading OFF @${this.playhead} next part: ${this.fragInfo(e,!1,c)}`),this.loadingParts=!1,Promise.resolve(null);if(!this.filterReplacedPrimary(c,t.details))return Promise.resolve(null);let l=this.loadKeyFor(e,i);if(this.fragContextChanged(e))return Promise.resolve(null);this.log(`Loading ${e.type} sn: ${e.sn} part: ${c.index} (${s}/${o.length-1}) of ${this.fragInfo(e,!1,c)} cc: ${e.cc} [${i.startSN}-${i.endSN}], target: ${n}${c.byteRange.length?` range:${c.byteRange.join(`-`)}`:``}`),this.nextLoadPosition=c.start+c.duration,this.state=$.FRAG_LOADING;let u,d=this.loadInitSegmentIfNeeded(e);if(l||d){let n=!!l;u=Promise.all([l,d]).then(([i])=>n&&(!i||this.fragContextChanged(i.frag))?null:this.doFragPartsLoad(e,c,t,r)).catch(t=>this.handleFragLoadError(t,e))}else u=this.doFragPartsLoad(e,c,t,r).catch(t=>this.handleFragLoadError(t,e));return this.hls.trigger(L.FRAG_LOADING,{frag:e,part:c,targetBufferTime:n}),this.fragCurrent===null?Promise.reject(Error(`frag load aborted, context changed in FRAG_LOADING parts`)):u}if(!e.url||this.loadedEndOfParts(o,n))return Promise.resolve(null)}}if(this.loadingParts)this.log(`LL-Part loading OFF after next part miss @${n} Check buffer at sn: ${e.sn} loaded parts: ${i.partList?.filter(e=>e.loaded).map(e=>`[${e.start}-${e.end}]`)}`),this.loadingParts=!1;else if(!e.url)return Promise.resolve(null);if(!this.filterReplacedPrimary(e,t.details))return Promise.resolve(null);let o=this.loadInitSegmentIfNeeded(e),s=this.loadKeyFor(e,i,o);if(this.fragContextChanged(e))return this.log(`Context changed in KEY_LOADING sn: ${e.sn} ${e.relurl} > ${this.fragCurrent?.relurl}`),o?.catch(()=>null),s?.catch(()=>null),Promise.resolve(null);this.log(`Loading ${e.type} sn: ${e.sn} of ${this.fragInfo(e,!1)} cc: ${e.cc} ${`[`+i.startSN+`-`+i.endSN+`]`}, target: ${n}${e.byteRange.length?` range:${e.byteRange.join(`-`)}`:``}`),P(e.sn)&&!this.bitrateTest&&(this.nextLoadPosition=e.start+e.duration),this.state=$.FRAG_LOADING;let c=this.config.progressive&&e.type!==z.SUBTITLE,l;return l=c&&s?s.then(t=>!t||this.fragContextChanged(t.frag)?null:this.fragmentLoader.load(e,this.iframesOnly,r,o)).catch(t=>this.handleFragLoadError(t,e)):Promise.all([this.fragmentLoader.load(e,this.iframesOnly,c?r:void 0,c?o:void 0),s,o]).then(([e])=>(!c&&r&&r(e),e)).catch(t=>this.handleFragLoadError(t,e)),this.hls.trigger(L.FRAG_LOADING,{frag:e,targetBufferTime:n}),this.fragCurrent===null?Promise.reject(Error(`frag load aborted, context changed in FRAG_LOADING`)):Promise.all([l,o]).then(([e])=>e)}doFragPartsLoad(e,t,n,r){return new Promise((i,a)=>{let o=[],s=n.details?.partList,c=t=>{this.fragmentLoader.loadPart(e,t,r).then(r=>{o[t.index]=r;let a=r.part;this.hls.trigger(L.FRAG_LOADED,r);let l=ms(n.details,e.sn,t.index+1)||hs(s,e.sn,t.index+1);if(l)c(l);else return i({frag:e,part:a,partsLoaded:o})}).catch(a)};c(t)})}handleFragLoadError(e,t){if(`data`in e){let n=e.data;n.details===I.INTERNAL_ABORTED?this.handleFragLoadAborted(t,n.part):n.type===F.KEY_SYSTEM_ERROR&&!n.fatal&&(t.abortRequests(),this.resetStartWhenNotLoaded(),this.resetFragmentLoading(t)),n.frag===t?this.hls.trigger(L.ERROR,n):(n.frag&&this.warn(`${n.details} error cascading from ${this.fragInfo(n.frag,!1,n.part)} to ${this.fragInfo(t,!1)}`),this.hls.trigger(L.ERROR,H(H({},n),{},{frag:t})))}else this.hls.trigger(L.ERROR,{type:F.OTHER_ERROR,details:I.INTERNAL_EXCEPTION,err:e,error:e,fatal:!0});return null}_handleTransmuxerFlush(e){let t=this.getCurrentContext(e);if(!t||this.state!==$.PARSING){!this.fragCurrent&&this.state!==$.STOPPED&&this.state!==$.ERROR&&(this.state=$.IDLE);return}let{frag:n,part:r,level:i}=t,a=self.performance.now();n.stats.parsing.end=a,r&&(r.stats.parsing.end=a);let o=this.getLevelDetails(),s=o&&n.sn>o.endSN||this.shouldLoadParts(o,n.end);s!==this.loadingParts&&(this.log(`LL-Part loading ${s?`ON`:`OFF`} after parsing segment ending @${n.end}`),this.loadingParts=s),this.updateLevelTiming(n,r,i,e)}shouldLoadParts(e,t){if(this.config.lowLatencyMode){if(!e)return this.loadingParts;if(e.partList&&!this.iframesOnly){let n=e.partList[0];if(t>=n.end+(e.fragmentHint?.duration||0)&&this.playhead>n.start-n.fragment.duration)return!0}}return!1}getCurrentContext(e){let{levels:t,fragCurrent:n}=this,{level:r,sn:i,part:a}=e;if(!(t!=null&&t[r]))return this.warn(`Levels object was unset while buffering fragment ${i} of ${this.playlistLabel()} ${r}. The current chunk will not be buffered.`),null;let o=t[r],s=o.details,c=a>-1?ms(s,i,a):null,l=c?c.fragment:ps(s,i,n);return l?(n&&n!==l&&(l.stats=n.stats),{frag:l,part:c,level:o}):null}bufferFragmentData(e,t,n,r,i){if(this.state!==$.PARSING)return;Tt(t)&&!this.fragContextChanged(t)&&(this.fragPrevious=t);let{data1:a,data2:o}=e,s=a;if(o&&(s=Tr(a,o)),!s.length)return;let c=this.initPTS[t.cc],l=c?-c.baseTime/c.timescale:void 0,u={type:e.type,frag:t,part:n,chunkMeta:r,offset:l,parent:t.type,data:s};if(this.hls.trigger(L.BUFFER_APPENDING,u),e.dropped&&e.independent&&!n){if(i)return;this.flushBufferGap(t)}}flushBufferGap(e){let t=this.media;if(!t)return;if(!J.isBuffered(t,t.currentTime)){this.flushMainBuffer(0,e.start);return}let n=t.currentTime,r=J.bufferInfo(t,n,0),i=e.duration,a=Math.min(this.config.maxFragLookUpTolerance*2,i*.25),o=Math.max(Math.min(e.start-a,r.end-a),n+a);e.start-o>a&&this.flushMainBuffer(o,e.start)}getFwdBufferInfo(e,t){var n;let r=this.playhead,i=this.lastCurrentTime>r||(n=this.media)!=null&&n.paused?0:this.config.maxBufferHole;return this.getFwdBufferInfoAtPos(e,r,t,i)}getFwdBufferInfoAtPos(e,t,n,r){let i=J.bufferInfo(e,t,r);if(i.len===0&&i.nextStart!==void 0){let a=this.fragmentTracker.getBufferedFrag(t,n);if(a&&(i.nextStart<=a.end||a.gap)){let n=Math.max(Math.min(i.nextStart,a.end)-t,r);return J.bufferInfo(e,t,n)}}return i}getMaxBufferLength(e){let{config:t}=this,n;return n=e?Math.max(8*t.maxBufferSize/e,t.maxBufferLength):t.maxBufferLength,Math.min(n,t.maxMaxBufferLength)}exceedsMaxBuffer(e,t,n){let r=e.nextStart;if(r&&n.start>r){let r=e.buffered;if(r){let i=e.len,a=e.bufferedIndex;for(let e=r.length-1;e>a;e--)r[e].start<n.start&&(i+=r[e].end-r[e].start);return i>=t}}return!1}reduceMaxBufferLength(e,t){let n=this.config,r=Math.max(Math.min(e-t,n.maxBufferLength),t/2),i=Math.max(e-t*3,n.maxMaxBufferLength/2,r);return i>=r&&(n.maxMaxBufferLength=i,this.warn(`Reduce max buffer length to ${i}s`),!0)}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 n=t.fragments,r=n.length;if(!r)return null;let{config:i}=this,a=t.fragmentStart,o=i.lowLatencyMode&&!!t.partList,s=null;if(t.live){let n=i.initialLiveManifestSize;if(r<n)return this.warn(`Not enough fragments to start playback (have: ${r}, need: ${n})`),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){s=this.getInitialLiveFragment(t);let n=this.config.startPosition,r=this.hls.startPosition,i=this.hls.liveSyncPosition,o=s?.start||0,c,l;if(r!==-1&&r>=a?(c=r,l=r===n?`config`:`next load start`):i?(c=i,l=`live edge`):(c=e,l=`buffer pos`),c<o&&(c=o,l=`live frag start`),c<a&&(c=a,l=`playlist start`),this.startPosition!=c||this.nextLoadPosition!=c){let u=t.live&&!this.filterReplacedPrimary(s,t)?-1:c;this.log(`Setting startPosition to ${u} next load ${c} ${r===-1?``:`(from ${n}) `}based on ${l}. live edge: ${i} live frag start: ${o} playlist start: ${a} buffer pos: ${e}`),this.startPosition=u,this.nextLoadPosition=c}}}else e<=a&&(s=n[0]);if(!s){let n=this.loadingParts?t.partEnd:t.fragmentEnd;s=this.getFragmentAtPosition(e,n,t)}let c=this.filterReplacedPrimary(s,t);return!c&&s&&(c=sa(t,s.sn),c&&(this.nextLoadPosition=c.start)),c}isLoopLoading(e,t){if(this.nextLoadPosition<=t)return!1;let n=this.fragmentTracker.getState(e);return!!(n===Z.OK||n===Z.PARTIAL&&(e.gap||e.stats.retry>1))}getNextFragmentLoopLoading(e,t,n,r,i){let a=null;if(e.gap&&(a=this.getNextFragment(this.nextLoadPosition,t),a&&!a.gap&&n.nextStart)){let e=this.getFwdBufferInfoAtPos(this.mediaBuffer?this.mediaBuffer:this.media,n.nextStart,r,0);if(e!==null&&n.len+e.len>=i){let e=a.sn;return this.loopSn!==e&&(this.log(`buffer full after gaps in "${r}" playlist starting at sn: ${e}`),this.loopSn=e),null}}return this.loopSn=void 0,a}get primaryPrefetch(){if(Os(this.config)){var e;if((e=this.hls.interstitialsManager)!=null&&(e=e.playingItem)!=null&&e.event)return!0}return!1}filterReplacedPrimary(e,t){if(!e)return e;if(Os(this.config)&&(`type`in e?e:e.fragment).type!==z.SUBTITLE){let n=this.hls.interstitialsManager,r=n?.bufferingItem;if(r){let n=r.event;if(n){if(!n.appendInPlace&&(Math.abs(e.start-r.start)>1||r.start===0))return null}else if(e.end<=r.start&&t?.live===!1||e.start>=r.end&&r.nextEvent&&(r.nextEvent.appendInPlace&&!r.nextEvent.hasPlayed||e.start-r.end>1))return null}if(Ds(e,n?.playerQueue,this.playhead))return null}return e}getNextPart(e,t,n){let r=-1,i=!1,a=!0;for(let o=0,s=e.length;o<s;o++){let s=e[o];if(a&&=!s.independent,r>-1&&n<s.start)break;let c=s.loaded||s.gap;c?r=-1:(i||(s.independent||a)&&s.fragment===t)&&(r=o),i=c&&!s.gap}let o=e[r];return o&&o.fragment!==t&&this.log(`Need buffer at ${n} but next unloaded part starts at ${o.start} (sn: ${t.sn} -> ${o.fragment.sn})`),r}loadedEndOfParts(e,t){let n;for(let r=e.length;r--;){if(n=e[r],!n.loaded)return!1;if(t>n.start)return!0}return!1}getInitialLiveFragment(e){let t=e.fragments,n=this.fragPrevious,r=null;if(n){if(e.hasProgramDateTime&&(r=ta(t,n.endProgramDateTime,this.config.maxFragLookUpTolerance),r&&this.log(`Live playlist, switching playlist, load frag with same PDT: ${n.programDateTime}`)),!r){let i=n.sn+1;if(i>=e.startSN&&i<=e.endSN){let a=t[i-e.startSN];n.cc===a.cc&&(r=a,this.log(`Live playlist, switching playlist, load frag with next SN: ${r.sn}`))}r||(r=oa(e,n.cc,n.end),r&&this.log(`Live playlist, switching playlist, load frag with same CC: ${r.sn}`))}}else{let t=this.hls.liveSyncPosition;t!==null&&(r=this.getFragmentAtPosition(t,this.bitrateTest?e.fragmentEnd:e.edge,e))}return r}getFragmentAtPosition(e,t,n){let{config:r}=this,{fragPrevious:i}=this,{fragments:a,endSN:o}=n,{fragmentHint:s}=n,{maxFragLookUpTolerance:c}=r,l=n.partList,u=!!(this.loadingParts&&l!=null&&l.length&&s);u&&!this.bitrateTest&&l[l.length-1].fragment.sn===s.sn&&(a=a.concat(s),o=s.sn),i&&this.fragmentTracker.getState(i)===Z.NOT_LOADED&&(i=null);let d;if(e<t){var f;let n=e<this.lastCurrentTime||e>t-c||(f=this.media)!=null&&f.paused||this.loadingParts||!this.startFragRequested?0:c;d=na(i,a,e,n)}else d=a[a.length-1];if(d){let e=d.sn,t=e-n.startSN,r=this.fragmentTracker.getState(d);if((r===Z.OK||r===Z.PARTIAL&&d.gap)&&(i=d),Et(d,i)&&(!u||l[0].fragment.sn>e||!n.live||!l.some(t=>t.fragment.sn===e&&!t.loaded&&!t.gap))){let e=a[t+1];d=d.sn<o&&this.fragmentTracker.getState(e)!==Z.OK?e:null}}return d}alignPlaylists(e,t,n){let r=e.fragments.length;if(!r)return this.warn(`No fragments in live playlist`),0;let i=e.fragmentStart,a=!t,o=e.alignedSliding&&P(i);if(a||!o&&!i){Cs(n,e,this);let i=e.fragmentStart;return this.log(`Live playlist sliding: ${i} start-sn: ${t?t.startSN:`na`}->${e.startSN} fragments: ${r}`),i}return i}waitForCdnTuneIn(e){return e.live&&e.canBlockReload&&e.partTarget&&e.tuneInGoal>Math.max(e.partHoldBack,e.partTarget*3)}setStartPosition(e,t){let n=this.startPosition;n<t&&(n=-1);let r=this.timelineOffset;if(n===-1){let i=this.startTimeOffset!==null,a=i?this.startTimeOffset:e.startTimeOffset;if(a!==null&&P(a))n=t+a,a<0&&(n+=e.edge),n=Math.min(Math.max(t,n),t+e.totalduration),this.log(`Setting startPosition to ${n} for start time offset ${a} found in ${i?`multivariant`:`media`} playlist`),this.startPosition=n;else if(e.live){let e=this.hls.liveSyncPosition;n=e||t,this.log(`Setting startPosition to -1 to start at ${e?`live edge`:`playlist start`} ${n}`),this.startPosition=-1}else this.log(`setting startPosition to 0 by default`),this.startPosition=n=0;this.lastCurrentTime=n+r}this.nextLoadPosition=n+r}getLoadPosition(){var e;let{media:t}=this,n=0;return(e=this.hls)!=null&&e.hasEnoughToStart&&t&&!this.iframesOnly?n=t.currentTime:this.nextLoadPosition>=0&&(n=this.nextLoadPosition),n}get playhead(){var e;if((e=this.hls)!=null&&e.hasEnoughToStart){let e=this.media?.currentTime;return P(e)?e:this.lastCurrentTime}return this.getLoadPosition()}get iframesOnly(){if(this.playlistType!==z.MAIN)return!1;let e=this.getLevelDetails();return e?e.iframesOnly:this.levelLastLoaded?.iframes}handleFragLoadAborted(e,t){this.transmuxer&&e.type===this.playlistType&&Tt(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!==$.STOPPED&&(!this.fragCurrent||!this.fragContextChanged(e)&&this.state!==$.FRAG_LOADING_WAITING_RETRY)&&(this.state=$.IDLE)}onFragmentOrKeyLoadError(e,t){if(t.chunkMeta&&!t.frag){let e=this.getCurrentContext(t.chunkMeta);e&&(t.frag=e.frag)}let{frag:n,part:r}=t;if(!n||!this.levels||n.type!==e)return;if(this.fragContextChanged(n)){this.warn(`Frag load error must match current frag to retry ${n.relurl} > ${this.fragCurrent?.relurl}`);return}let i=t.details===I.FRAG_GAP;i&&this.fragmentTracker.addAsGap(n);let a=t.errorAction;if(!a){this.state=$.ERROR;return}let{action:o,flags:s,retryCount:c=0,retryConfig:l}=a,u=!!l,d=u&&o===ca.RetryRequest,f=u&&!a.resolved&&s&la.MoveAllAlternatesMatchingHost,p=this.hls.latestLevelDetails,m=p?.live;if(!d&&f&&Tt(n)&&m&&n.sn<p.endSN&&!Bt(t))this.resetFragmentErrors(e),r?r.gap=!0:this.treatAsGap(n),a.resolved=!0;else if((d||f)&&c<l.maxNumRetry){let r=Kt(t.response?.code),i=Ht(l,c);if(this.resetStartWhenNotLoaded(),this.retryDate=self.performance.now()+i,this.state=$.FRAG_LOADING_WAITING_RETRY,a.resolved=!0,r){this.log(`Waiting for connection (offline)`),this.retryDate=1/0,t.reason=`offline`;return}this.warn(`Fragment ${n.sn} of ${e} ${n.level} errored with ${t.details}, retrying loading ${c+1}/${l.maxNumRetry} in ${i}ms`)}else if(l){if(this.resetFragmentErrors(e),c<l.maxNumRetry)!i&&o!==ca.RemoveAlternatePermanently&&(a.resolved=!0);else{this.warn(`${t.details} reached or exceeded max retry (${c})`);return}}else this.state=o===ca.SendAlternateToPenaltyBox?$.WAITING_LEVEL:$.ERROR;this.tickImmediate()}onSourceBufferError(e,t){var n;let{frag:r,part:i,sourceBufferName:a}=t,o=r&&((n=this.levels)==null||(n=n[r.level])==null?void 0:n.details);if(t.error.name!==ba||r?.type!==e||!Tt(r)||!(o!=null&&o.live))return;let s=i?i.index===0?i:null:r,c=s&&a?s.elementaryStreams[a]?.startPTS:void 0;if(this.markSourceBufferErrorGap(ps(o,r.sn)||r),c===void 0)return;let l=ps(o,r.sn-1);l&&this.fragmentTracker.getState(l)!==Z.NOT_LOADED&&!J.isBuffered(this.mediaBuffer||this.media,c-this.config.maxBufferHole)&&this.markSourceBufferErrorGap(l)}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,n=t===1/0;(!t||e>=t||n&&!Kt(0))&&(n&&this.log(`Connection restored (online)`),this.resetStartWhenNotLoaded(),this.state=$.IDLE)}reduceLengthAndFlushBuffer(e){if(this.state===$.PARSING||this.state===$.PARSED){let t=e.frag,n=e.parent,r=this.getFwdBufferInfo(this.mediaBuffer,n),i=r&&r.len>.5;i&&this.reduceMaxBufferLength(r.len,t?.duration||10);let a=!i;return a?this.warn(`Buffer full error while media.currentTime (${this.playhead}) is not buffered, flush ${n} buffer`):r.nextStart&&t&&r.nextStart>t.start&&this.flushMainBuffer(r.nextStart,1/0,n===z.AUDIO?n:void 0),t&&(this.fragmentTracker.removeFragment(t),this.nextLoadPosition=t.start),this.resetLoadingState(),a}return!1}resetFragmentErrors(e){e===z.AUDIO&&(this.fragCurrent=null),this.hls.hasEnoughToStart||(this.startFragRequested=!1),this.state!==$.STOPPED&&(this.state=$.IDLE)}afterBufferFlushed(e,t){if(!e)return;let n=J.getBuffered(e);this.fragmentTracker.detectEvictedFragments(t,n,this.playlistType),this.state===$.ENDED&&this.resetLoadingState()}resetLoadingState(){this.log(`Reset loading state`),this.fragCurrent=null,this.fragPrevious=null,this.state!==$.STOPPED&&(this.state=$.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,n,r){let i=n.details;if(!i){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((a,o)=>{let s=e.elementaryStreams[o];if(s){let c=s.endPTS-s.startPTS;if(c<=0)return this.warn(`Could not parse fragment ${e.sn} ${o} duration reliably (${c})`),a||!1;let l=0;return r.partial?t&&r.part===0&&(l=t.start-s.startPTS,e.startPTS=e.maxStartPTS=s.startPTS,e.startDTS=s.startDTS,e.start!==0&&e.setStart(s.startPTS),is(i,e,l)):l=rs(i,e,s.startPTS,s.endPTS,s.startDTS,s.endDTS,this.iframesOnly,this),this.hls.trigger(L.LEVEL_PTS_UPDATED,{details:i,level:n,drift:l,type:o,frag:e,part:t,start:s.startPTS,end:s.endPTS}),!0}return a},!1)){let r=this.transmuxer?.error===null,i=this.transmuxer?.error!=null,a=(this.levels?.length??0)>1;if((n.fragmentError===0||r&&(n.fragmentError<2||e.endList)||i&&a)&&this.treatAsGap(e,n),r){let r=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(r.message),this.hls.trigger(L.ERROR,{type:F.MEDIA_ERROR,details:I.FRAG_PARSING_ERROR,fatal:!1,error:r,frag:e,reason:`Found no media in msn ${e.sn} of ${this.playlistLabel()} "${n.url}"`}),!this.hls)return;this.resetTransmuxer()}}this.state=$.PARSED,this.log(`Parsed ${e.type} sn: ${e.sn}${t?` part: `+t.index:``} of ${this.fragInfo(e,!1,t)}`),this.hls.trigger(L.FRAG_PARSED,{frag:e,part:t,chunkMeta:r})}playlistLabel(){return`${this.playlistType} playlist`}fragInfo(e,t=!0,n){return`${e.type} playlist ${e.level} (${n?`part`:`frag`}:[${(t&&!n?e.startPTS:(n||e).start)??NaN}-${(t&&!n?e.endPTS:(n||e).end)??NaN}]${n&&e.type===`main`?`INDEPENDENT=`+(n.independent?`YES`:`NO`):``})`}treatAsGap(e,t){t&&t.fragmentError++,this.fragmentTracker.addAsGap(e)}resetTransmuxer(){var e;(e=this.transmuxer)==null||e.reset()}isFragmentNearlyDownloaded(e){let t=e.loader?.stats;if(!t||t.total<=0)return!1;let n=t.loading.first>0,r=(t.total-t.loaded)*8/(this.hls.bandwidthEstimate||this.hls.config.abrEwmaDefaultEstimate);return n&&r<=.15}recoverWorkerError(e){e.event===`demuxerWorker`&&(this.fragmentTracker.removeAllFragments(),this.transmuxer&&=(this.transmuxer.destroy(),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 n=0,{hls:r,media:i,config:a,levels:o,playlistType:s}=this,c=this.getLevelDetails();if(i&&!i.paused&&o){let t=s===z.AUDIO?xi(e.audioCodec,128e3):e.maxBitrate,i=1+r.ttfbEstimate/1e3,o=r.bandwidthEstimate*a.abrBandWidthUpFactor;n=i+t*(c&&(this.loadingParts?c.partTarget:c.averagetargetduration)||this.fragCurrent?.duration||6)/o,e.details||(n+=i)}let l=this.playhead,u=!(c!=null&&c.live)||t.end-l>n*1.5;return{fetchdelay:n,okToFlushForwardBuffer:u}}scheduleTrackSwitch(e,t,n){let{media:r,playlistType:i}=this;if(!r||!e)return;let a=n?this.getBufferedFrag(this.playhead+t):null;if(a){let e=this.followingBufferedFrag(a);if(e){this.abortCurrentFrag();let t=e.maxStartPTS?e.maxStartPTS:e.start,n=e.duration,r=Math.max(a.end,t+Math.min(Math.max(n-this.config.maxFragLookUpTolerance,n*(this.couldBacktrack?.5:.125)),n*(this.couldBacktrack?.75:.25)));if((this.getLevelDetails()?.fragmentStart||0)>r)return;let o=i===z.MAIN?null:`audio`;this.flushMainBuffer(r,1/0,o),this.cleanupBackBuffer()}}}cleanupBackBuffer(){let{media:e,playlistType:t}=this;if(!e)return;let n=this.getAppendedFrag(this.playhead);if(n&&n.start>1){let e=t===z.AUDIO;this.flushMainBuffer(0,n.start-+!e,e?`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 $.KEY_LOADING:case $.FRAG_LOADING:case $.FRAG_LOADING_WAITING_RETRY:case $.PARSING:case $.PARSED:this.state=$.IDLE}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 n=e.currentTime;if(J.isBuffered(e,n)?t=this.getAppendedFrag(n):J.isBuffered(e,n+.1)&&(t=this.getAppendedFrag(n+.1)),t&&(this.backtrackFragment=void 0,!Et(t,this.fragPlaying)))return this.fragPlaying=t,!0}return!1}getBufferOutput(){return null}nextLevelSwitch(){let{levels:e,media:t,hls:n,config:r,playlistType:i}=this;if(t!=null&&t.readyState&&e&&n&&r){let t=this.getBufferOutput(),r=this.getFwdBufferInfo(t,i);if(!r)return;let a=e[i===z.AUDIO?n.nextAudioTrack:n.nextLoadLevel],{fetchdelay:o,okToFlushForwardBuffer:s}=this.calculateOptimalSwitchPoint(a,r);this.scheduleTrackSwitch(r,o,s)}this.tickImmediate()}};function Ds(e,t,n){if(t)for(let r=t.length;r--;){let i=t[r].interstitial,a=i.startTime,o=Math.min(a+i.duration,i.resumeTime);if(i.appendInPlace&&(e.start>=a&&e.end<=o||n>e.start&&e.end>a&&e.start<o))return!0}return!1}function Os(e){return!!e.interstitialsController&&e.enableInterstitialPlayback!==!1}var ks=class{constructor(){this.chunks=[],this.dataLength=0}push(e){this.chunks.push(e),this.dataLength+=e.length}flush(){let{chunks:e,dataLength:t}=this,n;if(e.length)n=e.length===1?e[0]:As(e,t);else return new Uint8Array;return this.reset(),n}reset(){this.chunks.length=0,this.dataLength=0}};function As(e,t){let n=new Uint8Array(t),r=0;for(let t=0;t<e.length;t++){let i=e[t];n.set(i,r),r+=i.length}return n}var js={exports:{}},Ms;function Ns(){return Ms?js.exports:(Ms=1,(function(e){var t=Object.prototype.hasOwnProperty,n=`~`;function r(){}Object.create&&(r.prototype=Object.create(null),new r().__proto__||(n=!1));function i(e,t,n){this.fn=e,this.context=t,this.once=n||!1}function a(e,t,r,a,o){if(typeof r!=`function`)throw TypeError(`The listener must be a function`);var s=new i(r,a||e,o),c=n?n+t:t;return e._events[c]?e._events[c].fn?e._events[c]=[e._events[c],s]:e._events[c].push(s):(e._events[c]=s,e._eventsCount++),e}function o(e,t){--e._eventsCount===0?e._events=new r:delete e._events[t]}function s(){this._events=new r,this._eventsCount=0}s.prototype.eventNames=function(){var e=[],r,i;if(this._eventsCount===0)return e;for(i in r=this._events)t.call(r,i)&&e.push(n?i.slice(1):i);return Object.getOwnPropertySymbols?e.concat(Object.getOwnPropertySymbols(r)):e},s.prototype.listeners=function(e){var t=n?n+e:e,r=this._events[t];if(!r)return[];if(r.fn)return[r.fn];for(var i=0,a=r.length,o=Array(a);i<a;i++)o[i]=r[i].fn;return o},s.prototype.listenerCount=function(e){var t=n?n+e:e,r=this._events[t];return r?r.fn?1:r.length:0},s.prototype.emit=function(e,t,r,i,a,o){var s=n?n+e:e;if(!this._events[s])return!1;var c=this._events[s],l=arguments.length,u,d;if(c.fn){switch(c.once&&this.removeListener(e,c.fn,void 0,!0),l){case 1:return c.fn.call(c.context),!0;case 2:return c.fn.call(c.context,t),!0;case 3:return c.fn.call(c.context,t,r),!0;case 4:return c.fn.call(c.context,t,r,i),!0;case 5:return c.fn.call(c.context,t,r,i,a),!0;case 6:return c.fn.call(c.context,t,r,i,a,o),!0}for(d=1,u=Array(l-1);d<l;d++)u[d-1]=arguments[d];c.fn.apply(c.context,u)}else{var f=c.length,p;for(d=0;d<f;d++)switch(c[d].once&&this.removeListener(e,c[d].fn,void 0,!0),l){case 1:c[d].fn.call(c[d].context);break;case 2:c[d].fn.call(c[d].context,t);break;case 3:c[d].fn.call(c[d].context,t,r);break;case 4:c[d].fn.call(c[d].context,t,r,i);break;default:if(!u)for(p=1,u=Array(l-1);p<l;p++)u[p-1]=arguments[p];c[d].fn.apply(c[d].context,u)}}return!0},s.prototype.on=function(e,t,n){return a(this,e,t,n,!1)},s.prototype.once=function(e,t,n){return a(this,e,t,n,!0)},s.prototype.removeListener=function(e,t,r,i){var a=n?n+e:e;if(!this._events[a])return this;if(!t)return o(this,a),this;var s=this._events[a];if(s.fn)s.fn===t&&(!i||s.once)&&(!r||s.context===r)&&o(this,a);else{for(var c=0,l=[],u=s.length;c<u;c++)(s[c].fn!==t||i&&!s[c].once||r&&s[c].context!==r)&&l.push(s[c]);l.length?this._events[a]=l.length===1?l[0]:l:o(this,a)}return this},s.prototype.removeAllListeners=function(e){var t;return e?(t=n?n+e:e,this._events[t]&&o(this,t)):(this._events=new r,this._eventsCount=0),this},s.prototype.off=s.prototype.removeListener,s.prototype.addListener=s.prototype.on,s.prefixed=n,s.EventEmitter=s,e.exports=s})(js),js.exports)}var Ps=vt(Ns()),Fs=`1.7.4`,Is={};function Ls(){return typeof __HLS_WORKER_BUNDLE__==`function`}function Rs(){let e=Is[Fs];if(e)return e.clientCount++,e;let t=new self.Blob([`var exports={};var module={exports:exports};function define(f){f()};define.amd=true;(${__HLS_WORKER_BUNDLE__.toString()})(true);`],{type:`text/javascript`}),n=self.URL.createObjectURL(t),r={worker:new self.Worker(n),objectURL:n,clientCount:1};return Is[Fs]=r,r}function zs(e){let t=Is[e];if(t)return t.clientCount++,t;let n=new self.URL(e,self.location.href).href,r={worker:new self.Worker(n),scriptURL:n,clientCount:1};return Is[e]=r,r}function Bs(e){let t=Is[e||Fs];if(t&&t.clientCount--===1){let{worker:n,objectURL:r}=t;delete Is[e||Fs],r&&self.URL.revokeObjectURL(r),n.terminate()}}function Vs(e,t,n,r){let i=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],a=t[n+2],o=a>>2&15;if(o>12){let t=Error(`invalid ADTS sampling index:${o}`);e.emit(L.ERROR,L.ERROR,{type:F.MEDIA_ERROR,details:I.FRAG_PARSING_ERROR,fatal:!0,error:t,reason:t.message});return}let s=(a>>6&3)+1,c=t[n+3]>>6&3|(a&1)<<2,l=i[o],u=o;(s===5||s===29)&&(u-=3);let d,f=(u&14)>>1,p=(u&1)<<7|c<<3,m=0;if(s===1&&o>=6){m=5;let e=o-3;d=[m<<3|f,p|(e&14)>>1,(e&1)<<7|8,0]}else d=[s<<3|f,p];let h=`mp4a.40.`+(m||s);return U.log(`manifest codec:${r}, parsed codec:${h}, channels:${c}, rate:${l} (ADTS object type:${s} sampling index:${o} esds config:[${d.join(`,`)}])`),{config:d,samplerate:l,channelCount:c,codec:h,parsedCodec:h,manifestCodec:r}}function Hs(e,t){return e[t]===255&&(e[t+1]&246)==240}function Us(e,t){return e[t+1]&1?7:9}function Ws(e,t){return(e[t+3]&3)<<11|e[t+4]<<3|(e[t+5]&224)>>>5}function Gs(e,t){return t+5<e.length}function Ks(e,t){return t+1<e.length&&Hs(e,t)}function qs(e,t){return Gs(e,t)&&Hs(e,t)&&Ws(e,t)<=e.length-t}function Js(e,t){if(Ks(e,t)){let n=Us(e,t);if(t+n>=e.length)return!1;let r=Ws(e,t);if(r<=n)return!1;let i=t+r;return i===e.length||Ks(e,i)}return!1}function Ys(e,t,n,r,i){if(!e.samplerate){let a=Vs(t,n,r,i);if(!a)return;V(e,a)}}function Xs(e){return 9216e4/e}function Zs(e,t){let n=Us(e,t);if(t+n<=e.length){let r=Ws(e,t)-n;if(r>0)return{headerLength:n,frameLength:r}}}function Qs(e,t,n,r,i){let a=r+i*Xs(e.samplerate),o=Zs(t,n),s;if(o){let{frameLength:r,headerLength:i}=o,c=i+r,l=Math.max(0,n+c-t.length);l?(s=new Uint8Array(c-i),s.set(t.subarray(n+i,t.length),0)):s=t.subarray(n+i,n+c);let u={unit:s,pts:a};return l||e.samples.push(u),{sample:u,length:c,missing:l}}let c=t.length-n;return s=new Uint8Array(c),s.set(t.subarray(n,t.length),0),{sample:{unit:s,pts:a},length:c,missing:-1}}var $s=function(e){return e.audioId3=`org.id3`,e.dateRange=`com.apple.quicktime.HLS`,e.emsg=`https://aomedia.org/emsg/ID3`,e.misbklv=`urn:misb:KLV:bin:1910.1`,e}({});function ec(e=``,t=9e4){return{type:e,id:-1,pid:-1,inputTimeScale:t,sequenceNumber:-1,samples:[],dropped:0}}var tc=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,n,r){this._id3Track={type:`id3`,id:3,pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0}}resetTimeStamp(e){this.initPTS=e,this.resetContiguity()}resetContiguity(){this.basePTS=null,this.lastPTS=null,this.frameIndex=0}canParse(e,t){return!1}appendFrame(e,t,n){}demux(e,t){this.cachedData&&=(e=Tr(this.cachedData,e),null);let n=Cn(e,0),r=n?n.length:0,i,a=this._audioTrack,o=this._id3Track,s=n?Vn(n):void 0,c=e.length;for((this.basePTS===null||this.frameIndex===0&&P(s))&&(this.basePTS=nc(s,t,this.initPTS),this.lastPTS=this.basePTS),this.lastPTS===null&&(this.lastPTS=this.basePTS),n&&n.length>0&&o.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:n,type:$s.audioId3,duration:1/0});r<c;){if(this.canParse(e,r)){let t=this.appendFrame(a,e,r);t?(this.frameIndex++,this.lastPTS=t.sample.pts,r+=t.length,i=r):r=c}else xn(e,r)?(n=Cn(e,r),o.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:n,type:$s.audioId3,duration:1/0}),r+=n.length,i=r):r++;if(r===c&&i!==c){let t=e.slice(i);this.cachedData=this.cachedData?Tr(this.cachedData,t):t}}return{audioTrack:a,videoTrack:ec(),id3Track:o,textTrack:ec()}}demuxSampleAes(e,t,n){return Promise.reject(Error(`[${this}] This demuxer does not support Sample-AES decryption`))}flush(e){let t=this.cachedData;return t&&(this.cachedData=null,this.demux(t,0)),{audioTrack:this._audioTrack,videoTrack:ec(),id3Track:this._id3Track,textTrack:ec()}}destroy(){this.cachedData=null,this._audioTrack=this._id3Track=void 0}},nc=(e,t,n)=>{if(P(e))return e*90;let r=n?n.baseTime*9e4/n.timescale:0;return t*9e4+r},rc=[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],ic=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],ac=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],oc=[0,1,1,4];function sc(e,t,n,r,i){if(n+24>t.length)return;let a=cc(t,n);if(a&&n+a.frameLength<=t.length){let o=r+i*(a.samplesPerFrame*9e4/a.sampleRate),s={unit:t.subarray(n,n+a.frameLength),pts:o,dts:o};return e.config=[],e.channelCount=a.channelCount,e.samplerate=a.sampleRate,e.samples.push(s),{sample:s,length:a.frameLength,missing:0}}}function cc(e,t){let n=e[t+1]>>3&3,r=e[t+1]>>1&3,i=e[t+2]>>4&15,a=e[t+2]>>2&3;if(n!==1&&i!==0&&i!==15&&a!==3){let o=e[t+2]>>1&1,s=e[t+3]>>6,c=rc[(n===3?3-r:r===3?3:4)*14+i-1]*1e3,l=ic[(n===3?0:n===2?1:2)*3+a],u=s===3?1:2,d=ac[n][r],f=oc[r],p=d*8*f,m=Math.floor(d*c/l+o)*f,h=Wr();return h&&h<=87&&r===2&&c>=224e3&&s===0&&(e[t+3]=e[t+3]|128),{sampleRate:l,channelCount:u,frameLength:m,samplesPerFrame:p}}}function lc(e,t){return e[t]===255&&(e[t+1]&224)==224&&!!(e[t+1]&6)}function uc(e,t){return t+1<e.length&&lc(e,t)}function dc(e,t){return lc(e,t)&&4<=e.length-t}function fc(e,t){if(t+1<e.length&&lc(e,t)){let n=cc(e,t),r=4;n!=null&&n.frameLength&&(r=n.frameLength);let i=t+r;return i===e.length||uc(e,i)}return!1}var pc=class{constructor(e,t,n){this.keyData=void 0,this.decrypter=void 0,this.keyData=n,this.decrypter=new Ua(t,!0)}decryptBuffer(e){return this.decrypter.decrypt(e,this.keyData.key.buffer,this.keyData.iv.buffer,Ia.cbc,{start:0,end:e.byteLength})}decryptAacSample(e,t,n){let r=e[t].unit;if(r.length<=16)return;let i=r.subarray(16,r.length-r.length%16),a=i.buffer.slice(i.byteOffset,i.byteOffset+i.length);this.decryptBuffer(a).then(i=>{let a=new Uint8Array(i);r.set(a,16),this.decrypter.isSync()||this.decryptAacSamples(e,t+1,n)}).catch(n)}decryptAacSamples(e,t,n){for(;;t++){if(t>=e.length){n();return}if(!(e[t].unit.length<32)&&(this.decryptAacSample(e,t,n),!this.decrypter.isSync()))return}}getAvcEncryptedData(e){let t=Math.floor((e.length-48)/160)*16+16,n=new Int8Array(t),r=0;for(let t=32;t<e.length-16;t+=160,r+=16)n.set(e.subarray(t,t+16),r);return n}getAvcDecryptedUnit(e,t){let n=new Uint8Array(t),r=0;for(let t=32;t<e.length-16;t+=160,r+=16)e.set(n.subarray(r,r+16),t);return e}decryptAvcSample(e,t,n,r,i){let a=Ar(i.data),o=this.getAvcEncryptedData(a);this.decryptBuffer(o.buffer).then(o=>{i.data=this.getAvcDecryptedUnit(a,o),this.decrypter.isSync()||this.decryptAvcSamples(e,t,n+1,r)}).catch(r)}decryptAvcSamples(e,t,n,r){if(e instanceof Uint8Array)throw Error(`Cannot decrypt samples of type Uint8Array`);for(;;t++,n=0){if(t>=e.length){r();return}let i=e[t].units;for(;!(n>=i.length);n++){let a=i[n];if(!(a.data.length<=48||a.type!==1&&a.type!==5)&&(this.decryptAvcSample(e,t,n,r,a),!this.decrypter.isSync()))return}}}},mc=class extends tc{constructor(e,t){super(),this.observer=void 0,this.config=void 0,this.sampleAes=null,this.observer=e,this.config=t}resetInitSegment(e,t,n,r){super.resetInitSegment(e,t,n,r),this._audioTrack={container:`audio/adts`,type:`audio`,id:2,pid:-1,sequenceNumber:0,segmentCodec:`aac`,samples:[],manifestCodec:t,duration:r,inputTimeScale:9e4,dropped:0}}static probe(e,t){if(!e)return!1;let n=Cn(e,0)?.length||0;if(fc(e,n))return!1;for(let r=e.length;n<r;n++)if(Js(e,n))return t.log(`ADTS sync word found !`),!0;return!1}canParse(e,t){return qs(e,t)}appendFrame(e,t,n){Ys(e,this.observer,t,n,e.manifestCodec);let r=Qs(e,t,n,this.basePTS,this.frameIndex);if(r?.missing===0)return r}demuxSampleAes(e,t,n){let r=this.demux(e,n),i=this.sampleAes=new pc(this.observer,this.config,t);return new Promise(e=>{i.decryptAacSamples(r.audioTrack.samples,0,()=>{e(r)})})}},hc=(e,t)=>{let n=0,r=5;t+=r;let i=new Uint32Array(1),a=new Uint32Array(1),o=new Uint8Array(1);for(;r>0;){o[0]=e[t];let s=Math.min(r,8),c=8-s;a[0]=4278190080>>>24+c<<c,i[0]=(o[0]&a[0])>>c,n=n?n<<s|i[0]:i[0],t+=1,r-=s}return n},gc=class extends tc{constructor(e){super(),this.observer=void 0,this.observer=e}resetInitSegment(e,t,n,r){super.resetInitSegment(e,t,n,r),this._audioTrack={container:`audio/ac-3`,type:`audio`,id:2,pid:-1,sequenceNumber:0,segmentCodec:`ac3`,samples:[],manifestCodec:t,duration:r,inputTimeScale:9e4,dropped:0}}canParse(e,t){return t+64<e.length}appendFrame(e,t,n){let r=_c(e,t,n,this.basePTS,this.frameIndex);if(r!==-1)return{sample:e.samples[e.samples.length-1],length:r,missing:0}}static probe(e){if(!e)return!1;let t=Cn(e,0);if(!t)return!1;let n=t.length;if(e[n]===11&&e[n+1]===119&&Vn(t)!==void 0){if(hc(e,n)<16)return!0;throw Error(`Containerless ec-3 is not supported`)}return!1}};function _c(e,t,n,r,i){if(n+8>t.length||t[n]!==11||t[n+1]!==119)return-1;let a=t[n+4]>>6;if(a>=3)return-1;let o=[48e3,44100,32e3][a],s=t[n+4]&63,c=[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][s*3+a]*2;if(n+c>t.length)return-1;let l=t[n+6]>>5,u=0;l===2?u+=2:(l&1&&l!==1&&(u+=2),l&4&&(u+=2));let d=(t[n+6]<<8|t[n+7])>>12-u&1,f=[2,1,2,3,3,4,4,5][l]+d,p=t[n+5]>>3,m=t[n+5]&7,h=new Uint8Array([a<<6|p<<1|m>>2,(m&3)<<6|l<<3|d<<2|s>>4,s<<4&224]),g=r+i*(1536/o*9e4),_=t.subarray(n,n+c);return e.config=h,e.channelCount=f,e.samplerate=o,e.samples.push({unit:_,pts:g}),c}var vc=class extends tc{resetInitSegment(e,t,n,r){super.resetInitSegment(e,t,n,r),this._audioTrack={container:`audio/mpeg`,type:`audio`,id:2,pid:-1,sequenceNumber:0,segmentCodec:`mp3`,samples:[],manifestCodec:t,duration:r,inputTimeScale:9e4,dropped:0}}static probe(e){if(!e)return!1;let t=Cn(e,0),n=t?.length||0;if(t&&e[n]===11&&e[n+1]===119&&Vn(t)!==void 0&&hc(e,n)<=16)return!1;for(let t=e.length;n<t;n++)if(fc(e,n))return U.log(`MPEG Audio sync word found !`),!0;return!1}canParse(e,t){return dc(e,t)}appendFrame(e,t,n){if(this.basePTS!==null)return sc(e,t,n,this.basePTS,this.frameIndex)}},yc=/\/emsg[-/]ID3/i,bc=class{constructor(e,t,n,r=U){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=r}resetTimeStamp(){}resetInitSegment(e,t,n,r){let i=this.videoTrack=ec(`video`,1),a=this.audioTrack=ec(`audio`,1),o=this.txtTrack=ec(`text`,1);if(this.id3Track=ec(`id3`,1),this.initData=void 0,this.timeOffset=0,!(e!=null&&e.byteLength))return;let s=this.initData=sr(e);if(s.video){let{id:e,timescale:t,codec:n,supplemental:r}=s.video;i.id=e,i.timescale=o.timescale=t,i.codec=n,i.supplemental=r}if(s.audio){let{id:e,timescale:t,codec:n}=s.audio;a.id=e,a.timescale=t,a.codec=n}o.id=qn.text,i.sampleDuration=0,i.duration=a.duration=r}resetContiguity(){this.remainderData=null}static probe(e){return ir(e,`moof`)}demux(e,t,n){this.timeOffset=t;let r=e,i=this.videoTrack,a=this.txtTrack;if(this.config.progressive){this.remainderData&&(r=Tr(this.remainderData,e));let t=wr(r);this.remainderData=t.remainder,i.samples=t.valid||new Uint8Array}else i.samples=r;let o=this.extractID3Track(i,t),s=this.parseFragment(i,a,t,n);return{videoTrack:i,audioTrack:this.audioTrack,id3Track:o,textTrack:this.txtTrack,initData:this.initData,sampleData:s}}flush(e,t){let n=this.timeOffset,r=this.videoTrack,i=this.txtTrack;r.samples=this.remainderData||new Uint8Array,this.remainderData=null;let a=this.extractID3Track(r,this.timeOffset),o=this.parseFragment(r,i,n,t);return{videoTrack:r,audioTrack:ec(),id3Track:a,textTrack:ec(),initData:this.initData,sampleData:o}}parseFragment(e,t,n,r){let i=this.initData;if(i&&r){let{samples:a,sampleData:o}=Sr(n,e,i,this.logger,r.iframe);return t.samples=a,o}t.samples=Er(n,e)}extractID3Track(e,t){let n=this.id3Track;if(e.samples.length){let r=K(e.samples,[`emsg`]);r&&r.forEach(e=>{let r=jr(e);if(yc.test(r.schemeIdUri)){let e=xc(r,t),i=r.eventDuration===4294967295?1/0:r.eventDuration/r.timeScale;i<=.001&&(i=1/0);let a=r.payload;n.samples.push({data:a,len:a.byteLength,dts:e,pts:e,type:$s.emsg,duration:i})}else if(this.config.enableEmsgKLVMetadata){let e=this.config.emsgKLVSchemaUri||$s.misbklv;if(r.schemeIdUri.startsWith(e)){let e=xc(r,t);n.samples.push({data:r.payload,len:r.payload.byteLength,dts:e,pts:e,type:$s.misbklv,duration:1/0})}}})}return n}demuxSampleAes(e,t,n){return Promise.reject(Error(`The MP4 demuxer does not support SAMPLE-AES decryption`))}destroy(){this.config=null,this.remainderData=null,this.videoTrack=this.audioTrack=this.id3Track=this.txtTrack=void 0,this.initData=void 0}};function xc(e,t){return P(e.presentationTime)?e.presentationTime/e.timeScale:t+e.presentationTimeDelta/e.timeScale}var Sc=1,Cc=2,wc=3,Tc=-1,Ec=class{constructor(){this.VideoSample=null}createVideoSample(e,t,n){return{key:e,frame:!1,pts:t,dts:n,units:[],length:0}}getLastNalUnit(e){var t;let n=this.VideoSample,r;if((!n||n.units.length===0)&&(n=e[e.length-1]),(t=n)!=null&&t.units){let e=n.units;r=e[e.length-1]}return r}pushAccessUnit(e,t){if(e.units.length&&e.frame){if(e.pts===void 0){let n=t.samples,r=n.length;if(r){let t=n[r-1];e.pts=t.pts,e.dts=t.dts}else{t.dropped++;return}}t.samples.push(e)}}parseNALu(e,t,n){let r=t.byteLength;if(r===0)return[];let i=e.naluState||0,a=i===Tc?0:i,o=[],s=0,c=0,l=-1,u=0;for(i===Tc&&(l=0,u=this.getNALuType(t,0),c=1);c<r;){let n=t.indexOf(Sc,c);if(n===-1)break;c=n+1;let i=n;for(;i>0&&t[i-1]===0;)i--;let d=n-i+(i===0?a:0);if(d<Cc)continue;let f=Math.min(d,wc),p=Math.min(n-i,f),m=f-p;if(i=n-p,l>=0)o.push({data:t.subarray(l,i),type:u});else{let n=this.getLastNalUnit(e.samples);n&&(i>0?n.data=Tr(n.data,t.subarray(0,i)):m>0&&(n.data=n.data.subarray(0,n.data.byteLength-m)),n.state=0)}if(c<r)l=c,u=this.getNALuType(t,c);else{s=Tc,l=-1;break}}if(s!==Tc){let e=r;for(;e>0&&t[e-1]===0;)e--;s=r-e+(e===0?a:0)}if(l>=0)o.push({data:t.subarray(l),type:u,state:s});else if(o.length===0&&s!==Tc){let n=this.getLastNalUnit(e.samples);n&&(n.data=Tr(n.data,t),n.state=s)}return e.naluState=s,o}},Dc=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,n=e.byteLength-t,r=new Uint8Array(4),i=Math.min(4,t);if(i===0)throw Error(`no bytes available`);r.set(e.subarray(n,n+i)),this.word=new DataView(r.buffer).getUint32(0),this.bitsAvailable=i*8,this.bytesAvailable-=i}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),n=this.word>>>32-t;if(e>32&&U.error(`Cannot read more than 32 bits at a time`),this.bitsAvailable-=t,this.bitsAvailable>0)this.word<<=t;else if(this.bytesAvailable>0)this.loadWord();else throw Error(`no bits available`);return t=e-t,t>0&&this.bitsAvailable?n<<t|this.readBits(t):n}skipLZ(){let e=0;for(;e<this.bitsAvailable;++e)if(this.word&2147483648>>>e)return this.word<<=e,this.bitsAvailable-=e,e;return this.loadWord(),e+this.skipLZ()}skipUEG(){this.skipBits(1+this.skipLZ())}skipEG(){this.skipBits(1+this.skipLZ())}readUEG(){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)}},Oc=class extends Ec{parsePES(e,t,n,r,i){let a=i.iframe,o=this.parseNALu(e,n.data,r),s=this.VideoSample,c,l=!1;n.data=null,s&&o.length&&!e.audFound&&(this.pushAccessUnit(s,e),s=this.VideoSample=this.createVideoSample(!1,n.pts,n.dts)),o.forEach(r=>{var i,o;switch(r.type){case 1:{if(a)break;let t=!1;c=!0;let i=r.data;if(l&&i.length>4){let e=this.readSliceType(i);(e===2||e===4||e===7||e===9)&&(t=!0)}if(t){var u;(u=s)!=null&&u.frame&&!s.key&&(this.pushAccessUnit(s,e),s=this.VideoSample=null)}s||=this.VideoSample=this.createVideoSample(!0,n.pts,n.dts),s.frame=!0,s.key=t;break}case 5:c=!0,(i=s)!=null&&i.frame&&!s.key&&(this.pushAccessUnit(s,e),s=this.VideoSample=null),s||=this.VideoSample=this.createVideoSample(!0,n.pts,n.dts),s.key=!0,s.frame=!0;break;case 6:if(a)break;c=!0,kr(r.data,1,n.pts,t.samples);break;case 7:{c=!0,l=!0;let t=r.data,n=this.readSPS(t);if(!e.sps||e.width!==n.width||e.height!==n.height||e.pixelRatio?.[0]!==n.pixelRatio[0]||e.pixelRatio?.[1]!==n.pixelRatio[1]){e.width=n.width,e.height=n.height,e.pixelRatio=n.pixelRatio,e.sps=[t];let r=t.subarray(1,4),i=`avc1.`;for(let e=0;e<3;e++){let t=r[e].toString(16);t.length<2&&(t=`0`+t),i+=t}e.codec=i}break}case 8:c=!0,e.pps=[r.data];break;case 9:c=!0,e.audFound=!0,(o=s)!=null&&o.frame&&(this.pushAccessUnit(s,e),s=null),s||=this.VideoSample=this.createVideoSample(!1,n.pts,n.dts);break;case 12:c=!0;break;default:c=!1}s&&c&&s.units.push(r)}),r&&s&&(this.pushAccessUnit(s,e),this.VideoSample=null)}getNALuType(e,t){return e[t]&31}readSliceType(e){let t=new Dc(e);return t.readUByte(),t.readUEG(),t.readUEG()}skipScalingList(e,t){let n=8,r=8,i;for(let a=0;a<e;a++)r!==0&&(i=t.readEG(),r=(n+i+256)%256),n=r===0?n:r}readSPS(e){let t=new Dc(e),n=0,r=0,i=0,a=0,o,s,c,l=t.readUByte.bind(t),u=t.readBits.bind(t),d=t.readUEG.bind(t),f=t.readBoolean.bind(t),p=t.skipBits.bind(t),m=t.skipEG.bind(t),h=t.skipUEG.bind(t),g=this.skipScalingList.bind(this);l();let _=l();if(u(5),p(3),l(),h(),_===100||_===110||_===122||_===244||_===44||_===83||_===86||_===118||_===128){let e=d();if(e===3&&p(1),h(),h(),p(1),f())for(s=e===3?12:8,c=0;c<s;c++)f()&&g(c<6?16:64,t)}h();let v=d();if(v===0)d();else if(v===1)for(p(1),m(),m(),o=d(),c=0;c<o;c++)m();h(),p(1);let y=d(),b=d(),x=u(1);x===0&&p(1),p(1),f()&&(n=d(),r=d(),i=d(),a=d());let S=[1,1];if(f()&&f())switch(l()){case 1:S=[1,1];break;case 2:S=[12,11];break;case 3:S=[10,11];break;case 4:S=[16,11];break;case 5:S=[40,33];break;case 6:S=[24,11];break;case 7:S=[20,11];break;case 8:S=[32,11];break;case 9:S=[80,33];break;case 10:S=[18,11];break;case 11:S=[15,11];break;case 12:S=[64,33];break;case 13:S=[160,99];break;case 14:S=[4,3];break;case 15:S=[3,2];break;case 16:S=[2,1];break;case 255:S=[l()<<8|l(),l()<<8|l()]}return{width:Math.ceil((y+1)*16-n*2-r*2),height:(2-x)*(b+1)*16-(x?2:4)*(i+a),pixelRatio:S}}},kc=class extends Ec{constructor(...e){super(...e),this.initVPS=null}parsePES(e,t,n,r){let i=this.parseNALu(e,n.data,r),a=this.VideoSample,o,s=!1;n.data=null;let c=e=>(a=this.VideoSample=this.createVideoSample(e,n.pts,n.dts),a);i.forEach((r,i)=>{var l,u;if(this.startsNewAccessUnit(a,e,r,i)){this.pushAccessUnit(a,e);let t=r.type>=16&&r.type<=23;a=c(t),s=!1}switch(r.type){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:case 8:case 9:a||=c(!1),a.frame=!0,o=!0;break;case 16:case 17:case 18:case 21:case 22:case 23:if(o=!0,s){var d;(d=a)!=null&&d.frame&&!a.key&&(this.pushAccessUnit(a,e),a=this.VideoSample=null)}a||=c(!0),a.key=!0,a.frame=!0;break;case 19:case 20:o=!0,(l=a)!=null&&l.frame&&!a.key&&(this.pushAccessUnit(a,e),a=this.VideoSample=null),a||=c(!0),a.key=!0,a.frame=!0;break;case 39:o=!0,kr(r.data,2,n.pts,t.samples);break;case 32:o=!0,e.vps||(typeof e.params!=`object`&&(e.params={}),e.params=V(e.params,this.readVPS(r.data)),this.initVPS=r.data),e.vps=[r.data];break;case 33:if(o=!0,s=!0,e.vps!==void 0&&e.vps[0]!==this.initVPS&&e.sps!==void 0&&!this.matchSPS(e.sps[0],r.data)&&(this.initVPS=e.vps[0],e.sps=e.pps=void 0),!e.sps){let t=this.readSPS(r.data);e.width=t.width,e.height=t.height,e.pixelRatio=t.pixelRatio,e.codec=t.codecString,e.sps=[],typeof e.params!=`object`&&(e.params={});for(let n in t.params)e.params[n]=t.params[n]}this.pushParameterSet(e.sps,r.data,e.vps),a||=c(!1);break;case 34:if(o=!0,typeof e.params==`object`){if(!e.pps){e.pps=[];let t=this.readPPS(r.data);for(let n in t)e.params[n]=t[n]}this.pushParameterSet(e.pps,r.data,e.vps)}break;case 35:o=!0,e.audFound=!0,(u=a)!=null&&u.frame&&(this.pushAccessUnit(a,e),a=null),a||=c(!1);break;default:o=!1}a&&o&&a.units.push(r)}),r&&a&&(this.pushAccessUnit(a,e),this.VideoSample=null)}pushParameterSet(e,t,n){(n&&n[0]===this.initVPS||!n&&!e.length)&&e.push(t)}startsNewAccessUnit(e,t,n,r){if(!e)return!1;if(!t.audFound&&r===0)return!0;if(!e.frame)return!1;let{type:i,data:a}=n;return i>=32&&i<=35||i===39||i>=41&&i<=44||i>=48&&i<=55||i<=31&&a.length>2&&!!(a[2]&128)}getNALuType(e,t){return(e[t]&126)>>>1}ebsp2rbsp(e){let t=new Uint8Array(e.byteLength),n=0;for(let r=0;r<e.byteLength;r++)r>=2&&e[r]===3&&e[r-1]===0&&e[r-2]===0||(t[n]=e[r],n++);return new Uint8Array(t.buffer,0,n)}pushAccessUnit(e,t){super.pushAccessUnit(e,t),this.initVPS&&=null}readVPS(e){let t=new Dc(e);t.readUByte(),t.readUByte(),t.readBits(4),t.skipBits(2),t.readBits(6);let n=t.readBits(3),r=t.readBoolean();return{numTemporalLayers:n+1,temporalIdNested:r}}readSPS(e){let t=new Dc(this.ebsp2rbsp(e));t.readUByte(),t.readUByte(),t.readBits(4);let n=t.readBits(3);t.readBoolean();let r=t.readBits(2),i=t.readBoolean(),a=t.readBits(5),o=t.readUByte(),s=t.readUByte(),c=t.readUByte(),l=t.readUByte(),u=t.readUByte(),d=t.readUByte(),f=t.readUByte(),p=t.readUByte(),m=t.readUByte(),h=t.readUByte(),g=t.readUByte(),_=[],v=[];for(let e=0;e<n;e++)_.push(t.readBoolean()),v.push(t.readBoolean());if(n>0)for(let e=n;e<8;e++)t.readBits(2);for(let e=0;e<n;e++)_[e]&&(t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte()),v[e]&&t.readUByte();t.readUEG();let y=t.readUEG();y==3&&t.skipBits(1);let b=t.readUEG(),x=t.readUEG(),S=t.readBoolean(),C=0,w=0,T=0,E=0;S&&(C+=t.readUEG(),w+=t.readUEG(),T+=t.readUEG(),E+=t.readUEG());let D=t.readUEG(),O=t.readUEG(),k=t.readUEG(),A=t.readBoolean();for(let e=A?0:n;e<=n;e++)t.skipUEG(),t.skipUEG(),t.skipUEG();if(t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG(),t.readBoolean()&&t.readBoolean())for(let e=0;e<4;e++)for(let n=0;n<(e===3?2:6);n++)if(!t.readBoolean())t.readUEG();else{let n=Math.min(64,1<<4+(e<<1));e>1&&t.readEG();for(let e=0;e<n;e++)t.readEG()}t.readBoolean(),t.readBoolean(),t.readBoolean()&&(t.readUByte(),t.skipUEG(),t.skipUEG(),t.readBoolean());let j=t.readUEG(),M=0;for(let e=0;e<j;e++){let n=!1;if(e!==0&&(n=t.readBoolean()),n){e===j&&t.readUEG(),t.readBoolean(),t.readUEG();let n=0;for(let e=0;e<=M;e++){let e=t.readBoolean(),r=!1;e||(r=t.readBoolean()),(e||r)&&n++}M=n}else{let e=t.readUEG(),n=t.readUEG();M=e+n;for(let n=0;n<e;n++)t.readUEG(),t.readBoolean();for(let e=0;e<n;e++)t.readUEG(),t.readBoolean()}}if(t.readBoolean()){let e=t.readUEG();for(let n=0;n<e;n++){for(let e=0;e<k+4;e++)t.readBits(1);t.readBits(1)}}let N=0,ee=1,te=1,ne=!0,re=1,ie=0;t.readBoolean(),t.readBoolean();let ae=!1;if(t.readBoolean()){if(t.readBoolean()){let e=t.readUByte();e>0&&e<16?(ee=[1,12,10,16,40,24,20,32,80,18,15,64,160,4,3,2][e-1],te=[1,11,11,11,33,11,11,11,33,11,11,33,99,3,2,1][e-1]):e===255&&(ee=t.readBits(16),te=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(),ae=t.readBoolean(),ae&&(t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG()),t.readBoolean()&&(re=t.readBits(32),ie=t.readBits(32),t.readBoolean()&&t.readUEG(),t.readBoolean())){let e=t.readBoolean(),r=t.readBoolean(),i=!1;(e||r)&&(i=t.readBoolean(),i&&(t.readUByte(),t.readBits(5),t.readBoolean(),t.readBits(5)),t.readBits(4),t.readBits(4),i&&t.readBits(4),t.readBits(5),t.readBits(5),t.readBits(5));for(let a=0;a<=n;a++){ne=t.readBoolean();let n=ne||t.readBoolean(),a=!1;n?t.readEG():a=t.readBoolean();let o=a?1:t.readUEG()+1;if(e)for(let e=0;e<o;e++)t.readUEG(),t.readUEG(),i&&(t.readUEG(),t.readUEG()),t.skipBits(1);if(r)for(let e=0;e<o;e++)t.readUEG(),t.readUEG(),i&&(t.readUEG(),t.readUEG()),t.skipBits(1)}}t.readBoolean()&&(t.readBoolean(),t.readBoolean(),t.readBoolean(),N=t.readUEG())}let oe=b,se=x;if(S){let e=1,t=1;y===1?e=t=2:y==2&&(e=2),oe=b-e*w-e*C,se=x-t*E-t*T}let ce=r?[`A`,`B`,`C`][r]:``,le=o<<24|s<<16|c<<8|l,ue=0;for(let e=0;e<32;e++)ue=(ue|(le>>e&1)<<31-e)>>>0;let de=ue.toString(16);return a===1&&de===`2`&&(de=`6`),{codecString:`hvc1.${ce}${a}.${de}.${i?`H`:`L`}${g}.B0`,params:{general_tier_flag:i,general_profile_idc:a,general_profile_space:r,general_profile_compatibility_flags:[o,s,c,l],general_constraint_indicator_flags:[u,d,f,p,m,h],general_level_idc:g,bit_depth:D+8,bit_depth_luma_minus8:D,bit_depth_chroma_minus8:O,min_spatial_segmentation_idc:N,chroma_format_idc:y,frame_rate:{fixed:ne,fps:ie/re}},width:oe,height:se,pixelRatio:[ee,te]}}readPPS(e){let t=new Dc(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 n=t.readBoolean(),r=t.readBoolean(),i=1;return r&&n?i=0:r?i=3:n&&(i=2),{parallelismType:i}}matchSPS(e,t){return Gn(e).substring(3)===Gn(t).substring(3)}},Ac=188,jc=class e{constructor(e,t,n,r){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=n,this.logger=r,this.videoParser=null}static probe(t,n){let r=e.syncOffset(t);return r>0&&n.warn(`MPEG2-TS detected but first sync word found @ offset ${r}`),r!==-1}static syncOffset(e){let t=e.length,n=Math.min(940,t-Ac)+1,r=0;for(;r<n;){let i=!1,a=-1,o=0;for(let s=r;s<t;s+=Ac)if(e[s]===71&&(t-s===Ac||e[s+Ac]===71)){if(o++,a===-1&&(a=s,a!==0&&(n=Math.min(a+18612,e.length-Ac)+1)),i||=Mc(e,s)===0,i&&o>1&&(a===0&&o>2||s+Ac>n))return a}else if(o)return-1;else break;r++}return-1}static createTrack(e,t){return{container:e===`video`||e===`audio`?`video/mp2t`:void 0,type:e,id:qn[e],pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0,duration:e===`audio`?t:void 0}}resetInitSegment(t,n,r,i,a,o){this.pmtParsed=!1,this._pmtId=-1,this._videoTrack=e.createTrack(`video`),this._videoTrack.duration=i,this.videoIntegrityChecker=this.config.handleMpegTsVideoIntegrityErrors===`skip`?new Rc(this.logger):null,this._audioTrack=e.createTrack(`audio`,i),this._id3Track=e.createTrack(`id3`),this._txtTrack=e.createTrack(`text`),this._audioTrack.segmentCodec=`aac`,this.videoParser=null,this.aacOverFlow=null,this.remainderData=null,this.audioCodec=n,this.videoCodec=r,t&&this.demux(t,0,o,a?.method===`SAMPLE-AES`)}resetTimeStamp(){}resetContiguity(){let{_audioTrack:e,_videoTrack:t,_id3Track:n}=this;e&&(e.pesData=null),t&&(t.pesData=null),n&&(n.pesData=null),this.videoParser=null,this.aacOverFlow=null,this.remainderData=null}demux(t,n,r,i=!1,a=!1){i||(this.sampleAes=null);let o,s=this._videoTrack,c=this.videoIntegrityChecker,l=this._audioTrack,u=this._id3Track,d=this._txtTrack,f=r.iframe,p=s.pid,m=s.pesData,h=l.pid,g=u.pid,_=this._klvPid,v=l.pesData,y=u.pesData,b=null,x=null,S=this.pmtParsed,C=this._pmtId,w=t.length;if(this.remainderData&&=(t=Tr(this.remainderData,t),w=t.length,null),w<Ac&&!a)return this.remainderData=t,{audioTrack:l,videoTrack:s,id3Track:u,textTrack:d};let T=Math.max(0,e.syncOffset(t));w-=(w-T)%Ac,w<t.byteLength&&!a&&(this.remainderData=new Uint8Array(t.buffer,w,t.buffer.byteLength-w));let E=0;for(let e=T;e<w;e+=Ac)if(t[e]===71){let n=!!(t[e+1]&64),a=Mc(t,e),w=(t[e+3]&48)>>4,E;if(w>1){if(E=e+5+t[e+4],E===e+Ac)continue}else E=e+4;switch(a){case p:n&&(m&&!(c!=null&&c.isCorrupted)&&(o=Lc(m,this.logger))&&(this.readyVideoParser(s.segmentCodec),this.videoParser!==null&&this.videoParser.parsePES(s,d,o,!1,r)),m={data:[],size:0},c?.reset(p)),c?.handlePacket(t.subarray(e)),m&&(m.data.push(t.subarray(E,e+Ac)),m.size+=e+Ac-E);break;case h:if(f)break;if(n){if(v&&(o=Lc(v,this.logger)))switch(l.segmentCodec){case`aac`:this.parseAACPES(l,o,r);break;case`mp3`:this.parseMPEGPES(l,o);break;case`ac3`:this.parseAC3PES(l,o)}v={data:[],size:0}}v&&(v.data.push(t.subarray(E,e+Ac)),v.size+=e+Ac-E);break;case g:if(f)break;n&&(y&&(o=Lc(y,this.logger))&&this.parseID3PES(u,o),y={data:[],size:0}),y&&(y.data.push(t.subarray(E,e+Ac)),y.size+=e+Ac-E);break;case _:if(f)break;n&&(b&&(o=Lc(b,this.logger))&&this.parseKlvPES(u,o),b={data:[],size:0}),b&&(b.data.push(t.subarray(E,e+Ac)),b.size+=e+Ac-E);break;case 0:n&&(E+=t[E]+1),C=this._pmtId=Nc(t,E);break;case C:{n&&(E+=t[E]+1);let a=Pc(t,E,this.typeSupported,i,this.observer,this.logger,this.config,r);p=a.videoPid,p>0&&(s.pid=p,s.segmentCodec=a.segmentVideoCodec),h=a.audioPid,h>0&&(l.pid=h,l.segmentCodec=a.segmentAudioCodec),g=a.id3Pid,g>0&&(u.pid=g),_=a.klvPid,_>0&&(this._klvPid=_),x!==null&&!S&&(this.logger.warn(`MPEG-TS PMT found at ${e} after unknown PID '${x}'. Backtracking to sync byte @${T} to parse all TS packets.`),x=null,e=T-188),S=this.pmtParsed=!0;break}case 17:case 8191:break;default:x=a}}else E++;E>0&&Fc(this.observer,Error(`Found ${E} TS packet/s that do not start with 0x47`),r,void 0,this.logger),s.pesData=m,l.pesData=v,u.pesData=y;let D={audioTrack:l,videoTrack:s,id3Track:u,textTrack:d};return a&&this.extractRemainingSamples(D,r),D}flush(e,t){let{remainderData:n}=this;this.remainderData=null;let r;return r=n?this.demux(n,0,t,!1,!0):{videoTrack:this._videoTrack,audioTrack:this._audioTrack,id3Track:this._id3Track,textTrack:this._txtTrack},this.extractRemainingSamples(r,t),this.sampleAes?this.decrypt(r,this.sampleAes):r}extractRemainingSamples(e,t){let{audioTrack:n,videoTrack:r,id3Track:i,textTrack:a}=e,o=r.pesData,s=n.pesData,c=i.pesData,l=this.videoIntegrityChecker,u;if(o&&!(l!=null&&l.isCorrupted)&&(u=Lc(o,this.logger))?(this.readyVideoParser(r.segmentCodec),this.videoParser!==null&&(this.videoParser.parsePES(r,a,u,!0,t),r.pesData=null)):r.pesData=o,s&&(u=Lc(s,this.logger))){switch(n.segmentCodec){case`aac`:this.parseAACPES(n,u,t);break;case`mp3`:this.parseMPEGPES(n,u);break;case`ac3`:this.parseAC3PES(n,u)}n.pesData=null}else s!=null&&s.size&&this.logger.log(`last AAC PES packet truncated,might overlap between fragments`),n.pesData=s;c&&(u=Lc(c,this.logger))?(this.parseID3PES(i,u),i.pesData=null):i.pesData=c}demuxSampleAes(e,t,n,r){let i=this.demux(e,n,r,!0,!this.config.progressive),a=this.sampleAes=new pc(this.observer,this.config,t);return this.decrypt(i,a)}readyVideoParser(e){this.videoParser===null&&(e===`avc`?this.videoParser=new Oc:e===`hevc`&&(this.videoParser=new kc))}decrypt(e,t){return new Promise(n=>{let{audioTrack:r,videoTrack:i}=e;r.samples&&r.segmentCodec===`aac`?t.decryptAacSamples(r.samples,0,()=>{i.samples?t.decryptAvcSamples(i.samples,0,0,()=>{n(e)}):n(e)}):i.samples&&t.decryptAvcSamples(i.samples,0,0,()=>{n(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,n){let r=0,i=this.aacOverFlow,a=t.data;if(i){this.aacOverFlow=null;let t=i.missing,n=i.sample.unit.byteLength;if(t===-1)a=Tr(i.sample.unit,a);else{let o=n-t;i.sample.unit.set(a.subarray(0,t),o),e.samples.push(i.sample),r=i.missing}}let o,s;for(o=r,s=a.length;o<s-1&&!Ks(a,o);o++);if(o!==r){let e,t=o<s-1;if(e=t?`AAC PES did not start with ADTS header,offset:${o}`:`No ADTS header found in AAC PES`,Fc(this.observer,Error(e),n,t,this.logger),!t)return}Ys(e,this.observer,a,o,this.audioCodec);let c;if(t.pts!==void 0)c=t.pts;else if(i){let t=Xs(e.samplerate);c=i.sample.pts+t}else{this.logger.warn(`[tsdemuxer]: AAC PES unknown PTS`);return}let l=0,u;for(;o<s;){if(u=Qs(e,a,o,c,l),o+=u.length,u.missing){this.aacOverFlow=u;break}for(l++;o<s-1&&!Ks(a,o);o++);}}parseMPEGPES(e,t){let n=t.data,r=n.length,i=0,a=0,o=t.pts;if(o===void 0){this.logger.warn(`[tsdemuxer]: MPEG PES unknown PTS`);return}for(;a<r;)if(uc(n,a)){let t=sc(e,n,a,o,i);if(t)a+=t.length,i++;else break}else a++}parseAC3PES(e,t){{let n=t.data,r=t.pts;if(r===void 0){this.logger.warn(`[tsdemuxer]: AC3 PES unknown PTS`);return}let i=n.length,a=0,o=0,s;for(;o<i&&(s=_c(e,n,o,r,a++))>0;)o+=s}}parseID3PES(e,t){if(t.pts===void 0){this.logger.warn(`[tsdemuxer]: ID3 PES unknown PTS`);return}let n=V({},t,{type:this._videoTrack?$s.emsg:$s.audioId3,duration:1/0});e.samples.push(n)}parseKlvPES(e,t){let n=t.pts??t.dts;if(n===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 i=0;for(;i<r.length&&!(i+16>r.length);){let a=i;if(i+=16,i>=r.length)break;let o=r[i];i+=1;let s=0;if(o&128){let e=o&127;if(e===0||e>4||i+e>r.length){this.logger.warn(`[tsdemuxer]: Invalid KLV length encoding`);break}for(let t=0;t<e;t++)s=s<<8|r[i+t];i+=e}else s=o;if(i+s>r.length){this.logger.warn(`[tsdemuxer]: KLV value extends beyond PES payload`);break}let c=i+s,l=r.subarray(a,c),u={data:l,len:l.byteLength,pts:n,dts:t.dts??n,type:$s.misbklv,duration:1/0};e.samples.push(u),i=c}}};function Mc(e,t){return((e[t+1]&31)<<8)+e[t+2]}function Nc(e,t){return(e[t+10]&31)<<8|e[t+11]}function Pc(e,t,n,r,i,a,o,s){let c={audioPid:-1,videoPid:-1,id3Pid:-1,klvPid:-1,segmentVideoCodec:`avc`,segmentAudioCodec:`aac`},l=(e[t+1]&15)<<8|e[t+2],u=t+3+l-4,d=(e[t+10]&15)<<8|e[t+11];for(t+=12+d;t<u;){let l=Mc(e,t),u=(e[t+3]&15)<<8|e[t+4];switch(e[t]){case 207:if(!r){Ic(`ADTS AAC`,a);break}case 15:c.audioPid===-1&&(c.audioPid=l);break;case 21:c.id3Pid===-1&&(c.id3Pid=l);break;case 219:if(!r){Ic(`H.264`,a);break}case 27:c.videoPid===-1&&(c.videoPid=l);break;case 3:case 4:!n.mpeg&&!n.mp3?a.log(`MPEG audio found, not supported in this browser`):c.audioPid===-1&&(c.audioPid=l,c.segmentAudioCodec=`mp3`);break;case 193:if(!r){Ic(`AC-3`,a);break}case 129:n.ac3?c.audioPid===-1&&(c.audioPid=l,c.segmentAudioCodec=`ac3`):a.log(`AC-3 audio found, not supported in this browser`);break;case 6:if(u>0){let r=t+5,i=u;for(;i>2;){switch(e[r]){case 106:c.audioPid===-1&&(n.ac3===!0?(c.audioPid=l,c.segmentAudioCodec=`ac3`):a.log(`AC-3 audio found, not supported in this browser for now`));break;case 5:c.klvPid===-1&&o.enableEmsgKLVMetadata&&(c.klvPid=l,a.log(`KLV metadata PID found: ${l}`))}let t=e[r+1]+2;r+=t,i-=t}}break;case 194:case 135:return Fc(i,Error(`Unsupported EC-3 in M2TS found`),s,void 0,a),c;case 36:c.videoPid===-1&&(c.videoPid=l,c.segmentVideoCodec=`hevc`,a.log(`HEVC in M2TS found`))}t+=u+5}return c}function Fc(e,t,n,r,i){i.warn(`parsing error: ${t.message}`),e.emit(L.ERROR,L.ERROR,{type:F.MEDIA_ERROR,details:I.FRAG_PARSING_ERROR,fatal:!1,levelRetry:r,chunkMeta:n,error:t,reason:t.message})}function Ic(e,t){t.log(`${e} with AES-128-CBC encryption found in unencrypted stream`)}function Lc(e,t){let n=0,r,i,a,o,s,c=e.data;if(!e||e.size===0)return null;for(;c[0].length<19&&c.length>1;)c[0]=Tr(c[0],c[1]),c.splice(1,1);if(r=c[0],(r[0]<<16)+(r[1]<<8)+r[2]===1){if(i=(r[4]<<8)+r[5],i&&i>e.size-6)return null;let l=r[7];l&192&&(o=(r[9]&14)*536870912+(r[10]&255)*4194304+(r[11]&254)*16384+(r[12]&255)*128+(r[13]&254)/2,l&64?(s=(r[14]&14)*536870912+(r[15]&255)*4194304+(r[16]&254)*16384+(r[17]&255)*128+(r[18]&254)/2,o-s>54e5&&(t.warn(`${Math.round((o-s)/9e4)}s delta between PTS and DTS, align them`),o=s)):s=o),a=r[8];let u=a+9;if(e.size<=u)return null;e.size-=u;let d=new Uint8Array(e.size);for(let e=0,t=c.length;e<t;e++){r=c[e];let t=r.byteLength;if(u){if(u>t){u-=t;continue}r=r.subarray(u),t-=u,u=0}d.set(r,n),n+=t}return i&&(i-=a+3),{data:d,pts:o,dts:s,len:i}}return null}var Rc=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=Mc(e,0);if(t!==this.pid){this.logger.debug(`Packet PID mismatch, expected ${this.pid} got ${t}`);return}let n=(e[3]&48)>>4;if(n===0)return;let r=e[3]&15,i=this.lastContinuityCounter;this.lastContinuityCounter=r;let a=!!(n&1);if(n&2&&e[4]!=0&&e[5]&128||i<0)return;let o=a?i+1&15:i;if(r!==o){this.logger.warn(`MPEG-TS Continuity Counter check failed for PID='${t}', CC=${r}, Expected-CC=${o} Last-CC=${i}`),this.integrityState=`cc-failed`;return}if(e[1]&128){this.logger.warn(`MPEG-TS Packet had TEI flag set for PID='${t}'`),this.integrityState=`tei-bit`;return}}},zc=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||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])}}},Bc,Vc={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])},Hc=new Uint8Array([0,0,0,0,0,0,0,0]),Uc=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),Wc=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0]),Gc=new Uint8Array([0,0,0,0,0,0,0,0]),Kc=new Uint8Array([0,0,0,0,0,0,0,1]),qc=new Uint8Array([105,115,111,109]),Jc=new Uint8Array([97,118,99,49]),Yc=new Uint8Array([0,0,0,1]),Xc=class e{static box(e,...t){let n=8,r=t.length,i=r;for(;r--;)n+=t[r].byteLength;let a=new Uint8Array(n);for(Qn(a,0,n),Qn(a,4,e),r=0,n=8;r<i;r++)a.set(t[r],n),n+=t[r].byteLength;return a}static hdlr(t){return e.box(W.hdlr,Vc[t])}static mdat(t){return e.box(W.mdat,t)}static mdhd(t,n){n*=t;let r=Math.floor(n/(Kn+1)),i=Math.floor(n%(Kn+1));return e.box(W.mdhd,new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,t>>24&255,t>>16&255,t>>8&255,t&255,r>>24,r>>16&255,r>>8&255,r&255,i>>24,i>>16&255,i>>8&255,i&255,85,196,0,0]))}static mdia(t){return e.box(W.mdia,e.mdhd(t.timescale||0,t.duration||0),e.hdlr(t.type),e.minf(t))}static mfhd(t){return e.box(W.mfhd,new Uint8Array([0,0,0,0,t>>24,t>>16&255,t>>8&255,t&255]))}static minf(t){return t.type===`audio`?e.box(W.minf,e.box(W.smhd,Gc),e.DINF,e.stbl(t)):e.box(W.minf,e.box(W.vmhd,Wc),e.DINF,e.stbl(t))}static moof(t,n,r){return e.box(W.moof,e.mfhd(t),e.traf(r,n))}static moov(t){let n=t.length,r=[];for(;n--;)r[n]=e.trak(t[n]);return e.box.apply(null,[W.moov,e.mvhd(t[0].timescale||0,t[0].duration||0)].concat(r,e.mvex(t)))}static mvex(t){let n=t.length,r=[];for(;n--;)r[n]=e.trex(t[n]);return e.box.apply(null,[W.mvex,...r])}static mvhd(t,n){n*=t;let r=Math.floor(n/(Kn+1)),i=Math.floor(n%(Kn+1)),a=new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,t>>24&255,t>>16&255,t>>8&255,t&255,r>>24,r>>16&255,r>>8&255,r&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 e.box(W.mvhd,a)}static sdtp(t){let n=t.samples||[],r=new Uint8Array(4+n.length),i,a;for(i=0;i<n.length;i++)a=n[i].flags,r[i+4]=a.dependsOn<<4|a.isDependedOn<<2|a.hasRedundancy;return e.box(W.sdtp,r)}static stbl(t){return e.box(W.stbl,e.stsd(t),e.box(W.stts,Hc),e.box(W.stsc,Hc),e.box(W.stsz,Uc),e.box(W.stco,Hc))}static avc1(t){let n=[],r=[],i,a,o;for(i=0;i<t.sps.length;i++)a=t.sps[i],o=a.byteLength,n.push(o>>>8&255),n.push(o&255),n=n.concat(Array.prototype.slice.call(a));for(i=0;i<t.pps.length;i++)a=t.pps[i],o=a.byteLength,r.push(o>>>8&255),r.push(o&255),r=r.concat(Array.prototype.slice.call(a));let s=e.box(W.avcC,new Uint8Array([1,n[3],n[4],n[5],255,224|t.sps.length].concat(n,[t.pps.length],r))),c=t.width,l=t.height,u=t.pixelRatio[0],d=t.pixelRatio[1];return e.box(W.avc1,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,c>>8&255,c&255,l>>8&255,l&255,0,72,0,0,0,72,0,0,0,0,0,0,0,1,18,100,97,105,108,121,109,111,116,105,111,110,47,104,108,115,46,106,115,0,0,0,0,0,0,0,0,0,0,0,0,0,0,24,17,17]),s,e.box(W.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),e.box(W.pasp,new Uint8Array([u>>24,u>>16&255,u>>8&255,u&255,d>>24,d>>16&255,d>>8&255,d&255])))}static esds(e){let t=e.config,n=t.length;return new Uint8Array([0,0,0,0,3,23+n,0,1,0,4,15+n,64,21,0,0,0,0,0,0,0,0,0,0,0,5,n,...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(t){return e.box(W.mp4a,e.audioStsd(t),e.box(W.esds,e.esds(t)))}static mp3(t){return e.box(W[`.mp3`],e.audioStsd(t))}static ac3(t){return e.box(W[`ac-3`],e.audioStsd(t),e.box(W.dac3,t.config))}static stsd(t){let{segmentCodec:n}=t;if(t.type===`audio`){if(n===`aac`)return e.box(W.stsd,Kc,e.mp4a(t));if(n===`ac3`&&t.config)return e.box(W.stsd,Kc,e.ac3(t));if(n===`mp3`&&t.codec===`mp3`)return e.box(W.stsd,Kc,e.mp3(t))}else if(t.pps&&t.sps){if(n===`avc`)return e.box(W.stsd,Kc,e.avc1(t));if(n===`hevc`&&t.vps)return e.box(W.stsd,Kc,e.hvc1(t))}else throw Error(`video track missing pps or sps`);throw Error(`unsupported ${t.type} segment codec (${n}/${t.codec})`)}static tkhd(t){let n=t.id,r=(t.duration||0)*(t.timescale||0),i=t.width||0,a=t.height||0,o=Math.floor(r/(Kn+1)),s=Math.floor(r%(Kn+1));return e.box(W.tkhd,new Uint8Array([1,0,0,7,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,n>>24&255,n>>16&255,n>>8&255,n&255,0,0,0,0,o>>24,o>>16&255,o>>8&255,o&255,s>>24,s>>16&255,s>>8&255,s&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,a>>8&255,a&255,0,0]))}static traf(t,n){let r=e.sdtp(t),i=t.id,a=Math.floor(n/(Kn+1)),o=Math.floor(n%(Kn+1));return e.box(W.traf,e.box(W.tfhd,new Uint8Array([0,0,0,0,i>>24,i>>16&255,i>>8&255,i&255])),e.box(W.tfdt,new Uint8Array([1,0,0,0,a>>24,a>>16&255,a>>8&255,a&255,o>>24,o>>16&255,o>>8&255,o&255])),e.trun(t,r.length+16+20+8+16+8+8),r)}static trak(t){return t.duration=t.duration||4294967295,e.box(W.trak,e.tkhd(t),e.mdia(t))}static trex(t){let n=t.id;return e.box(W.trex,new Uint8Array([0,0,0,0,n>>24,n>>16&255,n>>8&255,n&255,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,1]))}static trun(t,n){let r=t.samples||[],i=r.length,a=12+16*i,o=new Uint8Array(a),s,c,l,u,d,f;for(n+=8+a,o.set([+(t.type===`video`),0,15,1,i>>>24&255,i>>>16&255,i>>>8&255,i&255,n>>>24&255,n>>>16&255,n>>>8&255,n&255],0),s=0;s<i;s++)c=r[s],l=c.duration,u=c.size,d=c.flags,f=c.cts,o.set([l>>>24&255,l>>>16&255,l>>>8&255,l&255,u>>>24&255,u>>>16&255,u>>>8&255,u&255,d.isLeading<<2|d.dependsOn,d.isDependedOn<<6|d.hasRedundancy<<4|d.paddingValue<<1|d.isNonSync,d.degradPrio&61440,d.degradPrio&15,f>>>24&255,f>>>16&255,f>>>8&255,f&255],12+16*s);return e.box(W.trun,o)}static initSegment(t){let n=e.moov(t);return Tr(e.FTYP,n)}static hvc1(t){let n=t.params,r=[t.vps,t.sps,t.pps],i=new Uint8Array([1,n.general_profile_space<<6|(n.general_tier_flag?32:0)|n.general_profile_idc,n.general_profile_compatibility_flags[0],n.general_profile_compatibility_flags[1],n.general_profile_compatibility_flags[2],n.general_profile_compatibility_flags[3],n.general_constraint_indicator_flags[0],n.general_constraint_indicator_flags[1],n.general_constraint_indicator_flags[2],n.general_constraint_indicator_flags[3],n.general_constraint_indicator_flags[4],n.general_constraint_indicator_flags[5],n.general_level_idc,240|n.min_spatial_segmentation_idc>>8,255&n.min_spatial_segmentation_idc,252|n.parallelismType,252|n.chroma_format_idc,248|n.bit_depth_luma_minus8,248|n.bit_depth_chroma_minus8,0,parseInt(n.frame_rate.fps),3|n.temporal_id_nested<<2|n.num_temporal_layers<<3|(n.frame_rate.fixed?64:0),r.length]),a=i.length;for(let e=0;e<r.length;e+=1){a+=3;for(let t=0;t<r[e].length;t+=1)a+=2+r[e][t].length}let o=new Uint8Array(a);o.set(i,0),a=i.length;let s=r.length-1;for(let e=0;e<r.length;e+=1){o.set(new Uint8Array([32+e|(e===s?128:0),0,r[e].length]),a),a+=3;for(let t=0;t<r[e].length;t+=1)o.set(new Uint8Array([r[e][t].length>>8,r[e][t].length&255]),a),a+=2,o.set(r[e][t],a),a+=r[e][t].length}let c=e.box(W.hvcC,o),l=t.width,u=t.height,d=t.pixelRatio[0],f=t.pixelRatio[1];return e.box(W.hvc1,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,l>>8&255,l&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,e.box(W.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),e.box(W.pasp,new Uint8Array([d>>24,d>>16&255,d>>8&255,d&255,f>>24,f>>16&255,f>>8&255,f&255])))}};Bc=Xc,Xc.FTYP=Bc.box(W.ftyp,qc,Yc,qc,Jc),Xc.DINF=Bc.box(W.dinf,Bc.box(W.dref,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,12,117,114,108,32,0,0,0,1])));var Zc=9e4;function Qc(e,t,n=1,r=!1){let i=e*t*n;return r?Math.round(i):i}function $c(e,t,n=1,r=!1){return Qc(e,t,1/n,r)}function el(e,t=!1){return Qc(e,1e3,1/Zc,t)}function tl(e,t=1){return Qc(e,Zc,1/t)}function nl(e){let{baseTime:t,timescale:n,trackId:r}=e;return`${t/n} (${t}/${n}) trackId: ${r}`}var rl=1e4,il=1024,al=1152,ol=1536,sl=8589934592;function cl(e,t,n,r){return{duration:t,size:n,cts:r,flags:{isLeading:0,isDependedOn:0,hasRedundancy:0,degradPrio:0,dependsOn:e?2:1,isNonSync:+!e,paddingValue:0}}}var ll=class extends Xt{constructor(e,t,n,r){super(`mp4-remuxer`,r),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=n,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&&nl(t)} > ${e&&nl(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,n=e[0].pts,r=e.reduce((e,r)=>{let i=r.pts,a=i-e;return a<-4294967296&&(t=!0,i=ul(i,n),a=i-e),a>0?e:i},n);return t&&this.debug(`PTS rollover detected`),r}remux(e,t,n,r,i,a,o,s,c){let l,u,d,f,p,m,h=i,g=i,_=!c.iframe&&e.pid>-1,v=t.pid>-1,y=t.samples.length,b=e.samples.length>0,x=o&&y>0||y>1;if((!_||b)&&(!v||x)||this.ISGenerated||o){if(this.ISGenerated){let e=this.videoTrackConfig;(e&&(t.width!==e.width||t.height!==e.height||t.pixelRatio?.[0]!==e.pixelRatio?.[0]||t.pixelRatio?.[1]!==e.pixelRatio?.[1])||!e&&x||this.nextAudioTs===null&&b)&&this.resetInitSegment()}this.ISGenerated||(d=this.generateIS(e,t,i,a));let n=this.isVideoContiguous,r=-1,o;if(x&&(r=dl(t.samples),!n&&this.config.forceKeyFrameOnDiscontinuity)){if(m=!0,r>0){this.warn(`Dropped ${r} out of ${y} video samples due to a missing keyframe`);let e=this.getVideoStartPts(t.samples);t.samples=t.samples.slice(r),t.dropped+=r,g+=(t.samples[0].pts-e)/t.inputTimeScale,o=g}else r===-1&&(this.warn(`No keyframe found out of ${y} video samples`),m=!1)}if(this.ISGenerated){if(b&&x&&i){let n=this.getVideoStartPts(t.samples),r=(ul(e.samples[0].pts,n)-n)/t.inputTimeScale;h+=Math.max(0,r),g+=Math.max(0,-r)}if(b){if(e.samplerate||(this.warn(`regenerate InitSegment as audio detected`),d=this.generateIS(e,t,i,a)),u=this.remuxAudio(e,h,this.isAudioContiguous,a,v||x||s===z.AUDIO?g:void 0,c),x){let r=u?u.endPTS-u.startPTS:0;t.inputTimeScale||(this.warn(`regenerate InitSegment as video detected`),d=this.generateIS(e,t,i,a)),l=this.remuxVideo(t,g,n,r,c)}}else x&&(l=this.remuxVideo(t,g,n,0,c));l&&(l.firstKeyFrame=r,l.independent=r!==-1,l.firstKeyFramePTS=o)}}return this.ISGenerated&&this._initPTS&&this._initDTS&&(n.samples.length&&(p=fl(n,i,this._initPTS,this._initDTS)),r.samples.length&&(f=pl(r,i,this._initPTS))),{audio:u,video:l,initSegment:d,independent:m,text:f,id3:p}}computeInitPts(e,t,n,r){let i=Math.round(n*t),a=ul(e,i);if(a<i)for(this.log(`Adjusting PTS for rollover in timeline near ${(i-a)/t} ${r}`);a<i;)a+=sl;return a-i}generateIS(e,t,n,r){let i=e.samples,a=t.samples,o=this.typeSupported,s={},c=this._initPTS,l=!c||r,u=`audio/mp4`,d,f,p,m=-1;if(l&&(d=f=1/0),e.config&&i.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`}if(s.audio={id:`audio`,container:u,codec:e.codec,initSegment:e.segmentCodec===`mp3`&&o.mpeg?new Uint8Array:Xc.initSegment([e]),metadata:{channelCount:e.channelCount}},l){m=e.id,p=e.inputTimeScale;let t=this.computeInitPts(i[0].pts,p,n,`audio`);(!c||p!==c.timescale||n===0&&t<c.baseTime)&&(d=f=t)}}if(t.sps&&t.pps&&a.length){if(t.timescale=t.inputTimeScale,s.video={id:`main`,container:`video/mp4`,codec:t.codec,initSegment:Xc.initSegment([t]),metadata:{width:t.width,height:t.height}},l){m=t.id,p=t.inputTimeScale;let e=this.getVideoStartPts(a),r=ul(a[0].dts,e),i=this.computeInitPts(r,p,n,`video`),o=this.computeInitPts(e,p,n,`video`);if(!c||p!==c.timescale||P(d)||n===0&&o<c.baseTime){f=Math.min(f,i);let e=!c&&this.isVideoContiguous?o:i;d=Math.min(d,e)}}this.videoTrackConfig={width:t.width,height:t.height,pixelRatio:t.pixelRatio}}if(Object.keys(s).length)return this.ISGenerated=!0,l&&P(d)?(c&&this.warn(`Timestamps at playlist time: ${r?``:`~`}${n} ${d/p} != initPTS: ${c.baseTime/c.timescale} (${c.baseTime}/${c.timescale}) trackId: ${c.trackId}`),this.log(`Found initPTS at playlist time: ${n} offset: ${d/p} (${d}/${p}) trackId: ${m}`),this._initPTS={baseTime:d,timescale:p,trackId:m},this._initDTS={baseTime:f,timescale:p,trackId:m}):d=p=void 0,{tracks:s,initPTS:d,timescale:p,trackId:m}}remuxVideo(e,t,n,r,i){let a=e.inputTimeScale,o=e.samples,s=[],c=o.length,l=this._initPTS,u=l.baseTime*a/l.timescale,d=this.nextVideoTs,f=8,p=this.videoSampleDuration,m,h,g=1/0,_=-1/0,v=!1;if(!n||d===null){let e=u+t*a,r=o[0].pts-ul(o[0].dts,o[0].pts);Wr()&&d!==null&&Math.abs(e-r-(d+u))<15e3?n=!0:d=e-r-u}let y=d+u;for(let e=0;e<c;e++){let t=o[e];t.pts=ul(t.pts,y),t.dts=ul(t.dts,y),t.dts<o[e>0?e-1:e].dts&&(v=!0)}v&&o.sort(function(e,t){let n=e.dts-t.dts,r=e.pts-t.pts;return n||r}),m=o[0].dts,h=o[o.length-1].dts;let b=h-m,x=b?Math.round(b/(c-1)):p||e.inputTimeScale/30;if(n){let n=m-y,r=n>x,i=n<-1;if((r||i)&&(r?this.warn(`${(e.segmentCodec||``).toUpperCase()}: ${el(n,!0)} ms (${n}dts) hole between fragments detected at ${t.toFixed(3)}`):this.warn(`${(e.segmentCodec||``).toUpperCase()}: ${el(-n,!0)} ms (${n}dts) overlapping between fragments detected at ${t.toFixed(3)}`),!i||y>=o[0].pts||Wr())){m=y;let e=o[0].pts-n;if(r)o[0].dts=m,o[0].pts=e;else{let t=!0;for(let r=0;r<o.length&&!(o[r].dts>e&&t);r++){let e=o[r].pts;if(o[r].dts-=n,o[r].pts-=n,r<o.length-1){let n=o[r+1].pts;t=n<=o[r].pts==n<=e}}}this.log(`Video: Initial PTS/DTS adjusted: ${el(e,!0)}/${el(m,!0)}, delta: ${el(n,!0)} ms`)}}m=Math.max(0,m);let S=0,C=0,w=m;for(let e=0;e<c;e++){let t=o[e],n=t.units,r=n.length,i=0;for(let e=0;e<r;e++)i+=n[e].data.length;C+=i,S+=r,t.length=i,t.dts<w?(t.dts=w,w+=x/4|0||1):w=t.dts,g=Math.min(t.pts,g),_=Math.max(t.pts,_)}h=o[c-1].dts;let T=C+4*S+8,E;try{E=new Uint8Array(T)}catch(e){this.observer.emit(L.ERROR,L.ERROR,{type:F.MUX_ERROR,details:I.REMUX_ALLOC_ERROR,fatal:!1,chunkMeta:i,error:e,bytes:T,reason:`fail allocating video mdat ${T}`});return}Qn(E,0,T),Qn(E,4,W.mdat);let D=!1,O=1/0,k=1/0,A=-1/0,j=-1/0;for(let e=0;e<c;e++){let t=o[e],l=t.units,d=0;for(let e=0,t=l.length;e<t;e++){let t=l[e],n=t.data,r=t.data.byteLength;Qn(E,f,r),f+=4,E.set(n,f),f+=r,d+=4+r}let m;if(e<c-1)p=o[e+1].dts-t.dts,m=o[e+1].pts-t.pts;else{let n=this.config,i=e>0?t.dts-o[e-1].dts:x;if(m=e>0?t.pts-o[e-1].pts:x,n.stretchShortVideoTrack&&this.nextAudioTs!==null){let e=Math.floor(n.maxBufferHole*a),o=(r?g+r*a:this.nextAudioTs+u)-t.pts;o>e?(p=o-i,p<0?p=i:D=!0,this.log(`It is approximately ${o/90} ms to the next segment; using duration ${p/90} ms for the last video frame.`)):p=i}else p=i}let h=Math.round(t.pts-t.dts);if(O=Math.min(O,p),A=Math.max(A,p),k=Math.min(k,m),j=Math.max(j,m),!n&&e===0&&h>p){let e=Math.round(h/x)*x;e-h===1&&(this.log(`pad first CTS ${h} -> ${e} of sn: ${i.sn}`),h=e)}s.push(cl(t.key,p,d,h))}if(s.length){let e=Wr();if(e){if(e<70){let e=s[0].flags;e.dependsOn=2,e.isNonSync=0}}else if(Ur()&&j-k<A-O&&x/A<.025&&s[0].cts===0){this.warn(`Found irregular gaps in sample duration. Using PTS instead of DTS to determine MP4 sample duration.`);let e=m;for(let t=0,n=s.length;t<n;t++){let r=e+s[t].duration,i=e+s[t].cts;if(t<n-1){let e=r+s[t+1].cts;s[t].duration=e-i}else s[t].duration=t?s[t-1].duration:x;s[t].cts=0,e=r}}}p=D||!p?x:p;let M=h+p;this.nextVideoTs=d=M-u,this.videoSampleDuration=p,this.isVideoContiguous=!0,i.iframe&&(s.length===1?(s[0].duration=p=i.duration*a,this.nextVideoTs=d=m+p-u):this.warn(`Not adjusting IFrame duration (sample count ${s.length})`));let N={data1:Xc.moof(i.sn,m,V(e,{samples:s})),data2:E,startPTS:(g-u)/a,endPTS:(_+p-u)/a,startDTS:(m-u)/a,endDTS:d/a,type:`video`,hasAudio:!1,hasVideo:!0,nb:s.length,dropped:e.dropped};return e.samples=[],e.dropped=0,N}getSamplesPerFrame(e){switch(e.segmentCodec){case`mp3`:return al;case`ac3`:return ol;default:return il}}remuxAudio(e,t,n,r,i,a){let o=e.inputTimeScale,s=o/(e.samplerate?e.samplerate:o),c=this.getSamplesPerFrame(e),l=c*s,u=this._initPTS,d=e.segmentCodec===`mp3`&&this.typeSupported.mpeg,f=[],p=i!==void 0,m=e.samples,h=d?0:8,g=this.nextAudioTs||-1,_=u.baseTime*o/u.timescale,v=_+t*o;if(this.isAudioContiguous=n||=m.length&&g>0&&(r&&Math.abs(v-(g+_))<9e3||Math.abs(ul(m[0].pts,v)-(g+_))<20*l),m.forEach(function(e){e.pts=ul(e.pts,v)}),!n||g<0){let e=m.length;if(m=m.filter(e=>e.pts>=0),e!==m.length&&this.warn(`Removed ${m.length-e} of ${e} samples (initPTS ${_} / ${o})`),!m.length)return;g=i===0?0:r&&!p?Math.max(0,v-_):m[0].pts-_}if(e.segmentCodec===`aac`){let t=this.config.maxAudioFramesDrift;for(let n=0,r=g+_;n<m.length;n++){let i=m[n],a=i.pts,s=a-r,c=Math.abs(1e3*s/o);if(s<=-t*l&&p)n===0&&(this.warn(`Audio frame @ ${(a/o).toFixed(3)}s overlaps marker by ${Math.round(1e3*s/o)} ms.`),this.nextAudioTs=g=a-_,r=a);else if(s>=t*l&&c<rl&&p){let t=Math.round(s/l);for(r=a-t*l;r<_&&t&&l;)t--,r+=l;n===0&&(this.nextAudioTs=g=r-_),this.warn(`Injecting ${t} audio frames @ ${((r-_)/o).toFixed(3)}s due to ${Math.round(1e3*s/o)} ms gap.`);for(let a=0;a<t;a++){let t=zc.getSilentFrame(e.parsedCodec||e.manifestCodec||e.codec,e.channelCount);t||=(this.log(`Unable to get silent frame for given audio codec; duplicating last frame instead.`),i.unit.subarray()),m.splice(n,0,{unit:t,pts:r}),r+=l,n++}}i.pts=r,r+=l}}let y=null,b=null,x,S=0,C=m.length;for(;C--;)S+=m[C].unit.byteLength;for(let t=0,r=m.length;t<r;t++){let r=m[t],i=r.unit,o=r.pts;if(b!==null){let e=f[t-1];e.duration=Math.round((o-b)/s)}else if(n&&e.segmentCodec===`aac`&&(o=g+_),y=o,S>0){S+=h;try{x=new Uint8Array(S)}catch(e){this.observer.emit(L.ERROR,L.ERROR,{type:F.MUX_ERROR,details:I.REMUX_ALLOC_ERROR,fatal:!1,chunkMeta:a,error:e,bytes:S,reason:`fail allocating audio mdat ${S}`});return}d||(Qn(x,0,S),Qn(x,4,W.mdat))}else return;x&&x.set(i,h);let l=i.byteLength;h+=l,f.push(cl(!0,c,l,0)),b=o}let w=f.length;if(!w)return;let T=f[f.length-1];g=b-_,this.nextAudioTs=g+s*T.duration;let E=d?new Uint8Array:Xc.moof(e.sequenceNumber++,y/s,V({},e,{samples:f}));e.samples=[];let D=(y-_)/o,O=this.nextAudioTs/o,k={data1:E,data2:x,startPTS:D,endPTS:O,startDTS:D,endDTS:O,type:`audio`,hasAudio:!0,hasVideo:!1,nb:w};return this.isAudioContiguous=!0,k}};function ul(e,t){let n;if(t===null)return e;for(n=t<e?-8589934592:sl;Math.abs(e-t)>4294967296;)e+=n;return e}function dl(e){for(let t=0;t<e.length;t++)if(e[t].key)return t;return-1}function fl(e,t,n,r){let i=e.samples.length;if(!i)return;let a=e.inputTimeScale;for(let o=0;o<i;o++){let i=e.samples[o];i.pts=ul(i.pts-n.baseTime*a/n.timescale,t*a)/a,i.dts=ul(i.dts-r.baseTime*a/r.timescale,t*a)/a}let o=e.samples;return e.samples=[],{samples:o}}function pl(e,t,n){let r=e.samples.length;if(!r)return;let i=e.inputTimeScale;for(let a=0;a<r;a++){let r=e.samples[a];r.pts=ul(r.pts-n.baseTime*i/n.timescale,t*i)/i}e.samples.sort((e,t)=>e.pts-t.pts);let a=e.samples;return e.samples=[],{samples:a}}var ml=class extends Xt{constructor(e,t,n,r){super(`passthrough-remuxer`,r),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,n,r){this.audioCodec=t,this.videoCodec=n,this.decryptdata=r,this.pendingInitSegment=e,this.videoOnlyRemux=!1,this.initTracks=void 0,this.initData=void 0,this.emitInitSegment=!0}generateInitSegment(e,t,n){this.videoOnlyRemux=!1;let{audioCodec:r,videoCodec:i}=this;if(!(e!=null&&e.byteLength)){this.initTracks=void 0,this.initData=void 0;return}let{audio:a,video:o}=this.initData=n||sr(e);if(t)mr(e,t);else{let e=a||o;e!=null&&e.encrypted&&this.warn(`Init segment with encrypted track with has no key ("${e.codec}")!`)}a&&(r=yl(a,B.AUDIO,this)),o&&(i=yl(o,B.VIDEO,this));let s={};a&&o?s.audiovideo={container:`video/mp4`,codec:r+`,`+i,supplemental:o.supplemental,encrypted:o.encrypted,initSegment:e,id:`main`}:a?s.audio={container:`audio/mp4`,codec:r,encrypted:a.encrypted,initSegment:e,id:`audio`}:o?s.video={container:`video/mp4`,codec:i,supplemental:o.supplemental,encrypted:o.encrypted,initSegment:e,id:`main`}:this.warn(`initSegment does not contain moov or trak boxes.`),this.initTracks=s}remux(e,t,n,r,i,a,o,s,c,l,u){var d,f;let{initPTS:p,lastEndTime:m}=this,h={audio:void 0,video:void 0,text:void 0,id3:n,initSegment:void 0};P(m)||(m=this.lastEndTime=i||0);let g=t.samples;if(!g.length)return h;let _=this.pendingInitSegment;_&&(this.pendingInitSegment=void 0,this.generateInitSegment(_,this.decryptdata,l));let v={initPTS:void 0,timescale:void 0,trackId:void 0},y=this.initData;if((d=y)!=null&&d.length||(this.generateInitSegment(g),y=this.initData),!((f=y)!=null&&f.length))return this.warn(`Failed to generate initSegment.`),h;if(c.iframe&&y.audio&&y.video){var b;let e=(b=this.initTracks)==null||(b=b.audiovideo)==null?void 0:b.initSegment,t=e?nr(e):null;if(t){var x;this.log(`Converted muxed init segment to video-only for I-Frame playback`),this.generateInitSegment(t,this.decryptdata),(x=this.initData)!=null&&x.length&&(y=this.initData,this.emitInitSegment=!0,this.videoOnlyRemux=!0)}}this.emitInitSegment&&=(v.tracks=this.initTracks,h.initSegment=v,!1);let S=c.iframe,C=u&&(!S||u.includeSampleDetails)?u.tracks:xr(g,y,c,this,S),w=y.audio?C[y.audio.id]:null,T=y.video?C[y.video.id]:null,E=!!y.audio,D=!!y.video,O=``;E&&(O+=`audio`),D&&(O+=`video`);let k=hl(T,1/0),A=hl(w,1/0),j=hl(T,0,!0),M=hl(w,0,!0),N=i,ee=0;T&&w&&y.audio&&(A>j||k>M)&&this.warn(`audio and video track sample timestamps do not overlap. v: ${k}-${j} a: ${A}-${M}}`,T,w);let te=!!w&&(!T||!p&&A<k||!!p&&p.trackId===y.audio.id),ne=te?w:T;if(!ne)return this.log(`No media samples found in ${s} ${c.level} ${c.part===-1?``:`part: ${c.part} of`} sn: ${c.sn} at playlist time: ${i}`),h;let re=g,ie,ae;if(T&&T.sampleCount>=1&&y.video&&c.iframe){let{trun:e,start:t}=T,n=e.length===1,r=e.length?n?e[0].samples:e[0].samples.concat(...e.slice(1).map(e=>e.samples)):[];if(r.length){let i=e[0],a=i;for(let t=e.length;t--;)if(e[t].samples.length){a=e[t];break}let o=a.lastSampleDurationOffset,{defaultSampleDurationOffset:s}=i,l=Math.abs(c.duration-(j-k))>.05,u=r.length<T.sampleCount;if(!(l||u||this.videoOnlyRemux||!n))ee=j-k;else{let e=u?a.sampleOffset+a.samples.reduce((e,t)=>e+t.size,0):void 0,n=l?c.duration:j-k,i=_l(r,n*y.video.timescale,o,s),d=rr(g,y.video.id,r.length,e,i);d?(re=d,ae=gl(t,r)):this.warn(`IFrame remux skipped (sn ${c.sn}); using native sample duration`),ee=d&&i?n:j-k}}else this.warn(`Could not remux IFrame track fragment (no samples in range, trun count ${e.length})`),ee=j-k}else ee=te?M-A:j-k;if(this.videoOnlyRemux&&re===g)return this.warn(`Dropping muxed I-Frame fragment that could not be remuxed to video-only (sn: ${c.sn})`),h;let oe=ne.timescale,se=ne.start-i*oe,ce=te?y.audio.id:y.video.id;if(N=ne.start/oe,!(p&&c.id>1)&&(a||!p)&&(vl(p,N,i,ee)||oe!==p.timescale)){let e=!1,t=te?`audio`:`video`;if(p){let n=i===0?1+N/1:N/i;e=N>=0&&Math.abs(1-n)<.001,this.log(`${t} timestamps in track ${ce} at playlist time: ${a?``:`~`}${i} maps to ${N} with initPTS: ${p.baseTime/p.timescale} (${se/oe-p.baseTime/p.timescale}s diff) (${O}) drift estimate: ${n} ${e?`(ignoring drift)`:`remapping timestamps (initPTS)`}`)}e||(this.log(`Found initPTS in ${t} track ${ce} at playlist time: ${i} offset: ${N-i} (${se}/${oe})`),p=null,v.initPTS=se,v.timescale=oe,v.trackId=ce)}p?(v.initPTS=p.baseTime,v.timescale=p.timescale,v.trackId=p.trackId):((!v.timescale||v.trackId===void 0||v.initPTS===void 0)&&(this.warn(`Could not set initPTS`),v.initPTS=N,v.timescale=1,v.trackId=-1),this.initPTS=p={baseTime:v.initPTS,timescale:v.timescale,trackId:v.trackId});let le=N-p.baseTime/p.timescale,ue=le+ee,de=D&&ne?.ptsMin!==void 0?ne.ptsMin/ne.timescale-p.baseTime/p.timescale:le,fe=ae!==void 0&&T?ae/T.timescale-p.baseTime/p.timescale:D&&ne!=null&&ne.ptsMax?ne.ptsMax/ne.timescale-p.baseTime/p.timescale:ue;ee>0?this.lastEndTime=ue:(this.warn(`Duration parsed from mp4 should be greater than zero`),this.resetNextTimestamp());let pe=(y.audio?y.audio.encrypted:!1)||(y.video?y.video.encrypted:!1),me={data1:re,data2:ie,startPTS:de,startDTS:le,endPTS:fe,endDTS:ue,type:O,hasAudio:E,hasVideo:D,nb:1,dropped:0,encrypted:pe};h.audio=E&&!D?me:void 0,h.video=D?me:void 0;let he=this.isVideoContiguous,ge=T?.sampleCount;if(ge){let e=T.keyFrameIndex,t=e!==-1;me.nb=ge,me.dropped=e===0||he?0:t?e:ge,me.independent=t,me.firstKeyFrame=e,t&&T.keyFrameStart&&(me.firstKeyFramePTS=(T.keyFrameStart-p.baseTime)/p.timescale),he||(h.independent=t),this.isVideoContiguous||=t,me.dropped&&this.warn(`fmp4 does not start with IDR: firstIDR ${e}/${ge} dropped: ${me.dropped} start: ${me.firstKeyFramePTS||`NA`}`)}return h.initSegment=v,h.id3=fl(n,i,p,p),r.samples.length&&(h.text=pl(r,i,p)),h}};function hl(e,t,n=!1){return e?.start===void 0?t:(e.start+(n?e.duration:0))/e.timescale}function gl(e,t){let n=e,r=e;for(let e=0;e<t.length;e++){let{cts:i,duration:a}=t[e];r=Math.max(r,n+(i||0)+a),n+=a}return r}function _l(e,t,n,r){if(n!==void 0){let r=e[e.length-1],i=t;for(let t=0;t<e.length-1;t++)i-=e[t].duration;return i<=0&&(i=r.duration),r.duration=i,{durationOffset:n,value:i}}if(r===void 0)return;let i=Math.round(t/e.length);for(let t=0;t<e.length;t++)e[t].duration=i;return{durationOffset:r,value:i}}function vl(e,t,n,r){if(e===null)return!0;let i=Math.max(r,1),a=t-e.baseTime/e.timescale;return Math.abs(a-n)>=i}function yl(e,t,n){let r=e.codec;return r&&r.length>4?r:t===B.AUDIO?r===`ec-3`||r===`ac-3`||r===`alac`?r:r===`fLaC`||r===`Opus`?ai(r,!1):(n.warn(`Unhandled audio codec "${r}" in mp4 MAP`),r||`mp4a`):r===`mjpg`?r:(n.warn(`Unhandled video codec "${r}" in mp4 MAP`),r||`avc1`)}var bl;try{bl=self.performance.now.bind(self.performance)}catch{bl=Date.now}var xl=[{demux:bc,remux:ml},{demux:jc,remux:ll},{demux:mc,remux:ll},{demux:vc,remux:ll}];xl.splice(2,0,{demux:gc,remux:ll});var Sl=class{constructor(e,t,n,r,i,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=n,this.id=i,this.logger=a}configure(e){this.transmuxConfig=e,this.decrypter&&this.decrypter.reset()}push(e,t,n,r){if(!this.observer)return wl(n);let i=n.transmuxing;i.executeStart=bl();let a=new Uint8Array(e),{currentTransmuxState:o,transmuxConfig:s}=this;r&&(this.currentTransmuxState=r);let{contiguous:c,discontinuity:l,trackSwitch:u,accurateTimeOffset:d,timeOffset:f,initSegmentChange:p}=r||o,{audioCodec:m,videoCodec:h,defaultInitPts:g,duration:_,initSegmentData:v}=s,y=Cl(a,t);if(y&&ho(y.method)){let e=this.getDecrypter(),t=go(y.method);return this.asyncResult=!0,this.decryptionPromise=e.decrypt(a,y.key.buffer,y.iv.buffer,t,n.decryptRange).then(e=>{let t=this.push(e,null,n);return this.decryptionPromise=null,t}),this.decryptionPromise}let b=this.needsProbing(l,u);if(b){let e=n.iframe&&v&&jc.probe(v,this.logger)?v:a,t=this.configureTransmuxer(e);if(t)return this.logger.warn(`[transmuxer] ${t.message}`),this.observer.emit(L.ERROR,L.ERROR,{type:F.MEDIA_ERROR,details:I.FRAG_PARSING_ERROR,fatal:!1,error:t,reason:t.message}),i.executeEnd=bl(),wl(n)}(l||u||p||b)&&this.resetInitSegment(v,m,h,_,t,n),(l||p||b)&&this.resetInitialTimestamp(g),c||this.resetContiguity();let x=this.transmux(a,y,f,d,n);this.asyncResult=Tl(x);let S=this.currentTransmuxState;return S.contiguous=!0,S.discontinuity=!1,S.trackSwitch=!1,i.executeEnd=bl(),x}flush(e){let t=e.transmuxing;t.executeStart=bl();let{decrypter:n,currentTransmuxState:r,decryptionPromise:i}=this;if(i)return this.asyncResult=!0,i.then(()=>this.flush(e));let a=[],{timeOffset:o}=r;if(n){let t=n.flush();t&&a.push(this.push(t.buffer,null,e))}let{demuxer:s,remuxer:c}=this;if(!s||!c){t.executeEnd=bl();let n=[wl(e)];return this.asyncResult?Promise.resolve(n):n}let l=s.flush(o,e);return Tl(l)?(this.asyncResult=!0,l.then(t=>(this.flushRemux(a,t,e),a))):(this.flushRemux(a,l,e),this.asyncResult?Promise.resolve(a):a)}flushRemux(e,t,n){if(!this.remuxer)return;let{audioTrack:r,videoTrack:i,id3Track:a,textTrack:o}=t,{accurateTimeOffset:s,timeOffset:c}=this.currentTransmuxState;this.logger.log(`[transmuxer.ts]: Flushed ${this.id} sn: ${n.sn}${n.part>-1?` part: `+n.part:``} of ${this.id} playlist ${n.level}`);let l=this.remuxer.remux(r,i,a,o,c,s,!0,this.id,n,t.initData,t.sampleData);e.push({remuxResult:l,chunkMeta:n}),n.transmuxing.executeEnd=bl()}resetInitialTimestamp(e){let{demuxer:t,remuxer:n}=this;t&&n&&(t.resetTimeStamp(e),n.resetTimeStamp(e))}resetContiguity(){let{demuxer:e,remuxer:t}=this;e&&t&&(e.resetContiguity(),t.resetNextTimestamp())}resetInitSegment(e,t,n,r,i,a){let{demuxer:o,remuxer:s}=this;o&&s&&(o.resetInitSegment(e,t,n,r,i,a),s.resetInitSegment(e,t,n,i))}destroy(){this.demuxer&&=(this.demuxer.destroy(),void 0),this.remuxer&&=(this.remuxer.destroy(),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,n,r,i){let a;return a=t?.method===`SAMPLE-AES`?this.transmuxSampleAes(e,t,n,r,i):this.transmuxUnencrypted(e,n,r,i),a}transmuxUnencrypted(e,t,n,r){let{demuxer:i,remuxer:a}=this;if(!i||!a)return wl(r);let o=i.demux(e,t,r,!1,!this.config.progressive),{audioTrack:s,videoTrack:c,id3Track:l,textTrack:u}=o;return{remuxResult:a.remux(s,c,l,u,t,n,!1,this.id,r,o.initData,o.sampleData),chunkMeta:r}}transmuxSampleAes(e,t,n,r,i){return this.demuxer?this.demuxer.demuxSampleAes(e,t,n,i).then(e=>({remuxResult:this.remuxer.remux(e.audioTrack,e.videoTrack,e.id3Track,e.textTrack,n,r,!1,this.id,i,e.initData,e.sampleData),chunkMeta:i})):Promise.reject(Error(`no demuxer`))}configureTransmuxer(e){let{config:t,observer:n,typeSupported:r}=this;if(!n)return;let i;try{for(let t=0,n=xl.length;t<n;t++){var a;if((a=xl[t].demux)!=null&&a.probe(e,this.logger)){i=xl[t];break}}}catch(e){return e}if(!i)return Error(`Failed to find demuxer by probing fragment data`);let o=this.demuxer,s=this.remuxer,c=i.demux,l=i.remux;(!o||!(o instanceof c))&&(this.logger.log(`Using ${c.name}`),this.demuxer=new c(n,t,r,this.logger),this.probe=c.probe),(!s||!(s instanceof l))&&(this.logger.log(`Using ${l.name}`),this.remuxer=new l(n,t,r,this.logger))}needsProbing(e,t){return!this.demuxer||!this.remuxer||e||t}getDecrypter(){let e=this.decrypter;return e||=this.decrypter=new Ua(this.config),e}};function Cl(e,t){let n=null;return e.byteLength>0&&t?.key!=null&&t.iv!==null&&t.method!=null&&(n=t),n}var wl=e=>({remuxResult:{},chunkMeta:e});function Tl(e){return`then`in e&&e.then instanceof Function}var El=class{constructor(e,t,n,r,i){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=n,this.duration=r,this.defaultInitPts=i||null}},Dl=class{constructor(e,t,n,r,i,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=n,this.trackSwitch=r,this.timeOffset=i,this.initSegmentChange=a}},Ol=0,kl=class{constructor(e,t,n,r){this.error=null,this.hls=void 0,this.id=void 0,this.instanceNo=Ol++,this.observer=void 0,this.frag=null,this.part=null,this.useWorker=void 0,this.workerContext=null,this.transmuxer=null,this.onTransmuxComplete=void 0,this.onFlush=void 0,this.onWorkerMessage=e=>{let t=e.data,n=this.hls;if(n&&t!=null&&t.event&&t.instanceNo===this.instanceNo)switch(t.event){case`init`:{let e=this.workerContext?.objectURL;e&&self.URL.revokeObjectURL(e);break}case`transmuxComplete`:this.handleTransmuxComplete(t.data);break;case`flush`:this.onFlush(t.data);break;case`workerLog`:n.logger[t.data.logType]&&n.logger[t.data.logType](t.data.message);break;default:t.data=t.data||{},t.data.frag=this.frag,t.data.part=this.part,t.data.id=this.id,n.trigger(t.event,t.data)}},this.onWorkerError=e=>{if(!this.hls)return;let t=Error(`${e.message} (${e.filename}:${e.lineno})`);this.hls.config.enableWorker=!1,this.hls.logger.warn(`Error in "${this.id}" Web Worker, fallback to inline`),this.hls.trigger(L.ERROR,{type:F.OTHER_ERROR,details:I.INTERNAL_EXCEPTION,fatal:!1,event:`demuxerWorker`,error:t})};let i=e.config;this.hls=e,this.id=t,this.useWorker=!!i.enableWorker,this.onTransmuxComplete=n,this.onFlush=r;let a=(e,t)=>{t||={},t.frag=this.frag||void 0,e===L.ERROR&&(t=t,t.parent=this.id,t.part=this.part,this.error=t.error),this.hls.trigger(e,t)};this.observer=new Ps,this.observer.on(L.FRAG_DECRYPTED,a),this.observer.on(L.ERROR,a);let o=di(i.preferManagedMediaSource);if(this.useWorker&&typeof Worker<`u`){let n=this.hls.logger;if(i.workerPath||Ls()){try{i.workerPath?(n.log(`loading Web Worker ${i.workerPath} for "${t}"`),this.workerContext=zs(i.workerPath)):(n.log(`injecting Web Worker for "${t}"`),this.workerContext=Rs());let{worker:e}=this.workerContext;e.addEventListener(`message`,this.onWorkerMessage),e.addEventListener(`error`,this.onWorkerError),e.postMessage({instanceNo:this.instanceNo,cmd:`init`,typeSupported:o,id:t,config:q(i)})}catch(r){n.warn(`Error setting up "${t}" Web Worker, fallback to inline`,r),this.terminateWorker(),this.error=null,this.transmuxer=new Sl(this.observer,o,i,``,t,e.logger)}return}}this.transmuxer=new Sl(this.observer,o,i,``,t,e.logger)}reset(){if(this.frag=null,this.part=null,this.workerContext){let e=this.instanceNo;this.instanceNo=Ol++;let t=this.hls.config,n=di(t.preferManagedMediaSource);this.workerContext.worker.postMessage({instanceNo:this.instanceNo,cmd:`reset`,resetNo:e,typeSupported:n,id:this.id,config:q(t)})}}terminateWorker(){if(this.workerContext){let{worker:e}=this.workerContext;this.workerContext=null,e.removeEventListener(`message`,this.onWorkerMessage),e.removeEventListener(`error`,this.onWorkerError),Bs(this.hls.config.workerPath)}}destroy(){if(this.workerContext)this.terminateWorker(),this.onWorkerMessage=this.onWorkerError=null;else{let e=this.transmuxer;e&&(e.destroy(),this.transmuxer=null)}let e=this.observer;e&&e.removeAllListeners(),this.frag=null,this.part=null,this.observer=null,this.hls=null}push(e,t,n,r,i,a,o,s,c,l){c.transmuxing.start=self.performance.now();let{instanceNo:u,transmuxer:d}=this,f=a?a.start:i.start,p=i.decryptdata,m=this.frag,h=!m||i.cc!==m.cc,g=!m||c.level!==m.level,_=m?c.sn-m.sn:-1,v=this.part?c.part-this.part.index:-1,y=_===0&&c.id>1&&c.id===m?.stats.chunkCount,b=!g&&(_===1||_===0&&(v===1||y&&v<=0)),x=self.performance.now();(g||_||i.stats.parsing.start===0)&&(i.stats.parsing.start=x),a&&(v||!b)&&(a.stats.parsing.start=x);let S=!(m&&i.initSegment?.url===m.initSegment?.url),C=new Dl(h,b,s,g,f,S);if(!b||h||S){this.hls.logger.log(`[transmuxer-interface]: Starting new transmux session for ${i.type} sn: ${c.sn}${c.part>-1?` part: `+c.part:``} ${this.id} playlist: ${c.level} id: ${c.id}
|
|
23
|
+
${n.m3u8}`)}function ds(e,t,n=!0,r){let i=t.startSN+t.skippedSegments-e.startSN,a=e.fragments,o=i>=0,s=0;if(o&&i<a.length)s=a[i].start,r?.log(`Aligning playlists based on SN ${t.startSN} (diff: ${s})`);else if(o&&t.startSN===e.endSN+1)s=e.fragmentEnd,r?.log(`Aligning playlists based on first/last SN ${t.startSN} (diff: ${s})`);else if(o&&n)s=e.fragmentStart+i*t.levelTargetDuration;else if(!t.skippedSegments&&t.fragmentStart===0)s=e.fragmentStart,r?.log(`Aligning playlists based on first SN ${t.startSN} (diff: ${s})`);else return s;return fs(t,s),s}function fs(e,t){if(t){let n=e.fragments;for(let r=e.skippedSegments;r<n.length;r++)n[r].addStart(t);e.fragmentHint&&e.fragmentHint.addStart(t)}}function ps(e,t=1/0){let n=1e3*e.targetduration;if(e.updated){let r=e.fragments;if(r.length&&n*4>t){let e=r[r.length-1].duration*1e3;e>0&&e<n&&(n=e)}}else n/=2;return Math.round(n)}function ms(e,t,n){if(!e)return null;let r=e.fragments[t-e.startSN];return r||(r=e.fragmentHint,r?.sn===t)?r:n&&t<e.startSN&&n.sn===t?n:null}function hs(e,t,n){return e?gs(e.partList,t,n):null}function gs(e,t,n){if(e)for(let r=e.length;r--;){let i=e[r];if(i.index===n&&i.fragment.sn===t)return i}return null}function _s(e){e.forEach((e,t)=>{var n;(n=e.details)==null||n.fragments.forEach(e=>{e.level=t,e.initSegment&&(e.initSegment.level=t)})})}function vs(e,t){return e!==t&&t?ys(e)!==ys(t):!1}function ys(e){return e.replace(/\?[^?]*$/,``)}function bs(e,t){for(let n=0,r=e.length;n<r;n++)if(e[n]?.cc===t)return e[n];return null}function xs(e,t){return!!(e&&t.startCC<e.endCC&&t.endCC>e.startCC)}function Ss(e,t){let n=e.start+t;e.setStart(n)}function Cs(e,t){let n=t.fragments;for(let t=0,r=n.length;t<r;t++)Ss(n[t],e);t.fragmentHint&&Ss(t.fragmentHint,e),t.alignedSliding=!0}function ws(e,t,n){e&&(Ts(t,e,n),t.alignedSliding||Es(t,e,n),!t.alignedSliding&&!t.skippedSegments&&ds(e,t,!1,n))}function Ts(e,t,n){if(!xs(t,e))return;let r=Math.min(t.endCC,e.endCC),i=bs(t.fragments,r),a=bs(e.fragments,r);if(!i||!a)return;let o=i.start-a.start;n.log(`Aligning playlists using dicontinuity sequence ${r} (diff: ${o})`),Cs(o,e)}function Es(e,t,n){if(!e.hasProgramDateTime||!t.hasProgramDateTime)return;let r=e.fragments,i=t.fragments;if(!r.length||!i.length)return;let a,o,s=Math.min(t.endCC,e.endCC);t.startCC<s&&e.startCC<s&&(a=bs(i,s),o=bs(r,s)),(!a||!o)&&(a=i[Math.floor(i.length/2)]||i.filter(e=>!!e)[0],o=bs(r,a.cc)||r[Math.floor(r.length/2)]);let c=a.programDateTime,l=o.programDateTime;if(!c||!l)return;let u=(l-c)/1e3;if(Math.abs(u)>Math.max(60,e.totalduration)){n.log(`Cannot align playlists using PDT without overlap (${Math.abs(u)} > ${e.totalduration})`);return}let d=u-(o.start-a.start);n.log(`Aligning playlists using PDT (diff: ${d})`),Cs(d,e)}var Q={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`},Ds=class extends Za{constructor(e,t,n,r,i){super(r,e.logger),this.hls=void 0,this.fragPrevious=null,this.fragCurrent=null,this.fragPlaying=null,this.fragmentTracker=void 0,this.transmuxer=null,this._state=Q.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:e,fragCurrent:t,media:n,mediaBuffer:r,state:i}=this,a=n?n.currentTime:0,o=J.bufferInfo(r||n,a,e.maxBufferHole),s=o.len;if(this.log(`Media seeking to ${a}, state: ${i}, ${s?`in`:`out of`} buffer`),this.state===Q.ENDED)this.resetLoadingState();else if(t){let n=e.maxFragLookUpTolerance,r=t.start-n,i=t.start+t.duration+n;if(!s||i<o.start||r>o.end){let e=a<r,n=a>i;(e||n)&&(t.loader&&(n||!this.isFragmentNearlyDownloaded(t))?(this.log(`Cancelling fragment load for seek (sn: ${t.sn}) - ${e?`backward`:`forward`} seek`),t.abortRequests(),this.resetLoadingState()):this.fragPrevious=null)}}if(n){var c;if((c=this.hls)!=null&&c.hasEnoughToStart&&!s&&a!==this.startPosition&&this.fragmentTracker.removeFragmentsInRange(a,1/0,this.playlistType,!0),a>this.lastCurrentTime&&(this.lastCurrentTime=a),!this.loadingParts){let e=Math.max(o.end,a),t=this.shouldLoadParts(this.getLevelDetails(),e);t&&(this.log(`LL-Part loading ON after seeking to ${a} with buffer @${e}`),this.loadingParts=t)}}let l=!J.isBuffered(n,a);(!this.hls.hasEnoughToStart||l)&&(this.log(`Setting ${l?`startPosition`:`nextLoadPosition`} to ${a} for seek without enough to start`),this.nextLoadPosition=a,l?this.startPosition=a:this.lastCurrentTime=a),s<1&&this.state===Q.IDLE&&this.tickImmediate()},this.onMediaEnded=()=>{this.log(`setting startPosition to 0 because media ended`),this.startPosition=this.nextLoadPosition=this.lastCurrentTime=0},this.playlistType=i,this.hls=e,this.fragmentLoader=new Ga(e.config),this.initFragmentLoader=new Ga(e.config),this.keyLoader=n,this.fragmentTracker=t,this.config=e.config,this.decrypter=new Ua(e.config)}registerListeners(){let{hls:e}=this;e.on(L.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(L.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(L.MANIFEST_LOADING,this.onManifestLoading,this),e.on(L.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(L.ERROR,this.onError,this)}unregisterListeners(){let{hls:e}=this;e.off(L.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(L.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(L.MANIFEST_LOADING,this.onManifestLoading,this),e.off(L.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(L.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===Q.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=Q.STOPPED}get startPositionValue(){let{nextLoadPosition:e,startPosition:t}=this;if(t===-1&&e){let t=this.getLevelDetails();return t!=null&&t.live?(this.hls.liveSyncPosition||t.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 n=e.end||0,r=this.config.timelineOffset||0;if(n<=r)return!1;let i=e.buffered;this.config.maxBufferHole&&i&&i.length>1&&(e=J.bufferedInfo(i,e.start,0));let a=e.nextStart;if(a&&a>r&&a<t.edge||this.media.currentTime<e.start)return!1;let o=t.partList;if(o!=null&&o.length){let e=o[o.length-1];return J.isBuffered(this.media,e.start+e.duration/2)}let s=t.fragments[t.fragments.length-1];return this.fragmentTracker.isEndListAppended(s.type)}getLevelDetails(){if(this.levels&&this.levelLastLoaded!==null)return this.levelLastLoaded.details}get timelineOffset(){let e=this.config.timelineOffset;return e?this.getLevelDetails()?.appliedTimelineOffset||e:0}onMediaAttached(e,t){let n=this.media=this.mediaBuffer=t.media;Y(n,`seeking`,this.onMediaSeeking),Y(n,`ended`,this.onMediaEnded);let r=this.config;this.levels&&r.autoStartLoad&&this.state===Q.STOPPED&&this.startLoad(r.startPosition)}onMediaDetaching(e,t){this.fragPlaying=null;let n=!!t.transferMedia,r=this.media;if(r===null)return;if(r.ended&&(this.log(`MSE detaching and video ended, reset startPosition`),this.startPosition=this.lastCurrentTime=0),X(r,`seeking`,this.onMediaSeeking),X(r,`ended`,this.onMediaEnded),this.media=this.mediaBuffer=null,this.loopSn=void 0,n){this.resetLoadingState(),this.resetTransmuxer();return}this.loadingParts=!1;let{fragmentTracker:i}=this,a=i.gapFragments();i.removeAllFragments(),a.forEach(e=>i.addAsGap(e)),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(),null),super.onHandlerDestroying(),this.hls=this.onMediaSeeking=this.onMediaEnded=null}onHandlerDestroyed(){this.state=Q.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,n){this.startFragRequested=!0,this._loadFragForPlayback(e,t,n)}_loadFragForPlayback(e,t,n){this._doFragLoad(e,t,n,e=>{let t=e.frag;if(this.fragContextChanged(t)){this.warn(`${t.type} sn: ${t.sn}${e.part?` part: `+e.part.index:``} of ${this.fragInfo(t,!1,e.part)} was dropped during download.`),this.fragmentTracker.removeFragment(t);return}let n=++t.stats.chunkCount;this.log(`load progress ${t.type} sn: ${t.sn}${e.part?` part: `+e.part.index:``} of ${this.fragInfo(t,!1,e.part)} chunk: ${n}`),this._handleFragmentLoadProgress(e)}).then(e=>{if(!e)return;let t=this.state,n=e.frag;if(this.fragContextChanged(n)){(t===Q.FRAG_LOADING||!this.fragCurrent&&t===Q.PARSING)&&(this.fragmentTracker.removeFragment(n),this.state=Q.IDLE);return}`payload`in e&&(this.log(`Loaded ${n.type} sn: ${n.sn} of ${this.playlistLabel()} ${n.level} (bytes ${n.stats.loaded})`),this.hls.trigger(L.FRAG_LOADED,e)),this._handleFragmentLoadComplete(e)}).catch(t=>{this.state!==Q.STOPPED&&this.state!==Q.ERROR&&(this.log(`Frag error ${e.type} sn:${e.sn} cc:${e.cc}: ${t?.message||t}`),this.resetFragmentLoading(e))})}clearTrackerIfNeeded(e){let{fragmentTracker:t}=this;if(t.getState(e)===Z.APPENDING){let n=e.type,r=this.getFwdBufferInfo(this.mediaBuffer,n),i=Math.max(e.duration,r?r.len:this.config.maxBufferLength),a=this.backtrackFragment;((a?e.sn-a.sn:0)===1||this.reduceMaxBufferLength(i,e.duration))&&t.removeFragment(e)}else this.mediaBuffer?.buffered.length===0?t.removeAllFragments():t.hasParts(e.type)&&(t.detectPartialFragments({frag:e,part:null,stats:e.stats,id:e.type}),t.getState(e)===Z.PARTIAL&&t.removeFragment(e))}checkLiveUpdate(e){if(e.updated&&!e.live){let t=this.fragmentTracker,n=e.fragments[e.fragments.length-1];if(n.endList&&!t.isEndListAppended(this.playlistType)){let e=t.getPartialFragment(n.end);e&&(t.removeFragment(e),t.fragBuffered(n,!0))}t.detectPartialFragments({frag:n,part:null,stats:n.stats,id:n.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,n=null){if(!(e-t))return;let r={startOffset:e,endOffset:t,type:n};this.hls.trigger(L.BUFFER_FLUSHING,r)}_loadInitSegment(e){let{hls:t}=this;return this.initFragmentLoader.abort(),t.trigger(L.FRAG_LOADING,{frag:e,targetBufferTime:0}),this.initFragmentLoader.load(e).then(e=>{let t=e.frag;if(!this.levels||!Dt(t,this.fragCurrent?.initSegment))throw new Xa({type:F.NETWORK_ERROR,details:I.INTERNAL_ABORTED,error:Error(`init load aborted`),fatal:!1,frag:t,networkDetails:null});return e}).then(e=>{let{frag:n,payload:r}=e,i=n.decryptdata;if(r&&r.byteLength>0&&i!=null&&i.key&&i.iv&&ho(i.method)){let a=self.performance.now(),{decryptRange:o}=qa(n,null,this.iframesOnly);return this.decrypter.decrypt(new Uint8Array(r),i.key.buffer,i.iv.buffer,go(i.method),o).catch(e=>{throw t.trigger(L.ERROR,{type:F.MEDIA_ERROR,details:I.FRAG_DECRYPT_ERROR,fatal:!1,error:e,reason:e.message,frag:n}),this.fragmentLoader.abort(),e}).then(r=>{let i=self.performance.now();return t.trigger(L.FRAG_DECRYPTED,{frag:n,part:null,payload:r,stats:{tstart:a,tdecrypt:i}}),e.payload=r,this.completeInitSegmentLoad(e)})}return this.completeInitSegmentLoad(e)})}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&&Tt(e)&&t&&!t.data){var n;return(t.encrypted&&!((n=t.decryptdata)!=null&&n.key)?this.keyLoader.load(t).then(()=>this._loadInitSegment(t)):this._loadInitSegment(t)).catch(t=>{throw this.state===Q.STOPPED||this.state===Q.ERROR?t:(`data`in t&&(this.fragmentLoader.abort(),this.handleFragLoadError(t,e)),this.resetFragmentLoading(e),t)})}}unhandledEncryptionError(e,t){var n,r;let i=e.tracks;if(i&&!t.encrypted&&((n=i.audio)!=null&&n.encrypted||(r=i.video)!=null&&r.encrypted)&&(!this.config.emeEnabled||!this.keyLoader.emeController)){let e=this.media,n=Error(`Encrypted track with no key in ${this.fragInfo(t)} (media ${e?`attached mediaKeys: `+e.mediaKeys:`detached`})`);return this.warn(n.message),!e||e.mediaKeys?!1:(this.hls.trigger(L.ERROR,{type:F.KEY_SYSTEM_ERROR,details:I.KEY_SYSTEM_NO_KEYS,fatal:!1,error:n,frag:t}),this.resetTransmuxer(),!0)}return!1}fragContextChanged(e){let{fragCurrent:t}=this;return!e||!Dt(e,t)}fragBufferedComplete(e,t){let n=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:${n?_a(J.getBuffered(n)):`(detached)`})`),Tt(e)){if(e.type!==z.SUBTITLE){let t=e.elementaryStreams;if(!Object.keys(t).some(e=>!!t[e])){this.state=Q.IDLE;return}}let n=this.levels?.[e.level];n!=null&&n.fragmentError&&(t||this.fragmentTracker.getState(e)!==Z.PARTIAL)&&(this.log(`Resetting level fragment error count of ${n.fragmentError} on frag buffered`),n.fragmentError=0,e.stats.retry=0)}this.state=Q.IDLE}_handleFragmentLoadComplete(e){let{transmuxer:t}=this;if(!t)return;let n=e.frag,{part:r,partsLoaded:i}=e,a=!i||i.length===0||i.some(e=>!e),{decryptRange:o}=qa(n,r),s=new Qa(n.level,n.sn,n.stats.chunkCount+1,0,r?r.index:-1,!a,n.duration,this.iframesOnly,o);this.log(`load complete ${n.type} sn: ${n.sn}${r?` part: `+r.index:``} of ${this.fragInfo(n,!1,r)}`),t.flush(s)}_handleFragmentLoadProgress(e){}loadKeyFor(e,t,n){var r;let i=null;return e.encrypted&&!((r=e.decryptdata)!=null&&r.key)?(this.log(`Loading key for ${e.sn} of [${t.startSN}-${t.endSN}], ${this.playlistLabel()} ${e.level}`),this.state=Q.KEY_LOADING,i=this.keyLoader.load(e,n).then(e=>{if(!this.fragContextChanged(e.frag))return this.hls.trigger(L.KEY_LOADED,e),this.state===Q.KEY_LOADING&&(this.state=Q.IDLE),e}),this.hls.trigger(L.KEY_LOADING,{frag:e})):e.encrypted||(i=this.keyLoader.loadClear(e,t.encryptedFragments,this.startFragRequested),i&&this.log(`[eme] blocking frag sn: ${e.sn} load until media-keys acquired`)),i}_doFragLoad(e,t,n=null,r){this.fragCurrent=e;let i=t.details;if(!this.levels||!i)throw Error(`frag load aborted, missing level${i?``:` detail`}s`);let a=this.fragPrevious;if(!Et(e,a)){let n=this.shouldLoadParts(t.details,e.end);n!==this.loadingParts&&(this.log(`LL-Part loading ${n?`ON`:`OFF`} loading sn ${a?.sn}->${e.sn}`),this.loadingParts=n)}if(n=Math.max(e.start,n||0),this.loadingParts){let o=i.partList;if(o&&r){n>i.fragmentEnd&&i.fragmentHint&&(e=i.fragmentHint);let s=this.getNextPart(o,e,n);if(s>-1){let c=o[s];if(e=this.fragCurrent=c.fragment,!Et(e,a)&&!this.shouldLoadParts(t.details,e.end))return this.log(`LL-Part loading OFF @${this.playhead} next part: ${this.fragInfo(e,!1,c)}`),this.loadingParts=!1,Promise.resolve(null);if(!this.filterReplacedPrimary(c,t.details))return Promise.resolve(null);let l=this.loadKeyFor(e,i);if(this.fragContextChanged(e))return Promise.resolve(null);this.log(`Loading ${e.type} sn: ${e.sn} part: ${c.index} (${s}/${o.length-1}) of ${this.fragInfo(e,!1,c)} cc: ${e.cc} [${i.startSN}-${i.endSN}], target: ${n}${c.byteRange.length?` range:${c.byteRange.join(`-`)}`:``}`),this.nextLoadPosition=c.start+c.duration,this.state=Q.FRAG_LOADING;let u,d=this.loadInitSegmentIfNeeded(e);if(l||d){let n=!!l;u=Promise.all([l,d]).then(([i])=>n&&(!i||this.fragContextChanged(i.frag))?null:this.doFragPartsLoad(e,c,t,r)).catch(t=>this.handleFragLoadError(t,e))}else u=this.doFragPartsLoad(e,c,t,r).catch(t=>this.handleFragLoadError(t,e));return this.hls.trigger(L.FRAG_LOADING,{frag:e,part:c,targetBufferTime:n}),this.fragCurrent===null?Promise.reject(Error(`frag load aborted, context changed in FRAG_LOADING parts`)):u}if(!e.url||this.loadedEndOfParts(o,n))return Promise.resolve(null)}}if(this.loadingParts)this.log(`LL-Part loading OFF after next part miss @${n} Check buffer at sn: ${e.sn} loaded parts: ${i.partList?.filter(e=>e.loaded).map(e=>`[${e.start}-${e.end}]`)}`),this.loadingParts=!1;else if(!e.url)return Promise.resolve(null);if(!this.filterReplacedPrimary(e,t.details))return Promise.resolve(null);let o=this.loadInitSegmentIfNeeded(e),s=this.loadKeyFor(e,i,o);if(this.fragContextChanged(e))return this.log(`Context changed in KEY_LOADING sn: ${e.sn} ${e.relurl} > ${this.fragCurrent?.relurl}`),o?.catch(()=>null),s?.catch(()=>null),Promise.resolve(null);this.log(`Loading ${e.type} sn: ${e.sn} of ${this.fragInfo(e,!1)} cc: ${e.cc} ${`[`+i.startSN+`-`+i.endSN+`]`}, target: ${n}${e.byteRange.length?` range:${e.byteRange.join(`-`)}`:``}`),P(e.sn)&&!this.bitrateTest&&(this.nextLoadPosition=e.start+e.duration),this.state=Q.FRAG_LOADING;let c=this.config.progressive&&e.type!==z.SUBTITLE,l;return l=c&&s?s.then(t=>!t||this.fragContextChanged(t.frag)?null:this.fragmentLoader.load(e,this.iframesOnly,r,o)).catch(t=>this.handleFragLoadError(t,e)):Promise.all([this.fragmentLoader.load(e,this.iframesOnly,c?r:void 0,c?o:void 0),s,o]).then(([e])=>(!c&&r&&r(e),e)).catch(t=>this.handleFragLoadError(t,e)),this.hls.trigger(L.FRAG_LOADING,{frag:e,targetBufferTime:n}),this.fragCurrent===null?Promise.reject(Error(`frag load aborted, context changed in FRAG_LOADING`)):Promise.all([l,o]).then(([e])=>e)}doFragPartsLoad(e,t,n,r){return new Promise((i,a)=>{let o=[],s=n.details?.partList,c=t=>{this.fragmentLoader.loadPart(e,t,r).then(r=>{o[t.index]=r;let a=r.part;this.hls.trigger(L.FRAG_LOADED,r);let l=hs(n.details,e.sn,t.index+1)||gs(s,e.sn,t.index+1);if(l)c(l);else return i({frag:e,part:a,partsLoaded:o})}).catch(a)};c(t)})}handleFragLoadError(e,t){if(`data`in e){let n=e.data;n.details===I.INTERNAL_ABORTED?this.handleFragLoadAborted(t,n.part):n.type===F.KEY_SYSTEM_ERROR&&!n.fatal&&(t.abortRequests(),this.resetStartWhenNotLoaded(),this.resetFragmentLoading(t)),n.frag===t?this.hls.trigger(L.ERROR,n):(n.frag&&this.warn(`${n.details} error cascading from ${this.fragInfo(n.frag,!1,n.part)} to ${this.fragInfo(t,!1)}`),this.hls.trigger(L.ERROR,H(H({},n),{},{frag:t})))}else this.hls.trigger(L.ERROR,{type:F.OTHER_ERROR,details:I.INTERNAL_EXCEPTION,err:e,error:e,fatal:!0});return null}_handleTransmuxerFlush(e){let t=this.getCurrentContext(e);if(!t||this.state!==Q.PARSING){!this.fragCurrent&&this.state!==Q.STOPPED&&this.state!==Q.ERROR&&(this.state=Q.IDLE);return}let{frag:n,part:r,level:i}=t,a=self.performance.now();n.stats.parsing.end=a,r&&(r.stats.parsing.end=a);let o=this.getLevelDetails(),s=o&&n.sn>o.endSN||this.shouldLoadParts(o,n.end);s!==this.loadingParts&&(this.log(`LL-Part loading ${s?`ON`:`OFF`} after parsing segment ending @${n.end}`),this.loadingParts=s),this.updateLevelTiming(n,r,i,e)}shouldLoadParts(e,t){if(this.config.lowLatencyMode){if(!e)return this.loadingParts;if(e.partList&&!this.iframesOnly){let n=e.partList[0];if(t>=n.end+(e.fragmentHint?.duration||0)&&this.playhead>n.start-n.fragment.duration)return!0}}return!1}getCurrentContext(e){let{levels:t,fragCurrent:n}=this,{level:r,sn:i,part:a}=e;if(!(t!=null&&t[r]))return this.warn(`Levels object was unset while buffering fragment ${i} of ${this.playlistLabel()} ${r}. The current chunk will not be buffered.`),null;let o=t[r],s=o.details,c=a>-1?hs(s,i,a):null,l=c?c.fragment:ms(s,i,n);return l?(n&&n!==l&&(l.stats=n.stats),{frag:l,part:c,level:o}):null}bufferFragmentData(e,t,n,r,i){if(this.state!==Q.PARSING)return;Tt(t)&&!this.fragContextChanged(t)&&(this.fragPrevious=t);let{data1:a,data2:o}=e,s=a;if(o&&(s=Tr(a,o)),!s.length)return;let c=this.initPTS[t.cc],l=c?-c.baseTime/c.timescale:void 0,u={type:e.type,frag:t,part:n,chunkMeta:r,offset:l,parent:t.type,data:s};if(this.hls.trigger(L.BUFFER_APPENDING,u),e.dropped&&e.independent&&!n){if(i)return;this.flushBufferGap(t)}}flushBufferGap(e){let t=this.media;if(!t)return;if(!J.isBuffered(t,t.currentTime)){this.flushMainBuffer(0,e.start);return}let n=t.currentTime,r=J.bufferInfo(t,n,0),i=e.duration,a=Math.min(this.config.maxFragLookUpTolerance*2,i*.25),o=Math.max(Math.min(e.start-a,r.end-a),n+a);e.start-o>a&&this.flushMainBuffer(o,e.start)}getFwdBufferInfo(e,t){var n;let r=this.playhead,i=this.lastCurrentTime>r||(n=this.media)!=null&&n.paused?0:this.config.maxBufferHole;return this.getFwdBufferInfoAtPos(e,r,t,i)}getFwdBufferInfoAtPos(e,t,n,r){let i=J.bufferInfo(e,t,r);if(i.len===0&&i.nextStart!==void 0){let a=this.fragmentTracker.getBufferedFrag(t,n);if(a&&(i.nextStart<=a.end||a.gap)){let n=Math.max(Math.min(i.nextStart,a.end)-t,r);return J.bufferInfo(e,t,n)}}return i}getMaxBufferLength(e){let{config:t}=this,n;return n=e?Math.max(8*t.maxBufferSize/e,t.maxBufferLength):t.maxBufferLength,Math.min(n,t.maxMaxBufferLength)}exceedsMaxBuffer(e,t,n){let r=e.nextStart;if(r&&n.start>r){let r=e.buffered;if(r){let i=e.len,a=e.bufferedIndex;for(let e=r.length-1;e>a;e--)r[e].start<n.start&&(i+=r[e].end-r[e].start);return i>=t}}return!1}reduceMaxBufferLength(e,t){let n=this.config,r=Math.max(Math.min(e-t,n.maxBufferLength),t/2),i=Math.max(e-t*3,n.maxMaxBufferLength/2,r);return i>=r&&(n.maxMaxBufferLength=i,this.warn(`Reduce max buffer length to ${i}s`),!0)}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 n=t.fragments,r=n.length;if(!r)return null;let{config:i}=this,a=t.fragmentStart,o=i.lowLatencyMode&&!!t.partList,s=null;if(t.live){let n=i.initialLiveManifestSize;if(r<n)return this.warn(`Not enough fragments to start playback (have: ${r}, need: ${n})`),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){s=this.getInitialLiveFragment(t);let n=this.config.startPosition,r=this.hls.startPosition,i=this.hls.liveSyncPosition,o=s?.start||0,c,l;if(r!==-1&&r>=a?(c=r,l=r===n?`config`:`next load start`):i?(c=i,l=`live edge`):(c=e,l=`buffer pos`),c<o&&(c=o,l=`live frag start`),c<a&&(c=a,l=`playlist start`),this.startPosition!=c||this.nextLoadPosition!=c){let u=t.live&&!this.filterReplacedPrimary(s,t)?-1:c;this.log(`Setting startPosition to ${u} next load ${c} ${r===-1?``:`(from ${n}) `}based on ${l}. live edge: ${i} live frag start: ${o} playlist start: ${a} buffer pos: ${e}`),this.startPosition=u,this.nextLoadPosition=c}}}else e<=a&&(s=n[0]);if(!s){let n=this.loadingParts?t.partEnd:t.fragmentEnd;s=this.getFragmentAtPosition(e,n,t)}let c=this.filterReplacedPrimary(s,t);return!c&&s&&(c=sa(t,s.sn),c&&(this.nextLoadPosition=c.start)),c}isLoopLoading(e,t){if(this.nextLoadPosition<=t)return!1;let n=this.fragmentTracker.getState(e);return!!(n===Z.OK||n===Z.PARTIAL&&(e.gap||e.stats.retry>1))}getNextFragmentLoopLoading(e,t,n,r,i){let a=null;if(e.gap&&(a=this.getNextFragment(this.nextLoadPosition,t),a&&!a.gap&&n.nextStart)){let e=this.getFwdBufferInfoAtPos(this.mediaBuffer?this.mediaBuffer:this.media,n.nextStart,r,0);if(e!==null&&n.len+e.len>=i){let e=a.sn;return this.loopSn!==e&&(this.log(`buffer full after gaps in "${r}" playlist starting at sn: ${e}`),this.loopSn=e),null}}return this.loopSn=void 0,a}get primaryPrefetch(){if(ks(this.config)){var e;if((e=this.hls.interstitialsManager)!=null&&(e=e.playingItem)!=null&&e.event)return!0}return!1}filterReplacedPrimary(e,t){if(!e)return e;if(ks(this.config)&&(`type`in e?e:e.fragment).type!==z.SUBTITLE){let n=this.hls.interstitialsManager,r=n?.bufferingItem;if(r){let n=r.event;if(n){if(!n.appendInPlace&&(Math.abs(e.start-r.start)>1||r.start===0))return null}else if(e.end<=r.start&&t?.live===!1||e.start>=r.end&&r.nextEvent&&(r.nextEvent.appendInPlace&&!r.nextEvent.hasPlayed||e.start-r.end>1))return null}if(Os(e,n?.playerQueue,this.playhead))return null}return e}getNextPart(e,t,n){let r=-1,i=!1,a=!0;for(let o=0,s=e.length;o<s;o++){let s=e[o];if(a&&=!s.independent,r>-1&&n<s.start)break;let c=s.loaded||s.gap;c?r=-1:(i||(s.independent||a)&&s.fragment===t)&&(r=o),i=c&&!s.gap}let o=e[r];return o&&o.fragment!==t&&this.log(`Need buffer at ${n} but next unloaded part starts at ${o.start} (sn: ${t.sn} -> ${o.fragment.sn})`),r}loadedEndOfParts(e,t){let n;for(let r=e.length;r--;){if(n=e[r],!n.loaded)return!1;if(t>n.start)return!0}return!1}getInitialLiveFragment(e){let t=e.fragments,n=this.fragPrevious,r=null;if(n){if(e.hasProgramDateTime&&(r=ta(t,n.endProgramDateTime,this.config.maxFragLookUpTolerance),r&&this.log(`Live playlist, switching playlist, load frag with same PDT: ${n.programDateTime}`)),!r){let i=n.sn+1;if(i>=e.startSN&&i<=e.endSN){let a=t[i-e.startSN];n.cc===a.cc&&(r=a,this.log(`Live playlist, switching playlist, load frag with next SN: ${r.sn}`))}r||(r=oa(e,n.cc,n.end),r&&this.log(`Live playlist, switching playlist, load frag with same CC: ${r.sn}`))}}else{let t=this.hls.liveSyncPosition;t!==null&&(r=this.getFragmentAtPosition(t,this.bitrateTest?e.fragmentEnd:e.edge,e))}return r}getFragmentAtPosition(e,t,n){let{config:r}=this,{fragPrevious:i}=this,{fragments:a,endSN:o}=n,{fragmentHint:s}=n,{maxFragLookUpTolerance:c}=r,l=n.partList,u=!!(this.loadingParts&&l!=null&&l.length&&s);u&&!this.bitrateTest&&l[l.length-1].fragment.sn===s.sn&&(a=a.concat(s),o=s.sn),i&&this.fragmentTracker.getState(i)===Z.NOT_LOADED&&(i=null);let d;if(e<t){var f;let n=e<this.lastCurrentTime||e>t-c||(f=this.media)!=null&&f.paused||this.loadingParts||!this.startFragRequested?0:c;d=na(i,a,e,n)}else d=a[a.length-1];if(d){let e=d.sn,t=e-n.startSN,r=this.fragmentTracker.getState(d);if((r===Z.OK||r===Z.PARTIAL&&d.gap)&&(i=d),Et(d,i)&&(!u||l[0].fragment.sn>e||!n.live||!l.some(t=>t.fragment.sn===e&&!t.loaded&&!t.gap))){let e=a[t+1];d=d.sn<o&&this.fragmentTracker.getState(e)!==Z.OK?e:null}}return d}alignPlaylists(e,t,n){let r=e.fragments.length;if(!r)return this.warn(`No fragments in live playlist`),0;let i=e.fragmentStart,a=!t,o=e.alignedSliding&&P(i);if(a||!o&&!i){ws(n,e,this);let i=e.fragmentStart;return this.log(`Live playlist sliding: ${i} start-sn: ${t?t.startSN:`na`}->${e.startSN} fragments: ${r}`),i}return i}waitForCdnTuneIn(e){return e.live&&e.canBlockReload&&e.partTarget&&e.tuneInGoal>Math.max(e.partHoldBack,e.partTarget*3)}setStartPosition(e,t){let n=this.startPosition;n<t&&(n=-1);let r=this.timelineOffset;if(n===-1){let i=this.startTimeOffset!==null,a=i?this.startTimeOffset:e.startTimeOffset;if(a!==null&&P(a))n=t+a,a<0&&(n+=e.edge),n=Math.min(Math.max(t,n),t+e.totalduration),this.log(`Setting startPosition to ${n} for start time offset ${a} found in ${i?`multivariant`:`media`} playlist`),this.startPosition=n;else if(e.live){let e=this.hls.liveSyncPosition;n=e||t,this.log(`Setting startPosition to -1 to start at ${e?`live edge`:`playlist start`} ${n}`),this.startPosition=-1}else this.log(`setting startPosition to 0 by default`),this.startPosition=n=0;this.lastCurrentTime=n+r}this.nextLoadPosition=n+r}getLoadPosition(){var e;let{media:t}=this,n=0;return(e=this.hls)!=null&&e.hasEnoughToStart&&t&&!this.iframesOnly?n=t.currentTime:this.nextLoadPosition>=0&&(n=this.nextLoadPosition),n}get playhead(){var e;if((e=this.hls)!=null&&e.hasEnoughToStart){let e=this.media?.currentTime;return P(e)?e:this.lastCurrentTime}return this.getLoadPosition()}get iframesOnly(){if(this.playlistType!==z.MAIN)return!1;let e=this.getLevelDetails();return e?e.iframesOnly:this.levelLastLoaded?.iframes}handleFragLoadAborted(e,t){this.transmuxer&&e.type===this.playlistType&&Tt(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!==Q.STOPPED&&(!this.fragCurrent||!this.fragContextChanged(e)&&this.state!==Q.FRAG_LOADING_WAITING_RETRY)&&(this.state=Q.IDLE)}onFragmentOrKeyLoadError(e,t){if(t.chunkMeta&&!t.frag){let e=this.getCurrentContext(t.chunkMeta);e&&(t.frag=e.frag)}let{frag:n,part:r}=t;if(!n||!this.levels||n.type!==e)return;if(this.fragContextChanged(n)){this.warn(`Frag load error must match current frag to retry ${n.relurl} > ${this.fragCurrent?.relurl}`);return}let i=t.details===I.FRAG_GAP;i&&this.fragmentTracker.addAsGap(n);let a=t.errorAction;if(!a){this.state=Q.ERROR;return}let{action:o,flags:s,retryCount:c=0,retryConfig:l}=a,u=!!l,d=u&&o===ca.RetryRequest,f=u&&!a.resolved&&s&la.MoveAllAlternatesMatchingHost,p=this.hls.latestLevelDetails,m=p?.live;if(!d&&f&&Tt(n)&&m&&n.sn<p.endSN&&!Bt(t))this.resetFragmentErrors(e),r?r.gap=!0:this.treatAsGap(n),a.resolved=!0;else if((d||f)&&c<l.maxNumRetry){let r=Kt(t.response?.code),i=Ht(l,c);if(this.resetStartWhenNotLoaded(),this.retryDate=self.performance.now()+i,this.state=Q.FRAG_LOADING_WAITING_RETRY,a.resolved=!0,r){this.log(`Waiting for connection (offline)`),this.retryDate=1/0,t.reason=`offline`;return}this.warn(`Fragment ${n.sn} of ${e} ${n.level} errored with ${t.details}, retrying loading ${c+1}/${l.maxNumRetry} in ${i}ms`)}else if(l){if(this.resetFragmentErrors(e),c<l.maxNumRetry)!i&&o!==ca.RemoveAlternatePermanently&&(a.resolved=!0);else{this.warn(`${t.details} reached or exceeded max retry (${c})`);return}}else this.state=o===ca.SendAlternateToPenaltyBox?Q.WAITING_LEVEL:Q.ERROR;this.tickImmediate()}onSourceBufferError(e,t){var n;let{frag:r,part:i,sourceBufferName:a}=t,o=r&&((n=this.levels)==null||(n=n[r.level])==null?void 0:n.details);if(t.error.name!==ba||r?.type!==e||!Tt(r)||!(o!=null&&o.live))return;let s=i?i.index===0?i:null:r,c=s&&a?s.elementaryStreams[a]?.startPTS:void 0;if(this.markSourceBufferErrorGap(ms(o,r.sn)||r),c===void 0)return;let l=ms(o,r.sn-1);l&&this.fragmentTracker.getState(l)!==Z.NOT_LOADED&&!J.isBuffered(this.mediaBuffer||this.media,c-this.config.maxBufferHole)&&this.markSourceBufferErrorGap(l)}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,n=t===1/0;(!t||e>=t||n&&!Kt(0))&&(n&&this.log(`Connection restored (online)`),this.resetStartWhenNotLoaded(),this.state=Q.IDLE)}reduceLengthAndFlushBuffer(e){if(this.state===Q.PARSING||this.state===Q.PARSED){let t=e.frag,n=e.parent,r=this.getFwdBufferInfo(this.mediaBuffer,n),i=r&&r.len>.5;i&&this.reduceMaxBufferLength(r.len,t?.duration||10);let a=!i;return a?this.warn(`Buffer full error while media.currentTime (${this.playhead}) is not buffered, flush ${n} buffer`):r.nextStart&&t&&r.nextStart>t.start&&this.flushMainBuffer(r.nextStart,1/0,n===z.AUDIO?n:void 0),t&&(this.fragmentTracker.removeFragment(t),this.nextLoadPosition=t.start),this.resetLoadingState(),a}return!1}resetFragmentErrors(e){e===z.AUDIO&&(this.fragCurrent=null),this.hls.hasEnoughToStart||(this.startFragRequested=!1),this.state!==Q.STOPPED&&(this.state=Q.IDLE)}afterBufferFlushed(e,t){if(!e)return;let n=J.getBuffered(e);this.fragmentTracker.detectEvictedFragments(t,n,this.playlistType),this.state===Q.ENDED&&this.resetLoadingState()}resetLoadingState(){this.log(`Reset loading state`),this.fragCurrent=null,this.fragPrevious=null,this.state!==Q.STOPPED&&(this.state=Q.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,n,r){let i=n.details;if(!i){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((a,o)=>{let s=e.elementaryStreams[o];if(s){let c=s.endPTS-s.startPTS;if(c<=0)return this.warn(`Could not parse fragment ${e.sn} ${o} duration reliably (${c})`),a||!1;let l=0;return r.partial?t&&r.part===0&&(l=t.start-s.startPTS,e.startPTS=e.maxStartPTS=s.startPTS,e.startDTS=s.startDTS,e.start!==0&&e.setStart(s.startPTS),as(i,e,l)):l=is(i,e,s.startPTS,s.endPTS,s.startDTS,s.endDTS,this.iframesOnly,this),this.hls.trigger(L.LEVEL_PTS_UPDATED,{details:i,level:n,drift:l,type:o,frag:e,part:t,start:s.startPTS,end:s.endPTS}),!0}return a},!1)){let r=this.transmuxer?.error===null,i=this.transmuxer?.error!=null,a=(this.levels?.length??0)>1;if((n.fragmentError===0||r&&(n.fragmentError<2||e.endList)||i&&a)&&this.treatAsGap(e,n),r){let r=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(r.message),this.hls.trigger(L.ERROR,{type:F.MEDIA_ERROR,details:I.FRAG_PARSING_ERROR,fatal:!1,error:r,frag:e,reason:`Found no media in msn ${e.sn} of ${this.playlistLabel()} "${n.url}"`}),!this.hls)return;this.resetTransmuxer()}}this.state=Q.PARSED,this.log(`Parsed ${e.type} sn: ${e.sn}${t?` part: `+t.index:``} of ${this.fragInfo(e,!1,t)}`),this.hls.trigger(L.FRAG_PARSED,{frag:e,part:t,chunkMeta:r})}playlistLabel(){return`${this.playlistType} playlist`}fragInfo(e,t=!0,n){return`${e.type} playlist ${e.level} (${n?`part`:`frag`}:[${(t&&!n?e.startPTS:(n||e).start)??NaN}-${(t&&!n?e.endPTS:(n||e).end)??NaN}]${n&&e.type===`main`?`INDEPENDENT=`+(n.independent?`YES`:`NO`):``})`}treatAsGap(e,t){t&&t.fragmentError++,this.fragmentTracker.addAsGap(e)}resetTransmuxer(){var e;(e=this.transmuxer)==null||e.reset()}isFragmentNearlyDownloaded(e){let t=e.loader?.stats;if(!t||t.total<=0)return!1;let n=t.loading.first>0,r=(t.total-t.loaded)*8/(this.hls.bandwidthEstimate||this.hls.config.abrEwmaDefaultEstimate);return n&&r<=.15}recoverWorkerError(e){e.event===`demuxerWorker`&&(this.fragmentTracker.removeAllFragments(),this.transmuxer&&=(this.transmuxer.destroy(),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 n=0,{hls:r,media:i,config:a,levels:o,playlistType:s}=this,c=this.getLevelDetails();if(i&&!i.paused&&o){let t=s===z.AUDIO?xi(e.audioCodec,128e3):e.maxBitrate,i=1+r.ttfbEstimate/1e3,o=r.bandwidthEstimate*a.abrBandWidthUpFactor;n=i+t*(c&&(this.loadingParts?c.partTarget:c.averagetargetduration)||this.fragCurrent?.duration||6)/o,e.details||(n+=i)}let l=this.playhead,u=!(c!=null&&c.live)||t.end-l>n*1.5;return{fetchdelay:n,okToFlushForwardBuffer:u}}scheduleTrackSwitch(e,t,n){let{media:r,playlistType:i}=this;if(!r||!e)return;let a=n?this.getBufferedFrag(this.playhead+t):null;if(a){let e=this.followingBufferedFrag(a);if(e){this.abortCurrentFrag();let t=e.maxStartPTS?e.maxStartPTS:e.start,n=e.duration,r=Math.max(a.end,t+Math.min(Math.max(n-this.config.maxFragLookUpTolerance,n*(this.couldBacktrack?.5:.125)),n*(this.couldBacktrack?.75:.25)));if((this.getLevelDetails()?.fragmentStart||0)>r)return;let o=i===z.MAIN?null:`audio`;this.flushMainBuffer(r,1/0,o),this.cleanupBackBuffer()}}}cleanupBackBuffer(){let{media:e,playlistType:t}=this;if(!e)return;let n=this.getAppendedFrag(this.playhead);if(n&&n.start>1){let e=t===z.AUDIO;this.flushMainBuffer(0,n.start-+!e,e?`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 Q.KEY_LOADING:case Q.FRAG_LOADING:case Q.FRAG_LOADING_WAITING_RETRY:case Q.PARSING:case Q.PARSED:this.state=Q.IDLE}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 n=e.currentTime;if(J.isBuffered(e,n)?t=this.getAppendedFrag(n):J.isBuffered(e,n+.1)&&(t=this.getAppendedFrag(n+.1)),t&&(this.backtrackFragment=void 0,!Et(t,this.fragPlaying)))return this.fragPlaying=t,!0}return!1}getBufferOutput(){return null}nextLevelSwitch(){let{levels:e,media:t,hls:n,config:r,playlistType:i}=this;if(t!=null&&t.readyState&&e&&n&&r){let t=this.getBufferOutput(),r=this.getFwdBufferInfo(t,i);if(!r)return;let a=e[i===z.AUDIO?n.nextAudioTrack:n.nextLoadLevel],{fetchdelay:o,okToFlushForwardBuffer:s}=this.calculateOptimalSwitchPoint(a,r);this.scheduleTrackSwitch(r,o,s)}this.tickImmediate()}};function Os(e,t,n){if(t)for(let r=t.length;r--;){let i=t[r].interstitial,a=i.startTime,o=Math.min(a+i.duration,i.resumeTime);if(i.appendInPlace&&(e.start>=a&&e.end<=o||n>e.start&&e.end>a&&e.start<o))return!0}return!1}function ks(e){return!!e.interstitialsController&&e.enableInterstitialPlayback!==!1}var As=class{constructor(){this.chunks=[],this.dataLength=0}push(e){this.chunks.push(e),this.dataLength+=e.length}flush(){let{chunks:e,dataLength:t}=this,n;if(e.length)n=e.length===1?e[0]:js(e,t);else return new Uint8Array;return this.reset(),n}reset(){this.chunks.length=0,this.dataLength=0}};function js(e,t){let n=new Uint8Array(t),r=0;for(let t=0;t<e.length;t++){let i=e[t];n.set(i,r),r+=i.length}return n}var Ms={exports:{}},Ns;function Ps(){return Ns?Ms.exports:(Ns=1,(function(e){var t=Object.prototype.hasOwnProperty,n=`~`;function r(){}Object.create&&(r.prototype=Object.create(null),new r().__proto__||(n=!1));function i(e,t,n){this.fn=e,this.context=t,this.once=n||!1}function a(e,t,r,a,o){if(typeof r!=`function`)throw TypeError(`The listener must be a function`);var s=new i(r,a||e,o),c=n?n+t:t;return e._events[c]?e._events[c].fn?e._events[c]=[e._events[c],s]:e._events[c].push(s):(e._events[c]=s,e._eventsCount++),e}function o(e,t){--e._eventsCount===0?e._events=new r:delete e._events[t]}function s(){this._events=new r,this._eventsCount=0}s.prototype.eventNames=function(){var e=[],r,i;if(this._eventsCount===0)return e;for(i in r=this._events)t.call(r,i)&&e.push(n?i.slice(1):i);return Object.getOwnPropertySymbols?e.concat(Object.getOwnPropertySymbols(r)):e},s.prototype.listeners=function(e){var t=n?n+e:e,r=this._events[t];if(!r)return[];if(r.fn)return[r.fn];for(var i=0,a=r.length,o=Array(a);i<a;i++)o[i]=r[i].fn;return o},s.prototype.listenerCount=function(e){var t=n?n+e:e,r=this._events[t];return r?r.fn?1:r.length:0},s.prototype.emit=function(e,t,r,i,a,o){var s=n?n+e:e;if(!this._events[s])return!1;var c=this._events[s],l=arguments.length,u,d;if(c.fn){switch(c.once&&this.removeListener(e,c.fn,void 0,!0),l){case 1:return c.fn.call(c.context),!0;case 2:return c.fn.call(c.context,t),!0;case 3:return c.fn.call(c.context,t,r),!0;case 4:return c.fn.call(c.context,t,r,i),!0;case 5:return c.fn.call(c.context,t,r,i,a),!0;case 6:return c.fn.call(c.context,t,r,i,a,o),!0}for(d=1,u=Array(l-1);d<l;d++)u[d-1]=arguments[d];c.fn.apply(c.context,u)}else{var f=c.length,p;for(d=0;d<f;d++)switch(c[d].once&&this.removeListener(e,c[d].fn,void 0,!0),l){case 1:c[d].fn.call(c[d].context);break;case 2:c[d].fn.call(c[d].context,t);break;case 3:c[d].fn.call(c[d].context,t,r);break;case 4:c[d].fn.call(c[d].context,t,r,i);break;default:if(!u)for(p=1,u=Array(l-1);p<l;p++)u[p-1]=arguments[p];c[d].fn.apply(c[d].context,u)}}return!0},s.prototype.on=function(e,t,n){return a(this,e,t,n,!1)},s.prototype.once=function(e,t,n){return a(this,e,t,n,!0)},s.prototype.removeListener=function(e,t,r,i){var a=n?n+e:e;if(!this._events[a])return this;if(!t)return o(this,a),this;var s=this._events[a];if(s.fn)s.fn===t&&(!i||s.once)&&(!r||s.context===r)&&o(this,a);else{for(var c=0,l=[],u=s.length;c<u;c++)(s[c].fn!==t||i&&!s[c].once||r&&s[c].context!==r)&&l.push(s[c]);l.length?this._events[a]=l.length===1?l[0]:l:o(this,a)}return this},s.prototype.removeAllListeners=function(e){var t;return e?(t=n?n+e:e,this._events[t]&&o(this,t)):(this._events=new r,this._eventsCount=0),this},s.prototype.off=s.prototype.removeListener,s.prototype.addListener=s.prototype.on,s.prefixed=n,s.EventEmitter=s,e.exports=s})(Ms),Ms.exports)}var Fs=vt(Ps()),Is=`1.7.4`,Ls={};function Rs(){return typeof __HLS_WORKER_BUNDLE__==`function`}function zs(){let e=Ls[Is];if(e)return e.clientCount++,e;let t=new self.Blob([`var exports={};var module={exports:exports};function define(f){f()};define.amd=true;(${__HLS_WORKER_BUNDLE__.toString()})(true);`],{type:`text/javascript`}),n=self.URL.createObjectURL(t),r={worker:new self.Worker(n),objectURL:n,clientCount:1};return Ls[Is]=r,r}function Bs(e){let t=Ls[e];if(t)return t.clientCount++,t;let n=new self.URL(e,self.location.href).href,r={worker:new self.Worker(n),scriptURL:n,clientCount:1};return Ls[e]=r,r}function Vs(e){let t=Ls[e||Is];if(t&&t.clientCount--===1){let{worker:n,objectURL:r}=t;delete Ls[e||Is],r&&self.URL.revokeObjectURL(r),n.terminate()}}function Hs(e,t,n,r){let i=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],a=t[n+2],o=a>>2&15;if(o>12){let t=Error(`invalid ADTS sampling index:${o}`);e.emit(L.ERROR,L.ERROR,{type:F.MEDIA_ERROR,details:I.FRAG_PARSING_ERROR,fatal:!0,error:t,reason:t.message});return}let s=(a>>6&3)+1,c=t[n+3]>>6&3|(a&1)<<2,l=i[o],u=o;(s===5||s===29)&&(u-=3);let d,f=(u&14)>>1,p=(u&1)<<7|c<<3,m=0;if(s===1&&o>=6){m=5;let e=o-3;d=[m<<3|f,p|(e&14)>>1,(e&1)<<7|8,0]}else d=[s<<3|f,p];let h=`mp4a.40.`+(m||s);return U.log(`manifest codec:${r}, parsed codec:${h}, channels:${c}, rate:${l} (ADTS object type:${s} sampling index:${o} esds config:[${d.join(`,`)}])`),{config:d,samplerate:l,channelCount:c,codec:h,parsedCodec:h,manifestCodec:r}}function Us(e,t){return e[t]===255&&(e[t+1]&246)==240}function Ws(e,t){return e[t+1]&1?7:9}function Gs(e,t){return(e[t+3]&3)<<11|e[t+4]<<3|(e[t+5]&224)>>>5}function Ks(e,t){return t+5<e.length}function qs(e,t){return t+1<e.length&&Us(e,t)}function Js(e,t){return Ks(e,t)&&Us(e,t)&&Gs(e,t)<=e.length-t}function Ys(e,t){if(qs(e,t)){let n=Ws(e,t);if(t+n>=e.length)return!1;let r=Gs(e,t);if(r<=n)return!1;let i=t+r;return i===e.length||qs(e,i)}return!1}function Xs(e,t,n,r,i){if(!e.samplerate){let a=Hs(t,n,r,i);if(!a)return;V(e,a)}}function Zs(e){return 9216e4/e}function Qs(e,t){let n=Ws(e,t);if(t+n<=e.length){let r=Gs(e,t)-n;if(r>0)return{headerLength:n,frameLength:r}}}function $s(e,t,n,r,i){let a=r+i*Zs(e.samplerate),o=Qs(t,n),s;if(o){let{frameLength:r,headerLength:i}=o,c=i+r,l=Math.max(0,n+c-t.length);l?(s=new Uint8Array(c-i),s.set(t.subarray(n+i,t.length),0)):s=t.subarray(n+i,n+c);let u={unit:s,pts:a};return l||e.samples.push(u),{sample:u,length:c,missing:l}}let c=t.length-n;return s=new Uint8Array(c),s.set(t.subarray(n,t.length),0),{sample:{unit:s,pts:a},length:c,missing:-1}}var ec=function(e){return e.audioId3=`org.id3`,e.dateRange=`com.apple.quicktime.HLS`,e.emsg=`https://aomedia.org/emsg/ID3`,e.misbklv=`urn:misb:KLV:bin:1910.1`,e}({});function tc(e=``,t=9e4){return{type:e,id:-1,pid:-1,inputTimeScale:t,sequenceNumber:-1,samples:[],dropped:0}}var nc=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,n,r){this._id3Track={type:`id3`,id:3,pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0}}resetTimeStamp(e){this.initPTS=e,this.resetContiguity()}resetContiguity(){this.basePTS=null,this.lastPTS=null,this.frameIndex=0}canParse(e,t){return!1}appendFrame(e,t,n){}demux(e,t){this.cachedData&&=(e=Tr(this.cachedData,e),null);let n=Cn(e,0),r=n?n.length:0,i,a=this._audioTrack,o=this._id3Track,s=n?Vn(n):void 0,c=e.length;for((this.basePTS===null||this.frameIndex===0&&P(s))&&(this.basePTS=rc(s,t,this.initPTS),this.lastPTS=this.basePTS),this.lastPTS===null&&(this.lastPTS=this.basePTS),n&&n.length>0&&o.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:n,type:ec.audioId3,duration:1/0});r<c;){if(this.canParse(e,r)){let t=this.appendFrame(a,e,r);t?(this.frameIndex++,this.lastPTS=t.sample.pts,r+=t.length,i=r):r=c}else xn(e,r)?(n=Cn(e,r),o.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:n,type:ec.audioId3,duration:1/0}),r+=n.length,i=r):r++;if(r===c&&i!==c){let t=e.slice(i);this.cachedData=this.cachedData?Tr(this.cachedData,t):t}}return{audioTrack:a,videoTrack:tc(),id3Track:o,textTrack:tc()}}demuxSampleAes(e,t,n){return Promise.reject(Error(`[${this}] This demuxer does not support Sample-AES decryption`))}flush(e){let t=this.cachedData;return t&&(this.cachedData=null,this.demux(t,0)),{audioTrack:this._audioTrack,videoTrack:tc(),id3Track:this._id3Track,textTrack:tc()}}destroy(){this.cachedData=null,this._audioTrack=this._id3Track=void 0}},rc=(e,t,n)=>{if(P(e))return e*90;let r=n?n.baseTime*9e4/n.timescale:0;return t*9e4+r},ic=[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],ac=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],oc=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],sc=[0,1,1,4];function cc(e,t,n,r,i){if(n+24>t.length)return;let a=lc(t,n);if(a&&n+a.frameLength<=t.length){let o=r+i*(a.samplesPerFrame*9e4/a.sampleRate),s={unit:t.subarray(n,n+a.frameLength),pts:o,dts:o};return e.config=[],e.channelCount=a.channelCount,e.samplerate=a.sampleRate,e.samples.push(s),{sample:s,length:a.frameLength,missing:0}}}function lc(e,t){let n=e[t+1]>>3&3,r=e[t+1]>>1&3,i=e[t+2]>>4&15,a=e[t+2]>>2&3;if(n!==1&&i!==0&&i!==15&&a!==3){let o=e[t+2]>>1&1,s=e[t+3]>>6,c=ic[(n===3?3-r:r===3?3:4)*14+i-1]*1e3,l=ac[(n===3?0:n===2?1:2)*3+a],u=s===3?1:2,d=oc[n][r],f=sc[r],p=d*8*f,m=Math.floor(d*c/l+o)*f,h=Wr();return h&&h<=87&&r===2&&c>=224e3&&s===0&&(e[t+3]=e[t+3]|128),{sampleRate:l,channelCount:u,frameLength:m,samplesPerFrame:p}}}function uc(e,t){return e[t]===255&&(e[t+1]&224)==224&&!!(e[t+1]&6)}function dc(e,t){return t+1<e.length&&uc(e,t)}function fc(e,t){return uc(e,t)&&4<=e.length-t}function pc(e,t){if(t+1<e.length&&uc(e,t)){let n=lc(e,t),r=4;n!=null&&n.frameLength&&(r=n.frameLength);let i=t+r;return i===e.length||dc(e,i)}return!1}var mc=class{constructor(e,t,n){this.keyData=void 0,this.decrypter=void 0,this.keyData=n,this.decrypter=new Ua(t,!0)}decryptBuffer(e){return this.decrypter.decrypt(e,this.keyData.key.buffer,this.keyData.iv.buffer,Ia.cbc,{start:0,end:e.byteLength})}decryptAacSample(e,t,n){let r=e[t].unit;if(r.length<=16)return;let i=r.subarray(16,r.length-r.length%16),a=i.buffer.slice(i.byteOffset,i.byteOffset+i.length);this.decryptBuffer(a).then(i=>{let a=new Uint8Array(i);r.set(a,16),this.decrypter.isSync()||this.decryptAacSamples(e,t+1,n)}).catch(n)}decryptAacSamples(e,t,n){for(;;t++){if(t>=e.length){n();return}if(!(e[t].unit.length<32)&&(this.decryptAacSample(e,t,n),!this.decrypter.isSync()))return}}getAvcEncryptedData(e){let t=Math.floor((e.length-48)/160)*16+16,n=new Int8Array(t),r=0;for(let t=32;t<e.length-16;t+=160,r+=16)n.set(e.subarray(t,t+16),r);return n}getAvcDecryptedUnit(e,t){let n=new Uint8Array(t),r=0;for(let t=32;t<e.length-16;t+=160,r+=16)e.set(n.subarray(r,r+16),t);return e}decryptAvcSample(e,t,n,r,i){let a=Ar(i.data),o=this.getAvcEncryptedData(a);this.decryptBuffer(o.buffer).then(o=>{i.data=this.getAvcDecryptedUnit(a,o),this.decrypter.isSync()||this.decryptAvcSamples(e,t,n+1,r)}).catch(r)}decryptAvcSamples(e,t,n,r){if(e instanceof Uint8Array)throw Error(`Cannot decrypt samples of type Uint8Array`);for(;;t++,n=0){if(t>=e.length){r();return}let i=e[t].units;for(;!(n>=i.length);n++){let a=i[n];if(!(a.data.length<=48||a.type!==1&&a.type!==5)&&(this.decryptAvcSample(e,t,n,r,a),!this.decrypter.isSync()))return}}}},hc=class extends nc{constructor(e,t){super(),this.observer=void 0,this.config=void 0,this.sampleAes=null,this.observer=e,this.config=t}resetInitSegment(e,t,n,r){super.resetInitSegment(e,t,n,r),this._audioTrack={container:`audio/adts`,type:`audio`,id:2,pid:-1,sequenceNumber:0,segmentCodec:`aac`,samples:[],manifestCodec:t,duration:r,inputTimeScale:9e4,dropped:0}}static probe(e,t){if(!e)return!1;let n=Cn(e,0)?.length||0;if(pc(e,n))return!1;for(let r=e.length;n<r;n++)if(Ys(e,n))return t.log(`ADTS sync word found !`),!0;return!1}canParse(e,t){return Js(e,t)}appendFrame(e,t,n){Xs(e,this.observer,t,n,e.manifestCodec);let r=$s(e,t,n,this.basePTS,this.frameIndex);if(r?.missing===0)return r}demuxSampleAes(e,t,n){let r=this.demux(e,n),i=this.sampleAes=new mc(this.observer,this.config,t);return new Promise(e=>{i.decryptAacSamples(r.audioTrack.samples,0,()=>{e(r)})})}},gc=(e,t)=>{let n=0,r=5;t+=r;let i=new Uint32Array(1),a=new Uint32Array(1),o=new Uint8Array(1);for(;r>0;){o[0]=e[t];let s=Math.min(r,8),c=8-s;a[0]=4278190080>>>24+c<<c,i[0]=(o[0]&a[0])>>c,n=n?n<<s|i[0]:i[0],t+=1,r-=s}return n},_c=class extends nc{constructor(e){super(),this.observer=void 0,this.observer=e}resetInitSegment(e,t,n,r){super.resetInitSegment(e,t,n,r),this._audioTrack={container:`audio/ac-3`,type:`audio`,id:2,pid:-1,sequenceNumber:0,segmentCodec:`ac3`,samples:[],manifestCodec:t,duration:r,inputTimeScale:9e4,dropped:0}}canParse(e,t){return t+64<e.length}appendFrame(e,t,n){let r=vc(e,t,n,this.basePTS,this.frameIndex);if(r!==-1)return{sample:e.samples[e.samples.length-1],length:r,missing:0}}static probe(e){if(!e)return!1;let t=Cn(e,0);if(!t)return!1;let n=t.length;if(e[n]===11&&e[n+1]===119&&Vn(t)!==void 0){if(gc(e,n)<16)return!0;throw Error(`Containerless ec-3 is not supported`)}return!1}};function vc(e,t,n,r,i){if(n+8>t.length||t[n]!==11||t[n+1]!==119)return-1;let a=t[n+4]>>6;if(a>=3)return-1;let o=[48e3,44100,32e3][a],s=t[n+4]&63,c=[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][s*3+a]*2;if(n+c>t.length)return-1;let l=t[n+6]>>5,u=0;l===2?u+=2:(l&1&&l!==1&&(u+=2),l&4&&(u+=2));let d=(t[n+6]<<8|t[n+7])>>12-u&1,f=[2,1,2,3,3,4,4,5][l]+d,p=t[n+5]>>3,m=t[n+5]&7,h=new Uint8Array([a<<6|p<<1|m>>2,(m&3)<<6|l<<3|d<<2|s>>4,s<<4&224]),g=r+i*(1536/o*9e4),_=t.subarray(n,n+c);return e.config=h,e.channelCount=f,e.samplerate=o,e.samples.push({unit:_,pts:g}),c}var yc=class extends nc{resetInitSegment(e,t,n,r){super.resetInitSegment(e,t,n,r),this._audioTrack={container:`audio/mpeg`,type:`audio`,id:2,pid:-1,sequenceNumber:0,segmentCodec:`mp3`,samples:[],manifestCodec:t,duration:r,inputTimeScale:9e4,dropped:0}}static probe(e){if(!e)return!1;let t=Cn(e,0),n=t?.length||0;if(t&&e[n]===11&&e[n+1]===119&&Vn(t)!==void 0&&gc(e,n)<=16)return!1;for(let t=e.length;n<t;n++)if(pc(e,n))return U.log(`MPEG Audio sync word found !`),!0;return!1}canParse(e,t){return fc(e,t)}appendFrame(e,t,n){if(this.basePTS!==null)return cc(e,t,n,this.basePTS,this.frameIndex)}},bc=/\/emsg[-/]ID3/i,xc=class{constructor(e,t,n,r=U){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=r}resetTimeStamp(){}resetInitSegment(e,t,n,r){let i=this.videoTrack=tc(`video`,1),a=this.audioTrack=tc(`audio`,1),o=this.txtTrack=tc(`text`,1);if(this.id3Track=tc(`id3`,1),this.initData=void 0,this.timeOffset=0,!(e!=null&&e.byteLength))return;let s=this.initData=sr(e);if(s.video){let{id:e,timescale:t,codec:n,supplemental:r}=s.video;i.id=e,i.timescale=o.timescale=t,i.codec=n,i.supplemental=r}if(s.audio){let{id:e,timescale:t,codec:n}=s.audio;a.id=e,a.timescale=t,a.codec=n}o.id=qn.text,i.sampleDuration=0,i.duration=a.duration=r}resetContiguity(){this.remainderData=null}static probe(e){return ir(e,`moof`)}demux(e,t,n){this.timeOffset=t;let r=e,i=this.videoTrack,a=this.txtTrack;if(this.config.progressive){this.remainderData&&(r=Tr(this.remainderData,e));let t=wr(r);this.remainderData=t.remainder,i.samples=t.valid||new Uint8Array}else i.samples=r;let o=this.extractID3Track(i,t),s=this.parseFragment(i,a,t,n);return{videoTrack:i,audioTrack:this.audioTrack,id3Track:o,textTrack:this.txtTrack,initData:this.initData,sampleData:s}}flush(e,t){let n=this.timeOffset,r=this.videoTrack,i=this.txtTrack;r.samples=this.remainderData||new Uint8Array,this.remainderData=null;let a=this.extractID3Track(r,this.timeOffset),o=this.parseFragment(r,i,n,t);return{videoTrack:r,audioTrack:tc(),id3Track:a,textTrack:tc(),initData:this.initData,sampleData:o}}parseFragment(e,t,n,r){let i=this.initData;if(i&&r){let{samples:a,sampleData:o}=Sr(n,e,i,this.logger,r.iframe);return t.samples=a,o}t.samples=Er(n,e)}extractID3Track(e,t){let n=this.id3Track;if(e.samples.length){let r=K(e.samples,[`emsg`]);r&&r.forEach(e=>{let r=jr(e);if(bc.test(r.schemeIdUri)){let e=Sc(r,t),i=r.eventDuration===4294967295?1/0:r.eventDuration/r.timeScale;i<=.001&&(i=1/0);let a=r.payload;n.samples.push({data:a,len:a.byteLength,dts:e,pts:e,type:ec.emsg,duration:i})}else if(this.config.enableEmsgKLVMetadata){let e=this.config.emsgKLVSchemaUri||ec.misbklv;if(r.schemeIdUri.startsWith(e)){let e=Sc(r,t);n.samples.push({data:r.payload,len:r.payload.byteLength,dts:e,pts:e,type:ec.misbklv,duration:1/0})}}})}return n}demuxSampleAes(e,t,n){return Promise.reject(Error(`The MP4 demuxer does not support SAMPLE-AES decryption`))}destroy(){this.config=null,this.remainderData=null,this.videoTrack=this.audioTrack=this.id3Track=this.txtTrack=void 0,this.initData=void 0}};function Sc(e,t){return P(e.presentationTime)?e.presentationTime/e.timeScale:t+e.presentationTimeDelta/e.timeScale}var Cc=1,wc=2,Tc=3,Ec=-1,Dc=class{constructor(){this.VideoSample=null}createVideoSample(e,t,n){return{key:e,frame:!1,pts:t,dts:n,units:[],length:0}}getLastNalUnit(e){var t;let n=this.VideoSample,r;if((!n||n.units.length===0)&&(n=e[e.length-1]),(t=n)!=null&&t.units){let e=n.units;r=e[e.length-1]}return r}pushAccessUnit(e,t){if(e.units.length&&e.frame){if(e.pts===void 0){let n=t.samples,r=n.length;if(r){let t=n[r-1];e.pts=t.pts,e.dts=t.dts}else{t.dropped++;return}}t.samples.push(e)}}parseNALu(e,t,n){let r=t.byteLength;if(r===0)return[];let i=e.naluState||0,a=i===Ec?0:i,o=[],s=0,c=0,l=-1,u=0;for(i===Ec&&(l=0,u=this.getNALuType(t,0),c=1);c<r;){let n=t.indexOf(Cc,c);if(n===-1)break;c=n+1;let i=n;for(;i>0&&t[i-1]===0;)i--;let d=n-i+(i===0?a:0);if(d<wc)continue;let f=Math.min(d,Tc),p=Math.min(n-i,f),m=f-p;if(i=n-p,l>=0)o.push({data:t.subarray(l,i),type:u});else{let n=this.getLastNalUnit(e.samples);n&&(i>0?n.data=Tr(n.data,t.subarray(0,i)):m>0&&(n.data=n.data.subarray(0,n.data.byteLength-m)),n.state=0)}if(c<r)l=c,u=this.getNALuType(t,c);else{s=Ec,l=-1;break}}if(s!==Ec){let e=r;for(;e>0&&t[e-1]===0;)e--;s=r-e+(e===0?a:0)}if(l>=0)o.push({data:t.subarray(l),type:u,state:s});else if(o.length===0&&s!==Ec){let n=this.getLastNalUnit(e.samples);n&&(n.data=Tr(n.data,t),n.state=s)}return e.naluState=s,o}},Oc=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,n=e.byteLength-t,r=new Uint8Array(4),i=Math.min(4,t);if(i===0)throw Error(`no bytes available`);r.set(e.subarray(n,n+i)),this.word=new DataView(r.buffer).getUint32(0),this.bitsAvailable=i*8,this.bytesAvailable-=i}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),n=this.word>>>32-t;if(e>32&&U.error(`Cannot read more than 32 bits at a time`),this.bitsAvailable-=t,this.bitsAvailable>0)this.word<<=t;else if(this.bytesAvailable>0)this.loadWord();else throw Error(`no bits available`);return t=e-t,t>0&&this.bitsAvailable?n<<t|this.readBits(t):n}skipLZ(){let e=0;for(;e<this.bitsAvailable;++e)if(this.word&2147483648>>>e)return this.word<<=e,this.bitsAvailable-=e,e;return this.loadWord(),e+this.skipLZ()}skipUEG(){this.skipBits(1+this.skipLZ())}skipEG(){this.skipBits(1+this.skipLZ())}readUEG(){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)}},kc=class extends Dc{parsePES(e,t,n,r,i){let a=i.iframe,o=this.parseNALu(e,n.data,r),s=this.VideoSample,c,l=!1;n.data=null,s&&o.length&&!e.audFound&&(this.pushAccessUnit(s,e),s=this.VideoSample=this.createVideoSample(!1,n.pts,n.dts)),o.forEach(r=>{var i,o;switch(r.type){case 1:{if(a)break;let t=!1;c=!0;let i=r.data;if(l&&i.length>4){let e=this.readSliceType(i);(e===2||e===4||e===7||e===9)&&(t=!0)}if(t){var u;(u=s)!=null&&u.frame&&!s.key&&(this.pushAccessUnit(s,e),s=this.VideoSample=null)}s||=this.VideoSample=this.createVideoSample(!0,n.pts,n.dts),s.frame=!0,s.key=t;break}case 5:c=!0,(i=s)!=null&&i.frame&&!s.key&&(this.pushAccessUnit(s,e),s=this.VideoSample=null),s||=this.VideoSample=this.createVideoSample(!0,n.pts,n.dts),s.key=!0,s.frame=!0;break;case 6:if(a)break;c=!0,kr(r.data,1,n.pts,t.samples);break;case 7:{c=!0,l=!0;let t=r.data,n=this.readSPS(t);if(!e.sps||e.width!==n.width||e.height!==n.height||e.pixelRatio?.[0]!==n.pixelRatio[0]||e.pixelRatio?.[1]!==n.pixelRatio[1]){e.width=n.width,e.height=n.height,e.pixelRatio=n.pixelRatio,e.sps=[t];let r=t.subarray(1,4),i=`avc1.`;for(let e=0;e<3;e++){let t=r[e].toString(16);t.length<2&&(t=`0`+t),i+=t}e.codec=i}break}case 8:c=!0,e.pps=[r.data];break;case 9:c=!0,e.audFound=!0,(o=s)!=null&&o.frame&&(this.pushAccessUnit(s,e),s=null),s||=this.VideoSample=this.createVideoSample(!1,n.pts,n.dts);break;case 12:c=!0;break;default:c=!1}s&&c&&s.units.push(r)}),r&&s&&(this.pushAccessUnit(s,e),this.VideoSample=null)}getNALuType(e,t){return e[t]&31}readSliceType(e){let t=new Oc(e);return t.readUByte(),t.readUEG(),t.readUEG()}skipScalingList(e,t){let n=8,r=8,i;for(let a=0;a<e;a++)r!==0&&(i=t.readEG(),r=(n+i+256)%256),n=r===0?n:r}readSPS(e){let t=new Oc(e),n=0,r=0,i=0,a=0,o,s,c,l=t.readUByte.bind(t),u=t.readBits.bind(t),d=t.readUEG.bind(t),f=t.readBoolean.bind(t),p=t.skipBits.bind(t),m=t.skipEG.bind(t),h=t.skipUEG.bind(t),g=this.skipScalingList.bind(this);l();let _=l();if(u(5),p(3),l(),h(),_===100||_===110||_===122||_===244||_===44||_===83||_===86||_===118||_===128){let e=d();if(e===3&&p(1),h(),h(),p(1),f())for(s=e===3?12:8,c=0;c<s;c++)f()&&g(c<6?16:64,t)}h();let v=d();if(v===0)d();else if(v===1)for(p(1),m(),m(),o=d(),c=0;c<o;c++)m();h(),p(1);let y=d(),b=d(),x=u(1);x===0&&p(1),p(1),f()&&(n=d(),r=d(),i=d(),a=d());let S=[1,1];if(f()&&f())switch(l()){case 1:S=[1,1];break;case 2:S=[12,11];break;case 3:S=[10,11];break;case 4:S=[16,11];break;case 5:S=[40,33];break;case 6:S=[24,11];break;case 7:S=[20,11];break;case 8:S=[32,11];break;case 9:S=[80,33];break;case 10:S=[18,11];break;case 11:S=[15,11];break;case 12:S=[64,33];break;case 13:S=[160,99];break;case 14:S=[4,3];break;case 15:S=[3,2];break;case 16:S=[2,1];break;case 255:S=[l()<<8|l(),l()<<8|l()]}return{width:Math.ceil((y+1)*16-n*2-r*2),height:(2-x)*(b+1)*16-(x?2:4)*(i+a),pixelRatio:S}}},Ac=class extends Dc{constructor(...e){super(...e),this.initVPS=null}parsePES(e,t,n,r){let i=this.parseNALu(e,n.data,r),a=this.VideoSample,o,s=!1;n.data=null;let c=e=>(a=this.VideoSample=this.createVideoSample(e,n.pts,n.dts),a);i.forEach((r,i)=>{var l,u;if(this.startsNewAccessUnit(a,e,r,i)){this.pushAccessUnit(a,e);let t=r.type>=16&&r.type<=23;a=c(t),s=!1}switch(r.type){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:case 8:case 9:a||=c(!1),a.frame=!0,o=!0;break;case 16:case 17:case 18:case 21:case 22:case 23:if(o=!0,s){var d;(d=a)!=null&&d.frame&&!a.key&&(this.pushAccessUnit(a,e),a=this.VideoSample=null)}a||=c(!0),a.key=!0,a.frame=!0;break;case 19:case 20:o=!0,(l=a)!=null&&l.frame&&!a.key&&(this.pushAccessUnit(a,e),a=this.VideoSample=null),a||=c(!0),a.key=!0,a.frame=!0;break;case 39:o=!0,kr(r.data,2,n.pts,t.samples);break;case 32:o=!0,e.vps||(typeof e.params!=`object`&&(e.params={}),e.params=V(e.params,this.readVPS(r.data)),this.initVPS=r.data),e.vps=[r.data];break;case 33:if(o=!0,s=!0,e.vps!==void 0&&e.vps[0]!==this.initVPS&&e.sps!==void 0&&!this.matchSPS(e.sps[0],r.data)&&(this.initVPS=e.vps[0],e.sps=e.pps=void 0),!e.sps){let t=this.readSPS(r.data);e.width=t.width,e.height=t.height,e.pixelRatio=t.pixelRatio,e.codec=t.codecString,e.sps=[],typeof e.params!=`object`&&(e.params={});for(let n in t.params)e.params[n]=t.params[n]}this.pushParameterSet(e.sps,r.data,e.vps),a||=c(!1);break;case 34:if(o=!0,typeof e.params==`object`){if(!e.pps){e.pps=[];let t=this.readPPS(r.data);for(let n in t)e.params[n]=t[n]}this.pushParameterSet(e.pps,r.data,e.vps)}break;case 35:o=!0,e.audFound=!0,(u=a)!=null&&u.frame&&(this.pushAccessUnit(a,e),a=null),a||=c(!1);break;default:o=!1}a&&o&&a.units.push(r)}),r&&a&&(this.pushAccessUnit(a,e),this.VideoSample=null)}pushParameterSet(e,t,n){(n&&n[0]===this.initVPS||!n&&!e.length)&&e.push(t)}startsNewAccessUnit(e,t,n,r){if(!e)return!1;if(!t.audFound&&r===0)return!0;if(!e.frame)return!1;let{type:i,data:a}=n;return i>=32&&i<=35||i===39||i>=41&&i<=44||i>=48&&i<=55||i<=31&&a.length>2&&!!(a[2]&128)}getNALuType(e,t){return(e[t]&126)>>>1}ebsp2rbsp(e){let t=new Uint8Array(e.byteLength),n=0;for(let r=0;r<e.byteLength;r++)r>=2&&e[r]===3&&e[r-1]===0&&e[r-2]===0||(t[n]=e[r],n++);return new Uint8Array(t.buffer,0,n)}pushAccessUnit(e,t){super.pushAccessUnit(e,t),this.initVPS&&=null}readVPS(e){let t=new Oc(e);t.readUByte(),t.readUByte(),t.readBits(4),t.skipBits(2),t.readBits(6);let n=t.readBits(3),r=t.readBoolean();return{numTemporalLayers:n+1,temporalIdNested:r}}readSPS(e){let t=new Oc(this.ebsp2rbsp(e));t.readUByte(),t.readUByte(),t.readBits(4);let n=t.readBits(3);t.readBoolean();let r=t.readBits(2),i=t.readBoolean(),a=t.readBits(5),o=t.readUByte(),s=t.readUByte(),c=t.readUByte(),l=t.readUByte(),u=t.readUByte(),d=t.readUByte(),f=t.readUByte(),p=t.readUByte(),m=t.readUByte(),h=t.readUByte(),g=t.readUByte(),_=[],v=[];for(let e=0;e<n;e++)_.push(t.readBoolean()),v.push(t.readBoolean());if(n>0)for(let e=n;e<8;e++)t.readBits(2);for(let e=0;e<n;e++)_[e]&&(t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte()),v[e]&&t.readUByte();t.readUEG();let y=t.readUEG();y==3&&t.skipBits(1);let b=t.readUEG(),x=t.readUEG(),S=t.readBoolean(),C=0,w=0,T=0,E=0;S&&(C+=t.readUEG(),w+=t.readUEG(),T+=t.readUEG(),E+=t.readUEG());let D=t.readUEG(),O=t.readUEG(),k=t.readUEG(),A=t.readBoolean();for(let e=A?0:n;e<=n;e++)t.skipUEG(),t.skipUEG(),t.skipUEG();if(t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG(),t.readBoolean()&&t.readBoolean())for(let e=0;e<4;e++)for(let n=0;n<(e===3?2:6);n++)if(!t.readBoolean())t.readUEG();else{let n=Math.min(64,1<<4+(e<<1));e>1&&t.readEG();for(let e=0;e<n;e++)t.readEG()}t.readBoolean(),t.readBoolean(),t.readBoolean()&&(t.readUByte(),t.skipUEG(),t.skipUEG(),t.readBoolean());let j=t.readUEG(),M=0;for(let e=0;e<j;e++){let n=!1;if(e!==0&&(n=t.readBoolean()),n){e===j&&t.readUEG(),t.readBoolean(),t.readUEG();let n=0;for(let e=0;e<=M;e++){let e=t.readBoolean(),r=!1;e||(r=t.readBoolean()),(e||r)&&n++}M=n}else{let e=t.readUEG(),n=t.readUEG();M=e+n;for(let n=0;n<e;n++)t.readUEG(),t.readBoolean();for(let e=0;e<n;e++)t.readUEG(),t.readBoolean()}}if(t.readBoolean()){let e=t.readUEG();for(let n=0;n<e;n++){for(let e=0;e<k+4;e++)t.readBits(1);t.readBits(1)}}let N=0,ee=1,te=1,ne=!0,re=1,ie=0;t.readBoolean(),t.readBoolean();let ae=!1;if(t.readBoolean()){if(t.readBoolean()){let e=t.readUByte();e>0&&e<16?(ee=[1,12,10,16,40,24,20,32,80,18,15,64,160,4,3,2][e-1],te=[1,11,11,11,33,11,11,11,33,11,11,33,99,3,2,1][e-1]):e===255&&(ee=t.readBits(16),te=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(),ae=t.readBoolean(),ae&&(t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG()),t.readBoolean()&&(re=t.readBits(32),ie=t.readBits(32),t.readBoolean()&&t.readUEG(),t.readBoolean())){let e=t.readBoolean(),r=t.readBoolean(),i=!1;(e||r)&&(i=t.readBoolean(),i&&(t.readUByte(),t.readBits(5),t.readBoolean(),t.readBits(5)),t.readBits(4),t.readBits(4),i&&t.readBits(4),t.readBits(5),t.readBits(5),t.readBits(5));for(let a=0;a<=n;a++){ne=t.readBoolean();let n=ne||t.readBoolean(),a=!1;n?t.readEG():a=t.readBoolean();let o=a?1:t.readUEG()+1;if(e)for(let e=0;e<o;e++)t.readUEG(),t.readUEG(),i&&(t.readUEG(),t.readUEG()),t.skipBits(1);if(r)for(let e=0;e<o;e++)t.readUEG(),t.readUEG(),i&&(t.readUEG(),t.readUEG()),t.skipBits(1)}}t.readBoolean()&&(t.readBoolean(),t.readBoolean(),t.readBoolean(),N=t.readUEG())}let oe=b,se=x;if(S){let e=1,t=1;y===1?e=t=2:y==2&&(e=2),oe=b-e*w-e*C,se=x-t*E-t*T}let ce=r?[`A`,`B`,`C`][r]:``,le=o<<24|s<<16|c<<8|l,ue=0;for(let e=0;e<32;e++)ue=(ue|(le>>e&1)<<31-e)>>>0;let de=ue.toString(16);return a===1&&de===`2`&&(de=`6`),{codecString:`hvc1.${ce}${a}.${de}.${i?`H`:`L`}${g}.B0`,params:{general_tier_flag:i,general_profile_idc:a,general_profile_space:r,general_profile_compatibility_flags:[o,s,c,l],general_constraint_indicator_flags:[u,d,f,p,m,h],general_level_idc:g,bit_depth:D+8,bit_depth_luma_minus8:D,bit_depth_chroma_minus8:O,min_spatial_segmentation_idc:N,chroma_format_idc:y,frame_rate:{fixed:ne,fps:ie/re}},width:oe,height:se,pixelRatio:[ee,te]}}readPPS(e){let t=new Oc(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 n=t.readBoolean(),r=t.readBoolean(),i=1;return r&&n?i=0:r?i=3:n&&(i=2),{parallelismType:i}}matchSPS(e,t){return Gn(e).substring(3)===Gn(t).substring(3)}},jc=188,Mc=class e{constructor(e,t,n,r){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=n,this.logger=r,this.videoParser=null}static probe(t,n){let r=e.syncOffset(t);return r>0&&n.warn(`MPEG2-TS detected but first sync word found @ offset ${r}`),r!==-1}static syncOffset(e){let t=e.length,n=Math.min(940,t-jc)+1,r=0;for(;r<n;){let i=!1,a=-1,o=0;for(let s=r;s<t;s+=jc)if(e[s]===71&&(t-s===jc||e[s+jc]===71)){if(o++,a===-1&&(a=s,a!==0&&(n=Math.min(a+18612,e.length-jc)+1)),i||=Nc(e,s)===0,i&&o>1&&(a===0&&o>2||s+jc>n))return a}else if(o)return-1;else break;r++}return-1}static createTrack(e,t){return{container:e===`video`||e===`audio`?`video/mp2t`:void 0,type:e,id:qn[e],pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0,duration:e===`audio`?t:void 0}}resetInitSegment(t,n,r,i,a,o){this.pmtParsed=!1,this._pmtId=-1,this._videoTrack=e.createTrack(`video`),this._videoTrack.duration=i,this.videoIntegrityChecker=this.config.handleMpegTsVideoIntegrityErrors===`skip`?new zc(this.logger):null,this._audioTrack=e.createTrack(`audio`,i),this._id3Track=e.createTrack(`id3`),this._txtTrack=e.createTrack(`text`),this._audioTrack.segmentCodec=`aac`,this.videoParser=null,this.aacOverFlow=null,this.remainderData=null,this.audioCodec=n,this.videoCodec=r,t&&this.demux(t,0,o,a?.method===`SAMPLE-AES`)}resetTimeStamp(){}resetContiguity(){let{_audioTrack:e,_videoTrack:t,_id3Track:n}=this;e&&(e.pesData=null),t&&(t.pesData=null),n&&(n.pesData=null),this.videoParser=null,this.aacOverFlow=null,this.remainderData=null}demux(t,n,r,i=!1,a=!1){i||(this.sampleAes=null);let o,s=this._videoTrack,c=this.videoIntegrityChecker,l=this._audioTrack,u=this._id3Track,d=this._txtTrack,f=r.iframe,p=s.pid,m=s.pesData,h=l.pid,g=u.pid,_=this._klvPid,v=l.pesData,y=u.pesData,b=null,x=null,S=this.pmtParsed,C=this._pmtId,w=t.length;if(this.remainderData&&=(t=Tr(this.remainderData,t),w=t.length,null),w<jc&&!a)return this.remainderData=t,{audioTrack:l,videoTrack:s,id3Track:u,textTrack:d};let T=Math.max(0,e.syncOffset(t));w-=(w-T)%jc,w<t.byteLength&&!a&&(this.remainderData=new Uint8Array(t.buffer,w,t.buffer.byteLength-w));let E=0;for(let e=T;e<w;e+=jc)if(t[e]===71){let n=!!(t[e+1]&64),a=Nc(t,e),w=(t[e+3]&48)>>4,E;if(w>1){if(E=e+5+t[e+4],E===e+jc)continue}else E=e+4;switch(a){case p:n&&(m&&!(c!=null&&c.isCorrupted)&&(o=Rc(m,this.logger))&&(this.readyVideoParser(s.segmentCodec),this.videoParser!==null&&this.videoParser.parsePES(s,d,o,!1,r)),m={data:[],size:0},c?.reset(p)),c?.handlePacket(t.subarray(e)),m&&(m.data.push(t.subarray(E,e+jc)),m.size+=e+jc-E);break;case h:if(f)break;if(n){if(v&&(o=Rc(v,this.logger)))switch(l.segmentCodec){case`aac`:this.parseAACPES(l,o,r);break;case`mp3`:this.parseMPEGPES(l,o);break;case`ac3`:this.parseAC3PES(l,o)}v={data:[],size:0}}v&&(v.data.push(t.subarray(E,e+jc)),v.size+=e+jc-E);break;case g:if(f)break;n&&(y&&(o=Rc(y,this.logger))&&this.parseID3PES(u,o),y={data:[],size:0}),y&&(y.data.push(t.subarray(E,e+jc)),y.size+=e+jc-E);break;case _:if(f)break;n&&(b&&(o=Rc(b,this.logger))&&this.parseKlvPES(u,o),b={data:[],size:0}),b&&(b.data.push(t.subarray(E,e+jc)),b.size+=e+jc-E);break;case 0:n&&(E+=t[E]+1),C=this._pmtId=Pc(t,E);break;case C:{n&&(E+=t[E]+1);let a=Fc(t,E,this.typeSupported,i,this.observer,this.logger,this.config,r);p=a.videoPid,p>0&&(s.pid=p,s.segmentCodec=a.segmentVideoCodec),h=a.audioPid,h>0&&(l.pid=h,l.segmentCodec=a.segmentAudioCodec),g=a.id3Pid,g>0&&(u.pid=g),_=a.klvPid,_>0&&(this._klvPid=_),x!==null&&!S&&(this.logger.warn(`MPEG-TS PMT found at ${e} after unknown PID '${x}'. Backtracking to sync byte @${T} to parse all TS packets.`),x=null,e=T-188),S=this.pmtParsed=!0;break}case 17:case 8191:break;default:x=a}}else E++;E>0&&Ic(this.observer,Error(`Found ${E} TS packet/s that do not start with 0x47`),r,void 0,this.logger),s.pesData=m,l.pesData=v,u.pesData=y;let D={audioTrack:l,videoTrack:s,id3Track:u,textTrack:d};return a&&this.extractRemainingSamples(D,r),D}flush(e,t){let{remainderData:n}=this;this.remainderData=null;let r;return r=n?this.demux(n,0,t,!1,!0):{videoTrack:this._videoTrack,audioTrack:this._audioTrack,id3Track:this._id3Track,textTrack:this._txtTrack},this.extractRemainingSamples(r,t),this.sampleAes?this.decrypt(r,this.sampleAes):r}extractRemainingSamples(e,t){let{audioTrack:n,videoTrack:r,id3Track:i,textTrack:a}=e,o=r.pesData,s=n.pesData,c=i.pesData,l=this.videoIntegrityChecker,u;if(o&&!(l!=null&&l.isCorrupted)&&(u=Rc(o,this.logger))?(this.readyVideoParser(r.segmentCodec),this.videoParser!==null&&(this.videoParser.parsePES(r,a,u,!0,t),r.pesData=null)):r.pesData=o,s&&(u=Rc(s,this.logger))){switch(n.segmentCodec){case`aac`:this.parseAACPES(n,u,t);break;case`mp3`:this.parseMPEGPES(n,u);break;case`ac3`:this.parseAC3PES(n,u)}n.pesData=null}else s!=null&&s.size&&this.logger.log(`last AAC PES packet truncated,might overlap between fragments`),n.pesData=s;c&&(u=Rc(c,this.logger))?(this.parseID3PES(i,u),i.pesData=null):i.pesData=c}demuxSampleAes(e,t,n,r){let i=this.demux(e,n,r,!0,!this.config.progressive),a=this.sampleAes=new mc(this.observer,this.config,t);return this.decrypt(i,a)}readyVideoParser(e){this.videoParser===null&&(e===`avc`?this.videoParser=new kc:e===`hevc`&&(this.videoParser=new Ac))}decrypt(e,t){return new Promise(n=>{let{audioTrack:r,videoTrack:i}=e;r.samples&&r.segmentCodec===`aac`?t.decryptAacSamples(r.samples,0,()=>{i.samples?t.decryptAvcSamples(i.samples,0,0,()=>{n(e)}):n(e)}):i.samples&&t.decryptAvcSamples(i.samples,0,0,()=>{n(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,n){let r=0,i=this.aacOverFlow,a=t.data;if(i){this.aacOverFlow=null;let t=i.missing,n=i.sample.unit.byteLength;if(t===-1)a=Tr(i.sample.unit,a);else{let o=n-t;i.sample.unit.set(a.subarray(0,t),o),e.samples.push(i.sample),r=i.missing}}let o,s;for(o=r,s=a.length;o<s-1&&!qs(a,o);o++);if(o!==r){let e,t=o<s-1;if(e=t?`AAC PES did not start with ADTS header,offset:${o}`:`No ADTS header found in AAC PES`,Ic(this.observer,Error(e),n,t,this.logger),!t)return}Xs(e,this.observer,a,o,this.audioCodec);let c;if(t.pts!==void 0)c=t.pts;else if(i){let t=Zs(e.samplerate);c=i.sample.pts+t}else{this.logger.warn(`[tsdemuxer]: AAC PES unknown PTS`);return}let l=0,u;for(;o<s;){if(u=$s(e,a,o,c,l),o+=u.length,u.missing){this.aacOverFlow=u;break}for(l++;o<s-1&&!qs(a,o);o++);}}parseMPEGPES(e,t){let n=t.data,r=n.length,i=0,a=0,o=t.pts;if(o===void 0){this.logger.warn(`[tsdemuxer]: MPEG PES unknown PTS`);return}for(;a<r;)if(dc(n,a)){let t=cc(e,n,a,o,i);if(t)a+=t.length,i++;else break}else a++}parseAC3PES(e,t){{let n=t.data,r=t.pts;if(r===void 0){this.logger.warn(`[tsdemuxer]: AC3 PES unknown PTS`);return}let i=n.length,a=0,o=0,s;for(;o<i&&(s=vc(e,n,o,r,a++))>0;)o+=s}}parseID3PES(e,t){if(t.pts===void 0){this.logger.warn(`[tsdemuxer]: ID3 PES unknown PTS`);return}let n=V({},t,{type:this._videoTrack?ec.emsg:ec.audioId3,duration:1/0});e.samples.push(n)}parseKlvPES(e,t){let n=t.pts??t.dts;if(n===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 i=0;for(;i<r.length&&!(i+16>r.length);){let a=i;if(i+=16,i>=r.length)break;let o=r[i];i+=1;let s=0;if(o&128){let e=o&127;if(e===0||e>4||i+e>r.length){this.logger.warn(`[tsdemuxer]: Invalid KLV length encoding`);break}for(let t=0;t<e;t++)s=s<<8|r[i+t];i+=e}else s=o;if(i+s>r.length){this.logger.warn(`[tsdemuxer]: KLV value extends beyond PES payload`);break}let c=i+s,l=r.subarray(a,c),u={data:l,len:l.byteLength,pts:n,dts:t.dts??n,type:ec.misbklv,duration:1/0};e.samples.push(u),i=c}}};function Nc(e,t){return((e[t+1]&31)<<8)+e[t+2]}function Pc(e,t){return(e[t+10]&31)<<8|e[t+11]}function Fc(e,t,n,r,i,a,o,s){let c={audioPid:-1,videoPid:-1,id3Pid:-1,klvPid:-1,segmentVideoCodec:`avc`,segmentAudioCodec:`aac`},l=(e[t+1]&15)<<8|e[t+2],u=t+3+l-4,d=(e[t+10]&15)<<8|e[t+11];for(t+=12+d;t<u;){let l=Nc(e,t),u=(e[t+3]&15)<<8|e[t+4];switch(e[t]){case 207:if(!r){Lc(`ADTS AAC`,a);break}case 15:c.audioPid===-1&&(c.audioPid=l);break;case 21:c.id3Pid===-1&&(c.id3Pid=l);break;case 219:if(!r){Lc(`H.264`,a);break}case 27:c.videoPid===-1&&(c.videoPid=l);break;case 3:case 4:!n.mpeg&&!n.mp3?a.log(`MPEG audio found, not supported in this browser`):c.audioPid===-1&&(c.audioPid=l,c.segmentAudioCodec=`mp3`);break;case 193:if(!r){Lc(`AC-3`,a);break}case 129:n.ac3?c.audioPid===-1&&(c.audioPid=l,c.segmentAudioCodec=`ac3`):a.log(`AC-3 audio found, not supported in this browser`);break;case 6:if(u>0){let r=t+5,i=u;for(;i>2;){switch(e[r]){case 106:c.audioPid===-1&&(n.ac3===!0?(c.audioPid=l,c.segmentAudioCodec=`ac3`):a.log(`AC-3 audio found, not supported in this browser for now`));break;case 5:c.klvPid===-1&&o.enableEmsgKLVMetadata&&(c.klvPid=l,a.log(`KLV metadata PID found: ${l}`))}let t=e[r+1]+2;r+=t,i-=t}}break;case 194:case 135:return Ic(i,Error(`Unsupported EC-3 in M2TS found`),s,void 0,a),c;case 36:c.videoPid===-1&&(c.videoPid=l,c.segmentVideoCodec=`hevc`,a.log(`HEVC in M2TS found`))}t+=u+5}return c}function Ic(e,t,n,r,i){i.warn(`parsing error: ${t.message}`),e.emit(L.ERROR,L.ERROR,{type:F.MEDIA_ERROR,details:I.FRAG_PARSING_ERROR,fatal:!1,levelRetry:r,chunkMeta:n,error:t,reason:t.message})}function Lc(e,t){t.log(`${e} with AES-128-CBC encryption found in unencrypted stream`)}function Rc(e,t){let n=0,r,i,a,o,s,c=e.data;if(!e||e.size===0)return null;for(;c[0].length<19&&c.length>1;)c[0]=Tr(c[0],c[1]),c.splice(1,1);if(r=c[0],(r[0]<<16)+(r[1]<<8)+r[2]===1){if(i=(r[4]<<8)+r[5],i&&i>e.size-6)return null;let l=r[7];l&192&&(o=(r[9]&14)*536870912+(r[10]&255)*4194304+(r[11]&254)*16384+(r[12]&255)*128+(r[13]&254)/2,l&64?(s=(r[14]&14)*536870912+(r[15]&255)*4194304+(r[16]&254)*16384+(r[17]&255)*128+(r[18]&254)/2,o-s>54e5&&(t.warn(`${Math.round((o-s)/9e4)}s delta between PTS and DTS, align them`),o=s)):s=o),a=r[8];let u=a+9;if(e.size<=u)return null;e.size-=u;let d=new Uint8Array(e.size);for(let e=0,t=c.length;e<t;e++){r=c[e];let t=r.byteLength;if(u){if(u>t){u-=t;continue}r=r.subarray(u),t-=u,u=0}d.set(r,n),n+=t}return i&&(i-=a+3),{data:d,pts:o,dts:s,len:i}}return null}var zc=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=Nc(e,0);if(t!==this.pid){this.logger.debug(`Packet PID mismatch, expected ${this.pid} got ${t}`);return}let n=(e[3]&48)>>4;if(n===0)return;let r=e[3]&15,i=this.lastContinuityCounter;this.lastContinuityCounter=r;let a=!!(n&1);if(n&2&&e[4]!=0&&e[5]&128||i<0)return;let o=a?i+1&15:i;if(r!==o){this.logger.warn(`MPEG-TS Continuity Counter check failed for PID='${t}', CC=${r}, Expected-CC=${o} Last-CC=${i}`),this.integrityState=`cc-failed`;return}if(e[1]&128){this.logger.warn(`MPEG-TS Packet had TEI flag set for PID='${t}'`),this.integrityState=`tei-bit`;return}}},Bc=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||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])}}},Vc,Hc={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])},Uc=new Uint8Array([0,0,0,0,0,0,0,0]),Wc=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),Gc=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0]),Kc=new Uint8Array([0,0,0,0,0,0,0,0]),qc=new Uint8Array([0,0,0,0,0,0,0,1]),Jc=new Uint8Array([105,115,111,109]),Yc=new Uint8Array([97,118,99,49]),Xc=new Uint8Array([0,0,0,1]),Zc=class e{static box(e,...t){let n=8,r=t.length,i=r;for(;r--;)n+=t[r].byteLength;let a=new Uint8Array(n);for(Qn(a,0,n),Qn(a,4,e),r=0,n=8;r<i;r++)a.set(t[r],n),n+=t[r].byteLength;return a}static hdlr(t){return e.box(W.hdlr,Hc[t])}static mdat(t){return e.box(W.mdat,t)}static mdhd(t,n){n*=t;let r=Math.floor(n/(Kn+1)),i=Math.floor(n%(Kn+1));return e.box(W.mdhd,new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,t>>24&255,t>>16&255,t>>8&255,t&255,r>>24,r>>16&255,r>>8&255,r&255,i>>24,i>>16&255,i>>8&255,i&255,85,196,0,0]))}static mdia(t){return e.box(W.mdia,e.mdhd(t.timescale||0,t.duration||0),e.hdlr(t.type),e.minf(t))}static mfhd(t){return e.box(W.mfhd,new Uint8Array([0,0,0,0,t>>24,t>>16&255,t>>8&255,t&255]))}static minf(t){return t.type===`audio`?e.box(W.minf,e.box(W.smhd,Kc),e.DINF,e.stbl(t)):e.box(W.minf,e.box(W.vmhd,Gc),e.DINF,e.stbl(t))}static moof(t,n,r){return e.box(W.moof,e.mfhd(t),e.traf(r,n))}static moov(t){let n=t.length,r=[];for(;n--;)r[n]=e.trak(t[n]);return e.box.apply(null,[W.moov,e.mvhd(t[0].timescale||0,t[0].duration||0)].concat(r,e.mvex(t)))}static mvex(t){let n=t.length,r=[];for(;n--;)r[n]=e.trex(t[n]);return e.box.apply(null,[W.mvex,...r])}static mvhd(t,n){n*=t;let r=Math.floor(n/(Kn+1)),i=Math.floor(n%(Kn+1)),a=new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,t>>24&255,t>>16&255,t>>8&255,t&255,r>>24,r>>16&255,r>>8&255,r&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 e.box(W.mvhd,a)}static sdtp(t){let n=t.samples||[],r=new Uint8Array(4+n.length),i,a;for(i=0;i<n.length;i++)a=n[i].flags,r[i+4]=a.dependsOn<<4|a.isDependedOn<<2|a.hasRedundancy;return e.box(W.sdtp,r)}static stbl(t){return e.box(W.stbl,e.stsd(t),e.box(W.stts,Uc),e.box(W.stsc,Uc),e.box(W.stsz,Wc),e.box(W.stco,Uc))}static avc1(t){let n=[],r=[],i,a,o;for(i=0;i<t.sps.length;i++)a=t.sps[i],o=a.byteLength,n.push(o>>>8&255),n.push(o&255),n=n.concat(Array.prototype.slice.call(a));for(i=0;i<t.pps.length;i++)a=t.pps[i],o=a.byteLength,r.push(o>>>8&255),r.push(o&255),r=r.concat(Array.prototype.slice.call(a));let s=e.box(W.avcC,new Uint8Array([1,n[3],n[4],n[5],255,224|t.sps.length].concat(n,[t.pps.length],r))),c=t.width,l=t.height,u=t.pixelRatio[0],d=t.pixelRatio[1];return e.box(W.avc1,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,c>>8&255,c&255,l>>8&255,l&255,0,72,0,0,0,72,0,0,0,0,0,0,0,1,18,100,97,105,108,121,109,111,116,105,111,110,47,104,108,115,46,106,115,0,0,0,0,0,0,0,0,0,0,0,0,0,0,24,17,17]),s,e.box(W.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),e.box(W.pasp,new Uint8Array([u>>24,u>>16&255,u>>8&255,u&255,d>>24,d>>16&255,d>>8&255,d&255])))}static esds(e){let t=e.config,n=t.length;return new Uint8Array([0,0,0,0,3,23+n,0,1,0,4,15+n,64,21,0,0,0,0,0,0,0,0,0,0,0,5,n,...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(t){return e.box(W.mp4a,e.audioStsd(t),e.box(W.esds,e.esds(t)))}static mp3(t){return e.box(W[`.mp3`],e.audioStsd(t))}static ac3(t){return e.box(W[`ac-3`],e.audioStsd(t),e.box(W.dac3,t.config))}static stsd(t){let{segmentCodec:n}=t;if(t.type===`audio`){if(n===`aac`)return e.box(W.stsd,qc,e.mp4a(t));if(n===`ac3`&&t.config)return e.box(W.stsd,qc,e.ac3(t));if(n===`mp3`&&t.codec===`mp3`)return e.box(W.stsd,qc,e.mp3(t))}else if(t.pps&&t.sps){if(n===`avc`)return e.box(W.stsd,qc,e.avc1(t));if(n===`hevc`&&t.vps)return e.box(W.stsd,qc,e.hvc1(t))}else throw Error(`video track missing pps or sps`);throw Error(`unsupported ${t.type} segment codec (${n}/${t.codec})`)}static tkhd(t){let n=t.id,r=(t.duration||0)*(t.timescale||0),i=t.width||0,a=t.height||0,o=Math.floor(r/(Kn+1)),s=Math.floor(r%(Kn+1));return e.box(W.tkhd,new Uint8Array([1,0,0,7,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,n>>24&255,n>>16&255,n>>8&255,n&255,0,0,0,0,o>>24,o>>16&255,o>>8&255,o&255,s>>24,s>>16&255,s>>8&255,s&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,a>>8&255,a&255,0,0]))}static traf(t,n){let r=e.sdtp(t),i=t.id,a=Math.floor(n/(Kn+1)),o=Math.floor(n%(Kn+1));return e.box(W.traf,e.box(W.tfhd,new Uint8Array([0,0,0,0,i>>24,i>>16&255,i>>8&255,i&255])),e.box(W.tfdt,new Uint8Array([1,0,0,0,a>>24,a>>16&255,a>>8&255,a&255,o>>24,o>>16&255,o>>8&255,o&255])),e.trun(t,r.length+16+20+8+16+8+8),r)}static trak(t){return t.duration=t.duration||4294967295,e.box(W.trak,e.tkhd(t),e.mdia(t))}static trex(t){let n=t.id;return e.box(W.trex,new Uint8Array([0,0,0,0,n>>24,n>>16&255,n>>8&255,n&255,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,1]))}static trun(t,n){let r=t.samples||[],i=r.length,a=12+16*i,o=new Uint8Array(a),s,c,l,u,d,f;for(n+=8+a,o.set([+(t.type===`video`),0,15,1,i>>>24&255,i>>>16&255,i>>>8&255,i&255,n>>>24&255,n>>>16&255,n>>>8&255,n&255],0),s=0;s<i;s++)c=r[s],l=c.duration,u=c.size,d=c.flags,f=c.cts,o.set([l>>>24&255,l>>>16&255,l>>>8&255,l&255,u>>>24&255,u>>>16&255,u>>>8&255,u&255,d.isLeading<<2|d.dependsOn,d.isDependedOn<<6|d.hasRedundancy<<4|d.paddingValue<<1|d.isNonSync,d.degradPrio&61440,d.degradPrio&15,f>>>24&255,f>>>16&255,f>>>8&255,f&255],12+16*s);return e.box(W.trun,o)}static initSegment(t){let n=e.moov(t);return Tr(e.FTYP,n)}static hvc1(t){let n=t.params,r=[t.vps,t.sps,t.pps],i=new Uint8Array([1,n.general_profile_space<<6|(n.general_tier_flag?32:0)|n.general_profile_idc,n.general_profile_compatibility_flags[0],n.general_profile_compatibility_flags[1],n.general_profile_compatibility_flags[2],n.general_profile_compatibility_flags[3],n.general_constraint_indicator_flags[0],n.general_constraint_indicator_flags[1],n.general_constraint_indicator_flags[2],n.general_constraint_indicator_flags[3],n.general_constraint_indicator_flags[4],n.general_constraint_indicator_flags[5],n.general_level_idc,240|n.min_spatial_segmentation_idc>>8,255&n.min_spatial_segmentation_idc,252|n.parallelismType,252|n.chroma_format_idc,248|n.bit_depth_luma_minus8,248|n.bit_depth_chroma_minus8,0,parseInt(n.frame_rate.fps),3|n.temporal_id_nested<<2|n.num_temporal_layers<<3|(n.frame_rate.fixed?64:0),r.length]),a=i.length;for(let e=0;e<r.length;e+=1){a+=3;for(let t=0;t<r[e].length;t+=1)a+=2+r[e][t].length}let o=new Uint8Array(a);o.set(i,0),a=i.length;let s=r.length-1;for(let e=0;e<r.length;e+=1){o.set(new Uint8Array([32+e|(e===s?128:0),0,r[e].length]),a),a+=3;for(let t=0;t<r[e].length;t+=1)o.set(new Uint8Array([r[e][t].length>>8,r[e][t].length&255]),a),a+=2,o.set(r[e][t],a),a+=r[e][t].length}let c=e.box(W.hvcC,o),l=t.width,u=t.height,d=t.pixelRatio[0],f=t.pixelRatio[1];return e.box(W.hvc1,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,l>>8&255,l&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,e.box(W.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),e.box(W.pasp,new Uint8Array([d>>24,d>>16&255,d>>8&255,d&255,f>>24,f>>16&255,f>>8&255,f&255])))}};Vc=Zc,Zc.FTYP=Vc.box(W.ftyp,Jc,Xc,Jc,Yc),Zc.DINF=Vc.box(W.dinf,Vc.box(W.dref,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,12,117,114,108,32,0,0,0,1])));var Qc=9e4;function $c(e,t,n=1,r=!1){let i=e*t*n;return r?Math.round(i):i}function el(e,t,n=1,r=!1){return $c(e,t,1/n,r)}function tl(e,t=!1){return $c(e,1e3,1/Qc,t)}function nl(e,t=1){return $c(e,Qc,1/t)}function rl(e){let{baseTime:t,timescale:n,trackId:r}=e;return`${t/n} (${t}/${n}) trackId: ${r}`}var il=1e4,al=1024,ol=1152,sl=1536,cl=8589934592;function ll(e,t,n,r){return{duration:t,size:n,cts:r,flags:{isLeading:0,isDependedOn:0,hasRedundancy:0,degradPrio:0,dependsOn:e?2:1,isNonSync:+!e,paddingValue:0}}}var ul=class extends Xt{constructor(e,t,n,r){super(`mp4-remuxer`,r),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=n,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&&rl(t)} > ${e&&rl(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,n=e[0].pts,r=e.reduce((e,r)=>{let i=r.pts,a=i-e;return a<-4294967296&&(t=!0,i=dl(i,n),a=i-e),a>0?e:i},n);return t&&this.debug(`PTS rollover detected`),r}remux(e,t,n,r,i,a,o,s,c){let l,u,d,f,p,m,h=i,g=i,_=!c.iframe&&e.pid>-1,v=t.pid>-1,y=t.samples.length,b=e.samples.length>0,x=o&&y>0||y>1;if((!_||b)&&(!v||x)||this.ISGenerated||o){if(this.ISGenerated){let e=this.videoTrackConfig;(e&&(t.width!==e.width||t.height!==e.height||t.pixelRatio?.[0]!==e.pixelRatio?.[0]||t.pixelRatio?.[1]!==e.pixelRatio?.[1])||!e&&x||this.nextAudioTs===null&&b)&&this.resetInitSegment()}this.ISGenerated||(d=this.generateIS(e,t,i,a));let n=this.isVideoContiguous,r=-1,o;if(x&&(r=fl(t.samples),!n&&this.config.forceKeyFrameOnDiscontinuity)){if(m=!0,r>0){this.warn(`Dropped ${r} out of ${y} video samples due to a missing keyframe`);let e=this.getVideoStartPts(t.samples);t.samples=t.samples.slice(r),t.dropped+=r,g+=(t.samples[0].pts-e)/t.inputTimeScale,o=g}else r===-1&&(this.warn(`No keyframe found out of ${y} video samples`),m=!1)}if(this.ISGenerated){if(b&&x&&i){let n=this.getVideoStartPts(t.samples),r=(dl(e.samples[0].pts,n)-n)/t.inputTimeScale;h+=Math.max(0,r),g+=Math.max(0,-r)}if(b){if(e.samplerate||(this.warn(`regenerate InitSegment as audio detected`),d=this.generateIS(e,t,i,a)),u=this.remuxAudio(e,h,this.isAudioContiguous,a,v||x||s===z.AUDIO?g:void 0,c),x){let r=u?u.endPTS-u.startPTS:0;t.inputTimeScale||(this.warn(`regenerate InitSegment as video detected`),d=this.generateIS(e,t,i,a)),l=this.remuxVideo(t,g,n,r,c)}}else x&&(l=this.remuxVideo(t,g,n,0,c));l&&(l.firstKeyFrame=r,l.independent=r!==-1,l.firstKeyFramePTS=o)}}return this.ISGenerated&&this._initPTS&&this._initDTS&&(n.samples.length&&(p=pl(n,i,this._initPTS,this._initDTS)),r.samples.length&&(f=ml(r,i,this._initPTS))),{audio:u,video:l,initSegment:d,independent:m,text:f,id3:p}}computeInitPts(e,t,n,r){let i=Math.round(n*t),a=dl(e,i);if(a<i)for(this.log(`Adjusting PTS for rollover in timeline near ${(i-a)/t} ${r}`);a<i;)a+=cl;return a-i}generateIS(e,t,n,r){let i=e.samples,a=t.samples,o=this.typeSupported,s={},c=this._initPTS,l=!c||r,u=`audio/mp4`,d,f,p,m=-1;if(l&&(d=f=1/0),e.config&&i.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`}if(s.audio={id:`audio`,container:u,codec:e.codec,initSegment:e.segmentCodec===`mp3`&&o.mpeg?new Uint8Array:Zc.initSegment([e]),metadata:{channelCount:e.channelCount}},l){m=e.id,p=e.inputTimeScale;let t=this.computeInitPts(i[0].pts,p,n,`audio`);(!c||p!==c.timescale||n===0&&t<c.baseTime)&&(d=f=t)}}if(t.sps&&t.pps&&a.length){if(t.timescale=t.inputTimeScale,s.video={id:`main`,container:`video/mp4`,codec:t.codec,initSegment:Zc.initSegment([t]),metadata:{width:t.width,height:t.height}},l){m=t.id,p=t.inputTimeScale;let e=this.getVideoStartPts(a),r=dl(a[0].dts,e),i=this.computeInitPts(r,p,n,`video`),o=this.computeInitPts(e,p,n,`video`);if(!c||p!==c.timescale||P(d)||n===0&&o<c.baseTime){f=Math.min(f,i);let e=!c&&this.isVideoContiguous?o:i;d=Math.min(d,e)}}this.videoTrackConfig={width:t.width,height:t.height,pixelRatio:t.pixelRatio}}if(Object.keys(s).length)return this.ISGenerated=!0,l&&P(d)?(c&&this.warn(`Timestamps at playlist time: ${r?``:`~`}${n} ${d/p} != initPTS: ${c.baseTime/c.timescale} (${c.baseTime}/${c.timescale}) trackId: ${c.trackId}`),this.log(`Found initPTS at playlist time: ${n} offset: ${d/p} (${d}/${p}) trackId: ${m}`),this._initPTS={baseTime:d,timescale:p,trackId:m},this._initDTS={baseTime:f,timescale:p,trackId:m}):d=p=void 0,{tracks:s,initPTS:d,timescale:p,trackId:m}}remuxVideo(e,t,n,r,i){let a=e.inputTimeScale,o=e.samples,s=[],c=o.length,l=this._initPTS,u=l.baseTime*a/l.timescale,d=this.nextVideoTs,f=8,p=this.videoSampleDuration,m,h,g=1/0,_=-1/0,v=!1;if(!n||d===null){let e=u+t*a,r=o[0].pts-dl(o[0].dts,o[0].pts);Wr()&&d!==null&&Math.abs(e-r-(d+u))<15e3?n=!0:d=e-r-u}let y=d+u;for(let e=0;e<c;e++){let t=o[e];t.pts=dl(t.pts,y),t.dts=dl(t.dts,y),t.dts<o[e>0?e-1:e].dts&&(v=!0)}v&&o.sort(function(e,t){let n=e.dts-t.dts,r=e.pts-t.pts;return n||r}),m=o[0].dts,h=o[o.length-1].dts;let b=h-m,x=b?Math.round(b/(c-1)):p||e.inputTimeScale/30;if(n){let n=m-y,r=n>x,i=n<-1;if((r||i)&&(r?this.warn(`${(e.segmentCodec||``).toUpperCase()}: ${tl(n,!0)} ms (${n}dts) hole between fragments detected at ${t.toFixed(3)}`):this.warn(`${(e.segmentCodec||``).toUpperCase()}: ${tl(-n,!0)} ms (${n}dts) overlapping between fragments detected at ${t.toFixed(3)}`),!i||y>=o[0].pts||Wr())){m=y;let e=o[0].pts-n;if(r)o[0].dts=m,o[0].pts=e;else{let t=!0;for(let r=0;r<o.length&&!(o[r].dts>e&&t);r++){let e=o[r].pts;if(o[r].dts-=n,o[r].pts-=n,r<o.length-1){let n=o[r+1].pts;t=n<=o[r].pts==n<=e}}}this.log(`Video: Initial PTS/DTS adjusted: ${tl(e,!0)}/${tl(m,!0)}, delta: ${tl(n,!0)} ms`)}}m=Math.max(0,m);let S=0,C=0,w=m;for(let e=0;e<c;e++){let t=o[e],n=t.units,r=n.length,i=0;for(let e=0;e<r;e++)i+=n[e].data.length;C+=i,S+=r,t.length=i,t.dts<w?(t.dts=w,w+=x/4|0||1):w=t.dts,g=Math.min(t.pts,g),_=Math.max(t.pts,_)}h=o[c-1].dts;let T=C+4*S+8,E;try{E=new Uint8Array(T)}catch(e){this.observer.emit(L.ERROR,L.ERROR,{type:F.MUX_ERROR,details:I.REMUX_ALLOC_ERROR,fatal:!1,chunkMeta:i,error:e,bytes:T,reason:`fail allocating video mdat ${T}`});return}Qn(E,0,T),Qn(E,4,W.mdat);let D=!1,O=1/0,k=1/0,A=-1/0,j=-1/0;for(let e=0;e<c;e++){let t=o[e],l=t.units,d=0;for(let e=0,t=l.length;e<t;e++){let t=l[e],n=t.data,r=t.data.byteLength;Qn(E,f,r),f+=4,E.set(n,f),f+=r,d+=4+r}let m;if(e<c-1)p=o[e+1].dts-t.dts,m=o[e+1].pts-t.pts;else{let n=this.config,i=e>0?t.dts-o[e-1].dts:x;if(m=e>0?t.pts-o[e-1].pts:x,n.stretchShortVideoTrack&&this.nextAudioTs!==null){let e=Math.floor(n.maxBufferHole*a),o=(r?g+r*a:this.nextAudioTs+u)-t.pts;o>e?(p=o-i,p<0?p=i:D=!0,this.log(`It is approximately ${o/90} ms to the next segment; using duration ${p/90} ms for the last video frame.`)):p=i}else p=i}let h=Math.round(t.pts-t.dts);if(O=Math.min(O,p),A=Math.max(A,p),k=Math.min(k,m),j=Math.max(j,m),!n&&e===0&&h>p){let e=Math.round(h/x)*x;e-h===1&&(this.log(`pad first CTS ${h} -> ${e} of sn: ${i.sn}`),h=e)}s.push(ll(t.key,p,d,h))}if(s.length){let e=Wr();if(e){if(e<70){let e=s[0].flags;e.dependsOn=2,e.isNonSync=0}}else if(Ur()&&j-k<A-O&&x/A<.025&&s[0].cts===0){this.warn(`Found irregular gaps in sample duration. Using PTS instead of DTS to determine MP4 sample duration.`);let e=m;for(let t=0,n=s.length;t<n;t++){let r=e+s[t].duration,i=e+s[t].cts;if(t<n-1){let e=r+s[t+1].cts;s[t].duration=e-i}else s[t].duration=t?s[t-1].duration:x;s[t].cts=0,e=r}}}p=D||!p?x:p;let M=h+p;this.nextVideoTs=d=M-u,this.videoSampleDuration=p,this.isVideoContiguous=!0,i.iframe&&(s.length===1?(s[0].duration=p=i.duration*a,this.nextVideoTs=d=m+p-u):this.warn(`Not adjusting IFrame duration (sample count ${s.length})`));let N={data1:Zc.moof(i.sn,m,V(e,{samples:s})),data2:E,startPTS:(g-u)/a,endPTS:(_+p-u)/a,startDTS:(m-u)/a,endDTS:d/a,type:`video`,hasAudio:!1,hasVideo:!0,nb:s.length,dropped:e.dropped};return e.samples=[],e.dropped=0,N}getSamplesPerFrame(e){switch(e.segmentCodec){case`mp3`:return ol;case`ac3`:return sl;default:return al}}remuxAudio(e,t,n,r,i,a){let o=e.inputTimeScale,s=o/(e.samplerate?e.samplerate:o),c=this.getSamplesPerFrame(e),l=c*s,u=this._initPTS,d=e.segmentCodec===`mp3`&&this.typeSupported.mpeg,f=[],p=i!==void 0,m=e.samples,h=d?0:8,g=this.nextAudioTs||-1,_=u.baseTime*o/u.timescale,v=_+t*o;if(this.isAudioContiguous=n||=m.length&&g>0&&(r&&Math.abs(v-(g+_))<9e3||Math.abs(dl(m[0].pts,v)-(g+_))<20*l),m.forEach(function(e){e.pts=dl(e.pts,v)}),!n||g<0){let e=m.length;if(m=m.filter(e=>e.pts>=0),e!==m.length&&this.warn(`Removed ${m.length-e} of ${e} samples (initPTS ${_} / ${o})`),!m.length)return;g=i===0?0:r&&!p?Math.max(0,v-_):m[0].pts-_}if(e.segmentCodec===`aac`){let t=this.config.maxAudioFramesDrift;for(let n=0,r=g+_;n<m.length;n++){let i=m[n],a=i.pts,s=a-r,c=Math.abs(1e3*s/o);if(s<=-t*l&&p)n===0&&(this.warn(`Audio frame @ ${(a/o).toFixed(3)}s overlaps marker by ${Math.round(1e3*s/o)} ms.`),this.nextAudioTs=g=a-_,r=a);else if(s>=t*l&&c<il&&p){let t=Math.round(s/l);for(r=a-t*l;r<_&&t&&l;)t--,r+=l;n===0&&(this.nextAudioTs=g=r-_),this.warn(`Injecting ${t} audio frames @ ${((r-_)/o).toFixed(3)}s due to ${Math.round(1e3*s/o)} ms gap.`);for(let a=0;a<t;a++){let t=Bc.getSilentFrame(e.parsedCodec||e.manifestCodec||e.codec,e.channelCount);t||=(this.log(`Unable to get silent frame for given audio codec; duplicating last frame instead.`),i.unit.subarray()),m.splice(n,0,{unit:t,pts:r}),r+=l,n++}}i.pts=r,r+=l}}let y=null,b=null,x,S=0,C=m.length;for(;C--;)S+=m[C].unit.byteLength;for(let t=0,r=m.length;t<r;t++){let r=m[t],i=r.unit,o=r.pts;if(b!==null){let e=f[t-1];e.duration=Math.round((o-b)/s)}else if(n&&e.segmentCodec===`aac`&&(o=g+_),y=o,S>0){S+=h;try{x=new Uint8Array(S)}catch(e){this.observer.emit(L.ERROR,L.ERROR,{type:F.MUX_ERROR,details:I.REMUX_ALLOC_ERROR,fatal:!1,chunkMeta:a,error:e,bytes:S,reason:`fail allocating audio mdat ${S}`});return}d||(Qn(x,0,S),Qn(x,4,W.mdat))}else return;x&&x.set(i,h);let l=i.byteLength;h+=l,f.push(ll(!0,c,l,0)),b=o}let w=f.length;if(!w)return;let T=f[f.length-1];g=b-_,this.nextAudioTs=g+s*T.duration;let E=d?new Uint8Array:Zc.moof(e.sequenceNumber++,y/s,V({},e,{samples:f}));e.samples=[];let D=(y-_)/o,O=this.nextAudioTs/o,k={data1:E,data2:x,startPTS:D,endPTS:O,startDTS:D,endDTS:O,type:`audio`,hasAudio:!0,hasVideo:!1,nb:w};return this.isAudioContiguous=!0,k}};function dl(e,t){let n;if(t===null)return e;for(n=t<e?-8589934592:cl;Math.abs(e-t)>4294967296;)e+=n;return e}function fl(e){for(let t=0;t<e.length;t++)if(e[t].key)return t;return-1}function pl(e,t,n,r){let i=e.samples.length;if(!i)return;let a=e.inputTimeScale;for(let o=0;o<i;o++){let i=e.samples[o];i.pts=dl(i.pts-n.baseTime*a/n.timescale,t*a)/a,i.dts=dl(i.dts-r.baseTime*a/r.timescale,t*a)/a}let o=e.samples;return e.samples=[],{samples:o}}function ml(e,t,n){let r=e.samples.length;if(!r)return;let i=e.inputTimeScale;for(let a=0;a<r;a++){let r=e.samples[a];r.pts=dl(r.pts-n.baseTime*i/n.timescale,t*i)/i}e.samples.sort((e,t)=>e.pts-t.pts);let a=e.samples;return e.samples=[],{samples:a}}var hl=class extends Xt{constructor(e,t,n,r){super(`passthrough-remuxer`,r),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,n,r){this.audioCodec=t,this.videoCodec=n,this.decryptdata=r,this.pendingInitSegment=e,this.videoOnlyRemux=!1,this.initTracks=void 0,this.initData=void 0,this.emitInitSegment=!0}generateInitSegment(e,t,n){this.videoOnlyRemux=!1;let{audioCodec:r,videoCodec:i}=this;if(!(e!=null&&e.byteLength)){this.initTracks=void 0,this.initData=void 0;return}let{audio:a,video:o}=this.initData=n||sr(e);if(t)mr(e,t);else{let e=a||o;e!=null&&e.encrypted&&this.warn(`Init segment with encrypted track with has no key ("${e.codec}")!`)}a&&(r=bl(a,B.AUDIO,this)),o&&(i=bl(o,B.VIDEO,this));let s={};a&&o?s.audiovideo={container:`video/mp4`,codec:r+`,`+i,supplemental:o.supplemental,encrypted:o.encrypted,initSegment:e,id:`main`}:a?s.audio={container:`audio/mp4`,codec:r,encrypted:a.encrypted,initSegment:e,id:`audio`}:o?s.video={container:`video/mp4`,codec:i,supplemental:o.supplemental,encrypted:o.encrypted,initSegment:e,id:`main`}:this.warn(`initSegment does not contain moov or trak boxes.`),this.initTracks=s}remux(e,t,n,r,i,a,o,s,c,l,u){var d,f;let{initPTS:p,lastEndTime:m}=this,h={audio:void 0,video:void 0,text:void 0,id3:n,initSegment:void 0};P(m)||(m=this.lastEndTime=i||0);let g=t.samples;if(!g.length)return h;let _=this.pendingInitSegment;_&&(this.pendingInitSegment=void 0,this.generateInitSegment(_,this.decryptdata,l));let v={initPTS:void 0,timescale:void 0,trackId:void 0},y=this.initData;if((d=y)!=null&&d.length||(this.generateInitSegment(g),y=this.initData),!((f=y)!=null&&f.length))return this.warn(`Failed to generate initSegment.`),h;if(c.iframe&&y.audio&&y.video){var b;let e=(b=this.initTracks)==null||(b=b.audiovideo)==null?void 0:b.initSegment,t=e?nr(e):null;if(t){var x;this.log(`Converted muxed init segment to video-only for I-Frame playback`),this.generateInitSegment(t,this.decryptdata),(x=this.initData)!=null&&x.length&&(y=this.initData,this.emitInitSegment=!0,this.videoOnlyRemux=!0)}}this.emitInitSegment&&=(v.tracks=this.initTracks,h.initSegment=v,!1);let S=c.iframe,C=u&&(!S||u.includeSampleDetails)?u.tracks:xr(g,y,c,this,S),w=y.audio?C[y.audio.id]:null,T=y.video?C[y.video.id]:null,E=!!y.audio,D=!!y.video,O=``;E&&(O+=`audio`),D&&(O+=`video`);let k=gl(T,1/0),A=gl(w,1/0),j=gl(T,0,!0),M=gl(w,0,!0),N=i,ee=0;T&&w&&y.audio&&(A>j||k>M)&&this.warn(`audio and video track sample timestamps do not overlap. v: ${k}-${j} a: ${A}-${M}}`,T,w);let te=!!w&&(!T||!p&&A<k||!!p&&p.trackId===y.audio.id),ne=te?w:T;if(!ne)return this.log(`No media samples found in ${s} ${c.level} ${c.part===-1?``:`part: ${c.part} of`} sn: ${c.sn} at playlist time: ${i}`),h;let re=g,ie,ae;if(T&&T.sampleCount>=1&&y.video&&c.iframe){let{trun:e,start:t}=T,n=e.length===1,r=e.length?n?e[0].samples:e[0].samples.concat(...e.slice(1).map(e=>e.samples)):[];if(r.length){let i=e[0],a=i;for(let t=e.length;t--;)if(e[t].samples.length){a=e[t];break}let o=a.lastSampleDurationOffset,{defaultSampleDurationOffset:s}=i,l=Math.abs(c.duration-(j-k))>.05,u=r.length<T.sampleCount;if(!(l||u||this.videoOnlyRemux||!n))ee=j-k;else{let e=u?a.sampleOffset+a.samples.reduce((e,t)=>e+t.size,0):void 0,n=l?c.duration:j-k,i=vl(r,n*y.video.timescale,o,s),d=rr(g,y.video.id,r.length,e,i);d?(re=d,ae=_l(t,r)):this.warn(`IFrame remux skipped (sn ${c.sn}); using native sample duration`),ee=d&&i?n:j-k}}else this.warn(`Could not remux IFrame track fragment (no samples in range, trun count ${e.length})`),ee=j-k}else ee=te?M-A:j-k;if(this.videoOnlyRemux&&re===g)return this.warn(`Dropping muxed I-Frame fragment that could not be remuxed to video-only (sn: ${c.sn})`),h;let oe=ne.timescale,se=ne.start-i*oe,ce=te?y.audio.id:y.video.id;if(N=ne.start/oe,!(p&&c.id>1)&&(a||!p)&&(yl(p,N,i,ee)||oe!==p.timescale)){let e=!1,t=te?`audio`:`video`;if(p){let n=i===0?1+N/1:N/i;e=N>=0&&Math.abs(1-n)<.001,this.log(`${t} timestamps in track ${ce} at playlist time: ${a?``:`~`}${i} maps to ${N} with initPTS: ${p.baseTime/p.timescale} (${se/oe-p.baseTime/p.timescale}s diff) (${O}) drift estimate: ${n} ${e?`(ignoring drift)`:`remapping timestamps (initPTS)`}`)}e||(this.log(`Found initPTS in ${t} track ${ce} at playlist time: ${i} offset: ${N-i} (${se}/${oe})`),p=null,v.initPTS=se,v.timescale=oe,v.trackId=ce)}p?(v.initPTS=p.baseTime,v.timescale=p.timescale,v.trackId=p.trackId):((!v.timescale||v.trackId===void 0||v.initPTS===void 0)&&(this.warn(`Could not set initPTS`),v.initPTS=N,v.timescale=1,v.trackId=-1),this.initPTS=p={baseTime:v.initPTS,timescale:v.timescale,trackId:v.trackId});let le=N-p.baseTime/p.timescale,ue=le+ee,de=D&&ne?.ptsMin!==void 0?ne.ptsMin/ne.timescale-p.baseTime/p.timescale:le,fe=ae!==void 0&&T?ae/T.timescale-p.baseTime/p.timescale:D&&ne!=null&&ne.ptsMax?ne.ptsMax/ne.timescale-p.baseTime/p.timescale:ue;ee>0?this.lastEndTime=ue:(this.warn(`Duration parsed from mp4 should be greater than zero`),this.resetNextTimestamp());let pe=(y.audio?y.audio.encrypted:!1)||(y.video?y.video.encrypted:!1),me={data1:re,data2:ie,startPTS:de,startDTS:le,endPTS:fe,endDTS:ue,type:O,hasAudio:E,hasVideo:D,nb:1,dropped:0,encrypted:pe};h.audio=E&&!D?me:void 0,h.video=D?me:void 0;let he=this.isVideoContiguous,ge=T?.sampleCount;if(ge){let e=T.keyFrameIndex,t=e!==-1;me.nb=ge,me.dropped=e===0||he?0:t?e:ge,me.independent=t,me.firstKeyFrame=e,t&&T.keyFrameStart&&(me.firstKeyFramePTS=(T.keyFrameStart-p.baseTime)/p.timescale),he||(h.independent=t),this.isVideoContiguous||=t,me.dropped&&this.warn(`fmp4 does not start with IDR: firstIDR ${e}/${ge} dropped: ${me.dropped} start: ${me.firstKeyFramePTS||`NA`}`)}return h.initSegment=v,h.id3=pl(n,i,p,p),r.samples.length&&(h.text=ml(r,i,p)),h}};function gl(e,t,n=!1){return e?.start===void 0?t:(e.start+(n?e.duration:0))/e.timescale}function _l(e,t){let n=e,r=e;for(let e=0;e<t.length;e++){let{cts:i,duration:a}=t[e];r=Math.max(r,n+(i||0)+a),n+=a}return r}function vl(e,t,n,r){if(n!==void 0){let r=e[e.length-1],i=t;for(let t=0;t<e.length-1;t++)i-=e[t].duration;return i<=0&&(i=r.duration),r.duration=i,{durationOffset:n,value:i}}if(r===void 0)return;let i=Math.round(t/e.length);for(let t=0;t<e.length;t++)e[t].duration=i;return{durationOffset:r,value:i}}function yl(e,t,n,r){if(e===null)return!0;let i=Math.max(r,1),a=t-e.baseTime/e.timescale;return Math.abs(a-n)>=i}function bl(e,t,n){let r=e.codec;return r&&r.length>4?r:t===B.AUDIO?r===`ec-3`||r===`ac-3`||r===`alac`?r:r===`fLaC`||r===`Opus`?ai(r,!1):(n.warn(`Unhandled audio codec "${r}" in mp4 MAP`),r||`mp4a`):r===`mjpg`?r:(n.warn(`Unhandled video codec "${r}" in mp4 MAP`),r||`avc1`)}var xl;try{xl=self.performance.now.bind(self.performance)}catch{xl=Date.now}var Sl=[{demux:xc,remux:hl},{demux:Mc,remux:ul},{demux:hc,remux:ul},{demux:yc,remux:ul}];Sl.splice(2,0,{demux:_c,remux:ul});var Cl=class{constructor(e,t,n,r,i,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=n,this.id=i,this.logger=a}configure(e){this.transmuxConfig=e,this.decrypter&&this.decrypter.reset()}push(e,t,n,r){if(!this.observer)return Tl(n);let i=n.transmuxing;i.executeStart=xl();let a=new Uint8Array(e),{currentTransmuxState:o,transmuxConfig:s}=this;r&&(this.currentTransmuxState=r);let{contiguous:c,discontinuity:l,trackSwitch:u,accurateTimeOffset:d,timeOffset:f,initSegmentChange:p}=r||o,{audioCodec:m,videoCodec:h,defaultInitPts:g,duration:_,initSegmentData:v}=s,y=wl(a,t);if(y&&ho(y.method)){let e=this.getDecrypter(),t=go(y.method);return this.asyncResult=!0,this.decryptionPromise=e.decrypt(a,y.key.buffer,y.iv.buffer,t,n.decryptRange).then(e=>{let t=this.push(e,null,n);return this.decryptionPromise=null,t}),this.decryptionPromise}let b=this.needsProbing(l,u);if(b){let e=n.iframe&&v&&Mc.probe(v,this.logger)?v:a,t=this.configureTransmuxer(e);if(t)return this.logger.warn(`[transmuxer] ${t.message}`),this.observer.emit(L.ERROR,L.ERROR,{type:F.MEDIA_ERROR,details:I.FRAG_PARSING_ERROR,fatal:!1,error:t,reason:t.message}),i.executeEnd=xl(),Tl(n)}(l||u||p||b)&&this.resetInitSegment(v,m,h,_,t,n),(l||p||b)&&this.resetInitialTimestamp(g),c||this.resetContiguity();let x=this.transmux(a,y,f,d,n);this.asyncResult=El(x);let S=this.currentTransmuxState;return S.contiguous=!0,S.discontinuity=!1,S.trackSwitch=!1,i.executeEnd=xl(),x}flush(e){let t=e.transmuxing;t.executeStart=xl();let{decrypter:n,currentTransmuxState:r,decryptionPromise:i}=this;if(i)return this.asyncResult=!0,i.then(()=>this.flush(e));let a=[],{timeOffset:o}=r;if(n){let t=n.flush();t&&a.push(this.push(t.buffer,null,e))}let{demuxer:s,remuxer:c}=this;if(!s||!c){t.executeEnd=xl();let n=[Tl(e)];return this.asyncResult?Promise.resolve(n):n}let l=s.flush(o,e);return El(l)?(this.asyncResult=!0,l.then(t=>(this.flushRemux(a,t,e),a))):(this.flushRemux(a,l,e),this.asyncResult?Promise.resolve(a):a)}flushRemux(e,t,n){if(!this.remuxer)return;let{audioTrack:r,videoTrack:i,id3Track:a,textTrack:o}=t,{accurateTimeOffset:s,timeOffset:c}=this.currentTransmuxState;this.logger.log(`[transmuxer.ts]: Flushed ${this.id} sn: ${n.sn}${n.part>-1?` part: `+n.part:``} of ${this.id} playlist ${n.level}`);let l=this.remuxer.remux(r,i,a,o,c,s,!0,this.id,n,t.initData,t.sampleData);e.push({remuxResult:l,chunkMeta:n}),n.transmuxing.executeEnd=xl()}resetInitialTimestamp(e){let{demuxer:t,remuxer:n}=this;t&&n&&(t.resetTimeStamp(e),n.resetTimeStamp(e))}resetContiguity(){let{demuxer:e,remuxer:t}=this;e&&t&&(e.resetContiguity(),t.resetNextTimestamp())}resetInitSegment(e,t,n,r,i,a){let{demuxer:o,remuxer:s}=this;o&&s&&(o.resetInitSegment(e,t,n,r,i,a),s.resetInitSegment(e,t,n,i))}destroy(){this.demuxer&&=(this.demuxer.destroy(),void 0),this.remuxer&&=(this.remuxer.destroy(),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,n,r,i){let a;return a=t?.method===`SAMPLE-AES`?this.transmuxSampleAes(e,t,n,r,i):this.transmuxUnencrypted(e,n,r,i),a}transmuxUnencrypted(e,t,n,r){let{demuxer:i,remuxer:a}=this;if(!i||!a)return Tl(r);let o=i.demux(e,t,r,!1,!this.config.progressive),{audioTrack:s,videoTrack:c,id3Track:l,textTrack:u}=o;return{remuxResult:a.remux(s,c,l,u,t,n,!1,this.id,r,o.initData,o.sampleData),chunkMeta:r}}transmuxSampleAes(e,t,n,r,i){return this.demuxer?this.demuxer.demuxSampleAes(e,t,n,i).then(e=>({remuxResult:this.remuxer.remux(e.audioTrack,e.videoTrack,e.id3Track,e.textTrack,n,r,!1,this.id,i,e.initData,e.sampleData),chunkMeta:i})):Promise.reject(Error(`no demuxer`))}configureTransmuxer(e){let{config:t,observer:n,typeSupported:r}=this;if(!n)return;let i;try{for(let t=0,n=Sl.length;t<n;t++){var a;if((a=Sl[t].demux)!=null&&a.probe(e,this.logger)){i=Sl[t];break}}}catch(e){return e}if(!i)return Error(`Failed to find demuxer by probing fragment data`);let o=this.demuxer,s=this.remuxer,c=i.demux,l=i.remux;(!o||!(o instanceof c))&&(this.logger.log(`Using ${c.name}`),this.demuxer=new c(n,t,r,this.logger),this.probe=c.probe),(!s||!(s instanceof l))&&(this.logger.log(`Using ${l.name}`),this.remuxer=new l(n,t,r,this.logger))}needsProbing(e,t){return!this.demuxer||!this.remuxer||e||t}getDecrypter(){let e=this.decrypter;return e||=this.decrypter=new Ua(this.config),e}};function wl(e,t){let n=null;return e.byteLength>0&&t?.key!=null&&t.iv!==null&&t.method!=null&&(n=t),n}var Tl=e=>({remuxResult:{},chunkMeta:e});function El(e){return`then`in e&&e.then instanceof Function}var Dl=class{constructor(e,t,n,r,i){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=n,this.duration=r,this.defaultInitPts=i||null}},Ol=class{constructor(e,t,n,r,i,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=n,this.trackSwitch=r,this.timeOffset=i,this.initSegmentChange=a}},kl=0,Al=class{constructor(e,t,n,r){this.error=null,this.hls=void 0,this.id=void 0,this.instanceNo=kl++,this.observer=void 0,this.frag=null,this.part=null,this.useWorker=void 0,this.workerContext=null,this.transmuxer=null,this.onTransmuxComplete=void 0,this.onFlush=void 0,this.onWorkerMessage=e=>{let t=e.data,n=this.hls;if(n&&t!=null&&t.event&&t.instanceNo===this.instanceNo)switch(t.event){case`init`:{let e=this.workerContext?.objectURL;e&&self.URL.revokeObjectURL(e);break}case`transmuxComplete`:this.handleTransmuxComplete(t.data);break;case`flush`:this.onFlush(t.data);break;case`workerLog`:n.logger[t.data.logType]&&n.logger[t.data.logType](t.data.message);break;default:t.data=t.data||{},t.data.frag=this.frag,t.data.part=this.part,t.data.id=this.id,n.trigger(t.event,t.data)}},this.onWorkerError=e=>{if(!this.hls)return;let t=Error(`${e.message} (${e.filename}:${e.lineno})`);this.hls.config.enableWorker=!1,this.hls.logger.warn(`Error in "${this.id}" Web Worker, fallback to inline`),this.hls.trigger(L.ERROR,{type:F.OTHER_ERROR,details:I.INTERNAL_EXCEPTION,fatal:!1,event:`demuxerWorker`,error:t})};let i=e.config;this.hls=e,this.id=t,this.useWorker=!!i.enableWorker,this.onTransmuxComplete=n,this.onFlush=r;let a=(e,t)=>{t||={},t.frag=this.frag||void 0,e===L.ERROR&&(t=t,t.parent=this.id,t.part=this.part,this.error=t.error),this.hls.trigger(e,t)};this.observer=new Fs,this.observer.on(L.FRAG_DECRYPTED,a),this.observer.on(L.ERROR,a);let o=di(i.preferManagedMediaSource);if(this.useWorker&&typeof Worker<`u`){let n=this.hls.logger;if(i.workerPath||Rs()){try{i.workerPath?(n.log(`loading Web Worker ${i.workerPath} for "${t}"`),this.workerContext=Bs(i.workerPath)):(n.log(`injecting Web Worker for "${t}"`),this.workerContext=zs());let{worker:e}=this.workerContext;e.addEventListener(`message`,this.onWorkerMessage),e.addEventListener(`error`,this.onWorkerError),e.postMessage({instanceNo:this.instanceNo,cmd:`init`,typeSupported:o,id:t,config:q(i)})}catch(r){n.warn(`Error setting up "${t}" Web Worker, fallback to inline`,r),this.terminateWorker(),this.error=null,this.transmuxer=new Cl(this.observer,o,i,``,t,e.logger)}return}}this.transmuxer=new Cl(this.observer,o,i,``,t,e.logger)}reset(){if(this.frag=null,this.part=null,this.workerContext){let e=this.instanceNo;this.instanceNo=kl++;let t=this.hls.config,n=di(t.preferManagedMediaSource);this.workerContext.worker.postMessage({instanceNo:this.instanceNo,cmd:`reset`,resetNo:e,typeSupported:n,id:this.id,config:q(t)})}}terminateWorker(){if(this.workerContext){let{worker:e}=this.workerContext;this.workerContext=null,e.removeEventListener(`message`,this.onWorkerMessage),e.removeEventListener(`error`,this.onWorkerError),Vs(this.hls.config.workerPath)}}destroy(){if(this.workerContext)this.terminateWorker(),this.onWorkerMessage=this.onWorkerError=null;else{let e=this.transmuxer;e&&(e.destroy(),this.transmuxer=null)}let e=this.observer;e&&e.removeAllListeners(),this.frag=null,this.part=null,this.observer=null,this.hls=null}push(e,t,n,r,i,a,o,s,c,l){c.transmuxing.start=self.performance.now();let{instanceNo:u,transmuxer:d}=this,f=a?a.start:i.start,p=i.decryptdata,m=this.frag,h=!m||i.cc!==m.cc,g=!m||c.level!==m.level,_=m?c.sn-m.sn:-1,v=this.part?c.part-this.part.index:-1,y=_===0&&c.id>1&&c.id===m?.stats.chunkCount,b=!g&&(_===1||_===0&&(v===1||y&&v<=0)),x=self.performance.now();(g||_||i.stats.parsing.start===0)&&(i.stats.parsing.start=x),a&&(v||!b)&&(a.stats.parsing.start=x);let S=!(m&&i.initSegment?.url===m.initSegment?.url),C=new Ol(h,b,s,g,f,S);if(!b||h||S){this.hls.logger.log(`[transmuxer-interface]: Starting new transmux session for ${i.type} sn: ${c.sn}${c.part>-1?` part: `+c.part:``} ${this.id} playlist: ${c.level} id: ${c.id}
|
|
24
24
|
discontinuity: ${h}
|
|
25
25
|
trackSwitch: ${g}
|
|
26
26
|
contiguous: ${b}
|
|
27
27
|
accurateTimeOffset: ${s}
|
|
28
28
|
timeOffset: ${f}
|
|
29
|
-
initSegmentChange: ${S}`);let e=new El(n,r,t,o,l);this.configureTransmuxer(e)}if(this.frag=i,this.part=a,this.workerContext)this.workerContext.worker.postMessage({instanceNo:u,cmd:`demux`,data:e,decryptdata:p,chunkMeta:c,state:C},e instanceof ArrayBuffer?[e]:[]);else if(d){let t=d.push(e,p,c,C);Tl(t)?t.then(e=>{this.handleTransmuxComplete(e)}).catch(e=>{this.transmuxerError(e,c,`transmuxer-interface push error`)}):this.handleTransmuxComplete(t)}}flush(e){e.transmuxing.start=self.performance.now();let{instanceNo:t,transmuxer:n}=this;if(this.workerContext)this.workerContext.worker.postMessage({instanceNo:t,cmd:`flush`,chunkMeta:e});else if(n){let t=n.flush(e);Tl(t)?t.then(t=>{this.handleFlushResult(t,e)}).catch(t=>{this.transmuxerError(t,e,`transmuxer-interface flush error`)}):this.handleFlushResult(t,e)}}transmuxerError(e,t,n){this.hls&&(this.error=e,this.hls.trigger(L.ERROR,{type:F.MEDIA_ERROR,details:I.FRAG_PARSING_ERROR,chunkMeta:t,frag:this.frag||void 0,part:this.part||void 0,fatal:!1,error:e,err:e,reason:n}))}handleFlushResult(e,t){e.forEach(e=>{this.handleTransmuxComplete(e)}),this.onFlush(t)}configureTransmuxer(e){let{instanceNo:t,transmuxer:n}=this;this.workerContext?this.workerContext.worker.postMessage({instanceNo:t,cmd:`configure`,config:e}):n&&n.configure(e)}handleTransmuxComplete(e){e.chunkMeta.transmuxing.end=self.performance.now(),this.onTransmuxComplete(e)}},Al=100,jl=class extends Es{constructor(e,t,n){super(e,t,n,`audio-stream-controller`,z.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(L.LEVEL_LOADED,this.onLevelLoaded,this),e.on(L.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.on(L.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(L.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(L.BUFFER_RESET,this.onBufferReset,this),e.on(L.BUFFER_CREATED,this.onBufferCreated,this),e.on(L.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(L.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(L.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(L.FRAG_LOADING,this.onFragLoading,this),e.on(L.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){let{hls:e}=this;e&&(super.unregisterListeners(),e.off(L.LEVEL_LOADED,this.onLevelLoaded,this),e.off(L.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.off(L.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(L.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(L.BUFFER_RESET,this.onBufferReset,this),e.off(L.BUFFER_CREATED,this.onBufferCreated,this),e.off(L.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(L.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(L.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(L.FRAG_LOADING,this.onFragLoading,this),e.off(L.FRAG_BUFFERED,this.onFragBuffered,this))}onInitPtsFound(e,t){let{frag:n,id:r,initPTS:i,timescale:a,trackId:o,timestampOffsets:s}=t;if(r===z.MAIN){let e=n.cc,t=this.fragCurrent;if(this.initPTS=s,this.log(`InitPTS for cc: ${e} found from main: ${i/a} (${i}/${a}) trackId: ${o}`),this.mainAnchor=n,this.state===$.WAITING_INIT_PTS){let t=this.waitingData;(!t&&!this.loadingParts||t&&t.frag.cc!==e)&&this.syncWithAnchor(n,t?.frag)}else!this.hls.hasEnoughToStart&&t&&t.cc!==e?(t.abortRequests(),this.syncWithAnchor(n,t)):this.state===$.IDLE&&this.tick()}}getLoadPosition(){return!this.startFragRequested&&this.nextLoadPosition>=0&&this.switchingTrack?.flushImmediate!==!1?this.nextLoadPosition:super.getLoadPosition()}syncWithAnchor(e,t){let n=this.mainFragLoading?.frag||null;if(t&&n?.cc===t.cc)return;let r=(n||e).cc,i=oa(this.getLevelDetails(),r,this.getLoadPosition());i&&this.fragmentTracker.getState(i)!==Z.OK&&(this.log(`Syncing with main frag at ${i.start} cc ${i.cc}`),this.startFragRequested=!1,this.nextLoadPosition=i.start,this.resetLoadingState(),this.state===$.IDLE&&this.doTickIdle())}startLoad(e,t){if(!this.levels){this.startPosition=e,this.state=$.STOPPED;return}let n=this.lastCurrentTime;this.stopLoad(),this.setInterval(Al),n>0&&e===-1&&!t&&this.initPTS.length&&(this.log(`Override startPosition with lastCurrentTime @${n.toFixed(3)}`),e=n),this.state=$.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 $.IDLE:this.doTickIdle();break;case $.WAITING_TRACK:{let{levels:e,trackId:t}=this,n=e?.[t],r=n?.details;if(r&&!this.waitForLive(n)){if(this.waitForCdnTuneIn(r))break;this.state=$.WAITING_INIT_PTS}break}case $.FRAG_LOADING_WAITING_RETRY:this.checkRetryDate();break;case $.WAITING_INIT_PTS:{let e=this.waitingData;if(e){let{frag:t,part:n,cache:r,complete:i}=e,a=this.mainAnchor;if(this.initPTS[t.cc]!==void 0){this.waitingData=null,this.state=$.FRAG_LOADING;let e={frag:t,part:n,payload:r.flush().buffer,networkDetails:null};this._handleFragmentLoadProgress(e),i&&super._handleFragmentLoadComplete(e)}else a&&a.cc!==e.frag.cc&&this.syncWithAnchor(a,e.frag)}else this.state=$.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(){let{hls:e,levels:t,media:n,trackId:r}=this,i=e.config;if(!this.buffering||!n&&!this.primaryPrefetch&&(this.startFragRequested||!i.startFragPrefetch)||!(t!=null&&t[r]))return;let a=t[r],o=a.details;if(!o||this.waitForLive(a)||this.waitForCdnTuneIn(o)){this.state=$.WAITING_TRACK,this.startFragRequested=!1;return}let s=this.getBufferOutput();this.bufferFlushed&&s&&(this.bufferFlushed=!1,this.afterBufferFlushed(s,B.AUDIO));let c=this.getFwdBufferInfo();if(c===null)return;if(!this.switchingTrack&&this._streamEnded(c,o)){e.trigger(L.BUFFER_EOS,{type:`audio`}),this.state=$.ENDED;return}let l=c.len,u=e.maxBufferLength,d=o.fragments,f=d[0].start,p=this.getLoadPosition(),m=this.flushing||this.switchingTrack&&!this.switchingTrack.flushImmediate?p:c.end;if(this.switchingTrack&&n){let e=p;o.PTSKnown&&e<f&&e>=this.timelineOffset&&(c.end>f||c.nextStart)&&(this.log(`Alt audio track ahead of main track, seek to start of alt audio track ${e} -> ${f} + 0.05`),n.currentTime=f+.05)}if(l>=u&&!this.switchingTrack&&m<d[d.length-1].start)return;let h=this.getNextFragment(m,o);if(h&&this.isLoopLoading(h,m)&&(h=this.getNextFragmentLoopLoading(h,o,c,z.MAIN,u)),!h){this.bufferFlushed=!0;return}if(this.exceedsMaxBuffer(c,u,h))return;let g=this.mainFragLoading?.frag||null;if(!this.audioOnly&&this.startFragRequested&&g&&Tt(h)&&!h.endList&&(!o.live||!this.loadingParts&&m<this.hls.liveSyncPosition)&&(this.fragmentTracker.getState(g)===Z.OK&&(this.mainFragLoading=g=null),g&&Tt(g))){if(h.start>g.end){let e=this.fragmentTracker.getFragAtPos(m,z.MAIN);e&&e.end>g.end&&(g=e,this.mainFragLoading={frag:e,targetBufferTime:null})}if(h.start>g.end)return}this.loadFragment(h,a,m)}onMediaDetaching(e,t){this.bufferFlushed=this.flushing=!1,super.onMediaDetaching(e,t)}onAudioTracksUpdated(e,{audioTracks:t}){this.resetTransmuxer(),this.levels=t.map(e=>new Mi(e))}onAudioTrackSwitching(e,t){let n=!!t.url;this.trackId=t.id;let{fragCurrent:r}=this;r&&(r.abortRequests(),this.removeUnbufferedFrags(r.start)),this.resetLoadingState(),n?(this.switchingTrack=t,t.flushImmediate||(this.nextTrackId=t.id,this.nextLevelSwitch()),this.flushAudioIfNeeded(t),this.state!==$.STOPPED&&(this.setInterval(Al),this.state=$.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 n=this.cachedTrackLoadedData;n&&(this.cachedTrackLoadedData=null,this.onAudioTrackLoaded(L.AUDIO_TRACK_LOADED,n))}onAudioTrackLoaded(e,t){var n;let{levels:r}=this,{details:i,id:a,groupId:o,track:s}=t;if(!r){this.warn(`Audio tracks reset while loading track ${a} "${s.name}" of "${o}"`);return}let c=this.mainDetails;if(!c||i.endCC>c.endCC||c.expired){this.cachedTrackLoadedData=t,this.state!==$.STOPPED&&(this.state=$.WAITING_TRACK);return}this.cachedTrackLoadedData=null,this.log(`Audio track ${a} "${s.name}" of "${o}" loaded [${i.startSN},${i.endSN}]${i.lastPartSn?`[part-${i.lastPartSn}-${i.lastPartIndex}]`:``},duration:${i.totalduration}`);let l=r[a],u=0;if(i.live||(n=l.details)!=null&&n.live){if(this.checkLiveUpdate(i),i.deltaUpdateFailed)return;l.details&&(u=this.alignPlaylists(i,l.details,this.levelLastLoaded?.details)),i.alignedSliding||(Cs(c,i,this),u=i.fragmentStart)}l.details=i,this.levelLastLoaded=l,this.startFragRequested||this.setStartPosition(c,u),this.hls.trigger(L.AUDIO_TRACK_UPDATED,{details:i,id:a,groupId:t.groupId}),this.state===$.WAITING_TRACK&&!this.waitForCdnTuneIn(i)&&(this.state=$.IDLE),this.tick()}_handleFragmentLoadProgress(e){let t=e.frag,{part:n,payload:r}=e,{config:i,trackId:a,levels:o}=this;if(!o){this.warn(`Audio tracks were reset while fragment load was in progress. Fragment ${t.sn} of level ${t.level} will not be buffered`);return}let s=o[a];if(!s){this.warn(`Audio track is undefined on fragment load progress`);return}let c=s.details;if(!c){this.warn(`Audio track details undefined on fragment load progress`),this.removeUnbufferedFrags(t.start);return}let l=i.defaultAudioCodec||s.audioCodec||`mp4a.40.2`,u=this.transmuxer;u||=this.transmuxer=new kl(this.hls,z.AUDIO,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this));let d=this.initPTS[t.cc],f=t.initSegment?.data;if(d!==void 0){let e=n?n.index:-1,i=e!==-1,a=new Qa(t.level,t.sn,t.stats.chunkCount,r.byteLength,e,i,t.duration);u.push(r,f,l,``,t,n,c.totalduration,!1,a,d)}else{this.log(`Unknown video PTS for cc ${t.cc}, waiting for video PTS before demuxing audio frag ${t.sn} of [${c.startSN} ,${c.endSN}],track ${a}`);let{cache:e}=this.waitingData=this.waitingData||{frag:t,part:n,cache:new ks,complete:!1};e.push(new Uint8Array(r)),this.state!==$.STOPPED&&(this.state=$.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 n=t.tracks.audio;n&&(this.mediaBuffer=n.buffer||null)}onFragLoading(e,t){!this.audioOnly&&t.frag.type===z.MAIN&&Tt(t.frag)&&(this.mainFragLoading=t,this.state===$.IDLE&&this.tick())}onFragBuffered(e,t){let{frag:n,part:r}=t;if(n.type!==z.AUDIO){!this.audioOnly&&n.type===z.MAIN&&!n.elementaryStreams.video&&!n.elementaryStreams.audiovideo&&(this.audioOnly=!0,this.mainFragLoading=null);return}if(this.fragContextChanged(n)){this.warn(`Fragment ${n.sn}${r?` p: `+r.index:``} of level ${n.level} finished buffering, but was aborted. state: ${this.state}, audioSwitch: ${this.switchingTrack?this.switchingTrack.name:`false`}`);return}if(Tt(n)){let e=this.switchingTrack;e&&(this.bufferedTrack=e)}this.fragBufferedComplete(n,r),this.media&&this.tick()}getFwdBufferInfo(){let e=this.getBufferOutput();return super.getFwdBufferInfo(e,z.AUDIO)}getBufferOutput(){return this.mediaBuffer?this.mediaBuffer:this.media}checkFragmentChanged(){let e=this.fragPlaying;if(!this.checkFragPlaying())return!1;let{fragPlaying:t,switchingTrack:n}=this,r=!t||t.level!==e?.level;return r&&e&&this.cleanupBackBuffer(),n&&(r||t?.level===n.id)&&this.completeAudioSwitch(n),!0}onError(e,t){if(t.fatal){this.state=$.ERROR;return}switch(t.details){case I.FRAG_GAP:case I.FRAG_PARSING_ERROR:case I.FRAG_DECRYPT_ERROR:case I.FRAG_LOAD_ERROR:case I.FRAG_LOAD_TIMEOUT:case I.KEY_LOAD_ERROR:case I.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(z.AUDIO,t);break;case I.AUDIO_TRACK_LOAD_ERROR:case I.AUDIO_TRACK_LOAD_TIMEOUT:case I.LEVEL_PARSING_ERROR:!t.levelRetry&&this.state===$.WAITING_TRACK&&t.context?.type===R.AUDIO_TRACK&&(this.state=$.IDLE);break;case I.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 I.MEDIA_SOURCE_REQUIRES_RESET:this.onSourceBufferError(z.AUDIO,t);break;case I.BUFFER_ADD_CODEC_ERROR:case I.BUFFER_APPEND_ERROR:if(t.parent!==`audio`)return;this.reduceLengthAndFlushBuffer(t)||this.resetLoadingState();break;case I.BUFFER_FULL_ERROR:if(t.parent!==`audio`)return;this.reduceLengthAndFlushBuffer(t)&&(this.bufferedTrack=null,super.flushMainBuffer(0,1/0,`audio`));break;case I.INTERNAL_EXCEPTION:this.recoverWorkerError(t)}}onBufferFlushing(e,{type:t}){t!==B.VIDEO&&(this.flushing=!0)}onBufferFlushed(e,{type:t}){if(t!==B.VIDEO){this.flushing=!1,this.bufferFlushed=!0,this.state===$.ENDED&&(this.state=$.IDLE);let e=this.getBufferOutput();e&&(this.afterBufferFlushed(e,t),this.tick())}}_handleTransmuxComplete(e){var t;let n=`audio`,{hls:r}=this,{remuxResult:i,chunkMeta:a}=e,o=this.getCurrentContext(a);if(!o){this.resetWhenMissingContext(a);return}let{frag:s,part:c,level:l}=o,{details:u}=l,{audio:d,text:f,id3:p,initSegment:m}=i;if(this.fragContextChanged(s)||!u){this.fragmentTracker.removeFragment(s),m!=null&&m.tracks&&this.resetTransmuxer();return}if(this.state=$.PARSING,d&&this.switchingTrack&&!this.switchingTrack.flushImmediate){let{config:e}=this,t=e.nextAudioTrackBufferFlushForwardOffset,n=Math.max(this.getLoadPosition()+t,(c||s).start);super.flushMainBuffer(n,1/0,z.AUDIO)}if(m!=null&&m.tracks){let e=s.initSegment||s;if(this.unhandledEncryptionError(m,s))return;this._bufferInitSegment(l,m.tracks,e,a),r.trigger(L.FRAG_PARSING_INIT_SEGMENT,{frag:e,id:n,tracks:m.tracks})}if(d){let{startPTS:e,endPTS:t,startDTS:n,endDTS:r}=d;c&&(c.elementaryStreams[B.AUDIO]={startPTS:e,endPTS:t,startDTS:n,endDTS:r}),s.setElementaryStreamInfo(B.AUDIO,e,t,n,r),this.bufferFragmentData(d,s,c,a)}if(p!=null&&(t=p.samples)!=null&&t.length){let e=V({id:n,frag:s,details:u},p);r.trigger(L.FRAG_PARSING_METADATA,e)}if(f){let e=V({id:n,frag:s,details:u},f);r.trigger(L.FRAG_PARSING_USERDATA,e)}}_bufferInitSegment(e,t,n,r){if(this.state!==$.PARSING||(t.video&&delete t.video,t.audiovideo&&delete t.audiovideo,!t.audio))return;let i=t.audio;i.id=z.AUDIO;let a=e.audioCodec;this.log(`Init audio buffer, container:${i.container}, codecs[level/parsed]=[${a}/${i.codec}]`),a?.split(`,`).length===1&&(i.levelCodec=a),this.hls.trigger(L.BUFFER_CODECS,t);let o=i.initSegment;if(o!=null&&o.byteLength){let e={type:`audio`,frag:n,part:null,chunkMeta:r,parent:n.type,data:o};this.hls.trigger(L.BUFFER_APPENDING,e)}this.tickImmediate()}loadFragment(e,t,n){let r=this.fragmentTracker.getState(e);if(this.switchingTrack||r===Z.NOT_LOADED||r===Z.PARTIAL){var i;if((i=t.details)!=null&&i.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=$.WAITING_INIT_PTS;let n=this.mainDetails;n&&n.fragmentStart!==t.details.fragmentStart&&Cs(n,t.details,this)}else super.loadFragment(e,t,n)}else this.clearTrackerIfNeeded(e)}flushAudioIfNeeded(e){if(this.media&&this.bufferedTrack&&e.flushImmediate){let{name:t,lang:n,assocLang:r,characteristics:i,audioCodec:a,channels:o}=this.bufferedTrack;Ui({name:t,lang:n,assocLang:r,characteristics:i,audioCodec:a,channels:o},e,Ki)||(Yi(e.url,this.hls)?(this.log(`Switching audio track : flushing all audio`),super.flushMainBuffer(0,1/0,`audio`),this.bufferedTrack=null):this.bufferedTrack=e)}}completeAudioSwitch(e){let{hls:t}=this;this.bufferedTrack=e,this.switchingTrack=null,t.trigger(L.AUDIO_TRACK_SWITCHED,H({},e))}get nextAudioTrack(){return this.nextTrackId}},Ml=class extends Xt{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,n){let r=t?.renditionReports;if(r){let i=-1;for(let n=0;n<r.length;n++){let a=r[n],o;try{o=new self.URL(a.URI,t.url).href}catch(e){this.warn(`Could not construct new URL for Rendition Report: ${e}`),o=a.URI||``}if(o===e){i=n;break}o===e.substring(0,o.length)&&(i=n)}if(i!==-1){let e=r[i],a=parseInt(e[`LAST-MSN`])||t.lastPartSn,o=parseInt(e[`LAST-PART`])||t.lastPartIndex;if(this.hls.config.lowLatencyMode){let e=Math.min(t.age-t.partTarget,t.targetduration);o>=0&&e>t.partTarget&&(o+=1)}let s=n&&Ai(n);return new ji(a,o>=0?o:void 0,s)}}}loadPlaylist(e){this.clearTimer()}loadingPlaylist(e,t){this.clearTimer()}shouldLoadPlaylist(e){return this.canLoad&&!!e&&!!e.url&&(!e.details||e.details.live)}getUrlWithDirectives(e,t){if(t)try{return t.addDirectives(e)}catch(e){this.warn(`Could not construct new URL with HLS Delivery Directives: ${e}`)}return e}playlistLoaded(e,t,n){let{details:r,stats:i}=t,a=r.fragments,o=self.performance.now(),s=i.loading.first?Math.max(0,Math.floor(o-i.loading.first)):0;r.advancedDateTime=Date.now()-s;let c=this.hls.config.timelineOffset;if(c!==r.appliedTimelineOffset){let e=Math.max(c||0,0);r.appliedTimelineOffset=e,a.forEach(t=>{t?.setStart(t.playlistOffset+e)})}if(r.live||n!=null&&n.live){let c=`levelInfo`in t?t.levelInfo:t.track;r.reloaded(n);let l=a[a.length-1]?.type;if(r.misses>=this.hls.config.liveMaxUnchangedPlaylistRefresh){let e=Error(`${l} playlist ${c.id} hit max allowed unchanged reloads.`);this.warn(e);let{networkDetails:n,context:a}=t;this.hls.trigger(L.ERROR,{type:F.NETWORK_ERROR,details:I.PLAYLIST_UNCHANGED_ERROR,fatal:!1,url:r.url,error:e,reason:e.message,level:t.level,parent:l,context:a,networkDetails:n,stats:i});return}if(n){as(n,r,this);let e=r.playlistParsingError;if(e){this.warn(e);let n=this.hls;if(!n.config.ignorePlaylistParsingErrors){let{networkDetails:a}=t;n.trigger(L.ERROR,{type:F.NETWORK_ERROR,details:I.LEVEL_PARSING_ERROR,fatal:!1,url:r.url,error:e,reason:e.message,level:t.level,parent:l,networkDetails:a,stats:i});return}r.playlistParsingError=null}}r.requestScheduled===-1&&(r.requestScheduled=i.loading.start);let u=this.hls.mainForwardBufferInfo,d=u?u.end-u.len:0,f=fs(r,(r.edge-d)*1e3);r.requestScheduled+f<o?r.requestScheduled=o:r.requestScheduled<=o&&(r.requestScheduled+=f);let p=t.deliveryDirectives;if(this.log(`live playlist ${e} ${r.advanced?`REFRESHED ${r.lastPartSn} - ${r.lastPartIndex}`:r.updated?`UPDATED`:`MISSED (received ${r.lastPartSn} - ${r.lastPartIndex}${p?` | requested ${p.msn} - ${p.part}`:``})`}`),!this.canLoad||!r.live)return;let m,h,g;if(r.canBlockReload&&r.advanced){let e=this.hls.config.lowLatencyMode,i=r.lastPartSn,a=r.endSN,s=r.lastPartIndex,l=s!==-1,u=i===a;l?u?(h=a+1,g=e?0:s):(h=i,g=e?s+1:r.maxPartIndex):h=a+1;let d=r.age,f=d+r.ageHeader,p=Math.min(f-r.partTarget,r.targetduration*1.5);if(p>0){if(f>r.targetduration*3)this.log(`Playlist last advanced ${d.toFixed(2)}s ago. Omitting segment and part directives.`),h=void 0,g=void 0;else if(n!=null&&n.tuneInGoal&&f-r.partTarget>n.tuneInGoal)this.warn(`CDN Tune-in goal increased from: ${n.tuneInGoal} to: ${p} with playlist age: ${r.age}`),p=0;else{let e=Math.floor(p/r.targetduration);if(h+=e,g!==void 0){let e=Math.round(p%r.targetduration/r.partTarget);g+=e}this.log(`CDN Tune-in age: ${r.ageHeader}s last advanced ${d.toFixed(2)}s goal: ${p} skip sn ${e} to part ${g}`)}r.tuneInGoal=p}if(m=this.getDeliveryDirectives(r,t.deliveryDirectives,h,g),e||!u){r.requestScheduled=o,this.loadingPlaylist(c,m);return}}else(r.canBlockReload||r.canSkipUntil)&&(m=this.getDeliveryDirectives(r,t.deliveryDirectives,h,g));m&&h!==void 0&&r.canBlockReload&&(r.requestScheduled=i.loading.first+Math.max(f-s*2,f/2)),this.scheduleLoading(c,m,r)}else this.clearTimer()}scheduleLoading(e,t,n){let r=n||e.details;if(!r){this.loadingPlaylist(e,t);return}let i=self.performance.now(),a=r.requestScheduled;if(i>=a&&!this.loadingSync){this.loadingSync=!0,this.loadingPlaylist(e,t),this.loadingSync=!1;return}let o=Math.max(a-i,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,n,r){let i=Ai(e);return t!=null&&t.skip&&e.deltaUpdateFailed&&(n=t.msn,r=t.part,i=ki.No),new ji(n,r,i)}checkRetry(e){let t=e.details,n=Rt(e),r=e.errorAction,{action:i,retryCount:a=0,retryConfig:o}=r||{},s=!!r&&!!o&&(i===ca.RetryRequest||!r.resolved&&i===ca.SendAlternateToPenaltyBox);if(s){var c;if(a>=o.maxNumRetry)return!1;if(n&&(c=e.context)!=null&&c.deliveryDirectives)this.warn(`Retrying playlist loading ${a+1}/${o.maxNumRetry} after "${t}" without delivery-directives`),this.loadPlaylist();else{let n=Kt(e.response?.code);if(this.clearTimer(),n)this.log(`Waiting for connection (offline)`),e.reason=`offline`,this.timer=self.setTimeout(()=>this.checkOfflineStatus(),1e3);else{let e=Ht(o,a);this.warn(`Retrying playlist loading ${a+1}/${o.maxNumRetry} after "${t}" in ${e}ms`),this.timer=self.setTimeout(()=>this.loadPlaylist(),e)}}e.levelRetry=!0,r.resolved=!0}return s}checkOfflineStatus(){this.clearTimer(),Kt(0)?this.timer=self.setTimeout(()=>this.checkOfflineStatus(),1e3):(this.log(`Connection restored (online)`),this.loadPlaylist())}};function Nl(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(!Pl(e[n].attrs,t[n].attrs))return!1;return!0}function Pl(e,t,n){let r=e[`STABLE-RENDITION-ID`];return r&&!n?r===t[`STABLE-RENDITION-ID`]:!(n||[`LANGUAGE`,`NAME`,`CHARACTERISTICS`,`AUTOSELECT`,`DEFAULT`,`FORCED`,`ASSOC-LANGUAGE`]).some(n=>e[n]!==t[n])}var Fl=class extends Ml{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(L.MANIFEST_LOADING,this.onManifestLoading,this),e.on(L.MANIFEST_PARSED,this.onManifestParsed,this),e.on(L.LEVEL_LOADING,this.onLevelLoading,this),e.on(L.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(L.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(L.ERROR,this.onError,this)}unregisterListeners(){let{hls:e}=this;e.off(L.MANIFEST_LOADING,this.onManifestLoading,this),e.off(L.MANIFEST_PARSED,this.onManifestParsed,this),e.off(L.LEVEL_LOADING,this.onLevelLoading,this),e.off(L.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(L.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(L.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:n,groupId:r,details:i}=t,a=this.tracksInGroup[n];if(!a||a.groupId!==r){this.warn(`Audio track with id:${n} and group:${r} not found in active group ${a?.groupId}`);return}let o=a.details;a.details=t.details,this.log(`Audio track ${n} "${a.name}" lang:${a.lang} group:${r} loaded [${i.startSN}-${i.endSN}]`),n===this.trackId&&this.playlistLoaded(n,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 n=t.audioGroups||null,r=this.groupIds,i=this.currentTrack;if(!n||r?.length!==n?.length||n!=null&&n.some(e=>r?.indexOf(e)===-1)){this.groupIds=n,this.trackId=-1,this.currentTrack=null;let e=this.tracks.filter(e=>Xi(e.groupId,n));if(e.length)this.selectDefaultTrack&&!e.some(e=>e.default)&&(this.selectDefaultTrack=!1),e.forEach((e,t)=>{e.id=t});else if(!i&&!this.tracksInGroup.length)return;this.tracksInGroup=e;let t=this.hls.config.audioPreference;if(!i&&t){let n=Hi(t,e,Ki);if(n>-1)i=e[n];else{let e=Hi(t,this.tracks);i=this.tracks[e]}}let r=this.findTrackId(i);r===-1&&i&&(r=this.findTrackId(null));let a={audioTracks:e};this.log(`Updating audio tracks, ${e.length} track(s) found in group(s): ${n?.join(`,`)}`),this.hls.trigger(L.AUDIO_TRACKS_UPDATED,a);let o=this.trackId;if(r!==-1&&o===-1)this.setAudioTrack(r);else if(e.length&&o===-1){let t=Error(`No audio track selected for current audio group-ID(s): ${this.groupIds?.join(`,`)} track count: ${e.length}`);this.warn(t.message),this.hls.trigger(L.ERROR,{type:F.MEDIA_ERROR,details:I.AUDIO_TRACK_LOAD_ERROR,fatal:!0,error:t})}}}onError(e,t){!t.fatal&&t.context&&t.context.type===R.AUDIO_TRACK&&t.context.id===this.trackId&&Xi(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 n=this.allAudioTracks;if(this.selectDefaultTrack=!1,n.length){let r=this.currentTrack;if(r&&Ui(e,r,Ki))return r;let i=Hi(e,this.tracksInGroup,Ki);if(i>-1){let t=this.tracksInGroup[i];return this.setAudioTrack(i,`flushImmediate`in e&&e.flushImmediate),t}if(r){let r=t.loadLevel;r===-1&&(r=t.firstAutoLevel);let i=qi(e,t.levels,n,r,Ki);if(i===-1)return null;t.nextLoadLevel=i}if(e.channels||e.audioCodec){let t=Hi(e,n);if(t>-1)return n[t]}}}return null}setAudioTrack(e,t=!0){let n=this.tracksInGroup;if(e<0||e>=n.length){this.warn(`Invalid audio track id: ${e}`);return}this.selectDefaultTrack=!1;let r=this.currentTrack,i=n[e],a=i.details&&!i.details.live;if(e===this.trackId&&i===r&&a||(this.log(`Switching to audio-track ${e} "${i.name}" lang:${i.lang} group:${i.groupId} channels:${i.channels}`),this.trackId=e,this.currentTrack=i,this.hls.trigger(L.AUDIO_TRACK_SWITCHING,H(H({},i),{},{flushImmediate:t})),a))return;let o=this.switchParams(i.url,r?.details,i.details);this.loadPlaylist(o)}findTrackId(e){let t=this.tracksInGroup;for(let n=0;n<t.length;n++){let r=t[n];if((!this.selectDefaultTrack||r.default)&&(!e||Ui(e,r,Ki)))return n}if(e){let{name:n,lang:r,assocLang:i,characteristics:a,audioCodec:o,channels:s}=e;for(let e=0;e<t.length;e++){let c=t[e];if(Ui({name:n,lang:r,assocLang:i,characteristics:a,audioCodec:o,channels:s},c,Ki))return e}for(let n=0;n<t.length;n++){let r=t[n];if(Pl(e.attrs,r.attrs,[`LANGUAGE`,`ASSOC-LANGUAGE`,`CHARACTERISTICS`]))return n}for(let n=0;n<t.length;n++){let r=t[n];if(Pl(e.attrs,r.attrs,[`LANGUAGE`]))return n}}return-1}loadPlaylist(e){super.loadPlaylist();let t=this.currentTrack;this.shouldLoadPlaylist(t)&&Yi(t.url,this.hls)&&this.scheduleLoading(t,e)}loadingPlaylist(e,t){super.loadingPlaylist(e,t);let n=e.id,r=e.groupId,i=this.getUrlWithDirectives(e.url,t),a=e.details,o=a?.age;this.log(`Loading audio-track ${n} "${e.name}" lang:${e.lang} group:${r}${t?.msn===void 0?``:` at sn `+t.msn+` part `+t.part}${o&&a.live?` age `+o.toFixed(1)+(a.type&&` `+a.type||``):``} ${i}`),this.hls.trigger(L.AUDIO_TRACK_LOADING,{url:i,id:n,groupId:r,deliveryDirectives:t||null,track:e})}},Il=class e{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=1/0,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(L.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.on(L.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(L.MANIFEST_PARSED,this.onManifestParsed,this),e.on(L.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(L.BUFFER_CODECS,this.onBufferCodecs,this),e.on(L.MEDIA_DETACHING,this.onMediaDetaching,this))}unregisterListener(){let{hls:e}=this;e&&(e.off(L.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.off(L.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(L.MANIFEST_PARSED,this.onManifestParsed,this),e.off(L.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(L.BUFFER_CODECS,this.onBufferCodecs,this),e.off(L.MEDIA_DETACHING,this.onMediaDetaching,this))}onFpsDropLevelCapping(e,t){if(!this.hls)return;let n=this.hls.levels[t.droppedLevel];this.isLevelAllowed(n)&&this.restrictedLevels.push({bitrate:n.bitrate,height:n.height,width:n.width})}onMediaAttaching(e,t){let n=t.media;this.clientRect=null,this.hls&&(n instanceof HTMLVideoElement?(this.media=n,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)&&(P(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(e=>!!e.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,n=this.getMaxLevel(e.length-1);n!==this.autoLevelCapping&&t.logger.log(`Setting autoLevelCapping to ${n}: ${e[n].height}p@${e[n].bitrate} for media ${this.mediaWidth}x${this.mediaHeight}`),t.autoLevelCapping=n,t.autoLevelEnabled&&t.autoLevelCapping>this.autoLevelCapping&&this.streamController&&this.streamController.nextLevelSwitch(),this.autoLevelCapping=t.autoLevelCapping}else e.length===1&&this.stopCapping()}}getMaxLevel(t){if(!this.hls)return-1;let n=this.hls.levels;if(!n.length)return-1;let r=n.filter((e,n)=>this.isLevelAllowed(e)&&n<=t);return this.observer||(this.clientRect=null),e.getMaxLevelByMediaSize(r,this.mediaWidth,this.mediaHeight)}observe(){let e=self.ResizeObserver;e&&(this.observer=new e(e=>{let t=e[0]?.contentRect;t&&(this.clientRect=t,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=1/0,this.observe(),this.observer||(this.timer=self.setInterval(this.detectPlayerSize.bind(this),1e3)),this.detectPlayerSize())}stopCapping(){this.restrictedLevels=[],this.autoLevelCapping=1/0,this.timer&&=(self.clearInterval(this.timer),void 0),this.observer&&=(this.observer.disconnect(),void 0)}getDimensions(){if(this.clientRect)return this.clientRect;let e=this.media,t={width:0,height:0};if(e){let n=e.getBoundingClientRect();t.width=n.width,t.height=n.height,!t.width&&!t.height&&(t.width=n.right-n.left||e.width||0,t.height=n.bottom-n.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:n}=this.hls.config;if(!t)try{e=self.devicePixelRatio}catch{}return Math.min(e,n)}isLevelAllowed(e){return!this.restrictedLevels.some(t=>e.bitrate===t.bitrate&&e.width===t.width&&e.height===t.height)}static getMaxLevelByMediaSize(e,t,n){if(!(e!=null&&e.length))return-1;let r=(e,t)=>!t||e.width!==t.width||e.height!==t.height,i=e.length-1,a=Math.max(t,n);for(let t=0;t<e.length;t+=1){let n=e[t];if((n.width>=a||n.height>=a)&&r(n,e[t+1])){i=t;break}}return i}},Ll=class e{constructor(t,n){Array.isArray(t)&&(t=t.map(t=>t instanceof e?t:new e(t))),this.value=t,this.params=n}},Rl=`Dict`;function zl(e){return Array.isArray(e)?JSON.stringify(e):e instanceof Map?`Map{}`:e instanceof Set?`Set{}`:typeof e==`object`?JSON.stringify(e):String(e)}function Bl(e,t,n,r){return Error(`failed to ${e} "${zl(t)}" as ${n}`,{cause:r})}var Vl=`Bare Item`,Hl=`Boolean`,Ul=`Byte Sequence`,Wl=`Decimal`,Gl=`Integer`;function Kl(e){return e<-999999999999999||999999999999999<e}var ql=`String`,Jl=/[\x00-\x1f\x7f]+/,Yl=class{constructor(e){this.description=e}},Xl=`Token`,Zl=`Key`;function Ql(e,t,n){return Bl(`serialize`,e,t,n)}function $l(e){if(typeof e!=`boolean`)throw Ql(e,Hl);return e?`?1`:`?0`}function eu(e){if(ArrayBuffer.isView(e)===!1)throw Ql(e,Ul);return`:${cn(e)}:`}function tu(e){if(Kl(e))throw Ql(e,Gl);return e.toString()}function nu(e){return`@${tu(e.getTime()/1e3)}`}function ru(e){let t=gn(e,3);if(Math.floor(Math.abs(t)).toString().length>12)throw Ql(e,Wl);let n=t.toString();return n.includes(`.`)?n:`${n}.0`}function iu(e){if(Jl.test(e))throw Ql(e,ql);return`"${e.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`)}"`}function au(e){return e.description||e.toString().slice(7,-1)}function ou(e){let t=au(e);if(/^([a-zA-Z*])([!#$%&'*+\-.^_`|~\w:/]*)$/.test(t)===!1)throw Ql(t,Xl);return t}function su(e){switch(typeof e){case`number`:if(!P(e))throw Ql(e,Vl);return Number.isInteger(e)?tu(e):ru(e);case`string`:return iu(e);case`symbol`:return ou(e);case`boolean`:return $l(e);case`object`:if(e instanceof Date)return nu(e);if(e instanceof Uint8Array)return eu(e);if(e instanceof Yl)return ou(e);default:throw Ql(e,Vl)}}function cu(e){if(/^[a-z*][a-z0-9\-_.*]*$/.test(e)===!1)throw Ql(e,Zl);return e}function lu(e){return e==null?``:Object.entries(e).map(([e,t])=>t===!0?`;${cu(e)}`:`;${cu(e)}=${su(t)}`).join(``)}function uu(e){return e instanceof Ll?`${su(e.value)}${lu(e.params)}`:su(e)}function du(e){return`(${e.value.map(uu).join(` `)})${lu(e.params)}`}function fu(e,t={whitespace:!0}){if(typeof e!=`object`||!e)throw Ql(e,Rl);let n=e instanceof Map?e.entries():Object.entries(e),r=t!=null&&t.whitespace?` `:``;return Array.from(n).map(([e,t])=>{t instanceof Ll||(t=new Ll(t));let n=cu(e);return t.value===!0?n+=lu(t.params):(n+=`=`,Array.isArray(t.value)?n+=du(t):n+=uu(t)),n}).join(`,${r}`)}function pu(e,t){return fu(e,t)}var mu=[`url`],hu=[`version`,`eventTargets`,`sid`,`transmissionMode`],gu=[`customData`,`headers`],_u=e=>e instanceof Ll?new Ll(Math.round(e.value),e.params):Math.round(e),vu=e=>Array.isArray(e)?e.map(_u):_u(e),yu=(e,t)=>Array.isArray(e)?e.map(e=>yu(e,t)):e instanceof Ll&&typeof e.value==`string`?new Ll(yu(e.value,t),e.params):(t.baseUrl&&(e=_n(e,hn(t.baseUrl))),t.version===1?encodeURIComponent(e):e),bu=e=>e instanceof Ll?new Ll(Math.round(e.value/100)*100,e.params):Math.round(e/100)*100,xu=e=>Array.isArray(e)?e.map(bu):bu(e),Su={br:vu,d:vu,bl:xu,dl:xu,mtp:xu,nor:(e,t)=>{let n=e;return t.version>=2&&(e instanceof Ll&&typeof e.value==`string`?n=new Ll([e]):typeof e==`string`&&(n=[e])),yu(n,t)},rtp:xu,tb:vu},Cu=2,wu=`bc`,Tu=`ps`,Eu=`pr`,Du=`e`,Ou=`t`,ku=`c`,Au=`b`,ju=`rr`,Mu=`ce`,Nu={BITRATE_CHANGE:wu,ERROR:Du,RESPONSE_RECEIVED:ju,CUSTOM_EVENT:Mu},Pu=new Map([[Tu,`sta`],[Eu,`pr`],[ku,`cid`],[Au,`bg`],[wu,`br`]]),Fu=`event`,Iu=`request`,Lu=[`cen`,`e`,`h`,`ts`],Ru=`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`.split(`.`),zu=/^[a-zA-Z0-9-.]+-[a-zA-Z0-9-.]+$/;function Bu(e){return zu.test(e)}var Vu=new Set(Ru);function Hu(e){return Vu.has(e)||Bu(e)}var Uu=[`cmsdd`,`cmsds`,`rc`,`smrt`,`ttfb`,`ttfbb`,`ttlb`,`url`],Wu=new Set(Uu);function Gu(e){return Wu.has(e)}var Ku=new Set(Lu);function qu(e){return Hu(e)||Gu(e)||Ku.has(e)}var Ju=new Set([`ab`,`bl`,`br`,`bsa`,`bsd`,`bsda`,`lab`,`lb`,`mtp`,`pb`,`tab`,`tb`,`tbl`,`tpb`]),Yu=[`bl`,`br`,`bs`,`cid`,`d`,`dl`,`mtp`,`nor`,`nrr`,`ot`,`pr`,`rtp`,`sf`,`sid`,`st`,`su`,`tb`,`v`],Xu=new Set(Yu);function Zu(e){return Xu.has(e)||Bu(e)}var Qu=new Set([`ot`,`sf`,`st`,`e`,`sta`]);function $u(e){return Qu.has(e)}function ed(e){return typeof e==`number`?P(e):e!=null&&e!==``&&e!==!1}var td={[Fu]:qu,[Iu]:Hu};function nd(e,t){if(Array.isArray(e)){let n;return t&&(n=e.find(e=>e.params?.ot===t)),n||=e[0],nd(n)}return e instanceof Ll?e.value:e}function rd(e){let t={};for(let[r,i]of Object.entries(e)){if(i==null){t[r]=i;continue}if(r===`nor`){let e=(Array.isArray(i)?i:[i])[0];if(e instanceof Ll){var n;t.nor=e.value,(n=e.params)!=null&&n.r&&(t.nrr=e.params.r)}else t.nor=e}else t[r]=Ju.has(r)?nd(i,e.ot):i}return t}function id(e,t={}){let n={};if(typeof e!=`object`||!e)return n;let r=t.version||e.v||Cu,i=t.reportingMode||Iu,a=r===1?rd(e):e,o=r===1?Zu:td[i],s=Object.keys(a).filter(o);a.e&&a.e!==ju&&(s=s.filter(e=>!Gu(e)));let c=t.filter;typeof c==`function`&&(s=s.filter(c));let l=i===Fu;if(l){let e=a.e;!s.includes(`e`)&&e!=null&&s.push(`e`),s.includes(`ts`)||s.push(`ts`),!s.includes(`cen`)&&a.cen!=null&&e===Mu&&s.push(`cen`);let t=e?Pu.get(e):void 0;t&&a[t]!=null&&!s.includes(t)&&s.push(t)}if(s.length===0)return n;r>1&&!s.includes(`v`)&&s.push(`v`);let u={version:r,reportingMode:i,baseUrl:t.baseUrl};s.sort();for(let e of s){let i=a[e],o=t.formatters?.[e]??Su[e];if(typeof o==`function`&&(i=o(i,u)),e===`v`){if(r===1)continue;i=r}if(e===`pr`&&i===1&&!(l&&a.e===Eu))continue;l&&e===`ts`&&!P(i)&&(i=Date.now());let s=l&&i===!1&&e===`bg`&&a.e===Au;(ed(i)||s)&&($u(e)&&typeof i==`string`&&(i=new Yl(i)),n[e]=i)}return n}var ad=`CMCD-Object`,od=`CMCD-Request`,sd=`CMCD-Session`,cd=`CMCD-Status`,ld={REQUEST:od},ud={ab:ad,br:ad,d:ad,lab:ad,lb:ad,ot:ad,tab:ad,tb:ad,tpb:ad,bl:od,cs:od,dfa:od,dl:od,ltc:od,mtp:od,nor:od,nrr:od,pb:od,sn:od,sta:od,su:od,tbl:od,cid:sd,msd:sd,sf:sd,sid:sd,st:sd,v:sd,bg:cd,bs:cd,bsa:cd,bsd:cd,bsda:cd,cdn:cd,ec:cd,nr:cd,pr:cd,pt:cd,rtp:cd};function dd(e){return Object.keys(e).reduce((t,n)=>{var r;return(r=e[n])==null||r.forEach(e=>t[e]=n),t},{})}function fd(e,t){let n={};if(!e)return n;let r=Object.keys(e),i=t?dd(t):{};for(let t of r){let r=ud[t]||i[t]||ld.REQUEST,a=n[r]??(n[r]={});a[t]=e[t]}return n}function pd(e,t){let n={},r=fd(e,t);for(let[e,t]of Object.entries(r)){let r=pu(t,{whitespace:!1});r&&(n[e]=r)}return n}var md=`CMCD`;function hd(e){return pu(e,{whitespace:!1})}function gd(e,t={}){return e?hd(id(e,t)):``}var _d=30,vd=[...Yu,...Ru,...Uu,...Lu].filter((e,t,n)=>n.indexOf(e)===t),yd=`application/cmcd`,bd=1,xd={MANIFEST:`m`,AUDIO:`a`,VIDEO:`v`,MUXED:`av`,INIT:`i`,CAPTION:`c`,TIMED_TEXT:`tt`,KEY:`k`,OTHER:`o`},Sd={STARTING:`s`,PLAYING:`p`,SEEKING:`k`,REBUFFERING:`r`,PAUSED:`a`,ENDED:`e`,FATAL_ERROR:`f`,PRELOADING:`d`},Cd=`query`,wd=`headers`;function Td(e,t,n){let r=new Set(t.enabledKeys??[]);return{version:t.version||Cu,reportingMode:e,filter:e=>r.has(e),baseUrl:n}}function Ed(e,t){if(e===t)return!0;if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++){let r=e[n],i=t[n];if(r===i)continue;if(typeof r==`number`||typeof i==`number`||r.value!==i.value)return!1;let a=r.params,o=i.params,s=a&&Object.keys(a)[0],c=o&&Object.keys(o)[0];if(s!==c||s!==void 0&&c!==void 0&&a&&o&&a[s]!==o[c])return!1}return!0}var Dd=Object.is,Od=e=>e,kd=Array.from(Pu,([e,t])=>t===`br`?{event:e,field:t,equal:(e,t)=>e===void 0||t===void 0?e===t:Ed(e,t),snapshot:e=>e.slice()}:{event:e,field:t,equal:Dd,snapshot:Od}),Ad=new Map(kd.map(e=>[e.event,e]));function jd(e){let{url:t}=e,n=Pt(e,mu);return fetch(t,n)}function Md(e){let{version:t=Cu,eventTargets:n=[],sid:r=vn(),transmissionMode:i=Cd}=e;return H(H({},Pt(e,hu)),{},{version:t,transmissionMode:i,sid:r,eventTargets:n.reduce((e,t)=>{var n;return t!=null&&t.url&&(n=t.events)!=null&&n.length&&e.push({version:t.version||Cu,enabledKeys:t.enabledKeys?.slice()||[],url:t.url,events:t.events.slice(),interval:t.interval??_d,batchSize:t.batchSize||1}),e},[])})}var Nd=class{constructor(e,t=jd){this.timeOrigin=performance.timeOrigin||performance.timing?.fetchStart||Date.now()-performance.now(),this.data={},this.msd=NaN,this.eventTargets=new Map,this.lastEmitted={},this.requestTarget={sn:0,msdSent:!1},this.config=Md(e),this.data={cid:this.config.cid,sid:this.config.sid,v:this.config.version},this.requester=t;for(let e of this.config.eventTargets)this.eventTargets.set(e,{intervalId:void 0,sn:0,msdSent:!1,queue:[]})}start(){this.eventTargets.forEach((e,t)=>{if(this.disarmInterval(e),t.interval===0||!t.events.includes(Ou))return;let n=()=>{this.recordTargetEvent(e,t,Ou),this.processEventTargets()};e.intervalId=setInterval(n,t.interval*1e3),n()})}stop(e=!1){e&&this.flush(),this.eventTargets.forEach(e=>{this.disarmInterval(e)})}flush(){this.processEventTargets(!0)}update(e){e.sid&&e.sid!==this.data.sid&&this.resetSession(),e.msd&&!isNaN(e.msd)&&(this.msd=e.msd),this.data=H(H(H({},this.data),e),{},{msd:void 0});for(let t of kd)t.field in e&&!t.equal(this.data[t.field],this.lastEmitted[t.field])&&this.recordEvent(t.event)}recordEvent(e,t={}){let n=Ad.get(e);if(n){let e=n.field,r=t[e];r!==void 0&&V(this.data,{[e]:r});let i=this.data[e];if(i===void 0||n.equal(i,this.lastEmitted[e]))return;V(this.lastEmitted,{[e]:n.snapshot(i)})}this.eventTargets.forEach((n,r)=>{this.recordTargetEvent(n,r,e,t)}),this.processEventTargets()}recordTargetEvent(e,t,n,r={}){if(!t.events.includes(n))return;let i=H(H(H({},this.data),r),{},{e:n,ts:r.ts??Date.now(),sn:e.sn++});!isNaN(this.msd)&&!e.msdSent&&(i.msd=this.msd,e.msdSent=!0),e.queue.push(i)}recordResponseReceived(e,t={}){let{request:n}=e,r=t.url??n?.url;if(!r)return;let i=new URL(r);i.searchParams.delete(md);let a={url:i.toString(),rc:e.status},o=e.resourceTiming;o&&(o.startTime!=null&&(a.ts=Math.round(this.timeOrigin+o.startTime),o.responseStart!=null&&(a.ttfb=Math.round(o.responseStart-o.startTime))),o.duration!=null&&(a.ttlb=Math.round(o.duration)));let s=n.customData?.cmcd??{};this.recordEvent(ju,H(H(H({},s),a),t))}applyRequestReport(e){return this.createRequestReport(e)??e}isRequestReportingEnabled(){var e;return!!((e=this.config.enabledKeys)!=null&&e.length)}createRequestReport(e,t){var n;let{customData:r={},headers:i={}}=e,a=H(H({},Pt(e,gu)),{},{headers:H({},i),customData:H(H({},r),{},{cmcd:{}})});if(!((n=this.config.enabledKeys)!=null&&n.length)||!a.url)return a;let o=new URL(a.url),s=H(H(H({},this.data),t),{},{sn:this.requestTarget.sn++}),c=Td(Iu,this.config,a.url);!isNaN(this.msd)&&!this.requestTarget.msdSent&&(s.msd=this.msd,this.requestTarget.msdSent=!0);let l=a.customData.cmcd=id(s,c);switch(this.config.transmissionMode){case Cd:let e=hd(l);e&&(o.searchParams.set(md,e),a.url=o.toString());break;case wd:V(a.headers,pd(l,c.customHeaderMap))}return a}processEventTargets(e=!1){let t=!1;this.eventTargets.forEach((n,r)=>{let{queue:i}=n;if(!i.length||i.length<r.batchSize&&!e)return;let a=e?i.length:r.batchSize,o=i.splice(0,a);this.sendEventReport(r,o).catch(()=>{n.queue.unshift(...o)}),t||=i.length>0}),t&&this.processEventTargets()}async sendEventReport(e,t){let n=Td(Fu,e),{status:r}=await this.requester({url:e.url,method:`POST`,headers:{"Content-Type":yd},body:t.map(e=>gd(e,n)).join(`
|
|
29
|
+
initSegmentChange: ${S}`);let e=new Dl(n,r,t,o,l);this.configureTransmuxer(e)}if(this.frag=i,this.part=a,this.workerContext)this.workerContext.worker.postMessage({instanceNo:u,cmd:`demux`,data:e,decryptdata:p,chunkMeta:c,state:C},e instanceof ArrayBuffer?[e]:[]);else if(d){let t=d.push(e,p,c,C);El(t)?t.then(e=>{this.handleTransmuxComplete(e)}).catch(e=>{this.transmuxerError(e,c,`transmuxer-interface push error`)}):this.handleTransmuxComplete(t)}}flush(e){e.transmuxing.start=self.performance.now();let{instanceNo:t,transmuxer:n}=this;if(this.workerContext)this.workerContext.worker.postMessage({instanceNo:t,cmd:`flush`,chunkMeta:e});else if(n){let t=n.flush(e);El(t)?t.then(t=>{this.handleFlushResult(t,e)}).catch(t=>{this.transmuxerError(t,e,`transmuxer-interface flush error`)}):this.handleFlushResult(t,e)}}transmuxerError(e,t,n){this.hls&&(this.error=e,this.hls.trigger(L.ERROR,{type:F.MEDIA_ERROR,details:I.FRAG_PARSING_ERROR,chunkMeta:t,frag:this.frag||void 0,part:this.part||void 0,fatal:!1,error:e,err:e,reason:n}))}handleFlushResult(e,t){e.forEach(e=>{this.handleTransmuxComplete(e)}),this.onFlush(t)}configureTransmuxer(e){let{instanceNo:t,transmuxer:n}=this;this.workerContext?this.workerContext.worker.postMessage({instanceNo:t,cmd:`configure`,config:e}):n&&n.configure(e)}handleTransmuxComplete(e){e.chunkMeta.transmuxing.end=self.performance.now(),this.onTransmuxComplete(e)}},jl=100,Ml=class extends Ds{constructor(e,t,n){super(e,t,n,`audio-stream-controller`,z.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(L.LEVEL_LOADED,this.onLevelLoaded,this),e.on(L.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.on(L.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(L.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(L.BUFFER_RESET,this.onBufferReset,this),e.on(L.BUFFER_CREATED,this.onBufferCreated,this),e.on(L.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(L.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(L.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(L.FRAG_LOADING,this.onFragLoading,this),e.on(L.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){let{hls:e}=this;e&&(super.unregisterListeners(),e.off(L.LEVEL_LOADED,this.onLevelLoaded,this),e.off(L.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.off(L.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(L.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(L.BUFFER_RESET,this.onBufferReset,this),e.off(L.BUFFER_CREATED,this.onBufferCreated,this),e.off(L.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(L.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(L.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(L.FRAG_LOADING,this.onFragLoading,this),e.off(L.FRAG_BUFFERED,this.onFragBuffered,this))}onInitPtsFound(e,t){let{frag:n,id:r,initPTS:i,timescale:a,trackId:o,timestampOffsets:s}=t;if(r===z.MAIN){let e=n.cc,t=this.fragCurrent;if(this.initPTS=s,this.log(`InitPTS for cc: ${e} found from main: ${i/a} (${i}/${a}) trackId: ${o}`),this.mainAnchor=n,this.state===Q.WAITING_INIT_PTS){let t=this.waitingData;(!t&&!this.loadingParts||t&&t.frag.cc!==e)&&this.syncWithAnchor(n,t?.frag)}else!this.hls.hasEnoughToStart&&t&&t.cc!==e?(t.abortRequests(),this.syncWithAnchor(n,t)):this.state===Q.IDLE&&this.tick()}}getLoadPosition(){return!this.startFragRequested&&this.nextLoadPosition>=0&&this.switchingTrack?.flushImmediate!==!1?this.nextLoadPosition:super.getLoadPosition()}syncWithAnchor(e,t){let n=this.mainFragLoading?.frag||null;if(t&&n?.cc===t.cc)return;let r=(n||e).cc,i=oa(this.getLevelDetails(),r,this.getLoadPosition());i&&this.fragmentTracker.getState(i)!==Z.OK&&(this.log(`Syncing with main frag at ${i.start} cc ${i.cc}`),this.startFragRequested=!1,this.nextLoadPosition=i.start,this.resetLoadingState(),this.state===Q.IDLE&&this.doTickIdle())}startLoad(e,t){if(!this.levels){this.startPosition=e,this.state=Q.STOPPED;return}let n=this.lastCurrentTime;this.stopLoad(),this.setInterval(jl),n>0&&e===-1&&!t&&this.initPTS.length&&(this.log(`Override startPosition with lastCurrentTime @${n.toFixed(3)}`),e=n),this.state=Q.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 Q.IDLE:this.doTickIdle();break;case Q.WAITING_TRACK:{let{levels:e,trackId:t}=this,n=e?.[t],r=n?.details;if(r&&!this.waitForLive(n)){if(this.waitForCdnTuneIn(r))break;this.state=Q.WAITING_INIT_PTS}break}case Q.FRAG_LOADING_WAITING_RETRY:this.checkRetryDate();break;case Q.WAITING_INIT_PTS:{let e=this.waitingData;if(e){let{frag:t,part:n,cache:r,complete:i}=e,a=this.mainAnchor;if(this.initPTS[t.cc]!==void 0){this.waitingData=null,this.state=Q.FRAG_LOADING;let e={frag:t,part:n,payload:r.flush().buffer,networkDetails:null};this._handleFragmentLoadProgress(e),i&&super._handleFragmentLoadComplete(e)}else a&&a.cc!==e.frag.cc&&this.syncWithAnchor(a,e.frag)}else this.state=Q.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(){let{hls:e,levels:t,media:n,trackId:r}=this,i=e.config;if(!this.buffering||!n&&!this.primaryPrefetch&&(this.startFragRequested||!i.startFragPrefetch)||!(t!=null&&t[r]))return;let a=t[r],o=a.details;if(!o||this.waitForLive(a)||this.waitForCdnTuneIn(o)){this.state=Q.WAITING_TRACK,this.startFragRequested=!1;return}let s=this.getBufferOutput();this.bufferFlushed&&s&&(this.bufferFlushed=!1,this.afterBufferFlushed(s,B.AUDIO));let c=this.getFwdBufferInfo();if(c===null)return;if(!this.switchingTrack&&this._streamEnded(c,o)){e.trigger(L.BUFFER_EOS,{type:`audio`}),this.state=Q.ENDED;return}let l=c.len,u=e.maxBufferLength,d=o.fragments,f=d[0].start,p=this.getLoadPosition(),m=this.flushing||this.switchingTrack&&!this.switchingTrack.flushImmediate?p:c.end;if(this.switchingTrack&&n){let e=p;o.PTSKnown&&e<f&&e>=this.timelineOffset&&(c.end>f||c.nextStart)&&(this.log(`Alt audio track ahead of main track, seek to start of alt audio track ${e} -> ${f} + 0.05`),n.currentTime=f+.05)}if(l>=u&&!this.switchingTrack&&m<d[d.length-1].start)return;let h=this.getNextFragment(m,o);if(h&&this.isLoopLoading(h,m)&&(h=this.getNextFragmentLoopLoading(h,o,c,z.MAIN,u)),!h){this.bufferFlushed=!0;return}if(this.exceedsMaxBuffer(c,u,h))return;let g=this.mainFragLoading?.frag||null;if(!this.audioOnly&&this.startFragRequested&&g&&Tt(h)&&!h.endList&&(!o.live||!this.loadingParts&&m<this.hls.liveSyncPosition)&&(this.fragmentTracker.getState(g)===Z.OK&&(this.mainFragLoading=g=null),g&&Tt(g))){if(h.start>g.end){let e=this.fragmentTracker.getFragAtPos(m,z.MAIN);e&&e.end>g.end&&(g=e,this.mainFragLoading={frag:e,targetBufferTime:null})}if(h.start>g.end)return}this.loadFragment(h,a,m)}onMediaDetaching(e,t){this.bufferFlushed=this.flushing=!1,super.onMediaDetaching(e,t)}onAudioTracksUpdated(e,{audioTracks:t}){this.resetTransmuxer(),this.levels=t.map(e=>new Mi(e))}onAudioTrackSwitching(e,t){let n=!!t.url;this.trackId=t.id;let{fragCurrent:r}=this;r&&(r.abortRequests(),this.removeUnbufferedFrags(r.start)),this.resetLoadingState(),n?(this.switchingTrack=t,t.flushImmediate||(this.nextTrackId=t.id,this.nextLevelSwitch()),this.flushAudioIfNeeded(t),this.state!==Q.STOPPED&&(this.setInterval(jl),this.state=Q.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 n=this.cachedTrackLoadedData;n&&(this.cachedTrackLoadedData=null,this.onAudioTrackLoaded(L.AUDIO_TRACK_LOADED,n))}onAudioTrackLoaded(e,t){var n;let{levels:r}=this,{details:i,id:a,groupId:o,track:s}=t;if(!r){this.warn(`Audio tracks reset while loading track ${a} "${s.name}" of "${o}"`);return}let c=this.mainDetails;if(!c||i.endCC>c.endCC||c.expired){this.cachedTrackLoadedData=t,this.state!==Q.STOPPED&&(this.state=Q.WAITING_TRACK);return}this.cachedTrackLoadedData=null,this.log(`Audio track ${a} "${s.name}" of "${o}" loaded [${i.startSN},${i.endSN}]${i.lastPartSn?`[part-${i.lastPartSn}-${i.lastPartIndex}]`:``},duration:${i.totalduration}`);let l=r[a],u=0;if(i.live||(n=l.details)!=null&&n.live){if(this.checkLiveUpdate(i),i.deltaUpdateFailed)return;l.details&&(u=this.alignPlaylists(i,l.details,this.levelLastLoaded?.details)),i.alignedSliding||(ws(c,i,this),u=i.fragmentStart)}l.details=i,this.levelLastLoaded=l,this.startFragRequested||this.setStartPosition(c,u),this.hls.trigger(L.AUDIO_TRACK_UPDATED,{details:i,id:a,groupId:t.groupId}),this.state===Q.WAITING_TRACK&&!this.waitForCdnTuneIn(i)&&(this.state=Q.IDLE),this.tick()}_handleFragmentLoadProgress(e){let t=e.frag,{part:n,payload:r}=e,{config:i,trackId:a,levels:o}=this;if(!o){this.warn(`Audio tracks were reset while fragment load was in progress. Fragment ${t.sn} of level ${t.level} will not be buffered`);return}let s=o[a];if(!s){this.warn(`Audio track is undefined on fragment load progress`);return}let c=s.details;if(!c){this.warn(`Audio track details undefined on fragment load progress`),this.removeUnbufferedFrags(t.start);return}let l=i.defaultAudioCodec||s.audioCodec||`mp4a.40.2`,u=this.transmuxer;u||=this.transmuxer=new Al(this.hls,z.AUDIO,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this));let d=this.initPTS[t.cc],f=t.initSegment?.data;if(d!==void 0){let e=n?n.index:-1,i=e!==-1,a=new Qa(t.level,t.sn,t.stats.chunkCount,r.byteLength,e,i,t.duration);u.push(r,f,l,``,t,n,c.totalduration,!1,a,d)}else{this.log(`Unknown video PTS for cc ${t.cc}, waiting for video PTS before demuxing audio frag ${t.sn} of [${c.startSN} ,${c.endSN}],track ${a}`);let{cache:e}=this.waitingData=this.waitingData||{frag:t,part:n,cache:new As,complete:!1};e.push(new Uint8Array(r)),this.state!==Q.STOPPED&&(this.state=Q.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 n=t.tracks.audio;n&&(this.mediaBuffer=n.buffer||null)}onFragLoading(e,t){!this.audioOnly&&t.frag.type===z.MAIN&&Tt(t.frag)&&(this.mainFragLoading=t,this.state===Q.IDLE&&this.tick())}onFragBuffered(e,t){let{frag:n,part:r}=t;if(n.type!==z.AUDIO){!this.audioOnly&&n.type===z.MAIN&&!n.elementaryStreams.video&&!n.elementaryStreams.audiovideo&&(this.audioOnly=!0,this.mainFragLoading=null);return}if(this.fragContextChanged(n)){this.warn(`Fragment ${n.sn}${r?` p: `+r.index:``} of level ${n.level} finished buffering, but was aborted. state: ${this.state}, audioSwitch: ${this.switchingTrack?this.switchingTrack.name:`false`}`);return}if(Tt(n)){let e=this.switchingTrack;e&&(this.bufferedTrack=e)}this.fragBufferedComplete(n,r),this.media&&this.tick()}getFwdBufferInfo(){let e=this.getBufferOutput();return super.getFwdBufferInfo(e,z.AUDIO)}getBufferOutput(){return this.mediaBuffer?this.mediaBuffer:this.media}checkFragmentChanged(){let e=this.fragPlaying;if(!this.checkFragPlaying())return!1;let{fragPlaying:t,switchingTrack:n}=this,r=!t||t.level!==e?.level;return r&&e&&this.cleanupBackBuffer(),n&&(r||t?.level===n.id)&&this.completeAudioSwitch(n),!0}onError(e,t){if(t.fatal){this.state=Q.ERROR;return}switch(t.details){case I.FRAG_GAP:case I.FRAG_PARSING_ERROR:case I.FRAG_DECRYPT_ERROR:case I.FRAG_LOAD_ERROR:case I.FRAG_LOAD_TIMEOUT:case I.KEY_LOAD_ERROR:case I.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(z.AUDIO,t);break;case I.AUDIO_TRACK_LOAD_ERROR:case I.AUDIO_TRACK_LOAD_TIMEOUT:case I.LEVEL_PARSING_ERROR:!t.levelRetry&&this.state===Q.WAITING_TRACK&&t.context?.type===R.AUDIO_TRACK&&(this.state=Q.IDLE);break;case I.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 I.MEDIA_SOURCE_REQUIRES_RESET:this.onSourceBufferError(z.AUDIO,t);break;case I.BUFFER_ADD_CODEC_ERROR:case I.BUFFER_APPEND_ERROR:if(t.parent!==`audio`)return;this.reduceLengthAndFlushBuffer(t)||this.resetLoadingState();break;case I.BUFFER_FULL_ERROR:if(t.parent!==`audio`)return;this.reduceLengthAndFlushBuffer(t)&&(this.bufferedTrack=null,super.flushMainBuffer(0,1/0,`audio`));break;case I.INTERNAL_EXCEPTION:this.recoverWorkerError(t)}}onBufferFlushing(e,{type:t}){t!==B.VIDEO&&(this.flushing=!0)}onBufferFlushed(e,{type:t}){if(t!==B.VIDEO){this.flushing=!1,this.bufferFlushed=!0,this.state===Q.ENDED&&(this.state=Q.IDLE);let e=this.getBufferOutput();e&&(this.afterBufferFlushed(e,t),this.tick())}}_handleTransmuxComplete(e){var t;let n=`audio`,{hls:r}=this,{remuxResult:i,chunkMeta:a}=e,o=this.getCurrentContext(a);if(!o){this.resetWhenMissingContext(a);return}let{frag:s,part:c,level:l}=o,{details:u}=l,{audio:d,text:f,id3:p,initSegment:m}=i;if(this.fragContextChanged(s)||!u){this.fragmentTracker.removeFragment(s),m!=null&&m.tracks&&this.resetTransmuxer();return}if(this.state=Q.PARSING,d&&this.switchingTrack&&!this.switchingTrack.flushImmediate){let{config:e}=this,t=e.nextAudioTrackBufferFlushForwardOffset,n=Math.max(this.getLoadPosition()+t,(c||s).start);super.flushMainBuffer(n,1/0,z.AUDIO)}if(m!=null&&m.tracks){let e=s.initSegment||s;if(this.unhandledEncryptionError(m,s))return;this._bufferInitSegment(l,m.tracks,e,a),r.trigger(L.FRAG_PARSING_INIT_SEGMENT,{frag:e,id:n,tracks:m.tracks})}if(d){let{startPTS:e,endPTS:t,startDTS:n,endDTS:r}=d;c&&(c.elementaryStreams[B.AUDIO]={startPTS:e,endPTS:t,startDTS:n,endDTS:r}),s.setElementaryStreamInfo(B.AUDIO,e,t,n,r),this.bufferFragmentData(d,s,c,a)}if(p!=null&&(t=p.samples)!=null&&t.length){let e=V({id:n,frag:s,details:u},p);r.trigger(L.FRAG_PARSING_METADATA,e)}if(f){let e=V({id:n,frag:s,details:u},f);r.trigger(L.FRAG_PARSING_USERDATA,e)}}_bufferInitSegment(e,t,n,r){if(this.state!==Q.PARSING||(t.video&&delete t.video,t.audiovideo&&delete t.audiovideo,!t.audio))return;let i=t.audio;i.id=z.AUDIO;let a=e.audioCodec;this.log(`Init audio buffer, container:${i.container}, codecs[level/parsed]=[${a}/${i.codec}]`),a?.split(`,`).length===1&&(i.levelCodec=a),this.hls.trigger(L.BUFFER_CODECS,t);let o=i.initSegment;if(o!=null&&o.byteLength){let e={type:`audio`,frag:n,part:null,chunkMeta:r,parent:n.type,data:o};this.hls.trigger(L.BUFFER_APPENDING,e)}this.tickImmediate()}loadFragment(e,t,n){let r=this.fragmentTracker.getState(e);if(this.switchingTrack||r===Z.NOT_LOADED||r===Z.PARTIAL){var i;if((i=t.details)!=null&&i.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=Q.WAITING_INIT_PTS;let n=this.mainDetails;n&&n.fragmentStart!==t.details.fragmentStart&&ws(n,t.details,this)}else super.loadFragment(e,t,n)}else this.clearTrackerIfNeeded(e)}flushAudioIfNeeded(e){if(this.media&&this.bufferedTrack&&e.flushImmediate){let{name:t,lang:n,assocLang:r,characteristics:i,audioCodec:a,channels:o}=this.bufferedTrack;Ui({name:t,lang:n,assocLang:r,characteristics:i,audioCodec:a,channels:o},e,Ki)||(Yi(e.url,this.hls)?(this.log(`Switching audio track : flushing all audio`),super.flushMainBuffer(0,1/0,`audio`),this.bufferedTrack=null):this.bufferedTrack=e)}}completeAudioSwitch(e){let{hls:t}=this;this.bufferedTrack=e,this.switchingTrack=null,t.trigger(L.AUDIO_TRACK_SWITCHED,H({},e))}get nextAudioTrack(){return this.nextTrackId}},Nl=class extends Xt{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,n){let r=t?.renditionReports;if(r){let i=-1;for(let n=0;n<r.length;n++){let a=r[n],o;try{o=new self.URL(a.URI,t.url).href}catch(e){this.warn(`Could not construct new URL for Rendition Report: ${e}`),o=a.URI||``}if(o===e){i=n;break}o===e.substring(0,o.length)&&(i=n)}if(i!==-1){let e=r[i],a=parseInt(e[`LAST-MSN`])||t.lastPartSn,o=parseInt(e[`LAST-PART`])||t.lastPartIndex;if(this.hls.config.lowLatencyMode){let e=Math.min(t.age-t.partTarget,t.targetduration);o>=0&&e>t.partTarget&&(o+=1)}let s=n&&Ai(n);return new ji(a,o>=0?o:void 0,s)}}}loadPlaylist(e){this.clearTimer()}loadingPlaylist(e,t){this.clearTimer()}shouldLoadPlaylist(e){return this.canLoad&&!!e&&!!e.url&&(!e.details||e.details.live)}getUrlWithDirectives(e,t){if(t)try{return t.addDirectives(e)}catch(e){this.warn(`Could not construct new URL with HLS Delivery Directives: ${e}`)}return e}playlistLoaded(e,t,n){let{details:r,stats:i}=t,a=r.fragments,o=self.performance.now(),s=i.loading.first?Math.max(0,Math.floor(o-i.loading.first)):0;r.advancedDateTime=Date.now()-s;let c=this.hls.config.timelineOffset;if(c!==r.appliedTimelineOffset){let e=Math.max(c||0,0);r.appliedTimelineOffset=e,a.forEach(t=>{t?.setStart(t.playlistOffset+e)})}if(r.live||n!=null&&n.live){let c=`levelInfo`in t?t.levelInfo:t.track;r.reloaded(n);let l=a[a.length-1]?.type;if(r.misses>=this.hls.config.liveMaxUnchangedPlaylistRefresh){let e=Error(`${l} playlist ${c.id} hit max allowed unchanged reloads.`);this.warn(e);let{networkDetails:n,context:a}=t;this.hls.trigger(L.ERROR,{type:F.NETWORK_ERROR,details:I.PLAYLIST_UNCHANGED_ERROR,fatal:!1,url:r.url,error:e,reason:e.message,level:t.level,parent:l,context:a,networkDetails:n,stats:i});return}if(n){os(n,r,this);let e=r.playlistParsingError;if(e){this.warn(e);let n=this.hls;if(!n.config.ignorePlaylistParsingErrors){let{networkDetails:a}=t;n.trigger(L.ERROR,{type:F.NETWORK_ERROR,details:I.LEVEL_PARSING_ERROR,fatal:!1,url:r.url,error:e,reason:e.message,level:t.level,parent:l,networkDetails:a,stats:i});return}r.playlistParsingError=null}}r.requestScheduled===-1&&(r.requestScheduled=i.loading.start);let u=this.hls.mainForwardBufferInfo,d=u?u.end-u.len:0,f=ps(r,(r.edge-d)*1e3);r.requestScheduled+f<o?r.requestScheduled=o:r.requestScheduled<=o&&(r.requestScheduled+=f);let p=t.deliveryDirectives;if(this.log(`live playlist ${e} ${r.advanced?`REFRESHED ${r.lastPartSn} - ${r.lastPartIndex}`:r.updated?`UPDATED`:`MISSED (received ${r.lastPartSn} - ${r.lastPartIndex}${p?` | requested ${p.msn} - ${p.part}`:``})`}`),!this.canLoad||!r.live)return;let m,h,g;if(r.canBlockReload&&r.advanced){let e=this.hls.config.lowLatencyMode,i=r.lastPartSn,a=r.endSN,s=r.lastPartIndex,l=s!==-1,u=i===a;l?u?(h=a+1,g=e?0:s):(h=i,g=e?s+1:r.maxPartIndex):h=a+1;let d=r.age,f=d+r.ageHeader,p=Math.min(f-r.partTarget,r.targetduration*1.5);if(p>0){if(f>r.targetduration*3)this.log(`Playlist last advanced ${d.toFixed(2)}s ago. Omitting segment and part directives.`),h=void 0,g=void 0;else if(n!=null&&n.tuneInGoal&&f-r.partTarget>n.tuneInGoal)this.warn(`CDN Tune-in goal increased from: ${n.tuneInGoal} to: ${p} with playlist age: ${r.age}`),p=0;else{let e=Math.floor(p/r.targetduration);if(h+=e,g!==void 0){let e=Math.round(p%r.targetduration/r.partTarget);g+=e}this.log(`CDN Tune-in age: ${r.ageHeader}s last advanced ${d.toFixed(2)}s goal: ${p} skip sn ${e} to part ${g}`)}r.tuneInGoal=p}if(m=this.getDeliveryDirectives(r,t.deliveryDirectives,h,g),e||!u){r.requestScheduled=o,this.loadingPlaylist(c,m);return}}else(r.canBlockReload||r.canSkipUntil)&&(m=this.getDeliveryDirectives(r,t.deliveryDirectives,h,g));m&&h!==void 0&&r.canBlockReload&&(r.requestScheduled=i.loading.first+Math.max(f-s*2,f/2)),this.scheduleLoading(c,m,r)}else this.clearTimer()}scheduleLoading(e,t,n){let r=n||e.details;if(!r){this.loadingPlaylist(e,t);return}let i=self.performance.now(),a=r.requestScheduled;if(i>=a&&!this.loadingSync){this.loadingSync=!0,this.loadingPlaylist(e,t),this.loadingSync=!1;return}let o=Math.max(a-i,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,n,r){let i=Ai(e);return t!=null&&t.skip&&e.deltaUpdateFailed&&(n=t.msn,r=t.part,i=ki.No),new ji(n,r,i)}checkRetry(e){let t=e.details,n=Rt(e),r=e.errorAction,{action:i,retryCount:a=0,retryConfig:o}=r||{},s=!!r&&!!o&&(i===ca.RetryRequest||!r.resolved&&i===ca.SendAlternateToPenaltyBox);if(s){var c;if(a>=o.maxNumRetry)return!1;if(n&&(c=e.context)!=null&&c.deliveryDirectives)this.warn(`Retrying playlist loading ${a+1}/${o.maxNumRetry} after "${t}" without delivery-directives`),this.loadPlaylist();else{let n=Kt(e.response?.code);if(this.clearTimer(),n)this.log(`Waiting for connection (offline)`),e.reason=`offline`,this.timer=self.setTimeout(()=>this.checkOfflineStatus(),1e3);else{let e=Ht(o,a);this.warn(`Retrying playlist loading ${a+1}/${o.maxNumRetry} after "${t}" in ${e}ms`),this.timer=self.setTimeout(()=>this.loadPlaylist(),e)}}e.levelRetry=!0,r.resolved=!0}return s}checkOfflineStatus(){this.clearTimer(),Kt(0)?this.timer=self.setTimeout(()=>this.checkOfflineStatus(),1e3):(this.log(`Connection restored (online)`),this.loadPlaylist())}};function Pl(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(!Fl(e[n].attrs,t[n].attrs))return!1;return!0}function Fl(e,t,n){let r=e[`STABLE-RENDITION-ID`];return r&&!n?r===t[`STABLE-RENDITION-ID`]:!(n||[`LANGUAGE`,`NAME`,`CHARACTERISTICS`,`AUTOSELECT`,`DEFAULT`,`FORCED`,`ASSOC-LANGUAGE`]).some(n=>e[n]!==t[n])}var Il=class extends Nl{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(L.MANIFEST_LOADING,this.onManifestLoading,this),e.on(L.MANIFEST_PARSED,this.onManifestParsed,this),e.on(L.LEVEL_LOADING,this.onLevelLoading,this),e.on(L.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(L.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(L.ERROR,this.onError,this)}unregisterListeners(){let{hls:e}=this;e.off(L.MANIFEST_LOADING,this.onManifestLoading,this),e.off(L.MANIFEST_PARSED,this.onManifestParsed,this),e.off(L.LEVEL_LOADING,this.onLevelLoading,this),e.off(L.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(L.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(L.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:n,groupId:r,details:i}=t,a=this.tracksInGroup[n];if(!a||a.groupId!==r){this.warn(`Audio track with id:${n} and group:${r} not found in active group ${a?.groupId}`);return}let o=a.details;a.details=t.details,this.log(`Audio track ${n} "${a.name}" lang:${a.lang} group:${r} loaded [${i.startSN}-${i.endSN}]`),n===this.trackId&&this.playlistLoaded(n,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 n=t.audioGroups||null,r=this.groupIds,i=this.currentTrack;if(!n||r?.length!==n?.length||n!=null&&n.some(e=>r?.indexOf(e)===-1)){this.groupIds=n,this.trackId=-1,this.currentTrack=null;let e=this.tracks.filter(e=>Xi(e.groupId,n));if(e.length)this.selectDefaultTrack&&!e.some(e=>e.default)&&(this.selectDefaultTrack=!1),e.forEach((e,t)=>{e.id=t});else if(!i&&!this.tracksInGroup.length)return;this.tracksInGroup=e;let t=this.hls.config.audioPreference;if(!i&&t){let n=Hi(t,e,Ki);if(n>-1)i=e[n];else{let e=Hi(t,this.tracks);i=this.tracks[e]}}let r=this.findTrackId(i);r===-1&&i&&(r=this.findTrackId(null));let a={audioTracks:e};this.log(`Updating audio tracks, ${e.length} track(s) found in group(s): ${n?.join(`,`)}`),this.hls.trigger(L.AUDIO_TRACKS_UPDATED,a);let o=this.trackId;if(r!==-1&&o===-1)this.setAudioTrack(r);else if(e.length&&o===-1){let t=Error(`No audio track selected for current audio group-ID(s): ${this.groupIds?.join(`,`)} track count: ${e.length}`);this.warn(t.message),this.hls.trigger(L.ERROR,{type:F.MEDIA_ERROR,details:I.AUDIO_TRACK_LOAD_ERROR,fatal:!0,error:t})}}}onError(e,t){!t.fatal&&t.context&&t.context.type===R.AUDIO_TRACK&&t.context.id===this.trackId&&Xi(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 n=this.allAudioTracks;if(this.selectDefaultTrack=!1,n.length){let r=this.currentTrack;if(r&&Ui(e,r,Ki))return r;let i=Hi(e,this.tracksInGroup,Ki);if(i>-1){let t=this.tracksInGroup[i];return this.setAudioTrack(i,`flushImmediate`in e&&e.flushImmediate),t}if(r){let r=t.loadLevel;r===-1&&(r=t.firstAutoLevel);let i=qi(e,t.levels,n,r,Ki);if(i===-1)return null;t.nextLoadLevel=i}if(e.channels||e.audioCodec){let t=Hi(e,n);if(t>-1)return n[t]}}}return null}setAudioTrack(e,t=!0){let n=this.tracksInGroup;if(e<0||e>=n.length){this.warn(`Invalid audio track id: ${e}`);return}this.selectDefaultTrack=!1;let r=this.currentTrack,i=n[e],a=i.details&&!i.details.live;if(e===this.trackId&&i===r&&a||(this.log(`Switching to audio-track ${e} "${i.name}" lang:${i.lang} group:${i.groupId} channels:${i.channels}`),this.trackId=e,this.currentTrack=i,this.hls.trigger(L.AUDIO_TRACK_SWITCHING,H(H({},i),{},{flushImmediate:t})),a))return;let o=this.switchParams(i.url,r?.details,i.details);this.loadPlaylist(o)}findTrackId(e){let t=this.tracksInGroup;for(let n=0;n<t.length;n++){let r=t[n];if((!this.selectDefaultTrack||r.default)&&(!e||Ui(e,r,Ki)))return n}if(e){let{name:n,lang:r,assocLang:i,characteristics:a,audioCodec:o,channels:s}=e;for(let e=0;e<t.length;e++){let c=t[e];if(Ui({name:n,lang:r,assocLang:i,characteristics:a,audioCodec:o,channels:s},c,Ki))return e}for(let n=0;n<t.length;n++){let r=t[n];if(Fl(e.attrs,r.attrs,[`LANGUAGE`,`ASSOC-LANGUAGE`,`CHARACTERISTICS`]))return n}for(let n=0;n<t.length;n++){let r=t[n];if(Fl(e.attrs,r.attrs,[`LANGUAGE`]))return n}}return-1}loadPlaylist(e){super.loadPlaylist();let t=this.currentTrack;this.shouldLoadPlaylist(t)&&Yi(t.url,this.hls)&&this.scheduleLoading(t,e)}loadingPlaylist(e,t){super.loadingPlaylist(e,t);let n=e.id,r=e.groupId,i=this.getUrlWithDirectives(e.url,t),a=e.details,o=a?.age;this.log(`Loading audio-track ${n} "${e.name}" lang:${e.lang} group:${r}${t?.msn===void 0?``:` at sn `+t.msn+` part `+t.part}${o&&a.live?` age `+o.toFixed(1)+(a.type&&` `+a.type||``):``} ${i}`),this.hls.trigger(L.AUDIO_TRACK_LOADING,{url:i,id:n,groupId:r,deliveryDirectives:t||null,track:e})}},Ll=class e{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=1/0,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(L.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.on(L.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(L.MANIFEST_PARSED,this.onManifestParsed,this),e.on(L.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(L.BUFFER_CODECS,this.onBufferCodecs,this),e.on(L.MEDIA_DETACHING,this.onMediaDetaching,this))}unregisterListener(){let{hls:e}=this;e&&(e.off(L.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.off(L.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(L.MANIFEST_PARSED,this.onManifestParsed,this),e.off(L.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(L.BUFFER_CODECS,this.onBufferCodecs,this),e.off(L.MEDIA_DETACHING,this.onMediaDetaching,this))}onFpsDropLevelCapping(e,t){if(!this.hls)return;let n=this.hls.levels[t.droppedLevel];this.isLevelAllowed(n)&&this.restrictedLevels.push({bitrate:n.bitrate,height:n.height,width:n.width})}onMediaAttaching(e,t){let n=t.media;this.clientRect=null,this.hls&&(n instanceof HTMLVideoElement?(this.media=n,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)&&(P(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(e=>!!e.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,n=this.getMaxLevel(e.length-1);n!==this.autoLevelCapping&&t.logger.log(`Setting autoLevelCapping to ${n}: ${e[n].height}p@${e[n].bitrate} for media ${this.mediaWidth}x${this.mediaHeight}`),t.autoLevelCapping=n,t.autoLevelEnabled&&t.autoLevelCapping>this.autoLevelCapping&&this.streamController&&this.streamController.nextLevelSwitch(),this.autoLevelCapping=t.autoLevelCapping}else e.length===1&&this.stopCapping()}}getMaxLevel(t){if(!this.hls)return-1;let n=this.hls.levels;if(!n.length)return-1;let r=n.filter((e,n)=>this.isLevelAllowed(e)&&n<=t);return this.observer||(this.clientRect=null),e.getMaxLevelByMediaSize(r,this.mediaWidth,this.mediaHeight)}observe(){let e=self.ResizeObserver;e&&(this.observer=new e(e=>{let t=e[0]?.contentRect;t&&(this.clientRect=t,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=1/0,this.observe(),this.observer||(this.timer=self.setInterval(this.detectPlayerSize.bind(this),1e3)),this.detectPlayerSize())}stopCapping(){this.restrictedLevels=[],this.autoLevelCapping=1/0,this.timer&&=(self.clearInterval(this.timer),void 0),this.observer&&=(this.observer.disconnect(),void 0)}getDimensions(){if(this.clientRect)return this.clientRect;let e=this.media,t={width:0,height:0};if(e){let n=e.getBoundingClientRect();t.width=n.width,t.height=n.height,!t.width&&!t.height&&(t.width=n.right-n.left||e.width||0,t.height=n.bottom-n.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:n}=this.hls.config;if(!t)try{e=self.devicePixelRatio}catch{}return Math.min(e,n)}isLevelAllowed(e){return!this.restrictedLevels.some(t=>e.bitrate===t.bitrate&&e.width===t.width&&e.height===t.height)}static getMaxLevelByMediaSize(e,t,n){if(!(e!=null&&e.length))return-1;let r=(e,t)=>!t||e.width!==t.width||e.height!==t.height,i=e.length-1,a=Math.max(t,n);for(let t=0;t<e.length;t+=1){let n=e[t];if((n.width>=a||n.height>=a)&&r(n,e[t+1])){i=t;break}}return i}},Rl=class e{constructor(t,n){Array.isArray(t)&&(t=t.map(t=>t instanceof e?t:new e(t))),this.value=t,this.params=n}},zl=`Dict`;function Bl(e){return Array.isArray(e)?JSON.stringify(e):e instanceof Map?`Map{}`:e instanceof Set?`Set{}`:typeof e==`object`?JSON.stringify(e):String(e)}function Vl(e,t,n,r){return Error(`failed to ${e} "${Bl(t)}" as ${n}`,{cause:r})}var Hl=`Bare Item`,Ul=`Boolean`,Wl=`Byte Sequence`,Gl=`Decimal`,Kl=`Integer`;function ql(e){return e<-999999999999999||999999999999999<e}var Jl=`String`,Yl=/[\x00-\x1f\x7f]+/,Xl=class{constructor(e){this.description=e}},Zl=`Token`,Ql=`Key`;function $l(e,t,n){return Vl(`serialize`,e,t,n)}function eu(e){if(typeof e!=`boolean`)throw $l(e,Ul);return e?`?1`:`?0`}function tu(e){if(ArrayBuffer.isView(e)===!1)throw $l(e,Wl);return`:${cn(e)}:`}function nu(e){if(ql(e))throw $l(e,Kl);return e.toString()}function ru(e){return`@${nu(e.getTime()/1e3)}`}function iu(e){let t=gn(e,3);if(Math.floor(Math.abs(t)).toString().length>12)throw $l(e,Gl);let n=t.toString();return n.includes(`.`)?n:`${n}.0`}function au(e){if(Yl.test(e))throw $l(e,Jl);return`"${e.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`)}"`}function ou(e){return e.description||e.toString().slice(7,-1)}function su(e){let t=ou(e);if(/^([a-zA-Z*])([!#$%&'*+\-.^_`|~\w:/]*)$/.test(t)===!1)throw $l(t,Zl);return t}function cu(e){switch(typeof e){case`number`:if(!P(e))throw $l(e,Hl);return Number.isInteger(e)?nu(e):iu(e);case`string`:return au(e);case`symbol`:return su(e);case`boolean`:return eu(e);case`object`:if(e instanceof Date)return ru(e);if(e instanceof Uint8Array)return tu(e);if(e instanceof Xl)return su(e);default:throw $l(e,Hl)}}function lu(e){if(/^[a-z*][a-z0-9\-_.*]*$/.test(e)===!1)throw $l(e,Ql);return e}function uu(e){return e==null?``:Object.entries(e).map(([e,t])=>t===!0?`;${lu(e)}`:`;${lu(e)}=${cu(t)}`).join(``)}function du(e){return e instanceof Rl?`${cu(e.value)}${uu(e.params)}`:cu(e)}function fu(e){return`(${e.value.map(du).join(` `)})${uu(e.params)}`}function pu(e,t={whitespace:!0}){if(typeof e!=`object`||!e)throw $l(e,zl);let n=e instanceof Map?e.entries():Object.entries(e),r=t!=null&&t.whitespace?` `:``;return Array.from(n).map(([e,t])=>{t instanceof Rl||(t=new Rl(t));let n=lu(e);return t.value===!0?n+=uu(t.params):(n+=`=`,Array.isArray(t.value)?n+=fu(t):n+=du(t)),n}).join(`,${r}`)}function mu(e,t){return pu(e,t)}var hu=[`url`],gu=[`version`,`eventTargets`,`sid`,`transmissionMode`],_u=[`customData`,`headers`],vu=e=>e instanceof Rl?new Rl(Math.round(e.value),e.params):Math.round(e),yu=e=>Array.isArray(e)?e.map(vu):vu(e),bu=(e,t)=>Array.isArray(e)?e.map(e=>bu(e,t)):e instanceof Rl&&typeof e.value==`string`?new Rl(bu(e.value,t),e.params):(t.baseUrl&&(e=_n(e,hn(t.baseUrl))),t.version===1?encodeURIComponent(e):e),xu=e=>e instanceof Rl?new Rl(Math.round(e.value/100)*100,e.params):Math.round(e/100)*100,Su=e=>Array.isArray(e)?e.map(xu):xu(e),Cu={br:yu,d:yu,bl:Su,dl:Su,mtp:Su,nor:(e,t)=>{let n=e;return t.version>=2&&(e instanceof Rl&&typeof e.value==`string`?n=new Rl([e]):typeof e==`string`&&(n=[e])),bu(n,t)},rtp:Su,tb:yu},wu=2,Tu=`bc`,Eu=`ps`,Du=`pr`,Ou=`e`,ku=`t`,Au=`c`,ju=`b`,Mu=`rr`,Nu=`ce`,Pu={BITRATE_CHANGE:Tu,ERROR:Ou,RESPONSE_RECEIVED:Mu,CUSTOM_EVENT:Nu},Fu=new Map([[Eu,`sta`],[Du,`pr`],[Au,`cid`],[ju,`bg`],[Tu,`br`]]),Iu=`event`,Lu=`request`,Ru=[`cen`,`e`,`h`,`ts`],zu=`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`.split(`.`),Bu=/^[a-zA-Z0-9-.]+-[a-zA-Z0-9-.]+$/;function Vu(e){return Bu.test(e)}var Hu=new Set(zu);function Uu(e){return Hu.has(e)||Vu(e)}var Wu=[`cmsdd`,`cmsds`,`rc`,`smrt`,`ttfb`,`ttfbb`,`ttlb`,`url`],Gu=new Set(Wu);function Ku(e){return Gu.has(e)}var qu=new Set(Ru);function Ju(e){return Uu(e)||Ku(e)||qu.has(e)}var Yu=new Set([`ab`,`bl`,`br`,`bsa`,`bsd`,`bsda`,`lab`,`lb`,`mtp`,`pb`,`tab`,`tb`,`tbl`,`tpb`]),Xu=[`bl`,`br`,`bs`,`cid`,`d`,`dl`,`mtp`,`nor`,`nrr`,`ot`,`pr`,`rtp`,`sf`,`sid`,`st`,`su`,`tb`,`v`],Zu=new Set(Xu);function Qu(e){return Zu.has(e)||Vu(e)}var $u=new Set([`ot`,`sf`,`st`,`e`,`sta`]);function ed(e){return $u.has(e)}function td(e){return typeof e==`number`?P(e):e!=null&&e!==``&&e!==!1}var nd={[Iu]:Ju,[Lu]:Uu};function rd(e,t){if(Array.isArray(e)){let n;return t&&(n=e.find(e=>e.params?.ot===t)),n||=e[0],rd(n)}return e instanceof Rl?e.value:e}function id(e){let t={};for(let[r,i]of Object.entries(e)){if(i==null){t[r]=i;continue}if(r===`nor`){let e=(Array.isArray(i)?i:[i])[0];if(e instanceof Rl){var n;t.nor=e.value,(n=e.params)!=null&&n.r&&(t.nrr=e.params.r)}else t.nor=e}else t[r]=Yu.has(r)?rd(i,e.ot):i}return t}function ad(e,t={}){let n={};if(typeof e!=`object`||!e)return n;let r=t.version||e.v||wu,i=t.reportingMode||Lu,a=r===1?id(e):e,o=r===1?Qu:nd[i],s=Object.keys(a).filter(o);a.e&&a.e!==Mu&&(s=s.filter(e=>!Ku(e)));let c=t.filter;typeof c==`function`&&(s=s.filter(c));let l=i===Iu;if(l){let e=a.e;!s.includes(`e`)&&e!=null&&s.push(`e`),s.includes(`ts`)||s.push(`ts`),!s.includes(`cen`)&&a.cen!=null&&e===Nu&&s.push(`cen`);let t=e?Fu.get(e):void 0;t&&a[t]!=null&&!s.includes(t)&&s.push(t)}if(s.length===0)return n;r>1&&!s.includes(`v`)&&s.push(`v`);let u={version:r,reportingMode:i,baseUrl:t.baseUrl};s.sort();for(let e of s){let i=a[e],o=t.formatters?.[e]??Cu[e];if(typeof o==`function`&&(i=o(i,u)),e===`v`){if(r===1)continue;i=r}if(e===`pr`&&i===1&&!(l&&a.e===Du))continue;l&&e===`ts`&&!P(i)&&(i=Date.now());let s=l&&i===!1&&e===`bg`&&a.e===ju;(td(i)||s)&&(ed(e)&&typeof i==`string`&&(i=new Xl(i)),n[e]=i)}return n}var od=`CMCD-Object`,sd=`CMCD-Request`,cd=`CMCD-Session`,ld=`CMCD-Status`,ud={REQUEST:sd},dd={ab:od,br:od,d:od,lab:od,lb:od,ot:od,tab:od,tb:od,tpb:od,bl:sd,cs:sd,dfa:sd,dl:sd,ltc:sd,mtp:sd,nor:sd,nrr:sd,pb:sd,sn:sd,sta:sd,su:sd,tbl:sd,cid:cd,msd:cd,sf:cd,sid:cd,st:cd,v:cd,bg:ld,bs:ld,bsa:ld,bsd:ld,bsda:ld,cdn:ld,ec:ld,nr:ld,pr:ld,pt:ld,rtp:ld};function fd(e){return Object.keys(e).reduce((t,n)=>{var r;return(r=e[n])==null||r.forEach(e=>t[e]=n),t},{})}function pd(e,t){let n={};if(!e)return n;let r=Object.keys(e),i=t?fd(t):{};for(let t of r){let r=dd[t]||i[t]||ud.REQUEST,a=n[r]??(n[r]={});a[t]=e[t]}return n}function md(e,t){let n={},r=pd(e,t);for(let[e,t]of Object.entries(r)){let r=mu(t,{whitespace:!1});r&&(n[e]=r)}return n}var hd=`CMCD`;function gd(e){return mu(e,{whitespace:!1})}function _d(e,t={}){return e?gd(ad(e,t)):``}var vd=30,yd=[...Xu,...zu,...Wu,...Ru].filter((e,t,n)=>n.indexOf(e)===t),bd=`application/cmcd`,xd=1,Sd={MANIFEST:`m`,AUDIO:`a`,VIDEO:`v`,MUXED:`av`,INIT:`i`,CAPTION:`c`,TIMED_TEXT:`tt`,KEY:`k`,OTHER:`o`},Cd={STARTING:`s`,PLAYING:`p`,SEEKING:`k`,REBUFFERING:`r`,PAUSED:`a`,ENDED:`e`,FATAL_ERROR:`f`,PRELOADING:`d`},wd=`query`,Td=`headers`;function Ed(e,t,n){let r=new Set(t.enabledKeys??[]);return{version:t.version||wu,reportingMode:e,filter:e=>r.has(e),baseUrl:n}}function Dd(e,t){if(e===t)return!0;if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++){let r=e[n],i=t[n];if(r===i)continue;if(typeof r==`number`||typeof i==`number`||r.value!==i.value)return!1;let a=r.params,o=i.params,s=a&&Object.keys(a)[0],c=o&&Object.keys(o)[0];if(s!==c||s!==void 0&&c!==void 0&&a&&o&&a[s]!==o[c])return!1}return!0}var Od=Object.is,kd=e=>e,Ad=Array.from(Fu,([e,t])=>t===`br`?{event:e,field:t,equal:(e,t)=>e===void 0||t===void 0?e===t:Dd(e,t),snapshot:e=>e.slice()}:{event:e,field:t,equal:Od,snapshot:kd}),jd=new Map(Ad.map(e=>[e.event,e]));function Md(e){let{url:t}=e,n=Pt(e,hu);return fetch(t,n)}function Nd(e){let{version:t=wu,eventTargets:n=[],sid:r=vn(),transmissionMode:i=wd}=e;return H(H({},Pt(e,gu)),{},{version:t,transmissionMode:i,sid:r,eventTargets:n.reduce((e,t)=>{var n;return t!=null&&t.url&&(n=t.events)!=null&&n.length&&e.push({version:t.version||wu,enabledKeys:t.enabledKeys?.slice()||[],url:t.url,events:t.events.slice(),interval:t.interval??vd,batchSize:t.batchSize||1}),e},[])})}var Pd=class{constructor(e,t=Md){this.timeOrigin=performance.timeOrigin||performance.timing?.fetchStart||Date.now()-performance.now(),this.data={},this.msd=NaN,this.eventTargets=new Map,this.lastEmitted={},this.requestTarget={sn:0,msdSent:!1},this.config=Nd(e),this.data={cid:this.config.cid,sid:this.config.sid,v:this.config.version},this.requester=t;for(let e of this.config.eventTargets)this.eventTargets.set(e,{intervalId:void 0,sn:0,msdSent:!1,queue:[]})}start(){this.eventTargets.forEach((e,t)=>{if(this.disarmInterval(e),t.interval===0||!t.events.includes(ku))return;let n=()=>{this.recordTargetEvent(e,t,ku),this.processEventTargets()};e.intervalId=setInterval(n,t.interval*1e3),n()})}stop(e=!1){e&&this.flush(),this.eventTargets.forEach(e=>{this.disarmInterval(e)})}flush(){this.processEventTargets(!0)}update(e){e.sid&&e.sid!==this.data.sid&&this.resetSession(),e.msd&&!isNaN(e.msd)&&(this.msd=e.msd),this.data=H(H(H({},this.data),e),{},{msd:void 0});for(let t of Ad)t.field in e&&!t.equal(this.data[t.field],this.lastEmitted[t.field])&&this.recordEvent(t.event)}recordEvent(e,t={}){let n=jd.get(e);if(n){let e=n.field,r=t[e];r!==void 0&&V(this.data,{[e]:r});let i=this.data[e];if(i===void 0||n.equal(i,this.lastEmitted[e]))return;V(this.lastEmitted,{[e]:n.snapshot(i)})}this.eventTargets.forEach((n,r)=>{this.recordTargetEvent(n,r,e,t)}),this.processEventTargets()}recordTargetEvent(e,t,n,r={}){if(!t.events.includes(n))return;let i=H(H(H({},this.data),r),{},{e:n,ts:r.ts??Date.now(),sn:e.sn++});!isNaN(this.msd)&&!e.msdSent&&(i.msd=this.msd,e.msdSent=!0),e.queue.push(i)}recordResponseReceived(e,t={}){let{request:n}=e,r=t.url??n?.url;if(!r)return;let i=new URL(r);i.searchParams.delete(hd);let a={url:i.toString(),rc:e.status},o=e.resourceTiming;o&&(o.startTime!=null&&(a.ts=Math.round(this.timeOrigin+o.startTime),o.responseStart!=null&&(a.ttfb=Math.round(o.responseStart-o.startTime))),o.duration!=null&&(a.ttlb=Math.round(o.duration)));let s=n.customData?.cmcd??{};this.recordEvent(Mu,H(H(H({},s),a),t))}applyRequestReport(e){return this.createRequestReport(e)??e}isRequestReportingEnabled(){var e;return!!((e=this.config.enabledKeys)!=null&&e.length)}createRequestReport(e,t){var n;let{customData:r={},headers:i={}}=e,a=H(H({},Pt(e,_u)),{},{headers:H({},i),customData:H(H({},r),{},{cmcd:{}})});if(!((n=this.config.enabledKeys)!=null&&n.length)||!a.url)return a;let o=new URL(a.url),s=H(H(H({},this.data),t),{},{sn:this.requestTarget.sn++}),c=Ed(Lu,this.config,a.url);!isNaN(this.msd)&&!this.requestTarget.msdSent&&(s.msd=this.msd,this.requestTarget.msdSent=!0);let l=a.customData.cmcd=ad(s,c);switch(this.config.transmissionMode){case wd:let e=gd(l);e&&(o.searchParams.set(hd,e),a.url=o.toString());break;case Td:V(a.headers,md(l,c.customHeaderMap))}return a}processEventTargets(e=!1){let t=!1;this.eventTargets.forEach((n,r)=>{let{queue:i}=n;if(!i.length||i.length<r.batchSize&&!e)return;let a=e?i.length:r.batchSize,o=i.splice(0,a);this.sendEventReport(r,o).catch(()=>{n.queue.unshift(...o)}),t||=i.length>0}),t&&this.processEventTargets()}async sendEventReport(e,t){let n=Ed(Iu,e),{status:r}=await this.requester({url:e.url,method:`POST`,headers:{"Content-Type":bd},body:t.map(e=>_d(e,n)).join(`
|
|
30
30
|
`)+`
|
|
31
|
-
`});if(r===410)this.disposeEventTarget(e);else if(r===429||r>499&&r<600)throw Error(`Event report failed with status ${r}`)}disarmInterval(e){clearInterval(e.intervalId),e.intervalId=void 0}disposeEventTarget(e){let t=this.eventTargets.get(e);t&&(this.disarmInterval(t),this.eventTargets.delete(e))}resetSession(){this.eventTargets.forEach(e=>e.sn=0),this.requestTarget.sn=0,this.lastEmitted={}}},Pd={HLS:`h`},Fd={VOD:`v`,LIVE:`l`,LOW_LATENCY:`ll`};function Id(e,t){return new Ll(e,t)}new Set(Yu),new Set(vd);var Ld=[`includeKeys`];function Rd(e){return Object.keys(e).every(Bu)}var zd=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(Sd.REBUFFERING)),this.buffering=!0},this.onPlay=()=>{this.initialized||this.setPlayerState(Sd.STARTING)},this.onPlaying=()=>{this.initialized||=!0,this.buffering=!1,this.setPlayerState(Sd.PLAYING)},this.onPause=()=>{this.media&&!this.media.ended&&this.setPlayerState(Sd.PAUSED)},this.onSeeking=()=>{this.initialized&&this.setPlayerState(Sd.SEEKING)},this.onSeeked=()=>{var e;this.initialized&&(e=this.media)!=null&&e.paused&&this.setPlayerState(Sd.PAUSED)},this.onRateChange=()=>{this.reporter&&this.media&&this.reporter.update({pr:this.media.playbackRate})},this.applyPlaylistData=e=>{try{this.apply(e,{ot:xd.MANIFEST,su:!this.initialized})}catch(e){this.hls.logger.warn(`Could not generate manifest CMCD data.`,e)}},this.applyFragmentData=e=>{try{let{frag:t,part:n}=e,r=this.hls.levels[t.level],i=this.getObjectType(t,r),a={d:(n||t).duration*1e3,ot:i};if(i===xd.VIDEO||i===xd.AUDIO||i===xd.MUXED||i==null&&(t.type===`main`||t.type===`audio`)){let e=r.bitrate/1e3;a.br=[e];let{cmcd:n}=this.config,o=n?.rtpSafetyFactor??5;if(a.rtp=Math.round(e*o/100)*100,i===xd.MUXED||i==null&&t.type===`main`){let e=this.getTopBandwidth()/1e3;P(e)&&(a.tb=[e]);let t=this.getLowestBandwidth()/1e3;P(t)&&(a.lb=[t])}let s=this.getBufferLength(t);if(P(s)){a.bl=[s];let e=this.media?.playbackRate||1;a.dl=Math.round(s/e/100)*100}this.playheadLevel&&(a.pb=[this.playheadLevel.bitrate/1e3]);let c=this.hls.maxAutoLevel;if(c>=0){let e=this.hls.levels[c];e&&(a.tpb=[e.bitrate/1e3])}}let o=n?this.getNextPart(n):this.getNextFrag(t);o!=null&&o.url&&o.url!==t.url&&(a.nor=o.byteRange.length>0?[Id(o.url,{r:`${o.byteRange[0]}-${o.byteRange[1]}`})]:[o.url]),this.apply(e,a)}catch(e){this.hls.logger.warn(`Could not generate segment CMCD data.`,e)}},this.recordFragmentResponse=(e,t,n)=>{var r;let{cmcd:i}=this.config,a=i==null||(r=i.eventTargets)==null?void 0:r.some(e=>e.events?.includes(Nu.RESPONSE_RECEIVED));if(this.reporter&&n.loading.first>0&&a)try{this.reporter.recordResponseReceived({request:{url:e},status:t.code,resourceTiming:{startTime:n.loading.start,responseStart:n.loading.first,duration:n.loading.end-n.loading.start,encodedBodySize:n.total}})}catch(e){this.hls.logger.warn(`Could not record fragment response CMCD data.`,e)}},this.hls=e;let t=this.config=e.config,{cmcd:n}=t;n!=null&&(t.pLoader=this.createPlaylistLoader(),t.fLoader=this.createFragmentLoader(),this.registerListeners())}createReporter(){let{cmcd:e}=this.config;if(e==null)return;let t=e.version||bd;if(this.reporter=new Nd({sid:e.sessionId||this.hls.sessionId,cid:e.contentId,version:t,transmissionMode:e.useHeaders===!0?wd:Cd,enabledKeys:e.includeKeys??[...t>=Cu?vd:Yu],eventTargets:(e.eventTargets??[]).map(e=>{let{includeKeys:t}=e;return H(H({},Pt(e,Ld)),{},{enabledKeys:t??vd})})},e.loader),this.reporter.update({sf:Pd.HLS,sta:this.playerState}),e.reporterCallback){let t=this.reporter;e.reporterCallback({updateCustomData:e=>{Rd(e)&&t.update(e)},recordCustomEvent:(e,n={})=>{Rd(n)&&t.recordEvent(Nu.CUSTOM_EVENT,H({cen:e},n))}})}this.reporter.start()}registerListeners(){let e=this.hls;e.on(L.MANIFEST_LOADING,this.onManifestLoading,this),e.on(L.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(L.MEDIA_DETACHED,this.onMediaDetached,this),e.on(L.MEDIA_ENDED,this.onMediaEnded,this),e.on(L.ERROR,this.onError,this),e.on(L.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(L.LEVEL_SWITCHED,this.onLevelSwitched,this),e.on(L.BUFFER_APPENDED,this.onBufferInfoChange,this),e.on(L.BUFFER_FLUSHED,this.onBufferInfoChange,this)}unregisterListeners(){let e=this.hls;e.off(L.MANIFEST_LOADING,this.onManifestLoading,this),e.off(L.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(L.MEDIA_DETACHED,this.onMediaDetached,this),e.off(L.MEDIA_ENDED,this.onMediaEnded,this),e.off(L.ERROR,this.onError,this),e.off(L.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(L.LEVEL_SWITCHED,this.onLevelSwitched,this),e.off(L.BUFFER_APPENDED,this.onBufferInfoChange,this),e.off(L.BUFFER_FLUSHED,this.onBufferInfoChange,this)}destroy(){this.unregisterListeners(),this.onMediaDetached(),this.reporter&&=(this.reporter.stop(!0),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 n=this.media=t.media;this.setPlayerState(this.media.autoplay?Sd.STARTING:Sd.PRELOADING),Y(n,`waiting`,this.onWaiting),Y(n,`play`,this.onPlay),Y(n,`playing`,this.onPlaying),Y(n,`pause`,this.onPause),Y(n,`seeking`,this.onSeeking),Y(n,`seeked`,this.onSeeked),Y(n,`ratechange`,this.onRateChange)}onMediaDetached(){let e=this.media;e&&(X(e,`waiting`,this.onWaiting),X(e,`play`,this.onPlay),X(e,`playing`,this.onPlaying),X(e,`pause`,this.onPause),X(e,`seeking`,this.onSeeking),X(e,`seeked`,this.onSeeked),X(e,`ratechange`,this.onRateChange),this.media=null)}onMediaEnded(e,t){this.setPlayerState(Sd.ENDED)}onManifestLoading(e,t){this.initialized=!1,this.starved=!1,this.buffering=!0,this.reporter&&=(this.reporter.stop(!0),void 0),this.createReporter(),this.media||this.setPlayerState(Sd.PRELOADING)}onError(e,t){t.fatal&&(this.setPlayerState(Sd.FATAL_ERROR),this.reporter&&this.reporter.recordEvent(Nu.ERROR,{ec:[t.details]}))}onLevelSwitching(e,t){if(!this.reporter)return;let n={br:[t.bitrate/1e3]},r=t.details?.fragments[0];r&&(n.ot=this.getObjectType(r,t)),this.reporter.recordEvent(Nu.BITRATE_CHANGE,n)}onLevelSwitched(e,t){let n=this.hls.levels[t.level];n&&(this.playheadLevel=n)}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?Fd.LOW_LATENCY:Fd.LIVE:Fd.VOD}apply(e,t={}){if(!this.reporter)return;this.reporter.update({mtp:[this.hls.bandwidthEstimate/1e3],pr:this.media?.playbackRate,st:this.getStreamType()});let n=t.ot===xd.INIT||t.ot===xd.VIDEO||t.ot===xd.MUXED;this.starved&&n&&(t.bs=!0,t.su=!0,this.starved=!1),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){let t=this.hls.levels[e.level]?.details;if(t){let n=e.sn-t.startSN;return t.fragments[n+1]}}getNextPart(e){var t;let{index:n,fragment:r}=e,i=(t=this.hls.levels[r.level])==null||(t=t.details)==null?void 0:t.partList;if(i){let{sn:e}=r;for(let t=i.length-1;t>=0;t--){let r=i[t];if(r.index===n&&r.fragment.sn===e)return i[t+1]}}}getObjectType(e,t){let{type:n}=e;if(n===`subtitle`)return xd.TIMED_TEXT;if(e.sn===`initSegment`)return xd.INIT;if(n===`audio`)return xd.AUDIO;if(n===`main`){if(e.hasStreams){let t=e.elementaryStreams;if(t.audiovideo)return xd.MUXED;if(t.video)return xd.VIDEO;if(t.audio)return xd.AUDIO}if(t){let{audioCodec:e,videoCodec:n}=t;if(!this.hls.audioTracks.length){if(e&&n)return xd.MUXED;if(e)return xd.AUDIO}if(n)return xd.VIDEO}}}getTopBandwidth(){let e=0,t=this.hls,n=t.maxAutoLevel,r=n>-1?n+1:t.levels.length;return t.levels.slice(0,r).forEach(t=>{t.bitrate>e&&(e=t.bitrate)}),e>0?e:NaN}getLowestBandwidth(){let e=1/0,t=this.hls,n=t.maxAutoLevel,r=n>-1?n+1:t.levels.length;return t.levels.slice(0,r).forEach(t=>{t.bitrate<e&&(e=t.bitrate)}),P(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 n=e||t;return n?n.len*1e3:NaN}onBufferInfoChange(e,t){if(!this.reporter)return;let n=this.getEventBufferLength();P(n)&&this.reporter.update({bl:[n]})}createPlaylistLoader(){let{pLoader:e}=this.config,t=this.applyPlaylistData,n=e||this.config.loader;return class{constructor(e){this.loader=void 0,this.loader=new n(e)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(e,n,r){t(e),this.loader.load(e,n,r)}}}createFragmentLoader(){let{fLoader:e}=this.config,t=this.applyFragmentData,n=this.recordFragmentResponse,r=e||this.config.loader;return class{constructor(e){this.loader=void 0,this.loader=new r(e)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(e,r,i){t(e);let{onSuccess:a}=i;this.loader.load(e,r,H(H({},i),{},{onSuccess:(t,r,i,o)=>{a(t,r,i,o),n(e.url,t,r)}}))}}}},Bd=3e5,Vd=class extends Xt{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(L.MANIFEST_LOADING,this.onManifestLoading,this),e.on(L.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(L.MANIFEST_PARSED,this.onManifestParsed,this),e.on(L.ERROR,this.onError,this)}unregisterListeners(){let e=this.hls;e&&(e.off(L.MANIFEST_LOADING,this.onManifestLoading,this),e.off(L.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(L.MANIFEST_PARSED,this.onManifestParsed,this),e.off(L.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(),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(t=>t!==e))}onManifestLoading(){this.stopLoad(),this.enabled=!0,this.timeToLoad=300,this.updated=0,this.uri=null,this.pathwayId=`.`,this.levels=this.audioTracks=this.subtitleTracks=null}onManifestLoaded(e,t){let{contentSteering:n}=t;n!==null&&(this.pathwayId=n.pathwayId,this.uri=n.uri,this.started&&this.startLoad())}onManifestParsed(e,t){this.audioTracks=t.audioTracks,this.subtitleTracks=t.subtitleTracks}onError(e,t){let{errorAction:n}=t;if(n?.action===ca.SendAlternateToPenaltyBox&&n.flags&la.MoveAllAlternatesMatchingHost){let e=this.levels,r=this._pathwayPriority,i=this.pathwayId;if(t.context){let{groupId:n,pathwayId:r,type:a}=t.context;n&&e?i=this.getPathwayForGroupId(n,a,i):r&&(i=r)}i in this.penalizedPathways||(this.penalizedPathways[i]=performance.now()),!r&&e&&(r=this.pathways()),r&&r.length>1&&(this.updatePathwayPriority(r),n.resolved=this.pathwayId!==i,!n.resolved&&(t.details!==I.BUFFER_APPEND_ERROR||t.fatal)&&this.warn(`Could not resolve ${t.details} ("${t.error.message}") with content-steering for Pathway: ${i} levels: ${e&&e.length} priorities: ${q(r)} penalized: ${q(this.penalizedPathways)}`))}}filterParsedLevels(e){this.levels=e;let t=this.getLevelsForPathway(this.pathwayId);if(t.length===0){let n=e[0].pathwayId;this.log(`No levels found in Pathway ${this.pathwayId}. Setting initial Pathway to "${n}"`),t=this.getLevelsForPathway(n),this.pathwayId=n}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,n=this.penalizedPathways,r=performance.now();Object.keys(n).forEach(e=>{r-n[e]>Bd&&delete n[e]});for(let r=0;r<e.length;r++){let i=e[r];if(i in n)continue;if(i===this.pathwayId)return;let a=this.hls.nextLoadLevel,o=this.hls.levels[a];if(t=this.getLevelsForPathway(i),t.length>0){this.log(`Setting Pathway to "${i}"`),this.pathwayId=i,gs(t),this.hls.trigger(L.LEVELS_UPDATED,{levels:t});let e=this.hls.levels[a];o&&e&&this.levels&&(e.attrs[`STABLE-VARIANT-ID`]!==o.attrs[`STABLE-VARIANT-ID`]&&e.bitrate!==o.bitrate&&this.log(`Unstable Pathways change from bitrate ${o.bitrate} to ${e.bitrate}`),this.hls.nextLoadLevel=a);break}}}getPathwayForGroupId(e,t,n){let r=this.getLevelsForPathway(n).concat(this.levels||[]);for(let n=0;n<r.length;n++)if(t===R.AUDIO_TRACK&&r[n].hasAudioGroup(e)||t===R.SUBTITLE_TRACK&&r[n].hasSubtitleGroup(e))return r[n].pathwayId;return n}clonePathways(e){let t=this.levels;if(!t)return;let n={},r={};e.forEach(e=>{let{ID:i,"BASE-ID":a,"URI-REPLACEMENT":o}=e;if(t.some(e=>e.pathwayId===i))return;let s=this.getLevelsForPathway(a).map(e=>{let t=new so(e.attrs);t[`PATHWAY-ID`]=i;let a=t.AUDIO&&`${t.AUDIO}_clone_${i}`,s=t.SUBTITLES&&`${t.SUBTITLES}_clone_${i}`;a&&(n[t.AUDIO]=a,t.AUDIO=a),s&&(r[t.SUBTITLES]=s,t.SUBTITLES=s);let c=Ud(e.uri,t[`STABLE-VARIANT-ID`],`PER-VARIANT-URIS`,o),l=new Mi({attrs:t,audioCodec:e.audioCodec,bitrate:e.bitrate,height:e.height,name:e.name,url:c,videoCodec:e.videoCodec,width:e.width});if(e.audioGroups)for(let t=1;t<e.audioGroups.length;t++)l.addGroupId(`audio`,`${e.audioGroups[t]}_clone_${i}`);if(e.subtitleGroups)for(let t=1;t<e.subtitleGroups.length;t++)l.addGroupId(`text`,`${e.subtitleGroups[t]}_clone_${i}`);return l});t.push(...s),Hd(this.audioTracks,n,o,i),Hd(this.subtitleTracks,r,o,i)})}loadSteeringManifest(e){let t=this.hls.config,n=t.loader;this.loader&&this.loader.destroy(),this.loader=new n(t);let r;try{r=new self.URL(e)}catch{this.enabled=!1,this.log(`Failed to parse Steering Manifest URI: ${e}`);return}if(r.protocol!==`data:`){let e=(this.hls.bandwidthEstimate||t.abrEwmaDefaultEstimate)|0;wi(r,`_HLS_pathway`,this.pathwayId),wi(r,`_HLS_throughput`,``+e)}let i={type:R.STEERING_MANIFEST,responseType:`json`,url:r.href},a=t.steeringManifestLoadPolicy.default,o=a.errorRetry||a.timeoutRetry||{},s={loadPolicy:a,timeout:a.maxLoadTimeMs,maxRetry:o.maxNumRetry||0,retryDelay:o.retryDelayMs||0,maxRetryDelay:o.maxRetryDelayMs||0};this.log(`Requesting steering manifest: ${r}`),this.loader.load(i,s,{onSuccess:(e,t,n,i)=>{this.log(`Loaded steering manifest: "${r}"`);let a=e.data;if(a?.VERSION!==1){this.log(`Steering VERSION ${a.VERSION} not supported!`);return}this.updated=performance.now(),this.timeToLoad=a.TTL;let{"RELOAD-URI":o,"PATHWAY-CLONES":s,"PATHWAY-PRIORITY":c}=a;if(o)try{this.uri=new self.URL(o,r).href}catch{this.enabled=!1,this.log(`Failed to parse Steering Manifest RELOAD-URI: ${o}`);return}this.scheduleRefresh(this.uri||n.url),s&&this.clonePathways(s);let l={steeringManifest:a,url:r.toString()};this.hls.trigger(L.STEERING_MANIFEST_LOADED,l),c&&this.updatePathwayPriority(c)},onError:(e,t,n,r)=>{if(this.log(`Error loading steering manifest: ${e.code} ${e.text} (${t.url})`),this.stopLoad(),e.code===410){this.enabled=!1,this.log(`Steering manifest ${t.url} no longer available`);return}let i=this.timeToLoad*1e3;if(e.code===429){let e=this.loader;if(typeof e?.getResponseHeader==`function`){let t=e.getResponseHeader(`Retry-After`);t&&(i=parseFloat(t)*1e3)}this.log(`Steering manifest ${t.url} rate limited`);return}this.scheduleRefresh(this.uri||t.url,i)},onTimeout:(e,t,n)=>{this.log(`Timeout loading steering manifest (${t.url})`),this.scheduleRefresh(this.uri||t.url)}})}scheduleRefresh(e,t=this.timeToLoad*1e3){this.clearTimeout(),this.reloadTimer=self.setTimeout(()=>{let t=this.hls?.media;if(t&&!t.ended){this.loadSteeringManifest(e);return}this.scheduleRefresh(e,this.timeToLoad*1e3)},t)}};function Hd(e,t,n,r){e&&Object.keys(t).forEach(i=>{let a=e.filter(e=>e.groupId===i).map(e=>{let a=V({},e);return a.details=void 0,a.attrs=new so(a.attrs),a.url=a.attrs.URI=Ud(e.url,e.attrs[`STABLE-RENDITION-ID`],`PER-RENDITION-URIS`,n),a.groupId=a.attrs[`GROUP-ID`]=t[i],a.attrs[`PATHWAY-ID`]=r,a});e.push(...a)})}function Ud(e,t,n,r){if(t){let{[n]:e}=r;if(e){let n=e[t];if(n)return n}}let{HOST:i,PARAMS:a}=r,o=new self.URL(e);return i&&(o.hostname=i),a&&Object.keys(a).sort().forEach(e=>{e&&wi(o,e,a[e])}),o.href}var Wd=class{constructor(){this.status=`initialized`,this.requestErrors=[],this.licenseXhr=void 0,this.onmessage=void 0,this.onkeystatuseschange=void 0,this.emitter=new Ps,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}},Gd=class extends Error{constructor(e,t){super(t),this.data=void 0,e.error||=Error(t),this.data=e,e.err=e.error}},Kd=class e extends Xt{constructor(t){super(`eme`,t.logger),this.hls=void 0,this.config=void 0,this.media=null,this.mediaResolved=void 0,this.keyFormatPromise=null,this.keySystemAccessPromises={},this.sessionSetupByUri={},this.mediaKeySessions=[],this.activeKeys={},this.mediaKeys=null,this.setMediaKeysChain=e.CDMCleanupPromise||Promise.resolve(),this.onMediaEncrypted=e=>{let{initDataType:t,initData:n}=e,r=`"${e.type}" event: init data type: "${t}"`;if(this.log(r),n!==null){if(!this.keyFormatPromise){let e=Object.keys(this.keySystemAccessPromises);e.length||(e=Eo(this.config));let t=e.map(To).filter(e=>!!e);this.keyFormatPromise=this.getKeyFormatPromise(t)}this.keyFormatPromise.then(i=>{let a,o=Co(i),s=this.activeLevelKeys();if(o===Q.FAIRPLAY&&t===`sinf`)try{let e=Gn(new Uint8Array(n)),t=_r(Wn(JSON.parse(e).sinf));if(!t)throw Error(`'schm' box missing or not cbcs/cenc with schi > tenc`);a=new Uint8Array(t.subarray(8,24))}catch(e){this.warn(`${r} Failed to parse sinf: ${e}`);return}else if(o===Q.PLAYREADY)a=jo(new Uint8Array(n));else if(o===Q.WIDEVINE){let e=Pr(n).filter(e=>e.systemId===wo.WIDEVINE);if(e.length){var c;let t=e[0];a=(c=t.kids)!=null&&c.length?t.kids[0]:null}}let l;if(a){let e=Hn(a);for(let r=0;r<s.length;r++){let i=s[r];if(i.keyId&&(po(a,i.keyId)||i.uri.replace(/-/g,``).indexOf(e)!==-1)){i.pssh||(i.scheme=t,i.pssh=new Uint8Array(n),i.keyId=a,No.setKeyIdForUri(i.uri,a)),l=this.getSessionForKey(i,`encrypted-event-key-match`);break}}}if(!l){if(s.length){var u,d;return(u=s[0]).scheme||(u.scheme=t),(d=s[0]).pssh||(d.pssh=new Uint8Array(n)),this.getSessionForKey(s[0],`encrypted-event-no-match`)}if(a)throw Error(`Key ID ${Hn(a)} not encountered in playlist`);this.log(`Ignoring "${e.type}" event - could not determine keyId`)}return l}).catch(e=>this.handleError(e))}},this.onWaitingForKey=e=>{this.log(`"${e.type}" event`)},this.hls=t,this.config=t.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(L.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(L.MEDIA_DETACHED,this.onMediaDetached,this),e.on(L.MANIFEST_LOADING,this.onManifestLoading,this),e.on(L.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(L.DESTROYING,this.onDestroying,this))}unregisterListeners(){let{hls:e}=this;e&&(e.off(L.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(L.MEDIA_DETACHED,this.onMediaDetached,this),e.off(L.MANIFEST_LOADING,this.onManifestLoading,this),e.off(L.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(L.DESTROYING,this.onDestroying,this))}attemptKeySystemAccess(e){if(!this.hls)return Promise.reject(Error(`destroyed`));let t=this.hls.levels,n=(e,t,n)=>!!e&&n.indexOf(e)===t,r=t.map(e=>e.audioCodec).filter(n),i=t.map(e=>e.videoCodec).filter(n);return r.length+i.length===0&&i.push(`avc1.42e01e`),new Promise((t,n)=>{let a=e=>{let o=e.shift();this.getMediaKeysPromise(o,r,i).then(e=>t({keySystem:o,mediaKeys:e})).catch(t=>{e.length?a(e):t instanceof Gd?n(t):n(new Gd({type:F.KEY_SYSTEM_ERROR,details:I.KEY_SYSTEM_NO_ACCESS,error:t,fatal:!0},t.message))})};a(e)})}requestMediaKeySystemAccess(e,t){let{requestMediaKeySystemAccessFunc:n}=this.config;if(typeof n!=`function`){let e=`Configured requestMediaKeySystemAccess is not a function ${n}`;return Do===null&&self.location.protocol===`http:`&&(e=`navigator.requestMediaKeySystemAccess is not available over insecure protocol ${location.protocol}`),Promise.reject(Error(e))}return n(e,t)}getMediaKeysPromise(e,t,n){let r=Oo(e,t,n,this.config.drmSystemOptions||{}),i=this.keySystemAccessPromises[e],a=i?.keySystemAccess;if(!a){this.log(`Requesting encrypted media "${e}" key-system access with config: ${q(r)}`),a=this.requestMediaKeySystemAccess(e,r);let t=i=this.keySystemAccessPromises[e]={keySystemAccess:a};return a.catch(t=>{this.log(`Failed to obtain access to key-system "${e}": ${t}`)}),a.then(n=>{this.throwIfDestroyed(),this.log(`Access for key-system "${n.keySystem}" obtained`);let r=this.fetchServerCertificate(e);this.log(`Create media-keys for "${e}"`);let i=t.mediaKeys=n.createMediaKeys().then(n=>(this.log(`Media-keys created for "${e}"`),t.createdMediaKeys=n,r.then(t=>t?this.setMediaKeysServerCertificate(n,e,t):n)));return i.catch(t=>{this.error(`Failed to create media-keys for "${e}"}: ${t}`)}),i})}return a.then(()=>i.mediaKeys)}getMediaKeySessionContext(e,t,n,r){let{mediaKeySessions:i}=this,a=` key-session "${e}" keyId: ${Hn(n.keyId||[])} keyUri: ${n.uri} for "${r}"`;for(let e=0;e<i.length;e++){let t=i[e];if(!t.initialized&&t.createdFor.levelKey.uri===n.uri)return this.log(`Reusing${a}`),t}this.log(`Creating${a}`);let o={keySystem:e,mediaKeys:t,mediaKeysSession:t.createSession(),keyRequests:{},keyStatuses:{},createdFor:{levelKey:n,reason:r},initialized:!1};return i.push(o),o}resetMediaKeys(){let e=this.mediaKeySessions[0]?.keySystem,t=this.keySystemAccessPromises[e];t&&(this.log(`reset mediaKeys`),this.mediaKeys=null,delete t.createdMediaKeys,delete t.mediaKeys,delete this.keySystemAccessPromises[e])}updateKeySession(e,t,n){let r=e.mediaKeysSession;return this.log(`Updating key-session "${r.sessionId}" for keyId ${Hn(t.keyId||[])}
|
|
32
|
-
} (data length: ${n.byteLength})`),r.update(n)}getSelectedKeySystemFormats(){return Object.keys(this.keySystemAccessPromises).map(e=>({keySystem:e,hasMediaKeys:!!this.keySystemAccessPromises[e].createdMediaKeys})).filter(({hasMediaKeys:e})=>!!e).map(({keySystem:e})=>To(e)).filter(e=>!!e)}getKeySystemAccess(e){return this.getKeySystemSelectionPromise(e).then(({keySystem:e,mediaKeys:t})=>this.attemptSetMediaKeys(e,t))}selectKeySystem(e){return this.getKeySystemSelectionPromise(e).then(({keySystem:e})=>{let t=To(e);if(!t)throw Error(`Unable to find format for key-system "${e}"`);return t})}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.getKeyFormatPromise(t)),this.keyFormatPromise}getKeyFormatPromise(e){let t=Eo(this.config),n=e.map(Co).filter(e=>!!e&&t.indexOf(e)!==-1);return this.selectKeySystem(n)}loadClear(e,t,n){if(this.config.emeEnabled&&!this.getSelectedKeySystemFormats().length){if(t.length)for(let r=0,i=t.length;r<i;r++){let a=t[r];if(e.cc<=a.cc&&(!Tt(e)||!Tt(a)||e.sn<a.sn)||!n&&r==i-1)return this.selectKeySystemFormat(a).then(e=>{if(!this.hls)return;a.setKeyFormat(e);let t=Co(e);if(t)return this.getKeySystemAccess([t])})}if(this.config.requireKeySystemAccessOnStart){let e=Eo(this.config);if(e.length)return this.getKeySystemAccess(e)}}return null}getKeyStatus(e){let{mediaKeySessions:t}=this;for(let n=0;n<t.length;n++){let r=Xd(e,t[n]);if(r)return r}}loadKey(e){let t=e.decryptdata,n=this.getKeyStatus(t);if(n===`internal-error`){let r=Zd(n,t);return r.data.frag=e,this.error(`${r.message} (${Hn(t.keyId||[])})`),Promise.reject(r)}let r=e.type,i=this.activeKeys,a=i[r];a&&!t.matches(a.decryptdata)&&(i.previous||=[],i.previous.push(a),delete i[r]),i[r]||(i[r]=e);for(let e=this.mediaKeySessions.length;e--;){let n=this.mediaKeySessions[e];if(t.keyId&&n.keyStatuses[Hn(t.keyId)]===`expired`)return this.renewKeySession(t,n)}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,n){let r=this.getSessionForKey(e,t);return r.catch(e=>this.handleError(e,n)),r.then(t=>e)}getSessionForKey(e,t){let n=this.findContextForKey(e);if(n!==void 0)return Promise.resolve(n);let r=e.uri,i=this.sessionSetupByUri[r],a;a=i===void 0?this.resolveSessionForKey(e,t):i.catch(()=>void 0).then(()=>(this.throwIfDestroyed(),this.resolveSessionForKey(e,t))),this.sessionSetupByUri[r]=a;let o=()=>{this.sessionSetupByUri[r]===a&&delete this.sessionSetupByUri[r]};return a.then(o,o),a}findContextForKey(e){let{mediaKeySessions:t}=this;for(let n=t.length;n--;){let r=t[n];if(Xd(e,r))return r}}resolveSessionForKey(e,t){return this.getKeySystemForKeyPromise(e).then(({keySystem:n,mediaKeys:r})=>{this.throwIfDestroyed();for(let n=this.mediaKeySessions.length;n--;){let r=this.mediaKeySessions[n];if(Xd(e,r))return r;let i=this.getUsableKeyPromise(r,e,t);if(i)return i}return this.attemptSetMediaKeys(n,r).then(()=>(this.throwIfDestroyed(),this.getMediaKeySessionContext(n,r,e,t))).then(n=>{this.throwIfDestroyed();let r=e.scheme||`cenc`,i=e.pssh?e.pssh.buffer:null;return this.generateRequestWithPreferredKeySession(n,e,r,i,t)})})}getUsableKeyPromise(e,t,n){let r=e.keyRequests[t.uri];if(r)return this.log(`Waiting for usable key (${n} keyId: ${Yd(t)} format: "${t.keyFormat}" URI: ${t.uri})`),r.useable.then(()=>e)}throwIfDestroyed(e=`Invalid state`){if(!this.hls)throw Error(`invalid state`)}handleError(e,t){if(this.hls){if(e instanceof Gd){t&&(e.data.frag=t);let n=e.data.decryptdata;this.error(`${e.message}${n?` (${Hn(n.keyId||[])})`:``}`),this.hls.trigger(L.ERROR,e.data)}else this.error(e.message),this.hls.trigger(L.ERROR,{type:F.KEY_SYSTEM_ERROR,details:I.KEY_SYSTEM_NO_KEYS,error:e,fatal:!0,reason:`${e.name}: ${e.message}`})}}getKeySystemForKeyPromise(e){let t=Co(e.keyFormat),n=t?[t]:Eo(this.config);return this.attemptKeySystemAccess(n)}getKeySystemSelectionPromise(e){if(e.length||(e=Eo(this.config)),e.length===0)throw new Gd({type:F.KEY_SYSTEM_ERROR,details:I.KEY_SYSTEM_NO_CONFIGURED_LICENSE,fatal:!0},`Missing key-system license configuration options ${q({drmSystems:this.config.drmSystems})}`);return this.attemptKeySystemAccess(e)}activeLevelKeys(){let e=this.activeKeys,t=(e.previous||[]).map(e=>e.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(e=>{this.log(`setMediaKeys failed: ${e}`)}),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((e,n)=>{this.mediaResolved=()=>{if(this.mediaResolved=void 0,!this.media)return n(Error(`Attempted to set mediaKeys without media element attached`));this.mediaKeys=t,this.media.setMediaKeys(t).then(e).catch(n)}})).then(()=>{this.log(`Media-keys set for "${e}"`)},e=>{throw this.mediaKeys===t&&(this.mediaKeys=null),e}))}filterInitData(e,t,n,r,i){var a;let o=(a=this.config.drmSystems)==null||(a=a[e.keySystem])==null?void 0:a.generateRequest;if(o)try{let a=o.call(this.hls,n,r,V({},e,{decryptdata:t,reason:i}),i);if(!a)throw Error(`Invalid response from configured generateRequest filter`);t.scheme=a.initDataType?a.initDataType:`cenc`;let s=a.initData?a.initData:null;return t.pssh=s?new Uint8Array(s):null,a}catch(e){var s;if(this.warn(e.message),(s=this.hls)!=null&&s.config.debug)throw e}return{initDataType:n,initData:r}}generateRequestWithPreferredKeySession(e,t,n,r,i){let a=this.getUsableKeyPromise(e,t,i);if(a)return a;let o=this.filterInitData(e,t,n,r,i);if(o&&(r=o.initData?o.initData:null,n=o.initDataType),r===null)return i.startsWith(`encrypted-event`)?Promise.reject(Error(`missing initialization data for "${i}"`)):(this.log(`Skipping key-session request for "${i}" (no initData)`),Promise.resolve(e));let s=t.uri,c=new Wd;e.keyRequests[s]=c;let l=n=>{let r=e.mediaKeysSession;if(!r){c.errored=Error(`invalid state`);return}let{messageType:i,message:a}=n;c.status=i,this.log(`"${i}" message event for session "${r.sessionId}" message size: ${a.byteLength}`),i===`license-request`||i===`license-renewal`?this.renewLicense(e,t,a).catch(t=>{c.errored=t,c.hasListeners||this.handleError(t),this.removeSession(e)}):i===`license-release`?e.keySystem===Q.FAIRPLAY&&this.updateKeySession(e,t,_o(`acknowledged`)).then(()=>this.removeSession(e)).catch(e=>this.handleError(e)):this.warn(`unhandled media key message type "${i}"`)};return c.onmessage=l,Y(e.mediaKeysSession,`message`,l),this.generateRequest(e,t,n,r,i,!1)}generateRequest(e,t,n,r,i,a){if(a){let a=this.filterInitData(e,t,n,r,i);a&&(r=a.initData?a.initData:r,n=a.initDataType)}let o=t.uri,s=e.keyRequests[o],c=Hn(t.keyId||[]),l=e=>{let n;e.startsWith(`usable`)?s.resolve():e===`internal-error`||e===`output-restricted`||e===`output-downscaled`?n=Zd(e,t):e===`expired`?n=Error(`key expired (keyId: ${c})`):e===`released`?n=Error(`key released`):e===`status-pending`||this.warn(`unhandled key status change "${e}" (keyId: ${c})`),n&&(s.errored=n,s.hasListeners||this.handleError(n))},u=n=>{if(!e.mediaKeysSession){s.errored=Error(`invalid state`);return}let r=e.keyStatuses=this.getKeyStatuses(e);if(!Object.keys(r).some(e=>r[e]!==`status-pending`))return;let i=this.activeLevelKeys();for(let n=0;n<i.length;n++)if(r[Hn(i[n].keyId||[])]===`expired`){this.log(`Expired key ${q(r)} in key-session "${e.mediaKeysSession?.sessionId}"`),this.renewKeySession(t,e).catch(e=>this.handleError(e));break}let a=r[c];if(a)l(a);else{var o;let n=1e3;e.keyStatusTimeouts||={},(o=e.keyStatusTimeouts)[c]||(o[c]=self.setTimeout(()=>{if(!e.mediaKeysSession)return;let r=this.getKeyStatus(t);if(r&&r!==`status-pending`)return this.log(`No status for keyId ${c} in key-session "${e.mediaKeysSession?.sessionId}". Using session key-status ${r} from other session.`),l(r);this.log(`key status for ${c} in key-session "${e.mediaKeysSession?.sessionId}" timed out after ${n}ms`),a=`internal-error`,l(a)},n)),this.log(`No status for keyId ${c} (${q(r)}).`)}};s.onkeystatuseschange=u,Y(e.mediaKeysSession,`keystatuseschange`,u);let d=s.useable;return this.log(`Generating key-session request for "${i}" keyId: ${c} URI: ${o} (init data type: ${n} length: ${r.byteLength})`),s.status=`started`,e.initialized=!0,e.mediaKeysSession.generateRequest(n,r).then(()=>{s.status=`generated`,this.log(`Request generated for key-session "${e.mediaKeysSession?.sessionId}" keyId: ${c} URI: ${o}`)}).catch(e=>{throw this.log(`mediaKeysSession.generateRequest failed: ${e}`),new Gd({type:F.KEY_SYSTEM_ERROR,details:I.KEY_SYSTEM_NO_SESSION,error:e,decryptdata:t,fatal:!1},`Error generating key-session request: ${e}`)}).then(()=>d).catch(t=>{this.log(`mediaKeysSession.generateRequest failed: ${t}`);let n=t.data?.details;return(n===I.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED||n===I.KEY_SYSTEM_STATUS_INTERNAL_ERROR)&&Object.keys(e.keyStatuses).some(t=>e.keyStatuses[t]===`usable`)?(this.handleError(t),e):this.removeSession(e).then(()=>{throw t})}).then(()=>e)}getKeyStatuses(e){let t={},n=e.mediaKeysSession.sessionId;return e.mediaKeysSession.keyStatuses.forEach((r,i)=>{if(typeof i==`string`&&typeof r==`object`){let e=i;i=r,r=e}let a=`buffer`in i?new Uint8Array(i.buffer,i.byteOffset,i.byteLength):new Uint8Array(i);if(e.keySystem===Q.PLAYREADY&&a.length===16){let e=Hn(a);t[e]=r,yo(a)}let o=Hn(a);this.log(`key status change "${r}" for keyStatuses keyId: ${o} key-session "${n}"`),t[o]=r}),t}fetchServerCertificate(e){let t=this.config,n=t.loader,r=new n(t),i=Jd(e,t);return i?(this.log(`Fetching server certificate for "${e}"`),new Promise((n,a)=>{let o={type:R.SERVER_CERTIFICATE,responseType:`arraybuffer`,url:i},s=t.certLoadPolicy.default,c={loadPolicy:s,timeout:s.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0};r.load(o,c,{onSuccess:(e,t,r,i)=>{n(e.data)},onError:(t,n,r,s)=>{a(new Gd({type:F.KEY_SYSTEM_ERROR,details:I.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:r,response:H({url:o.url,data:void 0},t)},`"${e}" certificate request failed (${i}). Status: ${t.code} (${t.text})`))},onTimeout:(t,n,r)=>{a(new Gd({type:F.KEY_SYSTEM_ERROR,details:I.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:r,response:{url:o.url,data:void 0}},`"${e}" certificate request timed out (${i})`))},onAbort:(e,t,n)=>{a(Error(`aborted`))}})})):(this.log(`No Server Certificate in config.drmSystems["${e}"]`),Promise.resolve())}setMediaKeysServerCertificate(e,t,n){return new Promise((r,i)=>{e.setServerCertificate(n).then(i=>{this.log(`setServerCertificate ${i?`success`:`not supported by CDM`} (${n.byteLength}) on "${t}"`),r(e)}).catch(e=>{i(new Gd({type:F.KEY_SYSTEM_ERROR,details:I.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED,error:e,fatal:!0},e.message))})})}renewLicense(e,t,n){return this.requestLicense(e,t,new Uint8Array(n)).then(n=>this.updateKeySession(e,t,new Uint8Array(n)).catch(e=>{throw new Gd({type:F.KEY_SYSTEM_ERROR,details:I.KEY_SYSTEM_SESSION_UPDATE_FAILED,decryptdata:t,error:e,fatal:!1},e.message)}))}unpackPlayReadyKeyMessage(e,t){let n=Gn(new Uint16Array(t.buffer));if(!n.includes(`PlayReadyKeyMessage`))return e.setRequestHeader(`Content-Type`,`text/xml; charset=utf-8`),t;let r=new DOMParser().parseFromString(n,`application/xml`),i=r.querySelectorAll(`HttpHeader`);if(i.length>0){let t;for(let n=0,r=i.length;n<r;n++){t=i[n];let r=t.querySelector(`name`)?.textContent,a=t.querySelector(`value`)?.textContent;r&&a&&e.setRequestHeader(r,a)}}let a=r.querySelector(`Challenge`)?.textContent;if(!a)throw Error(`Cannot find <Challenge> in key message`);return _o(atob(a))}setupLicenseXHR(e,t,n,r,i){let a=this.config.licenseXhrSetup;return a?Promise.resolve().then(()=>(this.throwIfDestroyed(),a.call(this.hls,e,t,H(H({},n),{},{decryptdata:r}),i))).catch(o=>{if(!n.mediaKeysSession)throw o;return e.open(`POST`,t,!0),a.call(this.hls,e,t,H(H({},n),{},{decryptdata:r}),i)}).then(n=>(e.readyState||e.open(`POST`,t,!0),{xhr:e,licenseChallenge:n||i})):(e.open(`POST`,t,!0),Promise.resolve({xhr:e,licenseChallenge:i}))}requestLicense(e,t,n){return new Promise((r,i)=>{let a=qd(e.keySystem,this.config);if(!a)return i(Error(`no license server URL configured for key-system "${e.keySystem}"`));let o=e.keyRequests[t.uri];if(!o)return i(Error(`License emitter removed`));this.log(`Sending license request to URL: ${a}`);let s=this.config.keyLoadPolicy.default,c=new XMLHttpRequest;c.responseType=`arraybuffer`,c.onreadystatechange=()=>{if(!this.hls||!e.mediaKeysSession)return i(Error(`invalid state`));if(c.readyState===4){if(c.status===200){o.requestErrors=[];let n=c.response;this.log(`License received ${n instanceof ArrayBuffer?n.byteLength:n}`);let i=this.config.licenseResponseCallback;if(i)try{n=i.call(this.hls,c,a,H(H({},e),{},{decryptdata:t}))}catch(e){this.error(e)}r(n)}else{let l=s.errorRetry,u=l?l.maxNumRetry:0;if(o.requestErrors.push({status:c.status,message:c.statusText}),o.requestErrors.length>u||c.status>=400&&c.status<500)i(new Gd({type:F.KEY_SYSTEM_ERROR,details:I.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 a=u-o.requestErrors.length;this.warn(`Retrying license request, ${a} attempts left`),this.requestLicense(e,t,n).then(r,i)}}}},o.licenseXhr&&o.licenseXhr.readyState!==XMLHttpRequest.DONE&&o.licenseXhr.abort(),o.licenseXhr=c,this.setupLicenseXHR(c,a,e,t,n).then(({xhr:t,licenseChallenge:n})=>{e.keySystem==Q.PLAYREADY&&(n=this.unpackPlayReadyKeyMessage(t,n)),t.send(n)}).catch(i)})}onDestroying(){this.unregisterListeners(),this._clear()}onMediaAttached(e,t){if(!this.config.emeEnabled)return;let n=t.media;this.media=n,Y(n,`encrypted`,this.onMediaEncrypted),Y(n,`waitingforkey`,this.onWaitingForKey);let r=this.mediaResolved;r?r():this.mediaKeys=n.mediaKeys}onMediaDetached(){let e=this.media;e&&(X(e,`encrypted`,this.onMediaEncrypted),X(e,`waitingforkey`,this.onWaitingForKey),this.media=null,this.mediaKeys=null)}_clear(t=!1){this.keyFormatPromise=null,t||(this.keySystemAccessPromises={}),this.activeKeys={},this.sessionSetupByUri={};let n=this.mediaResolved;if(n&&n(),!this.mediaKeys&&!this.mediaKeySessions.length)return;let r=this.media,i=t&&this.config.reuseKeySessions,a=i?[]:this.mediaKeySessions.slice();i||(this.mediaKeySessions=[],No.clearKeyUriToKeyIdMap()),t||(this.mediaKeys=null);let o=a.length,s=r&&!t?this.queueSetMediaKeys(()=>r.setMediaKeys(null)).catch(e=>{this.log(`Could not clear media keys: ${e}`),this.hls&&this.hls.trigger(L.ERROR,{type:F.OTHER_ERROR,details:I.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR,fatal:!1,error:Error(`Could not clear media keys: ${e}`)})}):Promise.resolve();e.CDMCleanupPromise=Promise.all(a.map(e=>this.removeSession(e)).concat(s)).catch(e=>{this.log(`Could not close sessions and clear media keys: ${e}`),this.hls&&this.hls.trigger(L.ERROR,{type:F.OTHER_ERROR,details:I.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:Error(`Could not close sessions and clear media keys: ${e}`)})}).then(()=>{o&&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,n=!!t&&Object.keys(this.keySystemAccessPromises).some(e=>e!==Q.FAIRPLAY&&this.keySystemAccessPromises[e]?.createdMediaKeys===t);this._clear(n),this.keyFormatPromise=null}onManifestLoaded(e,{sessionKeys:t}){if(t&&this.config.emeEnabled&&!this.keyFormatPromise){let e=t.reduce((e,t)=>(e.indexOf(t.keyFormat)===-1&&e.push(t.keyFormat),e),[]);this.log(`Selecting key-system from session-keys ${e.join(`, `)}`),this.keyFormatPromise=this.getKeyFormatPromise(e),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(n=>{let r=e.keyRequests[n];r.onmessage&&t.removeEventListener(`message`,r.onmessage),r.onkeystatuseschange&&t.removeEventListener(`keystatuseschange`,r.onkeystatuseschange),r.reset(),e.keyRequests[n]=void 0}),e.mediaKeysSession=void 0;let n=this.mediaKeySessions.indexOf(e);n>-1&&this.mediaKeySessions.splice(n,1);let{keyStatusTimeouts:r}=e;r&&Object.keys(r).forEach(e=>self.clearTimeout(r[e]));let{drmSystemOptions:i}=this.config;return(Ao(i)?new Promise((e,n)=>{self.setTimeout(()=>n(Error(`MediaKeySession.remove() timeout`)),8e3),t.remove().then(e).catch(n)}):Promise.resolve()).catch(e=>{this.log(`Could not remove session: ${e}`),this.hls&&this.hls.trigger(L.ERROR,{type:F.OTHER_ERROR,details:I.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR,fatal:!1,error:Error(`Could not remove session: ${e}`)})}).then(()=>t.close()).then(()=>t.closed).catch(e=>{this.log(`Could not close session: ${e}`),this.hls&&this.hls.trigger(L.ERROR,{type:F.OTHER_ERROR,details:I.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:Error(`Could not close session: ${e}`)})})}return Promise.resolve()}};Kd.CDMCleanupPromise=void 0;function qd(e,t){let{drmSystems:n,widevineLicenseUrl:r}=t,i=n?.[e];if(i)return i.licenseUrl;if(e===Q.WIDEVINE&&r)return r}function Jd(e,t){let{drmSystems:n}=t,r=n?.[e];if(r)return r.serverCertificateUrl}function Yd(e){if(e.keyFormat===So.FAIRPLAY)return e.uri;if(e.keyId===null)throw Error(`keyId is null`);return Hn(e.keyId)}function Xd(e,t){let n=e.keyId,r=t.mediaKeysSession;if(n&&r){let e=t.mediaKeysSession.keyStatuses;if(e.size)return e.has(n)?e.get(n):t.keyStatuses[Hn(n)]}}function Zd(e,t){let n=e===`output-restricted`,r=n?I.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:I.KEY_SYSTEM_STATUS_INTERNAL_ERROR;return new Gd({type:F.KEY_SYSTEM_ERROR,details:r,fatal:!1,decryptdata:t},n?`HDCP level output restricted`:`key status changed to "${e}"`)}var Qd=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(L.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.on(L.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListeners(){this.hls.off(L.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.off(L.MEDIA_DETACHING,this.onMediaDetaching,this)}destroy(){this.timer&&clearInterval(this.timer),this.unregisterListeners(),this.isVideoPlaybackQualityAvailable=!1,this.media=null}onMediaAttaching(e,t){let n=this.hls.config;if(n.capLevelOnFPSDrop){let e=t.media instanceof self.HTMLVideoElement?t.media:null;this.media=e,e&&typeof e.getVideoPlaybackQuality==`function`&&(this.isVideoPlaybackQualityAvailable=!0),self.clearInterval(this.timer),this.timer=self.setInterval(this.checkFPSInterval.bind(this),n.fpsDroppedMonitoringPeriod)}}onMediaDetaching(){this.media=null}checkFPS(e,t,n){let r=performance.now();if(t){if(this.lastTime){let e=r-this.lastTime,i=n-this.lastDroppedFrames,a=t-this.lastDecodedFrames,o=1e3*i/e,s=this.hls;if(s.trigger(L.FPS_DROP,{currentDropped:i,currentDecoded:a,totalDroppedFrames:n}),o>0&&i>s.config.fpsDroppedMonitoringThreshold*a){let e=s.currentLevel;s.logger.warn(`drop FPS ratio greater than max allowed value for currentLevel: `+e),e>0&&(s.autoLevelCapping===-1||s.autoLevelCapping>=e)&&(--e,s.trigger(L.FPS_DROP_LEVEL_CAPPING,{level:e,droppedLevel:s.currentLevel}),s.autoLevelCapping=e,this.streamController.nextLevelSwitch())}}this.lastTime=r,this.lastDroppedFrames=n,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)}}},$d=(function(){if(xo!=null&&xo.VTTCue)return self.VTTCue;let e=[``,`lr`,`rl`],t=[`start`,`middle`,`end`,`left`,`right`];function n(e,t){if(typeof t!=`string`||!Array.isArray(e))return!1;let n=t.toLowerCase();return~e.indexOf(n)?n:!1}function r(t){return n(e,t)}function i(e){return n(t,e)}function a(e,...t){let n=1;for(;n<arguments.length;n++){let t=arguments[n];for(let n in t)e[n]=t[n]}return e}function o(e,t,n){let o=this,s={enumerable:!0};o.hasBeenReset=!1;let c=``,l=!1,u=e,d=t,f=n,p=null,m=``,h=!0,g=`auto`,_=`start`,v=50,y=`middle`,b=50,x=`middle`;Object.defineProperty(o,"id",a({},s,{get:function(){return c},set:function(e){c=``+e}})),Object.defineProperty(o,"pauseOnExit",a({},s,{get:function(){return l},set:function(e){l=!!e}})),Object.defineProperty(o,"startTime",a({},s,{get:function(){return u},set:function(e){if(typeof e!=`number`)throw TypeError(`Start time must be set to a number.`);u=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"endTime",a({},s,{get:function(){return d},set:function(e){if(typeof e!=`number`)throw TypeError(`End time must be set to a number.`);d=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"text",a({},s,{get:function(){return f},set:function(e){f=``+e,this.hasBeenReset=!0}})),Object.defineProperty(o,"region",a({},s,{get:function(){return p},set:function(e){p=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"vertical",a({},s,{get:function(){return m},set:function(e){let t=r(e);if(t===!1)throw SyntaxError(`An invalid or illegal string was specified.`);m=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"snapToLines",a({},s,{get:function(){return h},set:function(e){h=!!e,this.hasBeenReset=!0}})),Object.defineProperty(o,"line",a({},s,{get:function(){return g},set:function(e){if(typeof e!=`number`&&e!==`auto`)throw SyntaxError(`An invalid number or illegal string was specified.`);g=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"lineAlign",a({},s,{get:function(){return _},set:function(e){let t=i(e);if(!t)throw SyntaxError(`An invalid or illegal string was specified.`);_=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"position",a({},s,{get:function(){return v},set:function(e){if(e<0||e>100)throw Error(`Position must be between 0 and 100.`);v=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"positionAlign",a({},s,{get:function(){return y},set:function(e){let t=i(e);if(!t)throw SyntaxError(`An invalid or illegal string was specified.`);y=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"size",a({},s,{get:function(){return b},set:function(e){if(e<0||e>100)throw Error(`Size must be between 0 and 100.`);b=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"align",a({},s,{get:function(){return x},set:function(e){let t=i(e);if(!t)throw SyntaxError(`An invalid or illegal string was specified.`);x=t,this.hasBeenReset=!0}})),o.displayState=void 0}return o.prototype.getCueAsHTML=function(){return self.WebVTT.convertCueToDOMTree(self,this.text)},o})(),ef=class{decode(e,t){if(!e)return``;if(typeof e!=`string`)throw Error(`Error - expected string data.`);return decodeURIComponent(encodeURIComponent(e))}};function tf(e){function t(e,t,n,r){return(e|0)*3600+(t|0)*60+(n|0)+parseFloat(r||0)}let n=e.match(/^(?:(\d+):)?(\d{2}):(\d{2})(\.\d+)?/);return n?parseFloat(n[2])>59?t(n[2],n[3],0,n[4]):t(n[1],n[2],n[3],n[4]):null}var nf=class{constructor(){this.values=Object.create(null)}set(e,t){!this.get(e)&&t!==``&&(this.values[e]=t)}get(e,t,n){return n?this.has(e)?this.values[e]:t[n]:this.has(e)?this.values[e]:t}has(e){return e in this.values}alt(e,t,n){for(let r=0;r<n.length;++r)if(t===n[r]){this.set(e,t);break}}integer(e,t){/^-?\d+$/.test(t)&&this.set(e,parseInt(t,10))}percent(e,t){if(/^([\d]{1,3})(\.[\d]*)?%$/.test(t)){let n=parseFloat(t);if(n>=0&&n<=100)return this.set(e,n),!0}return!1}};function rf(e,t,n,r){let i=r?e.split(r):[e];for(let e in i){if(typeof i[e]!=`string`)continue;let r=i[e].split(n);if(r.length!==2)continue;let a=r[0],o=r[1];t(a,o)}}var af=new $d(0,0,``),of=af.align===`middle`?`middle`:`center`;function sf(e,t,n){let r=e;function i(){let t=tf(e);if(t===null)throw Error(`Malformed timestamp: `+r);return e=e.replace(/^[^\sa-zA-Z-]+/,``),t}function a(e,t){let r=new nf;rf(e,function(e,t){let i;switch(e){case`region`:for(let i=n.length-1;i>=0;i--)if(n[i].id===t){r.set(e,n[i].region);break}break;case`vertical`:r.alt(e,t,[`rl`,`lr`]);break;case`line`:i=t.split(`,`),r.integer(e,i[0]),r.percent(e,i[0])&&r.set(`snapToLines`,!1),r.alt(e,i[0],[`auto`]),i.length===2&&r.alt(`lineAlign`,i[1],[`start`,of,`end`]);break;case`position`:i=t.split(`,`),r.percent(e,i[0]),i.length===2&&r.alt(`positionAlign`,i[1],[`start`,of,`end`,`line-left`,`line-right`,`auto`]);break;case`size`:r.percent(e,t);break;case`align`:r.alt(e,t,[`start`,of,`end`,`left`,`right`])}},/:/,/\s/),t.region=r.get(`region`,null),t.vertical=r.get(`vertical`,``);let i=r.get(`line`,`auto`);i===`auto`&&af.line===-1&&(i=-1),t.line=i,t.lineAlign=r.get(`lineAlign`,`start`),t.snapToLines=r.get(`snapToLines`,!0),t.size=r.get(`size`,100),t.align=r.get(`align`,of);let a=r.get(`position`,`auto`);a===`auto`&&af.position===50&&(a=t.align===`start`||t.align===`left`?0:t.align===`end`||t.align===`right`?100:50),t.position=a}function o(){e=e.replace(/^\s+/,``)}if(o(),t.startTime=i(),o(),e.slice(0,3)!==`-->`)throw Error(`Malformed time stamp (time stamps must be separated by '-->'): `+r);e=e.slice(3),o(),t.endTime=i(),o(),a(e,t)}function cf(e){return e.replace(/<br(?: \/)?>/gi,`
|
|
33
|
-
`)}var
|
|
31
|
+
`});if(r===410)this.disposeEventTarget(e);else if(r===429||r>499&&r<600)throw Error(`Event report failed with status ${r}`)}disarmInterval(e){clearInterval(e.intervalId),e.intervalId=void 0}disposeEventTarget(e){let t=this.eventTargets.get(e);t&&(this.disarmInterval(t),this.eventTargets.delete(e))}resetSession(){this.eventTargets.forEach(e=>e.sn=0),this.requestTarget.sn=0,this.lastEmitted={}}},Fd={HLS:`h`},Id={VOD:`v`,LIVE:`l`,LOW_LATENCY:`ll`};function Ld(e,t){return new Rl(e,t)}new Set(Xu),new Set(yd);var Rd=[`includeKeys`];function zd(e){return Object.keys(e).every(Vu)}var Bd=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(Cd.REBUFFERING)),this.buffering=!0},this.onPlay=()=>{this.initialized||this.setPlayerState(Cd.STARTING)},this.onPlaying=()=>{this.initialized||=!0,this.buffering=!1,this.setPlayerState(Cd.PLAYING)},this.onPause=()=>{this.media&&!this.media.ended&&this.setPlayerState(Cd.PAUSED)},this.onSeeking=()=>{this.initialized&&this.setPlayerState(Cd.SEEKING)},this.onSeeked=()=>{var e;this.initialized&&(e=this.media)!=null&&e.paused&&this.setPlayerState(Cd.PAUSED)},this.onRateChange=()=>{this.reporter&&this.media&&this.reporter.update({pr:this.media.playbackRate})},this.applyPlaylistData=e=>{try{this.apply(e,{ot:Sd.MANIFEST,su:!this.initialized})}catch(e){this.hls.logger.warn(`Could not generate manifest CMCD data.`,e)}},this.applyFragmentData=e=>{try{let{frag:t,part:n}=e,r=this.hls.levels[t.level],i=this.getObjectType(t,r),a={d:(n||t).duration*1e3,ot:i};if(i===Sd.VIDEO||i===Sd.AUDIO||i===Sd.MUXED||i==null&&(t.type===`main`||t.type===`audio`)){let e=r.bitrate/1e3;a.br=[e];let{cmcd:n}=this.config,o=n?.rtpSafetyFactor??5;if(a.rtp=Math.round(e*o/100)*100,i===Sd.MUXED||i==null&&t.type===`main`){let e=this.getTopBandwidth()/1e3;P(e)&&(a.tb=[e]);let t=this.getLowestBandwidth()/1e3;P(t)&&(a.lb=[t])}let s=this.getBufferLength(t);if(P(s)){a.bl=[s];let e=this.media?.playbackRate||1;a.dl=Math.round(s/e/100)*100}this.playheadLevel&&(a.pb=[this.playheadLevel.bitrate/1e3]);let c=this.hls.maxAutoLevel;if(c>=0){let e=this.hls.levels[c];e&&(a.tpb=[e.bitrate/1e3])}}let o=n?this.getNextPart(n):this.getNextFrag(t);o!=null&&o.url&&o.url!==t.url&&(a.nor=o.byteRange.length>0?[Ld(o.url,{r:`${o.byteRange[0]}-${o.byteRange[1]}`})]:[o.url]),this.apply(e,a)}catch(e){this.hls.logger.warn(`Could not generate segment CMCD data.`,e)}},this.recordFragmentResponse=(e,t,n)=>{var r;let{cmcd:i}=this.config,a=i==null||(r=i.eventTargets)==null?void 0:r.some(e=>e.events?.includes(Pu.RESPONSE_RECEIVED));if(this.reporter&&n.loading.first>0&&a)try{this.reporter.recordResponseReceived({request:{url:e},status:t.code,resourceTiming:{startTime:n.loading.start,responseStart:n.loading.first,duration:n.loading.end-n.loading.start,encodedBodySize:n.total}})}catch(e){this.hls.logger.warn(`Could not record fragment response CMCD data.`,e)}},this.hls=e;let t=this.config=e.config,{cmcd:n}=t;n!=null&&(t.pLoader=this.createPlaylistLoader(),t.fLoader=this.createFragmentLoader(),this.registerListeners())}createReporter(){let{cmcd:e}=this.config;if(e==null)return;let t=e.version||xd;if(this.reporter=new Pd({sid:e.sessionId||this.hls.sessionId,cid:e.contentId,version:t,transmissionMode:e.useHeaders===!0?Td:wd,enabledKeys:e.includeKeys??[...t>=wu?yd:Xu],eventTargets:(e.eventTargets??[]).map(e=>{let{includeKeys:t}=e;return H(H({},Pt(e,Rd)),{},{enabledKeys:t??yd})})},e.loader),this.reporter.update({sf:Fd.HLS,sta:this.playerState}),e.reporterCallback){let t=this.reporter;e.reporterCallback({updateCustomData:e=>{zd(e)&&t.update(e)},recordCustomEvent:(e,n={})=>{zd(n)&&t.recordEvent(Pu.CUSTOM_EVENT,H({cen:e},n))}})}this.reporter.start()}registerListeners(){let e=this.hls;e.on(L.MANIFEST_LOADING,this.onManifestLoading,this),e.on(L.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(L.MEDIA_DETACHED,this.onMediaDetached,this),e.on(L.MEDIA_ENDED,this.onMediaEnded,this),e.on(L.ERROR,this.onError,this),e.on(L.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(L.LEVEL_SWITCHED,this.onLevelSwitched,this),e.on(L.BUFFER_APPENDED,this.onBufferInfoChange,this),e.on(L.BUFFER_FLUSHED,this.onBufferInfoChange,this)}unregisterListeners(){let e=this.hls;e.off(L.MANIFEST_LOADING,this.onManifestLoading,this),e.off(L.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(L.MEDIA_DETACHED,this.onMediaDetached,this),e.off(L.MEDIA_ENDED,this.onMediaEnded,this),e.off(L.ERROR,this.onError,this),e.off(L.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(L.LEVEL_SWITCHED,this.onLevelSwitched,this),e.off(L.BUFFER_APPENDED,this.onBufferInfoChange,this),e.off(L.BUFFER_FLUSHED,this.onBufferInfoChange,this)}destroy(){this.unregisterListeners(),this.onMediaDetached(),this.reporter&&=(this.reporter.stop(!0),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 n=this.media=t.media;this.setPlayerState(this.media.autoplay?Cd.STARTING:Cd.PRELOADING),Y(n,`waiting`,this.onWaiting),Y(n,`play`,this.onPlay),Y(n,`playing`,this.onPlaying),Y(n,`pause`,this.onPause),Y(n,`seeking`,this.onSeeking),Y(n,`seeked`,this.onSeeked),Y(n,`ratechange`,this.onRateChange)}onMediaDetached(){let e=this.media;e&&(X(e,`waiting`,this.onWaiting),X(e,`play`,this.onPlay),X(e,`playing`,this.onPlaying),X(e,`pause`,this.onPause),X(e,`seeking`,this.onSeeking),X(e,`seeked`,this.onSeeked),X(e,`ratechange`,this.onRateChange),this.media=null)}onMediaEnded(e,t){this.setPlayerState(Cd.ENDED)}onManifestLoading(e,t){this.initialized=!1,this.starved=!1,this.buffering=!0,this.reporter&&=(this.reporter.stop(!0),void 0),this.createReporter(),this.media||this.setPlayerState(Cd.PRELOADING)}onError(e,t){t.fatal&&(this.setPlayerState(Cd.FATAL_ERROR),this.reporter&&this.reporter.recordEvent(Pu.ERROR,{ec:[t.details]}))}onLevelSwitching(e,t){if(!this.reporter)return;let n={br:[t.bitrate/1e3]},r=t.details?.fragments[0];r&&(n.ot=this.getObjectType(r,t)),this.reporter.recordEvent(Pu.BITRATE_CHANGE,n)}onLevelSwitched(e,t){let n=this.hls.levels[t.level];n&&(this.playheadLevel=n)}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?Id.LOW_LATENCY:Id.LIVE:Id.VOD}apply(e,t={}){if(!this.reporter)return;this.reporter.update({mtp:[this.hls.bandwidthEstimate/1e3],pr:this.media?.playbackRate,st:this.getStreamType()});let n=t.ot===Sd.INIT||t.ot===Sd.VIDEO||t.ot===Sd.MUXED;this.starved&&n&&(t.bs=!0,t.su=!0,this.starved=!1),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){let t=this.hls.levels[e.level]?.details;if(t){let n=e.sn-t.startSN;return t.fragments[n+1]}}getNextPart(e){var t;let{index:n,fragment:r}=e,i=(t=this.hls.levels[r.level])==null||(t=t.details)==null?void 0:t.partList;if(i){let{sn:e}=r;for(let t=i.length-1;t>=0;t--){let r=i[t];if(r.index===n&&r.fragment.sn===e)return i[t+1]}}}getObjectType(e,t){let{type:n}=e;if(n===`subtitle`)return Sd.TIMED_TEXT;if(e.sn===`initSegment`)return Sd.INIT;if(n===`audio`)return Sd.AUDIO;if(n===`main`){if(e.hasStreams){let t=e.elementaryStreams;if(t.audiovideo)return Sd.MUXED;if(t.video)return Sd.VIDEO;if(t.audio)return Sd.AUDIO}if(t){let{audioCodec:e,videoCodec:n}=t;if(!this.hls.audioTracks.length){if(e&&n)return Sd.MUXED;if(e)return Sd.AUDIO}if(n)return Sd.VIDEO}}}getTopBandwidth(){let e=0,t=this.hls,n=t.maxAutoLevel,r=n>-1?n+1:t.levels.length;return t.levels.slice(0,r).forEach(t=>{t.bitrate>e&&(e=t.bitrate)}),e>0?e:NaN}getLowestBandwidth(){let e=1/0,t=this.hls,n=t.maxAutoLevel,r=n>-1?n+1:t.levels.length;return t.levels.slice(0,r).forEach(t=>{t.bitrate<e&&(e=t.bitrate)}),P(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 n=e||t;return n?n.len*1e3:NaN}onBufferInfoChange(e,t){if(!this.reporter)return;let n=this.getEventBufferLength();P(n)&&this.reporter.update({bl:[n]})}createPlaylistLoader(){let{pLoader:e}=this.config,t=this.applyPlaylistData,n=e||this.config.loader;return class{constructor(e){this.loader=void 0,this.loader=new n(e)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(e,n,r){t(e),this.loader.load(e,n,r)}}}createFragmentLoader(){let{fLoader:e}=this.config,t=this.applyFragmentData,n=this.recordFragmentResponse,r=e||this.config.loader;return class{constructor(e){this.loader=void 0,this.loader=new r(e)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(e,r,i){t(e);let{onSuccess:a}=i;this.loader.load(e,r,H(H({},i),{},{onSuccess:(t,r,i,o)=>{a(t,r,i,o),n(e.url,t,r)}}))}}}},Vd=3e5,Hd=class extends Xt{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(L.MANIFEST_LOADING,this.onManifestLoading,this),e.on(L.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(L.MANIFEST_PARSED,this.onManifestParsed,this),e.on(L.ERROR,this.onError,this)}unregisterListeners(){let e=this.hls;e&&(e.off(L.MANIFEST_LOADING,this.onManifestLoading,this),e.off(L.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(L.MANIFEST_PARSED,this.onManifestParsed,this),e.off(L.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(),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(t=>t!==e))}onManifestLoading(){this.stopLoad(),this.enabled=!0,this.timeToLoad=300,this.updated=0,this.uri=null,this.pathwayId=`.`,this.levels=this.audioTracks=this.subtitleTracks=null}onManifestLoaded(e,t){let{contentSteering:n}=t;n!==null&&(this.pathwayId=n.pathwayId,this.uri=n.uri,this.started&&this.startLoad())}onManifestParsed(e,t){this.audioTracks=t.audioTracks,this.subtitleTracks=t.subtitleTracks}onError(e,t){let{errorAction:n}=t;if(n?.action===ca.SendAlternateToPenaltyBox&&n.flags&la.MoveAllAlternatesMatchingHost){let e=this.levels,r=this._pathwayPriority,i=this.pathwayId;if(t.context){let{groupId:n,pathwayId:r,type:a}=t.context;n&&e?i=this.getPathwayForGroupId(n,a,i):r&&(i=r)}i in this.penalizedPathways||(this.penalizedPathways[i]=performance.now()),!r&&e&&(r=this.pathways()),r&&r.length>1&&(this.updatePathwayPriority(r),n.resolved=this.pathwayId!==i,!n.resolved&&(t.details!==I.BUFFER_APPEND_ERROR||t.fatal)&&this.warn(`Could not resolve ${t.details} ("${t.error.message}") with content-steering for Pathway: ${i} levels: ${e&&e.length} priorities: ${q(r)} penalized: ${q(this.penalizedPathways)}`))}}filterParsedLevels(e){this.levels=e;let t=this.getLevelsForPathway(this.pathwayId);if(t.length===0){let n=e[0].pathwayId;this.log(`No levels found in Pathway ${this.pathwayId}. Setting initial Pathway to "${n}"`),t=this.getLevelsForPathway(n),this.pathwayId=n}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,n=this.penalizedPathways,r=performance.now();Object.keys(n).forEach(e=>{r-n[e]>Vd&&delete n[e]});for(let r=0;r<e.length;r++){let i=e[r];if(i in n)continue;if(i===this.pathwayId)return;let a=this.hls.nextLoadLevel,o=this.hls.levels[a];if(t=this.getLevelsForPathway(i),t.length>0){this.log(`Setting Pathway to "${i}"`),this.pathwayId=i,_s(t),this.hls.trigger(L.LEVELS_UPDATED,{levels:t});let e=this.hls.levels[a];o&&e&&this.levels&&(e.attrs[`STABLE-VARIANT-ID`]!==o.attrs[`STABLE-VARIANT-ID`]&&e.bitrate!==o.bitrate&&this.log(`Unstable Pathways change from bitrate ${o.bitrate} to ${e.bitrate}`),this.hls.nextLoadLevel=a);break}}}getPathwayForGroupId(e,t,n){let r=this.getLevelsForPathway(n).concat(this.levels||[]);for(let n=0;n<r.length;n++)if(t===R.AUDIO_TRACK&&r[n].hasAudioGroup(e)||t===R.SUBTITLE_TRACK&&r[n].hasSubtitleGroup(e))return r[n].pathwayId;return n}clonePathways(e){let t=this.levels;if(!t)return;let n={},r={};e.forEach(e=>{let{ID:i,"BASE-ID":a,"URI-REPLACEMENT":o}=e;if(t.some(e=>e.pathwayId===i))return;let s=this.getLevelsForPathway(a).map(e=>{let t=new so(e.attrs);t[`PATHWAY-ID`]=i;let a=t.AUDIO&&`${t.AUDIO}_clone_${i}`,s=t.SUBTITLES&&`${t.SUBTITLES}_clone_${i}`;a&&(n[t.AUDIO]=a,t.AUDIO=a),s&&(r[t.SUBTITLES]=s,t.SUBTITLES=s);let c=Wd(e.uri,t[`STABLE-VARIANT-ID`],`PER-VARIANT-URIS`,o),l=new Mi({attrs:t,audioCodec:e.audioCodec,bitrate:e.bitrate,height:e.height,name:e.name,url:c,videoCodec:e.videoCodec,width:e.width});if(e.audioGroups)for(let t=1;t<e.audioGroups.length;t++)l.addGroupId(`audio`,`${e.audioGroups[t]}_clone_${i}`);if(e.subtitleGroups)for(let t=1;t<e.subtitleGroups.length;t++)l.addGroupId(`text`,`${e.subtitleGroups[t]}_clone_${i}`);return l});t.push(...s),Ud(this.audioTracks,n,o,i),Ud(this.subtitleTracks,r,o,i)})}loadSteeringManifest(e){let t=this.hls.config,n=t.loader;this.loader&&this.loader.destroy(),this.loader=new n(t);let r;try{r=new self.URL(e)}catch{this.enabled=!1,this.log(`Failed to parse Steering Manifest URI: ${e}`);return}if(r.protocol!==`data:`){let e=(this.hls.bandwidthEstimate||t.abrEwmaDefaultEstimate)|0;wi(r,`_HLS_pathway`,this.pathwayId),wi(r,`_HLS_throughput`,``+e)}let i={type:R.STEERING_MANIFEST,responseType:`json`,url:r.href},a=t.steeringManifestLoadPolicy.default,o=a.errorRetry||a.timeoutRetry||{},s={loadPolicy:a,timeout:a.maxLoadTimeMs,maxRetry:o.maxNumRetry||0,retryDelay:o.retryDelayMs||0,maxRetryDelay:o.maxRetryDelayMs||0};this.log(`Requesting steering manifest: ${r}`),this.loader.load(i,s,{onSuccess:(e,t,n,i)=>{this.log(`Loaded steering manifest: "${r}"`);let a=e.data;if(a?.VERSION!==1){this.log(`Steering VERSION ${a.VERSION} not supported!`);return}this.updated=performance.now(),this.timeToLoad=a.TTL;let{"RELOAD-URI":o,"PATHWAY-CLONES":s,"PATHWAY-PRIORITY":c}=a;if(o)try{this.uri=new self.URL(o,r).href}catch{this.enabled=!1,this.log(`Failed to parse Steering Manifest RELOAD-URI: ${o}`);return}this.scheduleRefresh(this.uri||n.url),s&&this.clonePathways(s);let l={steeringManifest:a,url:r.toString()};this.hls.trigger(L.STEERING_MANIFEST_LOADED,l),c&&this.updatePathwayPriority(c)},onError:(e,t,n,r)=>{if(this.log(`Error loading steering manifest: ${e.code} ${e.text} (${t.url})`),this.stopLoad(),e.code===410){this.enabled=!1,this.log(`Steering manifest ${t.url} no longer available`);return}let i=this.timeToLoad*1e3;if(e.code===429){let e=this.loader;if(typeof e?.getResponseHeader==`function`){let t=e.getResponseHeader(`Retry-After`);t&&(i=parseFloat(t)*1e3)}this.log(`Steering manifest ${t.url} rate limited`);return}this.scheduleRefresh(this.uri||t.url,i)},onTimeout:(e,t,n)=>{this.log(`Timeout loading steering manifest (${t.url})`),this.scheduleRefresh(this.uri||t.url)}})}scheduleRefresh(e,t=this.timeToLoad*1e3){this.clearTimeout(),this.reloadTimer=self.setTimeout(()=>{let t=this.hls?.media;if(t&&!t.ended){this.loadSteeringManifest(e);return}this.scheduleRefresh(e,this.timeToLoad*1e3)},t)}};function Ud(e,t,n,r){e&&Object.keys(t).forEach(i=>{let a=e.filter(e=>e.groupId===i).map(e=>{let a=V({},e);return a.details=void 0,a.attrs=new so(a.attrs),a.url=a.attrs.URI=Wd(e.url,e.attrs[`STABLE-RENDITION-ID`],`PER-RENDITION-URIS`,n),a.groupId=a.attrs[`GROUP-ID`]=t[i],a.attrs[`PATHWAY-ID`]=r,a});e.push(...a)})}function Wd(e,t,n,r){if(t){let{[n]:e}=r;if(e){let n=e[t];if(n)return n}}let{HOST:i,PARAMS:a}=r,o=new self.URL(e);return i&&(o.hostname=i),a&&Object.keys(a).sort().forEach(e=>{e&&wi(o,e,a[e])}),o.href}var Gd=class{constructor(){this.status=`initialized`,this.requestErrors=[],this.licenseXhr=void 0,this.onmessage=void 0,this.onkeystatuseschange=void 0,this.emitter=new Fs,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}},Kd=class extends Error{constructor(e,t){super(t),this.data=void 0,e.error||=Error(t),this.data=e,e.err=e.error}},qd=class e extends Xt{constructor(t){super(`eme`,t.logger),this.hls=void 0,this.config=void 0,this.media=null,this.mediaResolved=void 0,this.keyFormatPromise=null,this.keySystemAccessPromises={},this.sessionSetupByUri={},this.mediaKeySessions=[],this.activeKeys={},this.mediaKeys=null,this.setMediaKeysChain=e.CDMCleanupPromise||Promise.resolve(),this.onMediaEncrypted=e=>{let{initDataType:t,initData:n}=e,r=`"${e.type}" event: init data type: "${t}"`;if(this.log(r),n!==null){if(!this.keyFormatPromise){let e=Object.keys(this.keySystemAccessPromises);e.length||(e=Do(this.config));let t=e.map(Eo).filter(e=>!!e);this.keyFormatPromise=this.getKeyFormatPromise(t)}this.keyFormatPromise.then(i=>{let a,o=wo(i),s=this.activeLevelKeys();if(o===So.FAIRPLAY&&t===`sinf`)try{let e=Gn(new Uint8Array(n)),t=_r(Wn(JSON.parse(e).sinf));if(!t)throw Error(`'schm' box missing or not cbcs/cenc with schi > tenc`);a=new Uint8Array(t.subarray(8,24))}catch(e){this.warn(`${r} Failed to parse sinf: ${e}`);return}else if(o===So.PLAYREADY)a=Mo(new Uint8Array(n));else if(o===So.WIDEVINE){let e=Pr(n).filter(e=>e.systemId===To.WIDEVINE);if(e.length){var c;let t=e[0];a=(c=t.kids)!=null&&c.length?t.kids[0]:null}}let l;if(a){let e=Hn(a);for(let r=0;r<s.length;r++){let i=s[r];if(i.keyId&&(po(a,i.keyId)||i.uri.replace(/-/g,``).indexOf(e)!==-1)){i.pssh||(i.scheme=t,i.pssh=new Uint8Array(n),i.keyId=a,Po.setKeyIdForUri(i.uri,a)),l=this.getSessionForKey(i,`encrypted-event-key-match`);break}}}if(!l){if(s.length){var u,d;return(u=s[0]).scheme||(u.scheme=t),(d=s[0]).pssh||(d.pssh=new Uint8Array(n)),this.getSessionForKey(s[0],`encrypted-event-no-match`)}if(a)throw Error(`Key ID ${Hn(a)} not encountered in playlist`);this.log(`Ignoring "${e.type}" event - could not determine keyId`)}return l}).catch(e=>this.handleError(e))}},this.onWaitingForKey=e=>{this.log(`"${e.type}" event`)},this.hls=t,this.config=t.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(L.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(L.MEDIA_DETACHED,this.onMediaDetached,this),e.on(L.MANIFEST_LOADING,this.onManifestLoading,this),e.on(L.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(L.DESTROYING,this.onDestroying,this))}unregisterListeners(){let{hls:e}=this;e&&(e.off(L.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(L.MEDIA_DETACHED,this.onMediaDetached,this),e.off(L.MANIFEST_LOADING,this.onManifestLoading,this),e.off(L.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(L.DESTROYING,this.onDestroying,this))}attemptKeySystemAccess(e){if(!this.hls)return Promise.reject(Error(`destroyed`));let t=this.hls.levels,n=(e,t,n)=>!!e&&n.indexOf(e)===t,r=t.map(e=>e.audioCodec).filter(n),i=t.map(e=>e.videoCodec).filter(n);return r.length+i.length===0&&i.push(`avc1.42e01e`),new Promise((t,n)=>{let a=e=>{let o=e.shift();this.getMediaKeysPromise(o,r,i).then(e=>t({keySystem:o,mediaKeys:e})).catch(t=>{e.length?a(e):t instanceof Kd?n(t):n(new Kd({type:F.KEY_SYSTEM_ERROR,details:I.KEY_SYSTEM_NO_ACCESS,error:t,fatal:!0},t.message))})};a(e)})}requestMediaKeySystemAccess(e,t){let{requestMediaKeySystemAccessFunc:n}=this.config;if(typeof n!=`function`){let e=`Configured requestMediaKeySystemAccess is not a function ${n}`;return Oo===null&&self.location.protocol===`http:`&&(e=`navigator.requestMediaKeySystemAccess is not available over insecure protocol ${location.protocol}`),Promise.reject(Error(e))}return n(e,t)}getMediaKeysPromise(e,t,n){let r=ko(e,t,n,this.config.drmSystemOptions||{}),i=this.keySystemAccessPromises[e],a=i?.keySystemAccess;if(!a){this.log(`Requesting encrypted media "${e}" key-system access with config: ${q(r)}`),a=this.requestMediaKeySystemAccess(e,r);let t=i=this.keySystemAccessPromises[e]={keySystemAccess:a};return a.catch(t=>{this.log(`Failed to obtain access to key-system "${e}": ${t}`)}),a.then(n=>{this.throwIfDestroyed(),this.log(`Access for key-system "${n.keySystem}" obtained`);let r=this.fetchServerCertificate(e);this.log(`Create media-keys for "${e}"`);let i=t.mediaKeys=n.createMediaKeys().then(n=>(this.log(`Media-keys created for "${e}"`),t.createdMediaKeys=n,r.then(t=>t?this.setMediaKeysServerCertificate(n,e,t):n)));return i.catch(t=>{this.error(`Failed to create media-keys for "${e}"}: ${t}`)}),i})}return a.then(()=>i.mediaKeys)}getMediaKeySessionContext(e,t,n,r){let{mediaKeySessions:i}=this,a=` key-session "${e}" keyId: ${Hn(n.keyId||[])} keyUri: ${n.uri} for "${r}"`;for(let e=0;e<i.length;e++){let t=i[e];if(!t.initialized&&t.createdFor.levelKey.uri===n.uri)return this.log(`Reusing${a}`),t}this.log(`Creating${a}`);let o={keySystem:e,mediaKeys:t,mediaKeysSession:t.createSession(),keyRequests:{},keyStatuses:{},createdFor:{levelKey:n,reason:r},initialized:!1};return i.push(o),o}resetMediaKeys(){let e=this.mediaKeySessions[0]?.keySystem,t=this.keySystemAccessPromises[e];t&&(this.log(`reset mediaKeys`),this.mediaKeys=null,delete t.createdMediaKeys,delete t.mediaKeys,delete this.keySystemAccessPromises[e])}updateKeySession(e,t,n){let r=e.mediaKeysSession;return this.log(`Updating key-session "${r.sessionId}" for keyId ${Hn(t.keyId||[])}
|
|
32
|
+
} (data length: ${n.byteLength})`),r.update(n)}getSelectedKeySystemFormats(){return Object.keys(this.keySystemAccessPromises).map(e=>({keySystem:e,hasMediaKeys:!!this.keySystemAccessPromises[e].createdMediaKeys})).filter(({hasMediaKeys:e})=>!!e).map(({keySystem:e})=>Eo(e)).filter(e=>!!e)}getKeySystemAccess(e){return this.getKeySystemSelectionPromise(e).then(({keySystem:e,mediaKeys:t})=>this.attemptSetMediaKeys(e,t))}selectKeySystem(e){return this.getKeySystemSelectionPromise(e).then(({keySystem:e})=>{let t=Eo(e);if(!t)throw Error(`Unable to find format for key-system "${e}"`);return t})}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.getKeyFormatPromise(t)),this.keyFormatPromise}getKeyFormatPromise(e){let t=Do(this.config),n=e.map(wo).filter(e=>!!e&&t.indexOf(e)!==-1);return this.selectKeySystem(n)}loadClear(e,t,n){if(this.config.emeEnabled&&!this.getSelectedKeySystemFormats().length){if(t.length)for(let r=0,i=t.length;r<i;r++){let a=t[r];if(e.cc<=a.cc&&(!Tt(e)||!Tt(a)||e.sn<a.sn)||!n&&r==i-1)return this.selectKeySystemFormat(a).then(e=>{if(!this.hls)return;a.setKeyFormat(e);let t=wo(e);if(t)return this.getKeySystemAccess([t])})}if(this.config.requireKeySystemAccessOnStart){let e=Do(this.config);if(e.length)return this.getKeySystemAccess(e)}}return null}getKeyStatus(e){let{mediaKeySessions:t}=this;for(let n=0;n<t.length;n++){let r=Zd(e,t[n]);if(r)return r}}loadKey(e){let t=e.decryptdata,n=this.getKeyStatus(t);if(n===`internal-error`){let r=Qd(n,t);return r.data.frag=e,this.error(`${r.message} (${Hn(t.keyId||[])})`),Promise.reject(r)}let r=e.type,i=this.activeKeys,a=i[r];a&&!t.matches(a.decryptdata)&&(i.previous||=[],i.previous.push(a),delete i[r]),i[r]||(i[r]=e);for(let e=this.mediaKeySessions.length;e--;){let n=this.mediaKeySessions[e];if(t.keyId&&n.keyStatuses[Hn(t.keyId)]===`expired`)return this.renewKeySession(t,n)}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,n){let r=this.getSessionForKey(e,t);return r.catch(e=>this.handleError(e,n)),r.then(t=>e)}getSessionForKey(e,t){let n=this.findContextForKey(e);if(n!==void 0)return Promise.resolve(n);let r=e.uri,i=this.sessionSetupByUri[r],a;a=i===void 0?this.resolveSessionForKey(e,t):i.catch(()=>void 0).then(()=>(this.throwIfDestroyed(),this.resolveSessionForKey(e,t))),this.sessionSetupByUri[r]=a;let o=()=>{this.sessionSetupByUri[r]===a&&delete this.sessionSetupByUri[r]};return a.then(o,o),a}findContextForKey(e){let{mediaKeySessions:t}=this;for(let n=t.length;n--;){let r=t[n];if(Zd(e,r))return r}}resolveSessionForKey(e,t){return this.getKeySystemForKeyPromise(e).then(({keySystem:n,mediaKeys:r})=>{this.throwIfDestroyed();for(let n=this.mediaKeySessions.length;n--;){let r=this.mediaKeySessions[n];if(Zd(e,r))return r;let i=this.getUsableKeyPromise(r,e,t);if(i)return i}return this.attemptSetMediaKeys(n,r).then(()=>(this.throwIfDestroyed(),this.getMediaKeySessionContext(n,r,e,t))).then(n=>{this.throwIfDestroyed();let r=e.scheme||`cenc`,i=e.pssh?e.pssh.buffer:null;return this.generateRequestWithPreferredKeySession(n,e,r,i,t)})})}getUsableKeyPromise(e,t,n){let r=e.keyRequests[t.uri];if(r)return this.log(`Waiting for usable key (${n} keyId: ${Xd(t)} format: "${t.keyFormat}" URI: ${t.uri})`),r.useable.then(()=>e)}throwIfDestroyed(e=`Invalid state`){if(!this.hls)throw Error(`invalid state`)}handleError(e,t){if(this.hls){if(e instanceof Kd){t&&(e.data.frag=t);let n=e.data.decryptdata;this.error(`${e.message}${n?` (${Hn(n.keyId||[])})`:``}`),this.hls.trigger(L.ERROR,e.data)}else this.error(e.message),this.hls.trigger(L.ERROR,{type:F.KEY_SYSTEM_ERROR,details:I.KEY_SYSTEM_NO_KEYS,error:e,fatal:!0,reason:`${e.name}: ${e.message}`})}}getKeySystemForKeyPromise(e){let t=wo(e.keyFormat),n=t?[t]:Do(this.config);return this.attemptKeySystemAccess(n)}getKeySystemSelectionPromise(e){if(e.length||(e=Do(this.config)),e.length===0)throw new Kd({type:F.KEY_SYSTEM_ERROR,details:I.KEY_SYSTEM_NO_CONFIGURED_LICENSE,fatal:!0},`Missing key-system license configuration options ${q({drmSystems:this.config.drmSystems})}`);return this.attemptKeySystemAccess(e)}activeLevelKeys(){let e=this.activeKeys,t=(e.previous||[]).map(e=>e.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(e=>{this.log(`setMediaKeys failed: ${e}`)}),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((e,n)=>{this.mediaResolved=()=>{if(this.mediaResolved=void 0,!this.media)return n(Error(`Attempted to set mediaKeys without media element attached`));this.mediaKeys=t,this.media.setMediaKeys(t).then(e).catch(n)}})).then(()=>{this.log(`Media-keys set for "${e}"`)},e=>{throw this.mediaKeys===t&&(this.mediaKeys=null),e}))}filterInitData(e,t,n,r,i){var a;let o=(a=this.config.drmSystems)==null||(a=a[e.keySystem])==null?void 0:a.generateRequest;if(o)try{let a=o.call(this.hls,n,r,V({},e,{decryptdata:t,reason:i}),i);if(!a)throw Error(`Invalid response from configured generateRequest filter`);t.scheme=a.initDataType?a.initDataType:`cenc`;let s=a.initData?a.initData:null;return t.pssh=s?new Uint8Array(s):null,a}catch(e){var s;if(this.warn(e.message),(s=this.hls)!=null&&s.config.debug)throw e}return{initDataType:n,initData:r}}generateRequestWithPreferredKeySession(e,t,n,r,i){let a=this.getUsableKeyPromise(e,t,i);if(a)return a;let o=this.filterInitData(e,t,n,r,i);if(o&&(r=o.initData?o.initData:null,n=o.initDataType),r===null)return i.startsWith(`encrypted-event`)?Promise.reject(Error(`missing initialization data for "${i}"`)):(this.log(`Skipping key-session request for "${i}" (no initData)`),Promise.resolve(e));let s=t.uri,c=new Gd;e.keyRequests[s]=c;let l=n=>{let r=e.mediaKeysSession;if(!r){c.errored=Error(`invalid state`);return}let{messageType:i,message:a}=n;c.status=i,this.log(`"${i}" message event for session "${r.sessionId}" message size: ${a.byteLength}`),i===`license-request`||i===`license-renewal`?this.renewLicense(e,t,a).catch(t=>{c.errored=t,c.hasListeners||this.handleError(t),this.removeSession(e)}):i===`license-release`?e.keySystem===So.FAIRPLAY&&this.updateKeySession(e,t,_o(`acknowledged`)).then(()=>this.removeSession(e)).catch(e=>this.handleError(e)):this.warn(`unhandled media key message type "${i}"`)};return c.onmessage=l,Y(e.mediaKeysSession,`message`,l),this.generateRequest(e,t,n,r,i,!1)}generateRequest(e,t,n,r,i,a){if(a){let a=this.filterInitData(e,t,n,r,i);a&&(r=a.initData?a.initData:r,n=a.initDataType)}let o=t.uri,s=e.keyRequests[o],c=Hn(t.keyId||[]),l=e=>{let n;e.startsWith(`usable`)?s.resolve():e===`internal-error`||e===`output-restricted`||e===`output-downscaled`?n=Qd(e,t):e===`expired`?n=Error(`key expired (keyId: ${c})`):e===`released`?n=Error(`key released`):e===`status-pending`||this.warn(`unhandled key status change "${e}" (keyId: ${c})`),n&&(s.errored=n,s.hasListeners||this.handleError(n))},u=n=>{if(!e.mediaKeysSession){s.errored=Error(`invalid state`);return}let r=e.keyStatuses=this.getKeyStatuses(e);if(!Object.keys(r).some(e=>r[e]!==`status-pending`))return;let i=this.activeLevelKeys();for(let n=0;n<i.length;n++)if(r[Hn(i[n].keyId||[])]===`expired`){this.log(`Expired key ${q(r)} in key-session "${e.mediaKeysSession?.sessionId}"`),this.renewKeySession(t,e).catch(e=>this.handleError(e));break}let a=r[c];if(a)l(a);else{var o;let n=1e3;e.keyStatusTimeouts||={},(o=e.keyStatusTimeouts)[c]||(o[c]=self.setTimeout(()=>{if(!e.mediaKeysSession)return;let r=this.getKeyStatus(t);if(r&&r!==`status-pending`)return this.log(`No status for keyId ${c} in key-session "${e.mediaKeysSession?.sessionId}". Using session key-status ${r} from other session.`),l(r);this.log(`key status for ${c} in key-session "${e.mediaKeysSession?.sessionId}" timed out after ${n}ms`),a=`internal-error`,l(a)},n)),this.log(`No status for keyId ${c} (${q(r)}).`)}};s.onkeystatuseschange=u,Y(e.mediaKeysSession,`keystatuseschange`,u);let d=s.useable;return this.log(`Generating key-session request for "${i}" keyId: ${c} URI: ${o} (init data type: ${n} length: ${r.byteLength})`),s.status=`started`,e.initialized=!0,e.mediaKeysSession.generateRequest(n,r).then(()=>{s.status=`generated`,this.log(`Request generated for key-session "${e.mediaKeysSession?.sessionId}" keyId: ${c} URI: ${o}`)}).catch(e=>{throw this.log(`mediaKeysSession.generateRequest failed: ${e}`),new Kd({type:F.KEY_SYSTEM_ERROR,details:I.KEY_SYSTEM_NO_SESSION,error:e,decryptdata:t,fatal:!1},`Error generating key-session request: ${e}`)}).then(()=>d).catch(t=>{this.log(`mediaKeysSession.generateRequest failed: ${t}`);let n=t.data?.details;return(n===I.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED||n===I.KEY_SYSTEM_STATUS_INTERNAL_ERROR)&&Object.keys(e.keyStatuses).some(t=>e.keyStatuses[t]===`usable`)?(this.handleError(t),e):this.removeSession(e).then(()=>{throw t})}).then(()=>e)}getKeyStatuses(e){let t={},n=e.mediaKeysSession.sessionId;return e.mediaKeysSession.keyStatuses.forEach((r,i)=>{if(typeof i==`string`&&typeof r==`object`){let e=i;i=r,r=e}let a=`buffer`in i?new Uint8Array(i.buffer,i.byteOffset,i.byteLength):new Uint8Array(i);if(e.keySystem===So.PLAYREADY&&a.length===16){let e=Hn(a);t[e]=r,yo(a)}let o=Hn(a);this.log(`key status change "${r}" for keyStatuses keyId: ${o} key-session "${n}"`),t[o]=r}),t}fetchServerCertificate(e){let t=this.config,n=t.loader,r=new n(t),i=Yd(e,t);return i?(this.log(`Fetching server certificate for "${e}"`),new Promise((n,a)=>{let o={type:R.SERVER_CERTIFICATE,responseType:`arraybuffer`,url:i},s=t.certLoadPolicy.default,c={loadPolicy:s,timeout:s.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0};r.load(o,c,{onSuccess:(e,t,r,i)=>{n(e.data)},onError:(t,n,r,s)=>{a(new Kd({type:F.KEY_SYSTEM_ERROR,details:I.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:r,response:H({url:o.url,data:void 0},t)},`"${e}" certificate request failed (${i}). Status: ${t.code} (${t.text})`))},onTimeout:(t,n,r)=>{a(new Kd({type:F.KEY_SYSTEM_ERROR,details:I.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:r,response:{url:o.url,data:void 0}},`"${e}" certificate request timed out (${i})`))},onAbort:(e,t,n)=>{a(Error(`aborted`))}})})):(this.log(`No Server Certificate in config.drmSystems["${e}"]`),Promise.resolve())}setMediaKeysServerCertificate(e,t,n){return new Promise((r,i)=>{e.setServerCertificate(n).then(i=>{this.log(`setServerCertificate ${i?`success`:`not supported by CDM`} (${n.byteLength}) on "${t}"`),r(e)}).catch(e=>{i(new Kd({type:F.KEY_SYSTEM_ERROR,details:I.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED,error:e,fatal:!0},e.message))})})}renewLicense(e,t,n){return this.requestLicense(e,t,new Uint8Array(n)).then(n=>this.updateKeySession(e,t,new Uint8Array(n)).catch(e=>{throw new Kd({type:F.KEY_SYSTEM_ERROR,details:I.KEY_SYSTEM_SESSION_UPDATE_FAILED,decryptdata:t,error:e,fatal:!1},e.message)}))}unpackPlayReadyKeyMessage(e,t){let n=Gn(new Uint16Array(t.buffer));if(!n.includes(`PlayReadyKeyMessage`))return e.setRequestHeader(`Content-Type`,`text/xml; charset=utf-8`),t;let r=new DOMParser().parseFromString(n,`application/xml`),i=r.querySelectorAll(`HttpHeader`);if(i.length>0){let t;for(let n=0,r=i.length;n<r;n++){t=i[n];let r=t.querySelector(`name`)?.textContent,a=t.querySelector(`value`)?.textContent;r&&a&&e.setRequestHeader(r,a)}}let a=r.querySelector(`Challenge`)?.textContent;if(!a)throw Error(`Cannot find <Challenge> in key message`);return _o(atob(a))}setupLicenseXHR(e,t,n,r,i){let a=this.config.licenseXhrSetup;return a?Promise.resolve().then(()=>(this.throwIfDestroyed(),a.call(this.hls,e,t,H(H({},n),{},{decryptdata:r}),i))).catch(o=>{if(!n.mediaKeysSession)throw o;return e.open(`POST`,t,!0),a.call(this.hls,e,t,H(H({},n),{},{decryptdata:r}),i)}).then(n=>(e.readyState||e.open(`POST`,t,!0),{xhr:e,licenseChallenge:n||i})):(e.open(`POST`,t,!0),Promise.resolve({xhr:e,licenseChallenge:i}))}requestLicense(e,t,n){return new Promise((r,i)=>{let a=Jd(e.keySystem,this.config);if(!a)return i(Error(`no license server URL configured for key-system "${e.keySystem}"`));let o=e.keyRequests[t.uri];if(!o)return i(Error(`License emitter removed`));this.log(`Sending license request to URL: ${a}`);let s=this.config.keyLoadPolicy.default,c=new XMLHttpRequest;c.responseType=`arraybuffer`,c.onreadystatechange=()=>{if(!this.hls||!e.mediaKeysSession)return i(Error(`invalid state`));if(c.readyState===4){if(c.status===200){o.requestErrors=[];let n=c.response;this.log(`License received ${n instanceof ArrayBuffer?n.byteLength:n}`);let i=this.config.licenseResponseCallback;if(i)try{n=i.call(this.hls,c,a,H(H({},e),{},{decryptdata:t}))}catch(e){this.error(e)}r(n)}else{let l=s.errorRetry,u=l?l.maxNumRetry:0;if(o.requestErrors.push({status:c.status,message:c.statusText}),o.requestErrors.length>u||c.status>=400&&c.status<500)i(new Kd({type:F.KEY_SYSTEM_ERROR,details:I.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 a=u-o.requestErrors.length;this.warn(`Retrying license request, ${a} attempts left`),this.requestLicense(e,t,n).then(r,i)}}}},o.licenseXhr&&o.licenseXhr.readyState!==XMLHttpRequest.DONE&&o.licenseXhr.abort(),o.licenseXhr=c,this.setupLicenseXHR(c,a,e,t,n).then(({xhr:t,licenseChallenge:n})=>{e.keySystem==So.PLAYREADY&&(n=this.unpackPlayReadyKeyMessage(t,n)),t.send(n)}).catch(i)})}onDestroying(){this.unregisterListeners(),this._clear()}onMediaAttached(e,t){if(!this.config.emeEnabled)return;let n=t.media;this.media=n,Y(n,`encrypted`,this.onMediaEncrypted),Y(n,`waitingforkey`,this.onWaitingForKey);let r=this.mediaResolved;r?r():this.mediaKeys=n.mediaKeys}onMediaDetached(){let e=this.media;e&&(X(e,`encrypted`,this.onMediaEncrypted),X(e,`waitingforkey`,this.onWaitingForKey),this.media=null,this.mediaKeys=null)}_clear(t=!1){this.keyFormatPromise=null,t||(this.keySystemAccessPromises={}),this.activeKeys={},this.sessionSetupByUri={};let n=this.mediaResolved;if(n&&n(),!this.mediaKeys&&!this.mediaKeySessions.length)return;let r=this.media,i=t&&this.config.reuseKeySessions,a=i?[]:this.mediaKeySessions.slice();i||(this.mediaKeySessions=[],Po.clearKeyUriToKeyIdMap()),t||(this.mediaKeys=null);let o=a.length,s=r&&!t?this.queueSetMediaKeys(()=>r.setMediaKeys(null)).catch(e=>{this.log(`Could not clear media keys: ${e}`),this.hls&&this.hls.trigger(L.ERROR,{type:F.OTHER_ERROR,details:I.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR,fatal:!1,error:Error(`Could not clear media keys: ${e}`)})}):Promise.resolve();e.CDMCleanupPromise=Promise.all(a.map(e=>this.removeSession(e)).concat(s)).catch(e=>{this.log(`Could not close sessions and clear media keys: ${e}`),this.hls&&this.hls.trigger(L.ERROR,{type:F.OTHER_ERROR,details:I.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:Error(`Could not close sessions and clear media keys: ${e}`)})}).then(()=>{o&&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,n=!!t&&Object.keys(this.keySystemAccessPromises).some(e=>e!==So.FAIRPLAY&&this.keySystemAccessPromises[e]?.createdMediaKeys===t);this._clear(n),this.keyFormatPromise=null}onManifestLoaded(e,{sessionKeys:t}){if(t&&this.config.emeEnabled&&!this.keyFormatPromise){let e=t.reduce((e,t)=>(e.indexOf(t.keyFormat)===-1&&e.push(t.keyFormat),e),[]);this.log(`Selecting key-system from session-keys ${e.join(`, `)}`),this.keyFormatPromise=this.getKeyFormatPromise(e),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(n=>{let r=e.keyRequests[n];r.onmessage&&t.removeEventListener(`message`,r.onmessage),r.onkeystatuseschange&&t.removeEventListener(`keystatuseschange`,r.onkeystatuseschange),r.reset(),e.keyRequests[n]=void 0}),e.mediaKeysSession=void 0;let n=this.mediaKeySessions.indexOf(e);n>-1&&this.mediaKeySessions.splice(n,1);let{keyStatusTimeouts:r}=e;r&&Object.keys(r).forEach(e=>self.clearTimeout(r[e]));let{drmSystemOptions:i}=this.config;return(jo(i)?new Promise((e,n)=>{self.setTimeout(()=>n(Error(`MediaKeySession.remove() timeout`)),8e3),t.remove().then(e).catch(n)}):Promise.resolve()).catch(e=>{this.log(`Could not remove session: ${e}`),this.hls&&this.hls.trigger(L.ERROR,{type:F.OTHER_ERROR,details:I.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR,fatal:!1,error:Error(`Could not remove session: ${e}`)})}).then(()=>t.close()).then(()=>t.closed).catch(e=>{this.log(`Could not close session: ${e}`),this.hls&&this.hls.trigger(L.ERROR,{type:F.OTHER_ERROR,details:I.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:Error(`Could not close session: ${e}`)})})}return Promise.resolve()}};qd.CDMCleanupPromise=void 0;function Jd(e,t){let{drmSystems:n,widevineLicenseUrl:r}=t,i=n?.[e];if(i)return i.licenseUrl;if(e===So.WIDEVINE&&r)return r}function Yd(e,t){let{drmSystems:n}=t,r=n?.[e];if(r)return r.serverCertificateUrl}function Xd(e){if(e.keyFormat===Co.FAIRPLAY)return e.uri;if(e.keyId===null)throw Error(`keyId is null`);return Hn(e.keyId)}function Zd(e,t){let n=e.keyId,r=t.mediaKeysSession;if(n&&r){let e=t.mediaKeysSession.keyStatuses;if(e.size)return e.has(n)?e.get(n):t.keyStatuses[Hn(n)]}}function Qd(e,t){let n=e===`output-restricted`,r=n?I.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:I.KEY_SYSTEM_STATUS_INTERNAL_ERROR;return new Kd({type:F.KEY_SYSTEM_ERROR,details:r,fatal:!1,decryptdata:t},n?`HDCP level output restricted`:`key status changed to "${e}"`)}var $d=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(L.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.on(L.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListeners(){this.hls.off(L.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.off(L.MEDIA_DETACHING,this.onMediaDetaching,this)}destroy(){this.timer&&clearInterval(this.timer),this.unregisterListeners(),this.isVideoPlaybackQualityAvailable=!1,this.media=null}onMediaAttaching(e,t){let n=this.hls.config;if(n.capLevelOnFPSDrop){let e=t.media instanceof self.HTMLVideoElement?t.media:null;this.media=e,e&&typeof e.getVideoPlaybackQuality==`function`&&(this.isVideoPlaybackQualityAvailable=!0),self.clearInterval(this.timer),this.timer=self.setInterval(this.checkFPSInterval.bind(this),n.fpsDroppedMonitoringPeriod)}}onMediaDetaching(){this.media=null}checkFPS(e,t,n){let r=performance.now();if(t){if(this.lastTime){let e=r-this.lastTime,i=n-this.lastDroppedFrames,a=t-this.lastDecodedFrames,o=1e3*i/e,s=this.hls;if(s.trigger(L.FPS_DROP,{currentDropped:i,currentDecoded:a,totalDroppedFrames:n}),o>0&&i>s.config.fpsDroppedMonitoringThreshold*a){let e=s.currentLevel;s.logger.warn(`drop FPS ratio greater than max allowed value for currentLevel: `+e),e>0&&(s.autoLevelCapping===-1||s.autoLevelCapping>=e)&&(--e,s.trigger(L.FPS_DROP_LEVEL_CAPPING,{level:e,droppedLevel:s.currentLevel}),s.autoLevelCapping=e,this.streamController.nextLevelSwitch())}}this.lastTime=r,this.lastDroppedFrames=n,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)}}},ef=(function(){if(xo!=null&&xo.VTTCue)return self.VTTCue;let e=[``,`lr`,`rl`],t=[`start`,`middle`,`end`,`left`,`right`];function n(e,t){if(typeof t!=`string`||!Array.isArray(e))return!1;let n=t.toLowerCase();return~e.indexOf(n)?n:!1}function r(t){return n(e,t)}function i(e){return n(t,e)}function a(e,...t){let n=1;for(;n<arguments.length;n++){let t=arguments[n];for(let n in t)e[n]=t[n]}return e}function o(e,t,n){let o=this,s={enumerable:!0};o.hasBeenReset=!1;let c=``,l=!1,u=e,d=t,f=n,p=null,m=``,h=!0,g=`auto`,_=`start`,v=50,y=`middle`,b=50,x=`middle`;Object.defineProperty(o,"id",a({},s,{get:function(){return c},set:function(e){c=``+e}})),Object.defineProperty(o,"pauseOnExit",a({},s,{get:function(){return l},set:function(e){l=!!e}})),Object.defineProperty(o,"startTime",a({},s,{get:function(){return u},set:function(e){if(typeof e!=`number`)throw TypeError(`Start time must be set to a number.`);u=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"endTime",a({},s,{get:function(){return d},set:function(e){if(typeof e!=`number`)throw TypeError(`End time must be set to a number.`);d=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"text",a({},s,{get:function(){return f},set:function(e){f=``+e,this.hasBeenReset=!0}})),Object.defineProperty(o,"region",a({},s,{get:function(){return p},set:function(e){p=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"vertical",a({},s,{get:function(){return m},set:function(e){let t=r(e);if(t===!1)throw SyntaxError(`An invalid or illegal string was specified.`);m=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"snapToLines",a({},s,{get:function(){return h},set:function(e){h=!!e,this.hasBeenReset=!0}})),Object.defineProperty(o,"line",a({},s,{get:function(){return g},set:function(e){if(typeof e!=`number`&&e!==`auto`)throw SyntaxError(`An invalid number or illegal string was specified.`);g=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"lineAlign",a({},s,{get:function(){return _},set:function(e){let t=i(e);if(!t)throw SyntaxError(`An invalid or illegal string was specified.`);_=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"position",a({},s,{get:function(){return v},set:function(e){if(e<0||e>100)throw Error(`Position must be between 0 and 100.`);v=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"positionAlign",a({},s,{get:function(){return y},set:function(e){let t=i(e);if(!t)throw SyntaxError(`An invalid or illegal string was specified.`);y=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"size",a({},s,{get:function(){return b},set:function(e){if(e<0||e>100)throw Error(`Size must be between 0 and 100.`);b=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"align",a({},s,{get:function(){return x},set:function(e){let t=i(e);if(!t)throw SyntaxError(`An invalid or illegal string was specified.`);x=t,this.hasBeenReset=!0}})),o.displayState=void 0}return o.prototype.getCueAsHTML=function(){return self.WebVTT.convertCueToDOMTree(self,this.text)},o})(),tf=class{decode(e,t){if(!e)return``;if(typeof e!=`string`)throw Error(`Error - expected string data.`);return decodeURIComponent(encodeURIComponent(e))}};function nf(e){function t(e,t,n,r){return(e|0)*3600+(t|0)*60+(n|0)+parseFloat(r||0)}let n=e.match(/^(?:(\d+):)?(\d{2}):(\d{2})(\.\d+)?/);return n?parseFloat(n[2])>59?t(n[2],n[3],0,n[4]):t(n[1],n[2],n[3],n[4]):null}var rf=class{constructor(){this.values=Object.create(null)}set(e,t){!this.get(e)&&t!==``&&(this.values[e]=t)}get(e,t,n){return n?this.has(e)?this.values[e]:t[n]:this.has(e)?this.values[e]:t}has(e){return e in this.values}alt(e,t,n){for(let r=0;r<n.length;++r)if(t===n[r]){this.set(e,t);break}}integer(e,t){/^-?\d+$/.test(t)&&this.set(e,parseInt(t,10))}percent(e,t){if(/^([\d]{1,3})(\.[\d]*)?%$/.test(t)){let n=parseFloat(t);if(n>=0&&n<=100)return this.set(e,n),!0}return!1}};function af(e,t,n,r){let i=r?e.split(r):[e];for(let e in i){if(typeof i[e]!=`string`)continue;let r=i[e].split(n);if(r.length!==2)continue;let a=r[0],o=r[1];t(a,o)}}var of=new ef(0,0,``),sf=of.align===`middle`?`middle`:`center`;function cf(e,t,n){let r=e;function i(){let t=nf(e);if(t===null)throw Error(`Malformed timestamp: `+r);return e=e.replace(/^[^\sa-zA-Z-]+/,``),t}function a(e,t){let r=new rf;af(e,function(e,t){let i;switch(e){case`region`:for(let i=n.length-1;i>=0;i--)if(n[i].id===t){r.set(e,n[i].region);break}break;case`vertical`:r.alt(e,t,[`rl`,`lr`]);break;case`line`:i=t.split(`,`),r.integer(e,i[0]),r.percent(e,i[0])&&r.set(`snapToLines`,!1),r.alt(e,i[0],[`auto`]),i.length===2&&r.alt(`lineAlign`,i[1],[`start`,sf,`end`]);break;case`position`:i=t.split(`,`),r.percent(e,i[0]),i.length===2&&r.alt(`positionAlign`,i[1],[`start`,sf,`end`,`line-left`,`line-right`,`auto`]);break;case`size`:r.percent(e,t);break;case`align`:r.alt(e,t,[`start`,sf,`end`,`left`,`right`])}},/:/,/\s/),t.region=r.get(`region`,null),t.vertical=r.get(`vertical`,``);let i=r.get(`line`,`auto`);i===`auto`&&of.line===-1&&(i=-1),t.line=i,t.lineAlign=r.get(`lineAlign`,`start`),t.snapToLines=r.get(`snapToLines`,!0),t.size=r.get(`size`,100),t.align=r.get(`align`,sf);let a=r.get(`position`,`auto`);a===`auto`&&of.position===50&&(a=t.align===`start`||t.align===`left`?0:t.align===`end`||t.align===`right`?100:50),t.position=a}function o(){e=e.replace(/^\s+/,``)}if(o(),t.startTime=i(),o(),e.slice(0,3)!==`-->`)throw Error(`Malformed time stamp (time stamps must be separated by '-->'): `+r);e=e.slice(3),o(),t.endTime=i(),o(),a(e,t)}function lf(e){return e.replace(/<br(?: \/)?>/gi,`
|
|
33
|
+
`)}var uf=class{constructor(){this.state=`INITIAL`,this.buffer=``,this.decoder=new tf,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 n(){let e=t.buffer,n=0;for(e=lf(e);n<e.length&&e[n]!==`\r`&&e[n]!==`
|
|
34
34
|
`;)++n;let r=e.slice(0,n);return e[n]===`\r`&&++n,e[n]===`
|
|
35
|
-
`&&++n,t.buffer=e.slice(n),r}function r(e){
|
|
35
|
+
`&&++n,t.buffer=e.slice(n),r}function r(e){af(e,function(e,t){},/:/)}try{let e=``;if(t.state===`INITIAL`){if(!/\r\n|\n/.test(t.buffer))return this;e=n();let r=e.match(/^()?WEBVTT([ \t].*)?$/);if(!(r!=null&&r[0]))throw Error(`Malformed WebVTT signature.`);t.state=`HEADER`}let i=!1;for(;t.buffer;){if(!/\r\n|\n/.test(t.buffer))return this;switch(i?i=!1:e=n(),t.state){case`HEADER`:/:/.test(e)?r(e):e||(t.state=`ID`);continue;case`NOTE`:e||(t.state=`ID`);continue;case`ID`:if(/^NOTE($|[ \t])/.test(e)){t.state=`NOTE`;break}if(!e)continue;if(t.cue=new ef(0,0,``),t.state=`CUE`,e.indexOf(`-->`)===-1){t.cue.id=e;continue}case`CUE`:if(!t.cue){t.state=`BADCUE`;continue}try{cf(e,t.cue,t.regionList)}catch{t.cue=null,t.state=`BADCUE`;continue}t.state=`CUETEXT`;continue;case`CUETEXT`:{let n=e.indexOf(`-->`)!==-1;if(!e||n&&(i=!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+=`
|
|
36
36
|
`),t.cue.text+=e}continue;case`BADCUE`:e||(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+=`
|
|
37
37
|
|
|
38
|
-
`,e.parse()),e.state===`INITIAL`||e.state===`BADWEBVTT`)throw Error(`Malformed WebVTT signature.`)}catch(t){e.onparsingerror&&e.onparsingerror(t)}return e.onflush&&e.onflush(),this}};function
|
|
38
|
+
`,e.parse()),e.state===`INITIAL`||e.state===`BADWEBVTT`)throw Error(`Malformed WebVTT signature.`)}catch(t){e.onparsingerror&&e.onparsingerror(t)}return e.onflush&&e.onflush(),this}};function df(e){let t=5381,n=e.length;for(;n;)t=t*33^e.charCodeAt(--n);return(t>>>0).toString()}var ff=/\r\n|\n\r|\n|\r/g,pf=function(e){let t=parseInt(e.slice(-3)),n=parseInt(e.slice(-6,-4)),r=parseInt(e.slice(-9,-7)),i=e.length>9?parseInt(e.substring(0,e.indexOf(`:`))):0;if(!P(t)||!P(n)||!P(r)||!P(i))throw Error(`Malformed X-TIMESTAMP-MAP: Local:${e}`);return t+=1e3*n,t+=6e4*r,t+=36e5*i,t};function mf(e,t,n){return df(e.toString())+df(t.toString())+df(n)}function hf(e,t,n,r,i,a,o){let s=new uf,c=kn(new Uint8Array(e)).trim().replace(ff,`
|
|
39
39
|
`).split(`
|
|
40
|
-
`),l=[],u=t?
|
|
41
|
-
`)}),s.flush()}var
|
|
40
|
+
`),l=[],u=t?nl(t.baseTime,t.timescale):0,d=`00:00.000`,f=0,p=0,m=!1,h,g=!0;s.oncue=function(e){let a=n[r],o=n.ccOffset,s=(f-u)/9e4;if(m){if(a!=null&&a.new&&(o=n.ccOffset=a.start),s){if(!t){h=Error(`Missing initPTS for VTT MPEGTS`);return}o=s-n.presentationOffset}}else if(t)o=-t.baseTime/t.timescale;else{h=Error(`Missing initPTS for VTT without X-TIMESTAMP-MAP`);return}let c=e.endTime-e.startTime,d=dl((e.startTime+o-p)*9e4,i*9e4)/9e4;e.startTime=Math.max(d,0),e.endTime=Math.max(d+c,0);let g=e.text.replace(/^[ \t\r\n\f]+|[ \t\r\n\f]+$/g,``);e.text=decodeURIComponent(encodeURIComponent(g)),e.id?r&&(e.id=`hlsjscc${r}_${e.id}`):e.id=mf(e.startTime,e.endTime,g.trim()),e.endTime>0&&l.push(e)},s.onparsingerror=function(e){h=e},s.onflush=function(){if(h){o(h);return}a(l)},c.forEach(e=>{if(g){if(e.startsWith(`X-TIMESTAMP-MAP=`)){g=!1,m=!0,e.slice(16).split(`,`).forEach(e=>{e.startsWith(`LOCAL:`)?d=e.slice(6):e.startsWith(`MPEGTS:`)&&(f=parseInt(e.slice(7)))});try{p=pf(d)/1e3}catch(e){h=e}return}e===``&&(g=!1)}s.parse(e+`
|
|
41
|
+
`)}),s.flush()}var gf=`stpp.ttml.im1t`,_f=/^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/,vf=/^(\d*(?:\.\d*)?)(h|m|s|ms|f|t)$/,yf={left:`start`,center:`center`,right:`end`,start:`start`,end:`end`};function bf(e,t,n,r){let i=K(new Uint8Array(e),[`mdat`]);if(i.length===0){r(Error(`Could not parse IMSC1 mdat`));return}let a=i.map(e=>kn(e)),o=el(t.baseTime,1,t.timescale);try{a.forEach(e=>n(xf(e,o)))}catch(e){r(e)}}function xf(e,t){let n=new DOMParser().parseFromString(e,`text/xml`).getElementsByTagName(`tt`)[0];if(!n)throw Error(`Invalid ttml`);let r={frameRate:30,subFrameRate:1,tickRate:1},i=Object.keys(r).reduce((e,t)=>(e[t]=n.getAttribute(`ttp:${t}`)||r[t],e),{}),a=(n.getAttribute(`ttp:frameRateMultiplier`)||``).trim().split(/\s+/).map(Number);a.length===2&&a[0]>0&&a[1]>0&&(i.frameRate=Number(i.frameRate)*a[0]/a[1]),!n.getAttribute(`ttp:tickRate`)&&n.getAttribute(`ttp:frameRate`)&&(i.tickRate=Number(i.frameRate)*Number(i.subFrameRate));let o=n.getAttribute(`xml:space`)!==`preserve`,s=Cf(Sf(n,`styling`,`style`)),c=Cf(Sf(n,`layout`,`region`)),l=Sf(n,`body`,`[begin]`);return[].map.call(l,e=>{let n=wf(e,o);if(!n||!e.hasAttribute(`begin`))return null;let r=kf(e.getAttribute(`begin`),i),a=kf(e.getAttribute(`dur`),i),l=kf(e.getAttribute(`end`),i);if(r===null)throw Of(e);if(l===null){if(a===null)throw Of(e);l=r+a}let u=new ef(r-t,l-t,n);u.id=mf(u.startTime,u.endTime,u.text);let d=c[e.getAttribute(`region`)],f=s[e.getAttribute(`style`)],p=Ef(d,f,s),{textAlign:m}=p;if(m){let e=yf[m];e&&(u.lineAlign=e),u.align=m}return V(u,p),u}).filter(e=>e!==null)}function Sf(e,t,n){let r=e.getElementsByTagName(t)[0];return r?[].slice.call(r.querySelectorAll(n)):[]}function Cf(e){return e.reduce((e,t)=>{let n=t.getAttribute(`xml:id`);return n&&(e[n]=t),e},{})}function wf(e,t){let n=Tf(e,t);return t?n.split(`
|
|
42
42
|
`).map(e=>e.replace(/ {2,}/g,` `).trim()).join(`
|
|
43
|
-
`):n}function
|
|
44
|
-
`:(i=n.childNodes)!=null&&i.length?e+wf(n,t):e+(t?n.textContent.replace(/\s+/g,` `):n.textContent)},``)}function Tf(e,t,n){let r=`http://www.w3.org/ns/ttml#styling`,i=null,a=[`displayAlign`,`textAlign`,`color`,`backgroundColor`,`fontSize`,`fontFamily`],o=e!=null&&e.hasAttribute(`style`)?e.getAttribute(`style`):null;return o&&n.hasOwnProperty(o)&&(i=n[o]),a.reduce((n,a)=>{let o=Ef(t,r,a)||Ef(e,r,a)||Ef(i,r,a);return o&&(n[a]=o),n},{})}function Ef(e,t,n){return e&&e.hasAttributeNS(t,n)?e.getAttributeNS(t,n):null}function Df(e){return Error(`Could not parse ttml timestamp ${e}`)}function Of(e,t){if(!e)return null;if(gf.test(e))return kf(e,t);let n=tf(e);return n===null&&_f.test(e)&&(n=Af(e,t)),n}function kf(e,t){let n=gf.exec(e),r=(n[4]|0)+(n[5]|0)/t.subFrameRate;return(n[1]|0)*3600+(n[2]|0)*60+(n[3]|0)+r/t.frameRate}function Af(e,t){let n=_f.exec(e),r=Number(n[1]);switch(n[2]){case`h`:return r*3600;case`m`:return r*60;case`ms`:return r/1e3;case`f`:return r/t.frameRate;case`t`:return r/t.tickRate}return r}function jf(e,t,n,r=``,i=`disabled`){let a=e.ownerDocument.createElement(`track`);return a.kind=t,a.label=n,r&&(a.srclang=r),a.src=`data:,WEBVTT`,a.track.mode=i,e.appendChild(a),a}function Mf(e){return e.forced&&qr()?`forced`:e.characteristics&&/transcribes-spoken-dialog/gi.test(e.characteristics)&&/describes-music-and-sound/gi.test(e.characteristics)?`captions`:`subtitles`}function Nf(e,t){let n=e.mode;if(n===`disabled`&&(e.mode=`hidden`),e.cues&&!e.cues.getCueById(t.id))try{if(e.addCue(t),!e.cues.getCueById(t.id))throw Error(`addCue is failed for: ${t}`)}catch(n){U.debug(`[texttrack-utils]: ${n}`);try{let n=new self.TextTrackCue(t.startTime,t.endTime,t.text);n.id=t.id,e.addCue(n)}catch(e){U.debug(`[texttrack-utils]: Legacy TextTrackCue fallback failed: ${e}`)}}n===`disabled`&&(e.mode=n)}function Pf(e,t,n,r){let i=e.mode;if(i===`disabled`&&(e.mode=`hidden`),e.cues&&e.cues.length>0){let i=If(e.cues,t,n);for(let t=0;t<i.length;t++)(!r||r(i[t]))&&e.removeCue(i[t])}i===`disabled`&&(e.mode=i)}function Ff(e,t){if(t<=e[0].startTime)return 0;let n=e.length-1;if(t>e[n].endTime)return-1;let r=0,i=n,a;for(;r<=i;)if(a=Math.floor((i+r)/2),t<e[a].startTime)i=a-1;else if(t>e[a].startTime&&r<n)r=a+1;else return a;return e[r].startTime-t<t-e[i].startTime?r:i}function If(e,t,n){let r=[],i=Ff(e,t);if(i>-1)for(let a=i,o=e.length;a<o;a++){let i=e[a];if(i.startTime>=t&&i.endTime<=n)r.push(i);else if(i.startTime>n)return r}return r}var Lf=class extends Ml{constructor(e){super(e,`subtitle-track-controller`),this.media=null,this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0,this.queuedDefaultTrack=-1,this.useTextTrackPolling=!1,this.subtitlePollingInterval=-1,this._subtitleDisplay=!0,this.asyncPollTrackChange=()=>this.pollTrackChange(0),this.onTextTracksChanged=()=>{if(this.useTextTrackPolling||self.clearInterval(this.subtitlePollingInterval),!this.media||!this.hls.config.renderTextTracksNatively)return;let e=-1,t=!1;if(this.currentTrack){let n=this.currentTrack.trackNode?.track.mode;n===`showing`?(e=this.trackId,t=!0):n===`hidden`&&(e=this.trackId)}if(!t)for(let t=0;t<this.tracksInGroup.length;t++){let n=this.tracksInGroup[t].trackNode?.track.mode;if(n===`showing`){e=t;break}e<0&&n===`hidden`&&(e=t)}e>-1&&(this._subtitleDisplay=this.tracksInGroup[e].trackNode?.track.mode===`showing`),this.setSubtitleTrack(e,!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(L.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(L.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(L.MANIFEST_LOADING,this.onManifestLoading,this),e.on(L.MANIFEST_PARSED,this.onManifestParsed,this),e.on(L.LEVEL_LOADING,this.onLevelLoading,this),e.on(L.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(L.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(L.ERROR,this.onError,this)}unregisterListeners(){let{hls:e}=this;e.off(L.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(L.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(L.MANIFEST_LOADING,this.onManifestLoading,this),e.off(L.MANIFEST_PARSED,this.onManifestParsed,this),e.off(L.LEVEL_LOADING,this.onLevelLoading,this),e.off(L.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(L.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(L.ERROR,this.onError,this)}createTracksInGroup(){var e;if(!this.media||!this.hls.config.renderTextTracksNatively)return;this.tracksInGroup.forEach(e=>{e.trackNode||=jf(this.media,Mf(e),e.name,e.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 n=t.media;this.media=n;let r=this.trackId;this.queuedDefaultTrack>-1&&(r=this.queuedDefaultTrack,this.queuedDefaultTrack=-1),this.setSubtitleTrack(r),this.createTracksInGroup(),this.useTextTrackPolling=!(n.textTracks&&`onchange`in n.textTracks),this.useTextTrackPolling?this.pollTrackChange(500):n.textTracks.addEventListener(`change`,this.asyncPollTrackChange)}pollTrackChange(e){self.clearInterval(this.subtitlePollingInterval),this.subtitlePollingInterval=self.setInterval(this.onTextTracksChanged,e)}onMediaDetaching(e,t){let n=this.media;if(!n)return;let r=!!t.transferMedia;self.clearInterval(this.subtitlePollingInterval),this.useTextTrackPolling||n.textTracks.removeEventListener(`change`,this.asyncPollTrackChange),this.trackId>-1&&(this.queuedDefaultTrack=this.trackId,this.setSubtitleTrack(-1)),this.media=null,!r&&this.hls.config.renderTextTracksNatively&&this.tracksInGroup.forEach(e=>{let t=e.trackNode;t&&(t.track.mode=`hidden`,t.remove(),e.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:n,groupId:r,details:i}=t,a=this.tracksInGroup[n];if(!a||a.groupId!==r){this.warn(`Subtitle track with id:${n} and group:${r} not found in active group ${a?.groupId}`);return}let o=a.details;a.details=t.details,this.log(`Subtitle track ${n} "${a.name}" lang:${a.lang} group:${r} loaded [${i.startSN}-${i.endSN}]`),n===this.trackId&&this.playlistLoaded(n,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 n=t.subtitleGroups||null,r=this.groupIds,i=this.currentTrack;if(!n||r?.length!==n?.length||n!=null&&n.some(e=>r?.indexOf(e)===-1)){this.groupIds=n;let e=[];if(this.tracks.forEach(t=>{(t.textCodec===hf?this.hls.config.enableIMSC1:this.hls.config.enableWebVTT)&&(!n||n.indexOf(t.groupId)>-1?(t.id=e.length,e.push(t)):t.trackNode&&=(t.trackNode.remove(),void 0))}),e.length===this.tracksInGroup.length){let t=!1;for(let n=0;n<e.length;n++)if(e[n]!==this.tracksInGroup[n]){t=!0;break}if(!t)return}e.length&&this.selectDefaultTrack&&!e.some(e=>e.default)&&(this.selectDefaultTrack=!1),this.tracksInGroup=e,this.trackId=-1,this.currentTrack=null;let t=this.hls.config.subtitlePreference;if(!i&&t){this.selectDefaultTrack=!1;let n=Hi(t,e);if(n>-1)i=e[n];else{let e=Hi(t,this.tracks);i=this.tracks[e]}}let r=this.findTrackId(i);r===-1&&i&&(r=this.findTrackId(null));let a={subtitleTracks:e};this.log(`Updating subtitle tracks, ${e.length} track(s) found in "${n?.join(`,`)}" group-id`),this.hls.trigger(L.SUBTITLE_TRACKS_UPDATED,a),this.setSubtitleTrack(r),this.createTracksInGroup()}}findTrackId(e){let t=this.tracksInGroup,n=this.selectDefaultTrack;for(let r=0;r<t.length;r++){let i=t[r];if(!(n&&!i.default||!n&&!e)&&(!e||Ui(i,e)))return r}if(e){for(let n=0;n<t.length;n++){let r=t[n];if(Pl(e.attrs,r.attrs,[`LANGUAGE`,`ASSOC-LANGUAGE`,`CHARACTERISTICS`]))return n}for(let n=0;n<t.length;n++){let r=t[n];if(Pl(e.attrs,r.attrs,[`LANGUAGE`]))return n}}return-1}onError(e,t){!t.fatal&&t.context&&t.context.type===R.SUBTITLE_TRACK&&t.context.id===this.trackId&&Xi(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 n=this.currentTrack;if(n&&Ui(e,n))return n;let r=Hi(e,this.tracksInGroup);if(r>-1){let e=this.tracksInGroup[r];return this.setSubtitleTrack(r,!0),e}if(n)return null;{let n=Hi(e,t);if(n>-1)return t[n]}}}return null}loadPlaylist(e){super.loadPlaylist(),this.shouldLoadPlaylist(this.currentTrack)&&this.scheduleLoading(this.currentTrack,e)}loadingPlaylist(e,t){super.loadingPlaylist(e,t);let n=e.id,r=e.groupId,i=this.getUrlWithDirectives(e.url,t),a=e.details,o=a?.age;this.log(`Loading subtitle ${n} "${e.name}" lang:${e.lang} group:${r}${t?.msn===void 0?``:` at sn `+t.msn+` part `+t.part}${o&&a.live?` age `+o.toFixed(1)+(a.type&&` `+a.type||``):``} ${i}`),this.hls.trigger(L.SUBTITLE_TRACK_LOADING,{url:i,id:n,groupId:r,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 n=t===e?this._subtitleDisplay?`showing`:`hidden`:`disabled`,r=t.trackNode.track;r.mode!==n&&(r.mode=n)}})}setSubtitleTrack(e,t=!1){let n=this.tracksInGroup;if(this.media||(this.queuedDefaultTrack=e),e<-1||e>=n.length||!P(e)){this.warn(`Invalid subtitle track id: ${e}`);return}let r=this.currentTrack,i=n[e]||null;if(this.trackId=e,this.currentTrack=i,t&&this.toggleTrackModes(),!i){r&&this.hls.trigger(L.SUBTITLE_TRACK_SWITCH,{id:e});return}let a=!!i.details&&!i.details.live;if(i===r&&a)return;this.log(`Switching to subtitle-track ${e}`+(i?` "${i.name}" lang:${i.lang} group:${i.groupId}`:``));let{id:o,groupId:s=``,name:c,type:l,url:u}=i;this.hls.trigger(L.SUBTITLE_TRACK_SWITCH,{id:o,groupId:s,name:c,type:l,url:u});let d=this.switchParams(i.url,r?.details,i.details);this.loadPlaylist(d)}},Rf=2,zf=100,Bf=class extends Za{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 e;(e=this.media)!=null&&e.seeking||(this.waiting=self.performance.now(),this.tick())},this.onMediaEnded=()=>{this.hls&&(this.ended=this.media?.currentTime||1,this.hls.trigger(L.MEDIA_ENDED,{stalled:!1}))},this.hls=e,this.fragmentTracker=t,this.lastCurrentTime=this.getCurrentTime(),this.registerListeners()}registerListeners(){let{hls:e}=this;e&&(e.on(L.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(L.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(L.BUFFER_APPENDED,this.onBufferAppended,this))}unregisterListeners(){let{hls:e}=this;e&&(e.off(L.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(L.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(L.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(zf),this.mediaSource=t.mediaSource;let n=this.media=t.media;Y(n,`playing`,this.onMediaPlaying),Y(n,`waiting`,this.onMediaWaiting),Y(n,`ended`,this.onMediaEnded)}onMediaDetaching(e,t){this.clearInterval();let{media:n}=this;n&&(X(n,`playing`,this.onMediaPlaying),X(n,`waiting`,this.onMediaWaiting),X(n,`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(){let e=this.hls?.config.timelineOffset||0;return this.media?Math.max(this.media.currentTime,e):e}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){let n=this.hls?.config;if(!n)return;let r=this.media;if(!r)return;let{seeking:i}=r,a=this.seeking&&!i,o=!this.seeking&&i,s=r.paused&&!i||r.ended||r.playbackRate===0;if(this.seeking=i,e!==t){t&&(this.ended=0),this.moved=!0,i||(this.skipRetry=this.nudgeRetry=0,n.nudgeOnVideoHole&&!s&&e>t&&this.nudgeOnVideoHole(e,t)),this.waiting===0&&this.stallResolved(e);return}if(o||a){a&&this.stallResolved(e);return}if(s){this.skipRetry=this.nudgeRetry=0,this.stallResolved(e),!this.ended&&r.ended&&this.hls&&(this.ended=e||1,this.hls.trigger(L.MEDIA_ENDED,{stalled:!1}));return}if(!J.getBuffered(r).length){this.skipRetry=this.nudgeRetry=0;return}let c=J.bufferInfo(r,e,0),l=this.fragmentTracker;l&&this.hls&&Wf(c,e,l,this.hls);let u=c.nextStart||0;if(i&&l&&this.hls){let t=Vf(this.hls.inFlightFragments,e),n=c.len>Rf,r=!u||t||u-e>Rf&&!l.getPartialFragment(e);if(n||r)return;this.moved=!1}let d=this.hls?.latestLevelDetails;if(!this.moved&&this.stalled!==null&&l){if(!(c.len>0)&&!u)return;let t=Math.max(u,c.start||0)-e,n=d!=null&&d.live?d.targetduration*2:Rf,i=Uf(e,l);if(t>0&&(t<=n||i)){r.paused||this._trySkipBufferHole(i);return}}let f=n.detectStallWithCurrentTimeMs,p=self.performance.now(),m=this.waiting,h=this.stalled;if(h===null){if(m>0&&p-m<f)h=this.stalled=m;else{this.stalled=p;return}}let g=p-h;if(!i&&(g>=f||m&&this.moved)&&this.hls){if(this.mediaSource?.readyState===`ended`&&!(d!=null&&d.live)&&Math.abs(e-(d?.edge||0))<1){if(this.ended)return;this.ended=e||1,this.hls.trigger(L.MEDIA_ENDED,{stalled:!0});return}if(this._reportStall(c),!this.media||!this.hls)return;if(r.currentTime!==e){let t=e;e=r.currentTime,this.moved=!0,this.log(`currentTime changed ${t} > ${e}`);return}}let _=J.bufferInfo(r,e,n.maxBufferHole);this._tryFixBufferStall(_,g,e)}stallResolved(e){let t=this.stalled;if(t&&this.hls&&(this.stalled=null,this.stallReported)){let n=self.performance.now()-t;this.log(`playback not stuck anymore @${e}, after ${Math.round(n)}ms`),this.stallReported=!1,this.waiting=0,this.hls.trigger(L.STALL_RESOLVED,{})}}nudgeOnVideoHole(e,t){var n;let r=this.buffered.video;if(this.hls&&this.media&&this.fragmentTracker&&(n=this.buffered.audio)!=null&&n.length&&r&&r.length>1&&e>r.end(0)){let n=J.bufferedInfo(J.timeRangesToArray(this.buffered.audio),e,0);if(n.len>1&&t>=n.start){let n=J.timeRangesToArray(r),i=J.bufferedInfo(n,t,0).bufferedIndex;if(i>-1&&i<n.length-1){let t=J.bufferedInfo(n,e,0).bufferedIndex,r=n[i].end,a=n[i+1].start;if((t===-1||t>i)&&a-r<1&&e-r<2){let n=Error(`nudging playhead to flush pipeline after video hole. currentTime: ${e} hole: ${r} -> ${a} buffered index: ${t}`);this.warn(n.message),this.media.currentTime+=1e-6;let i=Uf(e,this.fragmentTracker);i&&`fragment`in i?i=i.fragment:i||=void 0;let o=J.bufferInfo(this.media,e,0);this.hls.trigger(L.ERROR,{type:F.MEDIA_ERROR,details:I.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:n,reason:n.message,frag:i,buffer:o.len,bufferInfo:o})}}}}}_tryFixBufferStall(e,t,n){let{fragmentTracker:r,media:i}=this,a=this.hls?.config;if(!i||!r||!a)return;let o=this.hls?.latestLevelDetails,s=Uf(n,r);if((s||o!=null&&o.live&&n<o.fragmentStart)&&(this._trySkipBufferHole(s)||!this.media))return;let c=e.buffered,l=this.adjacentTraversal(e,n);(c&&c.length>1&&e.len>a.maxBufferHole||e.nextStart&&(e.nextStart-n<a.maxBufferHole||l))&&(t>a.highBufferWatchdogPeriod*1e3||this.waiting)&&(this.warn(`Trying to nudge playhead over buffer-hole`),this._tryNudgeBuffer(e))}adjacentTraversal(e,t){let n=this.fragmentTracker,r=e.nextStart;if(n&&r){let e=n.getFragAtPos(t,z.MAIN),i=n.getFragAtPos(r,z.MAIN);if(e&&i)return i.sn-e.sn<2}return!1}_reportStall(e){let{hls:t,media:n,stallReported:r,stalled:i}=this;if(!r&&i!==null&&n&&t){this.stallReported=!0;let r=Error(`Playback stalling at @${n.currentTime} due to low buffer (${q(e)})`);this.warn(r.message),t.trigger(L.ERROR,{type:F.MEDIA_ERROR,details:I.BUFFER_STALLED_ERROR,fatal:!1,error:r,buffer:e.len,bufferInfo:e,stalled:{start:i}})}}_trySkipBufferHole(e){let{fragmentTracker:t,media:n,hls:r}=this,i=r?.config;if(!n||!t||!i)return 0;let a=n.currentTime,o=J.bufferInfo(n,a,0);Wf(o,a,t,r);let s=a<o.start?o.start:o.nextStart;if(s){let l=o.len<=i.maxBufferHole,u=o.len>0&&o.len<1&&n.readyState<3,d=s-a;if(d>0&&(l||u)){if(d>i.maxBufferHole){let n=!1;if(a===0){let e=t.getAppendedFrag(0,z.MAIN);e&&s<e.end&&(n=!0)}if(!n&&e){var c;if(!((c=r.loadLevelObj)!=null&&c.details)||Vf(r.inFlightFragments,s))return 0;let n=!1,i=e.end;for(;i<s;){let e=Uf(i,t),r=e?e.duration:0;if(r>0)i+=r;else{n=!0;break}}if(n)return 0}}let{nudgeMaxRetry:l,skipBufferHolePadding:u}=i,f=++this.skipRetry>l,p=Math.max(s,a)+u;if(f||(this.warn(`skipping hole, adjusting currentTime from ${a} to ${p}`),this.moved=!0,n.currentTime=p),!(e!=null&&e.gap)||f){let t=Error(f?`Playhead still not moving after seeking over buffer hole from ${a} to ${p} after ${i.nudgeMaxRetry} attempts.`:`fragment loaded with buffer holes, seeking from ${a} to ${p}`),n={type:F.MEDIA_ERROR,details:I.BUFFER_SEEK_OVER_HOLE,fatal:f,error:t,reason:t.message,buffer:o.len,bufferInfo:o};e&&(`fragment`in e?n.part=e:n.frag=e),r.trigger(L.ERROR,n)}return p}}return 0}_tryNudgeBuffer(e){let{hls:t,media:n,nudgeRetry:r}=this,i=t?.config;if(!n||!i)return 0;let a=n.currentTime;if(this.nudgeRetry++,r<i.nudgeMaxRetry){let o=a+(r+1)*i.nudgeOffset,s=Error(`Nudging 'currentTime' from ${a} to ${o}`);this.warn(s.message),n.currentTime=o,t.trigger(L.ERROR,{type:F.MEDIA_ERROR,details:I.BUFFER_NUDGE_ON_STALL,error:s,fatal:!1,buffer:e.len,bufferInfo:e})}else{let n=Error(`Playhead still not moving while enough data buffered @${a} after ${i.nudgeMaxRetry} nudges`);this.error(n.message),t.trigger(L.ERROR,{type:F.MEDIA_ERROR,details:I.BUFFER_STALLED_ERROR,error:n,fatal:!0,buffer:e.len,bufferInfo:e})}}};function Vf(e,t){let n=Hf(e.main);if(n&&n.start<=t)return n;let r=Hf(e.audio);return r&&r.start<=t?r:null}function Hf(e){if(!e)return null;switch(e.state){case $.IDLE:case $.STOPPED:case $.ENDED:case $.ERROR:return null}return e.frag}function Uf(e,t){return t.getAppendedFrag(e,z.MAIN)||t.getPartialFragment(e)}function Wf(e,t,n,r){let i=r.latestLevelDetails,a=Uf(t,n);if(Os(r.config)&&!e.nextStart&&i&&a&&r.interstitialsManager){let n=`type`in a?a:a.fragment,o=sa(i,n.sn);o?.level===n.level&&Ds(o,r.interstitialsManager.playerQueue,t)&&(e.nextStart=o.start)}}var Gf=.25;function Kf(){if(!(typeof self>`u`))return self.VTTCue||self.TextTrackCue}function qf(e,t,n,r,i){let a=new e(t,n,``);try{a.value=r,i&&(a.type=i)}catch{a=new e(t,n,q(i?H({type:i},r):r))}return a}var Jf=(()=>{let e=Kf();try{e&&new e(0,1/0,``)}catch{return Number.MAX_VALUE}return 1/0})(),Yf=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(L.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(L.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(L.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(L.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(L.MANIFEST_LOADING,this.onManifestLoading,this),e.on(L.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.on(L.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(L.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(L.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))}_unregisterListeners(){let{hls:e}=this;e&&(e.off(L.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(L.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(L.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(L.MANIFEST_LOADING,this.onManifestLoading,this),e.off(L.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.off(L.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(L.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(L.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))}onMediaAttaching(e,t){this.media=t.media}onMediaAttached(){let e=this.hls?.latestLevelDetails;e&&this.updateDateRangeCues(e)}onMediaDetaching(e,t){this.media=null,!t.transferMedia&&(this.id3Track&&=(this.id3Track.remove(),null),this.dateRangeCuesAppended={})}onManifestLoading(){this.dateRangeCuesAppended={}}createTrack(e){return jf(e,`metadata`,`id3`,``,`hidden`)}onFragParsingMetadata(e,t){if(!this.media||!this.hls)return;let{enableEmsgMetadataCues:n,enableID3MetadataCues:r}=this.hls.config;if(!n&&!r)return;let{samples:i}=t;this.id3Track||=this.createTrack(this.media);let a=Kf();if(a)for(let e=0;e<i.length;e++){let t=i[e].type;if(t===$s.emsg&&!n||!r)continue;let o=Rn(i[e].data),s=i[e].pts,c=s+i[e].duration;c>Jf&&(c=Jf),c-s<=0&&(c=s+Gf);for(let e=0;e<o.length;e++){let n=o[e];if(!zn(n)){this.updateId3CueEnds(s,t);let e=qf(a,s,c,n,t);e&&this.id3Track.track.addCue(e)}}}}updateId3CueEnds(e,t){let n=this.id3Track?.track.cues;if(n)for(let r=n.length;r--;){let i=n[r];i.type===t&&i.startTime<e&&i.endTime===Jf&&(i.endTime=e)}}onBufferFlushing(e,{startOffset:t,endOffset:n,type:r}){let{id3Track:i,hls:a}=this;if(!a)return;let{config:{enableEmsgMetadataCues:o,enableID3MetadataCues:s}}=a;if(i&&(o||s)){let e;e=r===`audio`?e=>e.type===$s.audioId3&&s:r===`video`?e=>e.type===$s.emsg&&o:e=>e.type===$s.audioId3&&s||e.type===$s.emsg&&o,Pf(i.track,t,n,e)}}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:n,timelineOffset:r,enableDateRangeMetadataCues:i,interstitialsController:a}=this.hls.config;if(!i)return;let o=Kf();if(n&&r&&!a){let{fragmentStart:t,fragmentEnd:r}=e,i=this.assetCue;i?(i.startTime=t,i.endTime=r):o&&(i=this.assetCue=qf(o,t,r,{assetPlayerId:this.hls.config.assetPlayerId},`hlsjs.interstitial.asset`),i&&(i.id=n,this.id3Track||=this.createTrack(this.media),this.id3Track.track.addCue(i),i.addEventListener(`enter`,this.onEventCueEnter)))}if(!e.hasProgramDateTime)return;let{id3Track:s}=this,{dateRanges:c}=e,l=Object.keys(c),u=this.dateRangeCuesAppended;if(s&&t){var d;if((d=s.track.cues)!=null&&d.length){let e=Object.keys(u).filter(e=>l.indexOf(e)===-1);for(let t=e.length;t--;){let n=e[t],r=u[n]?.cues;delete u[n],r&&Object.keys(r).forEach(e=>{let t=r[e];if(t){t.removeEventListener(`enter`,this.onEventCueEnter);try{s.track.removeCue(t)}catch{}}})}}else u=this.dateRangeCuesAppended={}}let f=e.fragments[e.fragments.length-1];if(l.length!==0&&P(f?.programDateTime)){this.id3Track||=this.createTrack(this.media);for(let e=0;e<l.length;e++){let t=l[e],n=c[t],r=n.startTime,i=u[t],s=i?.cues||{},d=i?.durationKnown||!1,f=Jf,{duration:p,endDate:m}=n;if(m&&p!==null)f=r+p,d=!0;else if(n.endOnNext&&!d){let e=l.reduce((e,t)=>{if(t!==n.id){let r=c[t];if(r.class===n.class&&r.startDate>n.startDate&&(!e||n.startDate<e.startDate))return r}return e},null);e&&(f=e.startTime,d=!0)}let h=Object.keys(n.attr);for(let e=0;e<h.length;e++){let c=h[e];if(!lo(c))continue;let l=s[c];if(l)d&&!(i!=null&&i.durationKnown)?l.endTime=f:Math.abs(l.startTime-r)>.01&&(l.startTime=r,l.endTime=f);else if(o){let e=n.attr[c];uo(c)&&(e=Un(e));let i=qf(o,r,f,{key:c,data:e},$s.dateRange);i&&(i.id=t,this.id3Track.track.addCue(i),s[c]=i,a&&(c===`X-ASSET-LIST`||c===`X-ASSET-URL`)&&i.addEventListener(`enter`,this.onEventCueEnter))}}u[t]={cues:s,dateRange:n,durationKnown:d}}}}};function Xf(){return self.SourceBuffer||self.WebKitSourceBuffer}function Zf(){if(!an())return!1;let e=Xf();return!e||e.prototype&&typeof e.prototype.appendBuffer==`function`&&typeof e.prototype.remove==`function`}function Qf(){if(!Zf())return!1;let e=an();return typeof e?.isTypeSupported==`function`&&([`avc1.42E01E,mp4a.40.2`,`av01.0.01M.08`,`vp09.00.50.08`].some(t=>e.isTypeSupported($r(t,`video`)))||[`mp4a.40.2`,`fLaC`].some(t=>e.isTypeSupported($r(t,`audio`))))}function $f(){var e;let t=Xf();return typeof(t==null||(e=t.prototype)==null?void 0:e.changeType)==`function`}var ep={DISABLED:0,SWITCHING:1,SWITCHED:2},tp=100,np=class extends Es{constructor(e,t,n){super(e,t,n,`stream-controller`,z.MAIN),this.audioCodecSwap=!1,this.level=-1,this._forceStartLoad=!1,this._hasEnoughToStart=!1,this.altAudio=ep.DISABLED,this.audioOnly=!1,this._couldBacktrack=!1,this._backtrackFragment=void 0,this.audioCodecSwitch=!1,this.videoBuffer=null,this.onMediaPlaying=()=>{this.tick()},this.onMediaSeeked=()=>{let e=this.media,t=e?e.currentTime:null;if(t===null||!P(t)||(this.log(`Media seeked to ${t}`),!this.getBufferedFrag(t)))return;let n=this.getFwdBufferInfoAtPos(e,t,z.MAIN,0);if(!n||n.len===0){this.log(`Main buffer empty at ${t} on "seeked" event: ${n&&n.len}`);return}this.tick()},this.registerListeners()}registerListeners(){super.registerListeners();let{hls:e}=this;e.on(L.MANIFEST_PARSED,this.onManifestParsed,this),e.on(L.LEVEL_LOADING,this.onLevelLoading,this),e.on(L.LEVEL_LOADED,this.onLevelLoaded,this),e.on(L.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.on(L.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(L.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.on(L.BUFFER_CREATED,this.onBufferCreated,this),e.on(L.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(L.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(L.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){super.unregisterListeners();let{hls:e}=this;e.off(L.MANIFEST_PARSED,this.onManifestParsed,this),e.off(L.LEVEL_LOADED,this.onLevelLoaded,this),e.off(L.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.off(L.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(L.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.off(L.BUFFER_CREATED,this.onBufferCreated,this),e.off(L.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(L.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(L.FRAG_BUFFERED,this.onFragBuffered,this)}onHandlerDestroying(){this.onMediaPlaying=this.onMediaSeeked=null,this.unregisterListeners(),super.onHandlerDestroying()}startLoad(e,t){if(this.levels){let{lastCurrentTime:n,hls:r}=this;if(this.stopLoad(),this.setInterval(tp),this.level=-1,!this.startFragRequested){let e=r.startLevel;e===-1&&(r.config.testBandwidth&&this.levels.length>1?(e=0,this.bitrateTest=!0):e=r.firstAutoLevel),r.nextLoadLevel=e,this.level=r.loadLevel,this._hasEnoughToStart=!!t}n>0&&e===-1&&!t&&this.initPTS.length&&(this.log(`Override startPosition with lastCurrentTime @${n}`),e=n),this.state=$.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=$.STOPPED}stopLoad(){this._forceStartLoad=!1,super.stopLoad()}doTick(){switch(this.state){case $.WAITING_LEVEL:{let{levels:e,level:t}=this,n=e?.[t],r=n?.details;if(r&&(!r.live||this.levelLastLoaded===n&&!this.waitForLive(n))){if(this.waitForCdnTuneIn(r))break;this.state=$.IDLE;break}if(this.hls.nextLoadLevel!==this.level){this.state=$.IDLE;break}break}case $.FRAG_LOADING_WAITING_RETRY:this.checkRetryDate()}this.state===$.IDLE&&this.doTickIdle(),this.onTickEnd()}onTickEnd(){super.onTickEnd(),this.checkFragmentChanged()}doTickIdle(){let{hls:e,levelLastLoaded:t,levels:n,media:r}=this;if(t===null||!r&&!this.primaryPrefetch&&(this.startFragRequested||!e.config.startFragPrefetch)||this.altAudio&&this.audioOnly)return;let i=this.buffering?e.nextLoadLevel:e.loadLevel;if(!(n!=null&&n[i]))return;let a=n[i],o=this.getMainFwdBufferInfo();if(o===null)return;let s=this.getLevelDetails();if(s&&this._streamEnded(o,s)&&this.altAudio!==ep.SWITCHING){let e={type:this.targetBufferType()};this.hls.trigger(L.BUFFER_EOS,e),this.state=$.ENDED;return}if(!this.buffering)return;e.loadLevel!==i&&e.manualLevel===-1&&this.log(`Adapting to level ${i} from level ${this.level}`),this.level=e.nextLoadLevel=i;let c=a.details;if(!c||this.state===$.WAITING_LEVEL||this.waitForLive(a)){this.level=i,this.state=$.WAITING_LEVEL,this.startFragRequested=!1;return}let l=o.len,u=this.getMaxBufferLength(a.maxBitrate);if(l>=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&&Tt(f)&&this.fragmentTracker.getState(f)!==Z.OK){let e=(this.backtrackFragment??f).sn-c.startSN,t=c.fragments[e-1];t&&f.cc===t.cc&&(f=t,this.fragmentTracker.removeFragment(t))}else this.backtrackFragment&&o.len&&(this.backtrackFragment=void 0);if(f&&this.isLoopLoading(f,d)){if(!f.gap){let e=this.audioOnly&&!this.altAudio?B.AUDIO:B.VIDEO,t=(e===B.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;t&&this.afterBufferFlushed(t,e)}f=this.getNextFragmentLoopLoading(f,c,o,z.MAIN,u)}f&&(this.exceedsMaxBuffer(o,u,f)||this.loadFragment(f,a,d))}loadFragment(e,t,n){let r=this.fragmentTracker.getState(e);r===Z.NOT_LOADED||r===Z.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,n):this.clearTrackerIfNeeded(e)}immediateLevelSwitch(){this.abortCurrentFrag(),this.flushMainBuffer(0,1/0),this.altAudio!==ep.DISABLED&&(this.getLevelDetails()?.fragmentStart||0)>this.lastCurrentTime&&super.flushMainBuffer(0,1/0,`audio`)}getBufferOutput(){return this.mediaBuffer&&this.altAudio===ep.SWITCHED?this.mediaBuffer:this.media}checkFragmentChanged(){let e=this.fragPlaying;if(!this.checkFragPlaying())return!1;let t=this.fragPlaying;if(t){let n=t.level;this.hls.trigger(L.FRAG_CHANGED,{frag:t,previousFrag:e}),e?.level!==n&&this.hls.trigger(L.LEVEL_SWITCHED,{level:n})}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===ep.SWITCHED&&!this.audioOnly?`video`:null}onMediaAttached(e,t){super.onMediaAttached(e,t);let n=t.media;Y(n,`playing`,this.onMediaPlaying),Y(n,`seeked`,this.onMediaSeeked)}onMediaDetaching(e,t){let{media:n}=this;n&&(X(n,`playing`,this.onMediaPlaying),X(n,`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(L.BUFFER_RESET,void 0),this.couldBacktrack=!1,this.backtrackFragment=void 0,this.altAudio=ep.DISABLED,this.audioOnly=!1}onManifestParsed(e,t){let n=!1,r=!1;for(let e=0;e<t.levels.length;e++){let i=t.levels[e].audioCodec;i&&(n||=i.indexOf(`mp4a.40.2`)!==-1,r||=i.indexOf(`mp4a.40.5`)!==-1)}this.audioCodecSwitch=n&&r&&!$f(),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:n}=this;if(!n||this.state!==$.IDLE)return;let r=t.levelInfo;(!r.details||r.details.live&&(this.levelLastLoaded!==r||r.details.expired)||this.waitForCdnTuneIn(r.details))&&(this.state=$.WAITING_LEVEL)}onLevelLoaded(e,t){var n;let{levels:r,startFragRequested:i}=this,a=t.level,o=t.details,s=o.totalduration;if(!r){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:${s}`);let c=t.levelInfo,l=this.fragCurrent;l&&(this.state===$.FRAG_LOADING||this.state===$.FRAG_LOADING_WAITING_RETRY)&&l.level!==t.level&&l.loader&&this.abortCurrentFrag();let u=0;if(o.live||(n=c.details)!=null&&n.live){if(this.checkLiveUpdate(o),o.deltaUpdateFailed)return;u=this.alignPlaylists(o,c.details,this.levelLastLoaded?.details)}if(c.details=o,this.levelLastLoaded=c,i||this.setStartPosition(o,u),this.hls.trigger(L.LEVEL_UPDATED,{details:o,level:a}),this.state===$.WAITING_LEVEL){if(this.waitForCdnTuneIn(o))return;this.state=$.IDLE}i&&o.live&&this.synchronizeToLiveEdge(o),this.initPTS.some((e,t)=>{if(t>=o.startCC)return!0;delete this.initPTS[t]}),this.tick()}synchronizeToLiveEdge(e){let{config:t,media:n}=this;if(!n)return;let r=this.hls.liveSyncPosition,i=this.playhead,a=e.fragmentStart,o=e.edge,s=i>=a-t.maxFragLookUpTolerance&&i<=o;if(r!==null&&n.duration>r&&(i<r||!s)){let a=t.liveMaxLatencyDuration===void 0?t.liveMaxLatencyDurationCount*e.targetduration:t.liveMaxLatencyDuration;if((!s&&n.readyState<4||i<o-a)&&(this._hasEnoughToStart||(this.nextLoadPosition=r),n.readyState)){if(this.warn(`Playback: ${i} is located too far from the end of live sliding playlist: ${o}, reset currentTime to : ${r}`),this.config.liveSyncMode===`buffered`){var c;let e=J.bufferInfo(n,r,0);if(!((c=e.buffered)!=null&&c.length)){n.currentTime=r;return}if(e.start<=i){n.currentTime=r;return}let{nextStart:t}=J.bufferedInfo(e.buffered,i,0);t&&(n.currentTime=t)}else n.currentTime=r}}}_handleFragmentLoadProgress(e){let t=e.frag,{part:n,payload:r}=e,{levels:i}=this;if(!i){this.warn(`Levels were reset while fragment load was in progress. Fragment ${t.sn} of level ${t.level} will not be buffered`);return}let a=i[t.level];if(!a){this.warn(`Level ${t.level} not found on progress`);return}let o=a.details;if(!o){this.warn(`Dropping fragment ${t.sn} of level ${t.level} after level details were reset`),this.fragmentTracker.removeFragment(t);return}let s=a.videoCodec,c=o.PTSKnown||!o.live,l=t.initSegment?.data,u=this._getAudioCodec(a),d=this.transmuxer=this.transmuxer||new kl(this.hls,z.MAIN,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)),f=n?n.index:-1,p=f!==-1,{decryptRange:m,byteRange:h}=qa(t,n,this.iframesOnly),g=new Qa(t.level,t.sn,t.stats.chunkCount,h?h.end-h.start:r.byteLength,f,p,t.duration,this.iframesOnly,m),_=this.initPTS[t.cc];d.push(r,l,u,s,t,n,o.totalduration,c,g,_)}onAudioTrackSwitching(e,t){let n=this.hls,r=this.altAudio!==ep.DISABLED;if(Yi(t.url,n))this.altAudio=ep.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 e=this.fragCurrent;e&&(this.log(`Switching to main audio track, cancel main fragment load`),e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.resetTransmuxer(),this.resetLoadingState()}else this.audioOnly&&this.resetTransmuxer();if(r){this.altAudio=ep.DISABLED,this.fragmentTracker.removeAllFragments(),n.once(L.BUFFER_FLUSHED,()=>{this.hls&&this.hls.trigger(L.AUDIO_TRACK_SWITCHED,t)}),n.trigger(L.BUFFER_FLUSHING,{startOffset:0,endOffset:1/0,type:null});return}n.trigger(L.AUDIO_TRACK_SWITCHED,t)}}onAudioTrackSwitched(e,t){let n=Yi(t.url,this.hls);if(n){let e=this.videoBuffer;e&&this.mediaBuffer!==e&&(this.log(`Switching on alternate audio, use video.buffered to schedule main fragment loading`),this.mediaBuffer=e)}this.altAudio=n?ep.SWITCHED:ep.DISABLED,this.tick()}onBufferCreated(e,t){let n=t.tracks,r,i,a=!1;for(let e in n){let t=n[e];if(t.id===`main`){if(i=e,r=t,e===`video`){let t=n[e];t&&(this.videoBuffer=t.buffer)}}else a=!0}a&&r?(this.log(`Alternate track found, use ${i}.buffered to schedule main fragment loading`),this.mediaBuffer=r.buffer):this.mediaBuffer=this.media}onFragBuffered(e,t){let{frag:n,part:r}=t,i=n.type===z.MAIN;if(i){if(this.fragContextChanged(n)){this.warn(`Fragment ${n.sn}${r?` p: `+r.index:``} of level ${n.level} finished buffering, but was aborted. state: ${this.state}`),this.state===$.PARSED&&(this.state=$.IDLE);return}let e=!1;if(Tt(n)&&(e=!!n.gap&&!n.tagList.some(e=>e[0]===`GAP`)),this.fragBufferedComplete(n,r),e){n.stats.retry++;let e=this.levels?.[n.level];e&&e.fragmentError++}}let a=this.media;a&&(!this._hasEnoughToStart&&J.getBuffered(a).length&&(this.seekToStartPos(),this._hasEnoughToStart=!0),i&&this.tick())}get hasEnoughToStart(){return this._hasEnoughToStart}onError(e,t){if(t.fatal){this.state=$.ERROR;return}switch(t.details){case I.FRAG_GAP:case I.FRAG_PARSING_ERROR:case I.FRAG_DECRYPT_ERROR:case I.FRAG_LOAD_ERROR:case I.FRAG_LOAD_TIMEOUT:case I.KEY_LOAD_ERROR:case I.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(z.MAIN,t);break;case I.LEVEL_LOAD_ERROR:case I.LEVEL_LOAD_TIMEOUT:case I.LEVEL_PARSING_ERROR:!t.levelRetry&&this.state===$.WAITING_LEVEL&&t.context?.type===R.LEVEL&&(this.state=$.IDLE);break;case I.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 I.MEDIA_SOURCE_REQUIRES_RESET:this.onSourceBufferError(z.MAIN,t);break;case I.BUFFER_ADD_CODEC_ERROR:case I.BUFFER_APPEND_ERROR:if(t.parent!==`main`)return;this.reduceLengthAndFlushBuffer(t)&&this.resetLoadingState();break;case I.BUFFER_FULL_ERROR:if(t.parent!==`main`)return;this.reduceLengthAndFlushBuffer(t)&&(!this.config.interstitialsController&&this.config.assetPlayerId?this._hasEnoughToStart=!0:this.flushMainBuffer(0,1/0));break;case I.INTERNAL_EXCEPTION:this.recoverWorkerError(t)}}onFragLoadEmergencyAborted(){this.state=$.IDLE,this._hasEnoughToStart||(this.startFragRequested=!1,this.nextLoadPosition=this.lastCurrentTime),this.tickImmediate()}onBufferFlushed(e,{type:t}){if(t!==B.AUDIO||!this.altAudio){let e=(t===B.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;e&&(this.afterBufferFlushed(e,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,n=this.startPosition;if(n>=0&&t<n){if(e.seeking){this.log(`could not seek to ${n}, already seeking at ${t}`);return}let r=this.timelineOffset;r&&n&&(n+=r);let i=this.getLevelDetails(),a=J.getBuffered(e),o=a.length?a.start(0):0,s=o-n,c=Math.max(this.config.maxBufferHole,this.config.maxFragLookUpTolerance);(this.config.startOnSegmentBoundary||s>0&&(s<c||this.loadingParts&&s<2*(i?.partTarget||0)))&&(this.log(`adjusting start position by ${s} to match buffer start`),n+=s,this.startPosition=n),t<n&&(this.log(`seek to target start position ${n} from current time ${t} buffer start ${o}`),e.currentTime=n)}}_getAudioCodec(e){let t=this.config.defaultAudioCodec||e.audioCodec;return this.audioCodecSwap&&t&&(this.log(`Swapping audio codec`),t=t.indexOf(`mp4a.40.5`)===-1?`mp4a.40.5`:`mp4a.40.2`),t}_loadBitrateTestFrag(e,t){e.bitrateTest=!0,this._doFragLoad(e,t).then(e=>{let{hls:n}=this,r=e?.frag;if(!r||this.fragContextChanged(r))return;t.fragmentError=0,this.state=$.IDLE,this.startFragRequested=!1,this.bitrateTest=!1;let i=r.stats;i.parsing.start=i.parsing.end=i.buffering.start=i.buffering.end=self.performance.now(),n.trigger(L.FRAG_LOADED,e),r.bitrateTest=!1}).catch(t=>{this.state!==$.STOPPED&&this.state!==$.ERROR&&(this.warn(t),this.resetFragmentLoading(e))})}_handleTransmuxComplete(e){let t=this.playlistType,{hls:n}=this,{remuxResult:r,chunkMeta:i}=e,a=this.getCurrentContext(i);if(!a){this.resetWhenMissingContext(i);return}let{frag:o,part:s,level:c}=a,{video:l,text:u,id3:d,initSegment:f}=r,{details:p}=c,m=this.altAudio?void 0:r.audio;if(this.fragContextChanged(o)){this.fragmentTracker.removeFragment(o);return}if(this.state=$.PARSING,f){let e=f.tracks;if(e){let r=o.initSegment||o;if(this.unhandledEncryptionError(f,o))return;this._bufferInitSegment(c,e,r,i),n.trigger(L.FRAG_PARSING_INIT_SEGMENT,{frag:r,id:t,tracks:e})}let r=f.initPTS,a=f.timescale,s=this.initPTS[o.cc];if(P(r)&&(!s||s.baseTime!==r||s.timescale!==a)){let e=f.trackId;this.initPTS[o.cc]={baseTime:r,timescale:a,trackId:e};let i=this.initPTS.slice(0);n.trigger(L.INIT_PTS_FOUND,{timestampOffsets:i,frag:o,id:t,initPTS:r,timescale:a,trackId:e})}}if(l&&p){m&&l.type===`audiovideo`&&this.logMuxedErr(o);let e=p.fragments[o.sn-1-p.startSN],t=o.sn===p.startSN,n=!e||o.cc>e.cc;if(r.independent!==!1){let{startPTS:e,endPTS:r,startDTS:a,endDTS:c}=l;if(s)s.elementaryStreams[l.type]={startPTS:e,endPTS:r,startDTS:a,endDTS:c};else if(l.firstKeyFrame&&l.independent&&i.id===1&&!n&&(this.couldBacktrack=!0),l.dropped&&l.independent){let i=this.getMainFwdBufferInfo(),a=(i?i.end:this.getLoadPosition())+this.config.maxBufferHole,s=l.firstKeyFramePTS?l.firstKeyFramePTS:e;if(!t&&a<s-this.config.maxBufferHole&&!n){this.backtrack(o);return}n&&(o.gap=!0),o.setElementaryStreamInfo(l.type,o.start,r,o.start,c,!0)}else t&&e-(p.appliedTimelineOffset||0)>Rf&&(o.gap=!0);o.setElementaryStreamInfo(l.type,e,r,a,c),this.backtrackFragment&&=o,this.bufferFragmentData(l,o,s,i,t||n)}else if(t||n)o.gap=!0;else{this.backtrack(o);return}}if(m){let{startPTS:e,endPTS:t,startDTS:n,endDTS:r}=m;s&&(s.elementaryStreams[B.AUDIO]={startPTS:e,endPTS:t,startDTS:n,endDTS:r}),o.setElementaryStreamInfo(B.AUDIO,e,t,n,r),this.bufferFragmentData(m,o,s,i)}if(p&&d!=null&&d.samples.length){let e={id:t,frag:o,details:p,samples:d.samples};n.trigger(L.FRAG_PARSING_METADATA,e)}if(p&&u){let e={id:t,frag:o,details:p,samples:u.samples};n.trigger(L.FRAG_PARSING_USERDATA,e)}}logMuxedErr(e){this.warn(`${Tt(e)?`Media`:`Init`} segment with muxed audiovideo where only video expected: ${e.url}`)}_bufferInitSegment(e,t,n,r){if(this.state!==$.PARSING)return;this.audioOnly=!!t.audio&&!t.video,this.altAudio&&!this.audioOnly&&(delete t.audio,t.audiovideo&&this.logMuxedErr(n));let{audio:i,video:a,audiovideo:o}=t;if(i){let n=e.audioCodec,r=si(i.codec,n);if(r===`mp4a`&&(r=`mp4a.40.5`),this.audioCodecSwitch){r&&=r.indexOf(`mp4a.40.5`)===-1?`mp4a.40.5`:`mp4a.40.2`;let e=i.metadata;e&&`channelCount`in e&&(e.channelCount||1)!==1&&!Gr()&&(r=`mp4a.40.5`)}r&&r.indexOf(`mp4a.40.5`)!==-1&&Jr()&&i.container!==`audio/mpeg`&&(r=`mp4a.40.2`,this.log(`Android: force audio codec to ${r}`)),n&&n!==r&&this.log(`Swapping manifest audio codec "${n}" for "${r}"`),i.levelCodec=r,i.id=z.MAIN,this.log(`Init audio buffer, container:${i.container}, codecs[selected/level/parsed]=[${r||``}/${n||``}/${i.codec}]`),delete t.audiovideo}if(a){a.levelCodec=e.videoCodec,a.id=z.MAIN;let n=a.codec;if(n?.length===4)switch(n){case`hvc1`:case`hev1`:a.codec=`hvc1.1.6.L120.90`;break;case`av01`:a.codec=`av01.0.04M.08`;break;case`avc1`:a.codec=`avc1.42e01e`}this.log(`Init video buffer, container:${a.container}, codecs[level/parsed]=[${e.videoCodec||``}/${n}]${a.codec===n?``:` parsed-corrected=`+a.codec}${a.supplemental?` supplemental=`+a.supplemental:``}`),delete t.audiovideo}o&&(this.iframesOnly&&this.logMuxedErr(n),this.log(`Init audiovideo buffer, container:${o.container}, codecs[level/parsed]=[${e.codecs}/${o.codec}]`),delete t.video,delete t.audio);let s=Object.keys(t);if(s.length){if(this.hls.trigger(L.BUFFER_CODECS,t),!this.hls)return;s.forEach(e=>{let i=t[e].initSegment;i!=null&&i.byteLength&&this.hls.trigger(L.BUFFER_APPENDING,{type:e,data:i,frag:n,part:null,chunkMeta:r,parent:n.type})})}this.tickImmediate()}getMainFwdBufferInfo(){let e=this.getBufferOutput();return this.getFwdBufferInfo(e,z.MAIN)}get maxBufferLength(){let{levels:e,level:t}=this,n=e?.[t];return n?this.getMaxBufferLength(n.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=$.IDLE}get nextLevel(){let e=this.nextBufferedFrag;return e?e.level:-1}get currentFrag(){if(this.fragPlaying)return this.fragPlaying;let e=this.media?.currentTime||this.lastCurrentTime;return P(e)?this.getAppendedFrag(e):null}get currentProgramDateTime(){let e=this.media?.currentTime||this.lastCurrentTime;if(P(e)){let t=this.getLevelDetails(),n=this.currentFrag||(t?na(null,t.fragments,e):null);if(n){let t=n.programDateTime;if(t!==null){let r=t+(e-n.start)*1e3;return new Date(r)}}}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}},rp=class extends np{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 e=this.media;e!=null&&e.seeking&&(e.currentTime=e.currentTime)},this.onMediaSeeking=()=>{}}setInitPts(e){this.initPTS=e.slice()}loadMediaAt(e,t){if(!this.hls)return;let{seekOnAppend:n}=t,r=e+this.timelineOffset;switch(this.nextLoadPosition=this.lastCurrentTime=r,this.startPosition=e,this.state){case $.STOPPED:case $.ENDED:case $.ERROR:this.state=$.IDLE}this.state===$.IDLE?(this.hls.resumeBuffering(),this.tick(),this.currentOp=[r,t]):this.nextOp=[r,t],this.hls.off(L.BUFFERED_TO_END,this.onBufferedToEnd);let i=this.media;n&&i&&this.seekTo(r)&&(this.currentOp=[r,t],this.nextOp=void 0,this.flushPipeline(r,!0))}seekTo(e){let t=this.media;if(t){let n=this.getLevelDetails()?.edge,r=n===void 0?t.duration:n;if(e>=r&&(e=r-.01),J.bufferInfo(t,e,0).len>0&&this.getBufferedAt(e))return t.currentTime=e,!0}return!1}getBufferedAt(e){return this.fragmentTracker.getBufferedFrag(e,z.MAIN)}cacheSet(e,t){if(!this.hls)return;e.data=t;let n=this.cached;n.push(e),this.cachedSize+=t.buffer.byteLength;let r=this.hls.config.iframeCacheLimit;for(;this.cachedSize>r&&n.length>1;){let e=n.shift();if(e.data)this.cachedSize-=e.data.byteLength,e.data=void 0;else{this.cached=n.filter(e=>!!e.data),this.cachedSize=n.reduce((e,{data:t})=>t?t.buffer.byteLength:0,0);break}}}onHandlerDestroying(){this.cached.length=0,this.cachedSize=0,super.onHandlerDestroying()}_handleFragmentLoadProgress(e){let t=e.frag,{part:n,payload:r}=e;this.cacheFragmentData&&!n&&r!=null&&r.byteLength&&!t.data&&Tt(t)&&this.cacheSet(t,new Uint8Array(r.slice(0))),super._handleFragmentLoadProgress(e)}loadFragment(e,t,n){let r=this.fragmentTracker.getState(e);if((r===Z.NOT_LOADED||r===Z.PARTIAL)&&this.canReplayCached(e)){this.replayCachedFragment(e);return}super.loadFragment(e,t,n)}canReplayCached(e){var t;if(!this.cacheFragmentData||!((t=e.data)!=null&&t.byteLength))return!1;let n=e.decryptdata;return n?.keyFormat!==`identity`||!!n.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 n=e.stats=new Ct;n.loading.start=n.loading.first=n.loading.end=self.performance.now(),n.loaded=n.total=t.byteLength,n.chunkCount=1,this.state=$.FRAG_LOADING;let r={frag:e,part:null,payload:t,networkDetails:null};this._handleFragmentLoadProgress(r),this.hls.trigger(L.FRAG_LOADED,r),this._handleFragmentLoadComplete(r)}fragBufferedComplete(e,t){super.fragBufferedComplete(e,t);let{currentOp:n,nextOp:r}=this;this.currentOp=this.nextOp=void 0,this.state=$.STOPPED,n!=null&&n[1].seekOnAppend&&(this.flushPipeline(n[0],!r),this.seekTo(n[0])||this.log(`Could not seek to ${n[0]} after fragment buffered (superseded or flushed) buffer: ${this.media?_a(J.getBuffered(this.media)):`none`}`)),r&&this.loadMediaAt.apply(this,r)}flushPipeline(e,t){if(t){let t=this.media;if(t){let n=J.bufferInfo(t,e,0),r=n.len?n.nextStart:0;r&&(this.fragmentTracker.removeFragmentsInRange(r,1/0,z.MAIN),this.flushMainBuffer(r,1/0))}this.hls.once(L.BUFFERED_TO_END,this.onBufferedToEnd)}this.hls.trigger(L.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,n){let r=this.initDetails;return this.initDetails=null,super.alignPlaylists(e,t,n||r||void 0)}getMainFwdBufferInfo(){let e=this.playhead,t=this.getBufferedAt(e);if(t){let n=t.duration;return{len:n,start:e,end:e+n,bufferedIndex:-1}}return{len:0,start:e,end:e,bufferedIndex:-1}}_streamEnded(){let e=this.playhead,t=this.fragmentTracker.getBufferedFrag(e,z.MAIN);return!!(t!=null&&t.endList)}},ip=class extends rp{constructor(...e){super(...e),this._img=void 0,this.queued=void 0,this.cacheFragmentData=!1}get image(){return this._img}set image(e){let t=this._img?.src;t&&self.URL.revokeObjectURL(t),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 $.STOPPED:case $.ENDED:case $.ERROR:this.state=$.IDLE}if(this.state===$.IDLE){if(this.hls.resumeBuffering(),this.media||={},this.tick(),this.state===$.IDLE){let t=this.getBufferedAt(e);t&&(this.fragCurrent=t,this.updateImage(t,null))}}else{let n=this.fragCurrent;(!n||e>=n.start&&e<n.end)&&(this.queued=[t])}}updateImage(e,t,n){let r=e.data;r||this.fragmentTracker.removeFragment(e);let i=this._img;if(i&&r){let a=self.performance.now(),o=t?t.stats:e.stats;o.buffering.start=e.stats.buffering.start=a,i.onload=()=>{if(!this.hls)return;let r=this.hls.levels[e.level];r!=null&&r.fragmentError&&(r.fragmentError=0,e.stats.retry=0);let i=self.performance.now(),a=t?t.stats:e.stats;a.buffering.end=e.stats.buffering.end=i,this.hls.trigger(L.FRAG_BUFFERED,{frag:e,part:t,stats:a,id:e.type,chunkMeta:n})},i.onerror=()=>{this.handleError(`Image decode error`,e,t,n)};let s=i.src;s&&self.URL.revokeObjectURL(s);let c=new Blob([r],{type:`image/jpeg`});i.src=self.URL.createObjectURL(c)}else this.state=$.STOPPED,this.processQueued()}processQueued(){let e=this.queued;this.queued=void 0,e&&this.loadMediaAt.apply(this,e)}handleError(e,t,n,r){if(!this.hls)return;let i=Error(e);this.hls.trigger(L.ERROR,{type:F.MEDIA_ERROR,details:I.FRAG_PARSING_ERROR,chunkMeta:r,frag:t,part:n,fatal:!1,error:i,err:i})}_bufferInitSegment(){}bufferFragmentData(e,t,n,r){super.bufferFragmentData(e,t,n,r,!0);let i=K(new Uint8Array(e.data1),[`mdat`]);if(i.length===0){this.handleError(`Could not find I-Frame mdat`,t,n,r);return}let a=t;this.cacheSet(a,i[0]),this.updateImage(a,n,r)}fragBufferedComplete(e,t){this.fragmentTracker.fragBuffered(e,!0),super.fragBufferedComplete(e,t),this.processQueued()}checkFragPlaying(){let e=this.fragPrevious?.start;if(e!==void 0){let t=this.getAppendedFrag(e);if(t&&!Et(t,this.fragPlaying))return this.fragPlaying=t,!0}return!1}getMainFwdBufferInfo(){return{len:0,start:this.playhead,end:this.playhead,bufferedIndex:-1}}},ap=10,op=`Image I-Frame player does not accept HTMLMediaElements`,sp={seekOnAppend:!0},cp,lp,up=class extends Xt{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,cp||=dp(t),lp||=fp(cp),this.hls=e,this.iframeInstances=[],this.registerListeners()}registerListeners(){let e=this.hls;e&&(e.on(L.MANIFEST_LOADING,this.clearAsset,this),e.on(L.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(L.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(L.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(L.FRAG_BUFFERED,this.onFragBuffered,this),e.on(L.DESTROYING,this.onDestroying,this))}unregisterListeners(){let e=this.hls;e&&(e.off(L.MANIFEST_LOADING,this.clearAsset,this),e.off(L.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(L.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(L.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(L.FRAG_BUFFERED,this.onFragBuffered,this),e.off(L.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}){let n=this.hls?.pathwayPriority;t.length&&n&&this.iframeInstances.forEach(e=>{e.pathwayPriority=n})}onInitPtsFound(e,{id:t,timestampOffsets:n}){t===z.MAIN&&(this.initPTS=n)}onFragBuffered(e,t){let n=this.hls;n&&n.hasEnoughToStart&&(n.mainForwardBufferInfo?.len||0)>ap&&this.iframeInstances.forEach(e=>{if(!e.loadingEnabled){var t;e.startLoad(((t=this.hls)==null||(t=t.media)==null?void 0:t.currentTime)||0)}})}createIFramePlayer(e){return this.createInstance(cp,this.hls?.iframeVariants,e)}createImageIFramePlayer(e){let t=this.hls?.iframeVariants.filter(e=>e.imageCodec);return this.createInstance(lp,t,e,`image-`)}createInstance(e,t,n,r){let{hls:i}=this;if(!i)return null;let{url:a,userConfig:o,latestLevelDetails:s,loadLevelObj:c,loadLevel:l,bandwidthEstimate:u,sessionId:d}=i,{stats:f,variableList:p}=this;if(!(t!=null&&t.length)||!f||!a)return null;let m=`${r||``}iframe-player-${this.instanceCounter++}`,h=i.levels,g=c||h[l],_=Zi(g,o.videoPreference),v=g?.pathwayId||`.`,y=new e(H(H({},o),{},{loggerId:m,primarySessionId:d,videoPreference:_,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},n),a,this.initPTS,s);return this.iframeInstances=this.iframeInstances.filter(e=>!e.url),this.iframeInstances.push(y),y.trigger(L.MANIFEST_LOADED,{levels:t,contentSteering:{uri:``,pathwayId:v},sessionKeys:null,audioTracks:[],iframeVariants:[],sessionData:null,startTimeOffset:null,stats:f,networkDetails:null,url:a,variableList:p}),y}};function dp(e){return class extends e{constructor(e,t,n,r){e.streamController||=rp,super(e),this._url=t,this.streamController.setInitPts(n),this.streamController.initDetails=r}loadSource(){}loadMediaAt(e,t=sp){if(e<0)return;let n=H(H({},sp),t);this.loadingEnabled||this.startLoad(e),this.streamController.loadMediaAt(e,n)}}}function fp(e){return class extends e{constructor(e,t,n,r){e.cmcdController=void 0,e.emeController=void 0,e.streamController||=ip,e.capLevelController=void 0,e.bufferController=void 0,super(e,t,n,r)}attachImage(e){this.streamController.image=e}detachImage(){this.streamController.image=void 0}loadSource(){}attachMedia(){throw Error(op)}detachMedia(){}recoverMediaError(){}transferMedia(){return null}loadMediaAt(e){if(e<0)return null;this.loadingEnabled||this.startLoad(e),this.streamController.loadMediaAt(e)}}}var pp=.025,mp=function(e){return e[e.Point=0]=`Point`,e[e.Range=1]=`Range`,e}({});function hp(e,t,n){return`${e.identifier}-${n+1}-${uf(t)}`}var gp=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){if(e>0&&e>=this.assetList.length)return!0;let t=this.playoutLimit;return e<=0||isNaN(t)?!1:t===0||(this.assetList[e]?.startOffset||0)>t}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 vp(t,e)?_p(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;return t-_p(t,e)<.1}return!1}get resumptionOffset(){let e=this.resumeOffset,t=P(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 vp(t,e)?_p(e,t):e}return e}get appendInPlace(){return this.appendInPlaceStarted?!0:!this.appendInPlaceDisabled&&!!(!this.cue.once&&!this.cue.pre&&this.startIsAligned&&(isNaN(this.playoutLimit)&&isNaN(this.resumeOffset)||this.resumeOffset&&this.duration&&Math.abs(this.resumeOffset-this.duration)<pp))}set appendInPlace(e){if(this.appendInPlaceStarted){this.resetOnResume=!e;return}this.appendInPlaceDisabled=!e}get timelineStart(){return this._timelineStart===null?this.startTime:this._timelineStart}set timelineStart(e){this._timelineStart=e}get duration(){let e=this.playoutLimit,t;return t=this._duration===null?this.dateRange.duration?this.dateRange.duration:this.dateRange.plannedDuration||0:this._duration,!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`?mp.Range:mp.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 xp(this)}};function _p(e,t){return e-t.start<t.duration/2&&!(Math.abs(e-(t.start+t.duration))<pp)?t.start:t.start+t.duration}function vp(e,t){return t>e.start-pp&&t<e.start+e.duration+pp}function yp(e,t,n){let r=new self.URL(e,n);return r.protocol!==`data:`&&wi(r,`_HLS_primary_id`,t),r}function bp(e,t){for(;(n=e.assetList[++t])!=null&&n.error;)var n;return t}function xp(e){return`["${e.identifier}" ${e.cue.pre?`<pre>`:e.cue.post?`<post>`:``}${e.timelineStart.toFixed(2)}-${e.resumeTime.toFixed(2)}]`}function Sp(e){let t=e.timelineStart,n=e.duration||0;return`["${e.identifier}" ${t.toFixed(2)}-${(t+n).toFixed(2)}]`}var Cp=class{constructor(e,t,n,r){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(L.PLAYOUT_LIMIT_REACHED,{})};let i=this.hls=new e(t);this.interstitial=n,this.assetItem=r;let a=()=>{this.hasDetails=!0};i.once(L.LEVEL_LOADED,a),i.once(L.AUDIO_TRACK_LOADED,a),i.once(L.SUBTITLE_TRACK_LOADED,a),i.on(L.MEDIA_ATTACHING,(e,{media:t})=>{this.removeMediaListeners(),this.mediaAttached=t,this.interstitial.playoutLimit&&(t.addEventListener(`timeupdate`,this.checkPlayout),this.appendInPlace&&i.on(L.BUFFER_APPENDED,()=>{let e=this.bufferedEnd;this.reachedPlayout(e)&&(this._bufferedEosTime=e,i.trigger(L.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=yp(t,e.config.primarySessionId||``).href}catch{}e.loadSource(t)}}}bufferedInPlaceToEnd(e,t){var n;if(!this.appendInPlace)return!1;if((n=this.hls)!=null&&n.bufferedToEnd)return!0;if(!e)return!1;let r=Math.min(this._bufferedEosTime||1/0,this.duration),i=this.timelineOffset+(t||0),a=J.bufferInfo(e,i,.02);return this.getAssetTime(a.end)>=r-.02}reachedPlayout(e){let t=this.interstitial.playoutLimit;return this.startOffset+e>=t}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(){return this.hls?.media||null}get bufferedEnd(){let e=this.media||this.mediaAttached;if(!e)return this._bufferedEosTime?this._bufferedEosTime:this.currentTime;let t=J.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 n=t-this.startOffset;if(n>0&&n<e)return n}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(){return this.hls?.config.timelineOffset||0}set timelineOffset(e){let t=this.timelineOffset;if(e!==t){let n=e-t;if(Math.abs(n)>1/9e4&&this.hls){if(this.hasDetails)throw Error(`Cannot set timelineOffset after playlists are loaded`);this.hls.config.timelineOffset=e}}}getAssetTime(e){let t=this.timelineOffset,n=this.duration;return Math.min(Math.max(0,e-t),n)}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(){return this.bufferSnapShot(),this.hls?.transferMedia()||null}resetDetails(){let e=this.hls;if(e&&this.hasDetails){e.stopLoad();let t=e=>delete e.details;e.levels.forEach(t),e.allAudioTracks.forEach(t),e.allSubtitleTracks.forEach(t),this.hasDetails=!1}}on(e,t,n){var r;(r=this.hls)==null||r.on(e,t)}once(e,t,n){var r;(r=this.hls)==null||r.once(e,t)}off(e,t,n){var r;(r=this.hls)==null||r.off(e,t)}toString(){return`HlsAssetPlayer: ${Sp(this.assetItem)} ${this.hls?.sessionId} ${this.appendInPlace?`append-in-place`:``}`}},wp=.033,Tp=class extends Xt{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((n,r)=>e<=r.startOffset&&t>r.startOffset?(delete r.error,n+1):n,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 n=-1;e.nextEvent?n=this.findEventIndex(e.nextEvent.identifier)-1:e.previousEvent&&(n=this.findEventIndex(e.previousEvent.identifier)+1);let r=this.items;if(r)for(r[n]||(t===void 0&&(t=e.start),n=this.findItemIndexAtTime(t));n>=0&&(i=r[n])!=null&&i.event;){var i;n--}return n}findItemIndexAtTime(e,t){let n=this.items;if(n)for(let r=0;r<n.length;r++){let i=n[r];t&&t!==`primary`&&(i=i[t]);let a=i.start,o=n[r].event,s=o!=null&&o.cue.pre?o.duration:i.end;if(e===a||e>a&&e<s)return r}return-1}findJumpRestrictedIndex(e,t){let n=this.items;if(n)for(let r=e;r<=t&&n[r];r++){let e=n[r].event;if(e!=null&&e.restrictions.jump&&!e.appendInPlace)return r}return-1}findEventIndex(e){let t=this.items;if(t){for(let n=t.length;n--;)if(t[n].event?.identifier===e)return n}return-1}findAssetIndex(e,t){let n=e.assetList,r=n.length;if(r>1)for(let e=0;e<r;e++){let i=n[e];if(!i.error){let n=i.timelineStart;if(t===n||t>n&&(t<n+(i.duration||0)||e===r-1))return e}}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 e=t.assetList,n=e[e.length-1];if(n)return n.identifier}return null}parseInterstitialDateRanges(e,t,n=0){let r=e.main.details,{dateRanges:i}=r,a=this.events,o=this.parseDateRanges(i,{url:r.url},t),s=Object.keys(i),c=a?a.filter(e=>s.indexOf(e.identifier)===-1):[];o.length&&o.sort((e,t)=>{let n=e.cue.pre,r=e.cue.post,i=t.cue.pre,a=t.cue.post;if(n&&!i)return-1;if(i&&!n||r&&!a)return 1;if(a&&!r)return-1;if(!n&&!i&&!r&&!a){let n=e.startTime,r=t.startTime;if(n!==r)return n-r}return e.dateRange.tagOrder-t.dateRange.tagOrder}),this.events=o,c.forEach(e=>{this.removeEvent(e)}),this.updateSchedule(e,c,n)}updateSchedule(e,t=[],n=0,r=!1){let i=this.events||[];if(i.length||t.length||this.length<2){let a=this.items,o=this.parseSchedule(i,e,n);(r||t.length||a?.length!==o.length||o.some((e,t)=>Math.abs(e.playout.start-a[t].playout.start)>.005||Math.abs(e.playout.end-a[t].playout.end)>.005))&&(this.items=o,this.onScheduleUpdate(t,a))}}parseDateRanges(e,t,n){let r=[],i=Object.keys(e);for(let a=0;a<i.length;a++){let o=i[a],s=e[o];if(s.isInterstitial){let e=this.eventMap[o];e?e.setDateRange(s):(e=new gp(s,t),this.eventMap[o]=e,n===!1&&(e.appendInPlace=n)),r.push(e)}}return r}parseSchedule(e,t,n=0){let r=[],i=t.main.details,a=i.live?1/0:i.edge,o=0;if(e=e.filter(e=>!e.error&&!(e.cue.once&&e.hasPlayed)),e.length){this.resolveOffsets(e,t);let s=0,c=0;if(e.forEach((t,l)=>{let u=t.cue.pre,d=t.cue.post,f=e[l-1]||null,p=t.appendInPlace,m=d?a:t.startOffset,h=t.duration,g=t.timelineOccupancy===mp.Range?h:0,_=u&&i.live?n+(t.resumeOffset||0):0,v=_||t.resumptionOffset,y=f?.startTime===m,b=m+t.cumulativeDuration,x=p?b+h:m+v;if(u||!d&&m<=0){let e=c;c+=g,t.timelineStart=b;let n=o;o+=h,r.push({event:t,start:b,end:x,playout:{start:n,end:o},integrated:{start:e,end:c}})}else if(m<=a){if(!y){let n=m-s;if(n>wp){let i=s,a=c;c+=n;let u=o;o+=n;let d={previousEvent:e[l-1]||null,nextEvent:t,start:i,end:i+n,playout:{start:u,end:o},integrated:{start:a,end:c}};r.push(d)}else n>0&&f&&(f.cumulativeDuration+=n,r[r.length-1].end=m)}d&&(x=b),t.timelineStart=b;let n=c;c+=g;let i=o;o+=h,r.push({event:t,start:b,end:x,playout:{start:i,end:o},integrated:{start:n,end:c}})}else return;let S=_||t.resumeTime;s=d||S>a?a:!u&&x&&t.appendInPlaceStarted&&S-x>wp?x:S}),s<a){let e=s,t=c,n=a-s;c+=n;let i=o;o+=n,r.push({previousEvent:r[r.length-1]?.event||null,nextEvent:null,start:s,end:e+n,playout:{start:i,end:o},integrated:{start:t,end:c}})}this.setDurations(a,o,c)}else r.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 r}setDurations(e,t,n){this.durations={primary:e,playout:t,integrated:n}}resolveOffsets(e,t){let n=t.main.details,r=n.live?1/0:n.edge,i=0,a=-1;e.forEach((o,s)=>{let c=o.cue.pre,l=o.cue.post,u=c?0:l?r:o.startTime;this.updateAssetDurations(o),a===u?o.cumulativeDuration=i:(i=0,a=u),!l&&o.snapOptions.in&&(o.resumeAnchor=na(null,n.fragments,o.startOffset+o.resumptionOffset,0,0)||void 0),o.appendInPlace&&!o.appendInPlaceStarted&&(this.primaryCanResumeInPlaceAt(o,t)||(o.appendInPlace=!1)),!o.appendInPlace&&s+1<e.length&&e[s+1].startTime-e[s].resumeTime<wp&&(e[s+1].appendInPlace=!1,e[s+1].appendInPlace&&this.warn(`Could not change append strategy for abutting event ${o}`));let d=P(o.resumeOffset)?o.resumeOffset:o.duration;i+=d})}primaryCanResumeInPlaceAt(e,t){let n=e.resumeTime,r=e.startTime+e.resumptionOffset;return Math.abs(n-r)>pp?(this.log(`"${e.identifier}" resumption ${n} not aligned with estimated timeline end ${r}`),!1):!Object.keys(t).some(r=>{let i=t[r].details,a=i.edge;if(n>=a)return this.log(`"${e.identifier}" resumption ${n} past ${r} playlist end ${a}`),!1;let o=na(null,i.fragments,n);if(!o)return this.log(`"${e.identifier}" resumption ${n} does not align with any fragments in ${r} playlist (${i.fragStart}-${i.fragmentEnd})`),!0;let s=r===`audio`?.175:0;return Math.abs(o.start-n)<pp+s||Math.abs(o.end-n)<pp+s?!1:(this.log(`"${e.identifier}" resumption ${n} not aligned with ${r} fragment bounds (${o.start}-${o.end} sn: ${o.sn} cc: ${o.cc})`),!0)})}updateAssetDurations(e){if(!e.assetListLoaded)return;let t=e.timelineStart,n=0,r=!1,i=!1;for(let a=0;a<e.assetList.length;a++){let o=e.assetList[a],s=t+n;o.startOffset=n,o.timelineStart=s,r||=o.duration===null,i||=!!o.error;let c=o.error?0:o.duration||0;n+=c}e.duration=r&&!i?Math.max(n,e.duration):n}removeEvent(e){e.reset(),delete this.eventMap[e.identifier]}};function Ep(e){return`[${e.event?`"`+e.event.identifier+`"`:`primary`}: ${e.start.toFixed(2)}-${e.end.toFixed(2)}]`}var Dp=class{constructor(e){this.hls=void 0,this.hls=e}destroy(){this.hls=null}loadAssetList(e,t){let n=e.assetListUrl,r;try{r=yp(n,this.hls.sessionId,e.baseUrl)}catch(t){let r=this.assignAssetListError(e,I.ASSET_LIST_LOAD_ERROR,t,n);this.hls.trigger(L.ERROR,r);return}t&&r.protocol!==`data:`&&wi(r,`_HLS_start_offset`,``+t);let i=this.hls.config,a=i.loader,o=new a(i),s={type:R.INTERSTITIAL_ASSET_LIST,responseType:`json`,url:r.href},c=i.interstitialAssetListLoadPolicy.default,l={loadPolicy:c,timeout:c.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0};return o.load(s,l,{onSuccess:(t,n,r,i)=>{let a=t.data,o=a?.ASSETS;if(!Array.isArray(o)){let t=this.assignAssetListError(e,I.ASSET_LIST_PARSING_ERROR,Error(`Invalid interstitial asset list`),r.url,n,i);this.hls.trigger(L.ERROR,t);return}e.assetListResponse=a,this.hls.trigger(L.ASSET_LIST_LOADED,{event:e,assetListResponse:a,networkDetails:i})},onError:(t,n,r,i)=>{let a=this.assignAssetListError(e,I.ASSET_LIST_LOAD_ERROR,Error(`Error loading X-ASSET-LIST: HTTP status ${t.code} ${t.text} (${n.url})`),n.url,i,r);this.hls.trigger(L.ERROR,a)},onTimeout:(t,n,r)=>{let i=this.assignAssetListError(e,I.ASSET_LIST_LOAD_TIMEOUT,Error(`Timeout loading X-ASSET-LIST (${n.url})`),n.url,t,r);this.hls.trigger(L.ERROR,i)}}),this.hls.trigger(L.ASSET_LIST_LOADING,{event:e}),o}assignAssetListError(e,t,n,r,i,a){return e.error=n,{type:F.NETWORK_ERROR,details:t,fatal:!1,interstitial:e,url:r,error:n,networkDetails:a,stats:i}}};function Op(e){var t;e==null||(t=e.play())==null||t.catch(()=>{})}function kp(e,t){return`[${e}] Advancing timeline position to ${t}`}var Ap=class extends Xt{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 e=this.currentTime;if(e===void 0||this.playbackDisabled||!this.schedule)return;let t=e-this.timelinePos;if(Math.abs(t)<1/7056e5)return;let n=t<=-.01;this.timelinePos===-1&&!this.effectivePlayingItem&&this.checkStart(),this.timelinePos=e,this.bufferedPos=e;let r=this.playingItem;if(!r){this.checkBuffer();return}if(n&&this.schedule.resetErrorsInRange(e,e-t)&&this.updateSchedule(!0),this.checkBuffer(),n&&e<r.start||e>=r.end){var i;let t=this.findItemIndex(r),a=this.schedule.findItemIndexAtTime(e);if(a===-1&&(a=t+(n?-1:1),this.log(`seeked ${n?`back `:``}to position not covered by schedule ${e} (resolving from ${t} to ${a})`)),!this.isInterstitial(r)&&(i=this.media)!=null&&i.paused&&(this.shouldPlay=!1),!n&&a>t){let e=this.schedule.findJumpRestrictedIndex(t+1,a);if(e>t){this.setSchedulePosition(e);return}}this.setSchedulePosition(a);return}let a=this.playingAsset;if(!a){if(this.playingLastItem&&this.isInterstitial(r)){let t=r.event.assetList[0];t&&(this.endedItem=this.playingItem,this.playingItem=null,this.setScheduleToAssetAtTime(e,t))}return}let o=a.timelineStart,s=a.duration||0;if(n&&e<o||e>=o+s){var c;(c=r.event)!=null&&c.appendInPlace&&(this.clearAssetPlayers(r.event,r),this.flushFrontBuffer(e)),this.setScheduleToAssetAtTime(e,a)}},this.onTimeupdate=()=>{let e=this.currentTime;if(e===void 0||this.playbackDisabled)return;if(this.timelinePos===-1&&!this.effectivePlayingItem&&this.checkStart(),e>this.timelinePos)this.timelinePos=e,e>this.bufferedPos&&this.checkBuffer();else return;let t=this.playingItem;if(!t||this.playingLastItem)return;if(e>=t.end){this.timelinePos=t.end;let e=this.findItemIndex(t);this.setSchedulePosition(e+1)}let n=this.playingAsset;n&&e>=n.timelineStart+(n.duration||0)&&this.setScheduleToAssetAtTime(e,n)},this.onScheduleUpdate=(e,t)=>{let n=this.schedule;if(!n)return;let r=this.playingItem,i=n.events||[],a=n.items||[],o=n.durations,s=e.map(e=>e.identifier),c=!!(i.length||s.length);(c||t)&&this.log(`INTERSTITIALS_UPDATED (${i.length}): ${i}
|
|
45
|
-
Schedule: ${a.map(e=>Ep(e))} pos: ${this.timelinePos}`),s.length&&this.log(`Removed events ${s}`);let l=null,u=null;r&&(l=this.updateItem(r,this.timelinePos),this.itemsMatch(r,l)?this.playingItem=l:this.waitingItem=null);let d=this.waitingItem;d&&(this.waitingItem=this.updateItem(d),!this.waitingItem&&!r&&(this.log(`INTERSTITIAL_ENDED unresolved ${Ep(d)}`),this.hls.trigger(L.INTERSTITIAL_ENDED,{event:d.event,schedule:a.slice(0),scheduleIndex:-1})));let f=this.bufferingItem;if(f&&(u=this.updateItem(f,this.bufferedPos),this.itemsMatch(f,u)?this.bufferingItem=u:f.event&&(this.bufferingItem=this.playingItem,this.clearInterstitial(f.event,null))),e.forEach(e=>{e.assetList.forEach(e=>{this.clearAssetPlayer(e.identifier,null)})}),this.playerQueue.forEach(e=>{if(e.interstitial.appendInPlace){let t=e.assetItem.timelineStart,n=e.timelineOffset-t;if(n)try{e.timelineOffset=t}catch(r){Math.abs(n)>pp&&this.warn(`${r} ("${e.assetId}" ${e.timelineOffset}->${t})`)}}}),c||t){if(this.hls.trigger(L.INTERSTITIALS_UPDATED,{events:i.slice(0),schedule:a.slice(0),durations:o,removedIds:s}),this.isInterstitial(r)&&s.indexOf(r.event.identifier)>-1){this.warn(`Interstitial "${r.event.identifier}" removed while playing`),this.primaryFallback(r.event);return}r&&this.trimInPlace(l,r),f&&u!==l&&this.trimInPlace(u,f),this.checkBuffer()}},this.hls=e,this.HlsPlayerClass=t,this.assetListLoader=new Dp(e),this.schedule=new Tp(this.onScheduleUpdate,e.logger),this.registerListeners()}registerListeners(){let e=this.hls;e&&(e.on(L.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(L.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(L.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(L.MANIFEST_LOADING,this.onManifestLoading,this),e.on(L.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(L.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(L.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),e.on(L.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.on(L.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),e.on(L.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),e.on(L.ASSET_LIST_LOADED,this.onAssetListLoaded,this),e.on(L.BUFFER_APPENDED,this.onBufferAppended,this),e.on(L.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(L.BUFFERED_TO_END,this.onBufferedToEnd,this),e.on(L.MEDIA_ENDED,this.onMediaEnded,this),e.on(L.ERROR,this.onError,this),e.on(L.DESTROYING,this.onDestroying,this))}unregisterListeners(){let e=this.hls;e&&(e.off(L.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(L.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(L.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(L.MANIFEST_LOADING,this.onManifestLoading,this),e.off(L.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(L.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(L.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),e.off(L.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.off(L.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),e.off(L.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),e.off(L.ASSET_LIST_LOADED,this.onAssetListLoaded,this),e.off(L.BUFFER_CODECS,this.onBufferCodecs,this),e.off(L.BUFFER_APPENDED,this.onBufferAppended,this),e.off(L.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(L.BUFFERED_TO_END,this.onBufferedToEnd,this),e.off(L.MEDIA_ENDED,this.onMediaEnded,this),e.off(L.ERROR,this.onError,this),e.off(L.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){X(e,`play`,this.onPlay),X(e,`pause`,this.onPause),X(e,`seeking`,this.onSeeking),X(e,`timeupdate`,this.onTimeupdate)}onMediaAttaching(e,t){let n=this.media=t.media;Y(n,`seeking`,this.onSeeking),Y(n,`timeupdate`,this.onTimeupdate),Y(n,`play`,this.onPlay),Y(n,`pause`,this.onPause)}onMediaAttached(e,t){let n=this.effectivePlayingItem,r=this.detachedData;if(this.detachedData=null,n===null)this.checkStart();else if(!r){this.clearScheduleState();let e=this.findItemIndex(n);this.setSchedulePosition(e)}}clearScheduleState(){this.log(`clear schedule state`),this.playingItem=this.bufferingItem=this.waitingItem=this.endedItem=this.playingAsset=this.endedAsset=this.bufferingAsset=null}onMediaDetaching(e,t){let n=!!t.transferMedia,r=this.media;if(this.media=null,!n&&(r&&this.removeMediaListeners(r),this.detachedData)){let e=this.getBufferingPlayer();e&&(this.log(`Removing schedule state for detachedData and ${e}`),this.playingAsset=this.endedAsset=this.bufferingAsset=this.bufferingItem=this.waitingItem=this.detachedData=null,e.detachMedia()),this.shouldPlay=!1}}get interstitialsManager(){if(!this.hls)return null;if(this.manager)return this.manager;let e=this,t=()=>e.bufferingItem||e.waitingItem,n=t=>t&&e.getAssetPlayer(t.identifier),r=(t,r,i,o,s)=>{if(t){let c=t[r].start,l=t.event;if(l){if(r===`playout`||l.timelineOccupancy!==mp.Point){let e=n(i);e?.interstitial===l&&(c+=e.assetItem.startOffset+e[s])}}else{let n=o===`bufferedPos`?a():e[o];c+=n-t.start}return c}return 0},i=(t,n)=>{var r;if(t!==0&&n!==`primary`&&(r=e.schedule)!=null&&r.length){let r=e.schedule.findItemIndexAtTime(t),i=e.schedule.items?.[r];if(i)return t+(i[n].start-i.start)}return t},a=()=>{let t=e.bufferedPos;return t===Number.MAX_VALUE?o(`primary`):Math.max(t,0)},o=t=>{var n;return(n=e.primaryDetails)!=null&&n.live?e.primaryDetails.edge:e.schedule?.durations[t]||0},s=(t,i)=>{var a;let o=e.effectivePlayingItem;if(o!=null&&(a=o.event)!=null&&a.restrictions.skip||!e.schedule)return;e.log(`seek to ${t} "${i}"`);let s=e.effectivePlayingItem,c=e.schedule.findItemIndexAtTime(t,i),l=e.schedule.items?.[c],u=e.getBufferingPlayer(),d=u?.interstitial?.appendInPlace,f=s&&e.itemsMatch(s,l);if(s&&(d||f)){let a=n(e.playingAsset),o=a?.media||e.primaryMedia;if(o){let n=i===`primary`?o.currentTime:r(s,i,e.playingAsset,`timelinePos`,`currentTime`),c=t-n,l=(d?n:o.currentTime)+c;if(l>=0&&(!a||d||l<=a.duration)){o.currentTime=l;return}}}if(l){let n=t;if(i!==`primary`){let e=t-l[i].start;n=l.start+e}let r=!e.isInterstitial(l);if((!e.isInterstitial(s)||s.event.appendInPlace)&&(r||l.event.appendInPlace)){let t=e.media||(d?u?.media:null);t&&(t.currentTime=n)}else if(s){let a=e.findItemIndex(s);if(c>a){let t=e.schedule.findJumpRestrictedIndex(a+1,c);if(t>a){e.setSchedulePosition(t);return}}let o=0;if(r)e.timelinePos=n,e.checkBuffer();else{let e=l.event.assetList,n=t-(l[i]||l).start;for(let t=e.length;t--;){let r=e[t];if(r.duration&&n>=r.startOffset&&n<r.startOffset+r.duration){o=t;break}}}e.setSchedulePosition(c,o)}}},c=()=>{let n=e.effectivePlayingItem;if(e.isInterstitial(n))return n;let r=t();return e.isInterstitial(r)?r:null},l={get bufferedEnd(){let n=t(),i=e.bufferingItem;return i&&i===n&&(r(i,`playout`,e.bufferingAsset,`bufferedPos`,`bufferedEnd`)-i.playout.start||e.bufferingAsset?.startOffset)||0},get currentTime(){let t=c(),n=e.effectivePlayingItem;return n&&n===t?r(n,`playout`,e.effectivePlayingAsset,`timelinePos`,`currentTime`)-n.playout.start:0},set currentTime(t){let n=c(),r=e.effectivePlayingItem;r&&r===n&&s(t+r.playout.start,`playout`)},get duration(){let e=c();return e?e.playout.end-e.playout.start:0},get assetPlayers(){let t=c()?.event.assetList;return t?t.map(t=>e.getAssetPlayer(t.identifier)):[]},get playingIndex(){let t=c()?.event;return t&&e.effectivePlayingAsset?t.findAssetIndex(e.effectivePlayingAsset):-1},get scheduleItem(){return c()}};return this.manager={get events(){var t;return((t=e.schedule)==null||(t=t.events)==null?void 0:t.slice(0))||[]},get schedule(){var t;return((t=e.schedule)==null||(t=t.items)==null?void 0:t.slice(0))||[]},get interstitialPlayer(){return c()?l:null},get playerQueue(){return e.playerQueue.slice(0)},get bufferingAsset(){return e.bufferingAsset},get bufferingItem(){return t()},get bufferingIndex(){let n=t();return e.findItemIndex(n)},get playingAsset(){return e.effectivePlayingAsset},get playingItem(){return e.effectivePlayingItem},get playingIndex(){let t=e.effectivePlayingItem;return e.findItemIndex(t)},primary:{get bufferedEnd(){return a()},get currentTime(){let t=e.timelinePos;return t>0?t:0},set currentTime(e){s(e,`primary`)},get duration(){return o(`primary`)},get seekableStart(){return e.seekableStart}},integrated:{get bufferedEnd(){return r(t(),`integrated`,e.bufferingAsset,`bufferedPos`,`bufferedEnd`)},get currentTime(){return r(e.effectivePlayingItem,`integrated`,e.effectivePlayingAsset,`timelinePos`,`currentTime`)},set currentTime(e){s(e,`integrated`)},get duration(){return o(`integrated`)},get seekableStart(){return i(e.seekableStart,`integrated`)}},skip:()=>{let t=e.effectivePlayingItem,n=t?.event;if(n&&!n.restrictions.skip){let r=e.findItemIndex(t);if(n.appendInPlace){let e=t.playout.start+t.event.duration;s(e+.001,`playout`)}else e.advanceAfterAssetEnded(n,r,1/0)}}}}get effectivePlayingItem(){return this.waitingItem||this.playingItem||this.endedItem}get effectivePlayingAsset(){return this.playingAsset||this.endedAsset}get playingLastItem(){let e=this.playingItem,t=this.schedule?.items;return!this.playbackStarted||!e||!t?!1:this.findItemIndex(e)===t.length-1}get playbackStarted(){return this.effectivePlayingItem!==null}get currentTime(){var e;if(this.mediaSelection===null)return;let t=this.waitingItem||this.playingItem;if(this.isInterstitial(t)&&!t.event.appendInPlace)return;let n=this.media;!n&&(e=this.bufferingItem)!=null&&(e=e.event)!=null&&e.appendInPlace&&(n=this.primaryMedia);let r=n?.currentTime;if(r!==void 0&&P(r))return r}get primaryMedia(){return this.media||this.detachedData?.media||null}isInterstitial(e){return!!(e!=null&&e.event)}retreiveMediaSource(e,t){let n=this.getAssetPlayer(e);n&&this.transferMediaFromPlayer(n,t)}transferMediaFromPlayer(e,t){let n=e.interstitial.appendInPlace,r=e.media;if(n&&r===this.primaryMedia){if(this.bufferingAsset=null,(!t||this.isInterstitial(t)&&!t.event.appendInPlace)&&t&&r){this.detachedData={media:r};return}let n=e.transferMedia();this.log(`transfer MediaSource from ${e} ${q(n)}`),this.detachedData=n}else t&&r&&(this.shouldPlay||=!r.paused)}transferMediaTo(e,t){if(e.media===t)return;let n=null,r=this.hls,i=e!==r,a=i&&e.interstitial.appendInPlace,o=this.detachedData?.mediaSource,s;if(r.media)a&&(n=r.transferMedia(),this.detachedData=n),s=`Primary`;else{let e=this.getBufferingPlayer();e?(n=e.transferMedia(),this.detachedData=n,s=`${e}`):s=o?`detached MediaSource`:`detached media`}if(!n){if(o)n=this.detachedData,this.log(`using detachedData: MediaSource ${q(n)}`);else if(!this.detachedData||r.media===t){let e=this.playerQueue;e.length>1&&e.forEach(e=>{if(i&&e.interstitial.appendInPlace!==a){let t=e.interstitial;this.clearInterstitial(e.interstitial,null),t.appendInPlace=!1,t.appendInPlace&&this.warn(`Could not change append strategy for queued assets ${t}`)}}),this.hls.detachMedia(),this.detachedData={media:t}}}let c=n&&`mediaSource`in n&&n.mediaSource?.readyState!==`closed`;if(this.log(`${c?`transfering MediaSource`:`attaching media`} to ${i?e:`Primary`} from ${s} (media.currentTime: ${t.currentTime})`),!c&&!i){e.attachMedia(t);return}let l=c&&n?H({},n):{media:t},u=this.schedule;if(u&&i){let t=e.assetId===u.assetIdAtEnd;l.overrides={duration:u.duration,endOfStream:t||e.appendInPlace===!1}}if(!c&&a){let t=e,n=t.assetItem.timelineStart;if(n){let e=t.hls,r=Math.max(this.timelinePos-n,2**-52);e.startPosition!==r&&(this.log(`Set ${t} startPosition: ${r}`),e.config.startPosition=r,e.loadingEnabled&&e.startLoad(r))}}e.attachMedia(l)}onInterstitialCueEnter(){this.onTimeupdate()}checkStart(){let e=this.schedule,t=e?.events,n=this.hls;if(!t||this.playbackDisabled||!this.media||!n)return;this.bufferedPos===-1&&(this.bufferedPos=0);let r=this.timelinePos,i=this.effectivePlayingItem;if(r===-1){if(!n.loadingEnabled){this.log(`waiting for startLoad( <startPosition> )`);return}let r=n.startPosition;if(this.timelinePos=r,t.length===0)this.setSchedulePosition(0);else if(t[0].cue.pre){this.log(kp(`checkStart (preroll)`,r));let n=e.findEventIndex(t[0].identifier);this.setSchedulePosition(n)}else if(r>=0||!this.primaryLive){this.log(kp(`checkStart`,r));let t=this.timelinePos=r>0?r:0,n=e.findItemIndexAtTime(t);this.setSchedulePosition(n)}else n.liveSyncPosition===0?this.setSchedulePosition(0):this.log(`[checkStart] waiting for live start`)}else if(i&&!this.playingItem){this.log(kp(`checkStart (playing item)`,i.start));let t=e.findItemIndex(i);this.setSchedulePosition(t)}}advanceAssetBuffering(e,t){let n=e.event,r=bp(n,n.findAssetIndex(t));if(!n.isAssetPastPlayoutLimit(r))this.bufferedToEvent(e,r);else if(this.schedule){let t=this.getNextItemIndex(e,!0),n=this.schedule.items?.[t];n&&this.bufferedToItem(n)}}livePrerollResumption(e,t){if(e.cue.pre&&this.primaryLive&&!P(e.resumeOffset)&&this.hls){let e=this.getLiveStartPos();if(t){let t=this.getBufferingPlayer();return e+(t!=null&&t.interstitial.cue.pre?t.remaining:0)}return e}}getNextItemIndex(e,t){if(this.schedule){let n=this.livePrerollResumption(e.event,t);if(n!==void 0)return this.log(`find next item index @${n}`),this.schedule.findItemIndexAtTime(n)}return this.findItemIndex(e)+1}advanceAfterAssetEnded(e,t,n){let r=bp(e,n);if(!e.isAssetPastPlayoutLimit(r)){if(e.appendInPlace){let t=e.assetList[r];t&&this.advanceInPlace(t.timelineStart)}this.setSchedulePosition(t,r)}else if(this.schedule){let n=this.schedule.items;if(n){let r=n[t],i=r.event?this.getNextItemIndex(r):t+1;if(i>=n.length){this.setSchedulePosition(-1);return}let a=e.resumeTime;this.timelinePos<a&&(this.log(kp(`advanceAfterAssetEnded`,a)),this.timelinePos=a,e.appendInPlace&&!n[i].event&&this.hls.startLoad(a+.01),this.checkBuffer(this.bufferedPos<a)),this.setSchedulePosition(i)}}}setScheduleToAssetAtTime(e,t){let n=this.schedule;if(!n)return;let r=t.parentIdentifier,i=n.getEvent(r);if(i){let t=n.findEventIndex(r),a=n.findAssetIndex(i,e);this.advanceAfterAssetEnded(i,t,a-1)}}setSchedulePosition(e,t){let n=this.schedule?.items;if(!n||this.playbackDisabled)return;let r=e>=0?n[e]:null;this.log(`setSchedulePosition ${e}, ${t} (${r&&Ep(r)}) pos: ${this.timelinePos}`);let i=this.waitingItem||this.playingItem,a=this.playingLastItem;if(this.isInterstitial(i)){let s=i.event,c=this.playingAsset,l=c?.identifier,u=l?this.getAssetPlayer(l):null;if(u&&l&&(!this.eventItemsMatch(i,r)||t!==void 0&&l!==s.assetList[t].identifier)){var o;let t=s.findAssetIndex(c);if(this.log(`INTERSTITIAL_ASSET_ENDED ${t+1}/${s.assetList.length} ${Sp(c)}`),this.endedAsset=c,this.playingAsset=null,this.hls.trigger(L.INTERSTITIAL_ASSET_ENDED,{asset:c,assetListIndex:t,event:s,schedule:n.slice(0),scheduleIndex:e,player:u}),i!==this.playingItem){this.itemsMatch(i,this.playingItem)&&!this.playingAsset&&this.advanceAfterAssetEnded(s,this.findItemIndex(this.playingItem),t);return}this.retreiveMediaSource(l,r),u.media&&!((o=this.detachedData)!=null&&o.mediaSource)&&u.detachMedia()}if(!this.eventItemsMatch(i,r)&&(this.endedItem=i,this.playingItem=this.waitingItem=null,this.log(`INTERSTITIAL_ENDED ${s} ${Ep(i)}`),s.hasPlayed=!0,this.hls.trigger(L.INTERSTITIAL_ENDED,{event:s,schedule:n.slice(0),scheduleIndex:e}),s.cue.once&&this.hls)){this.updateSchedule();let e=this.schedule?.items;if(r&&e){let o=this.findItemIndex(r),c=this.livePrerollResumption(s);if(c!==void 0){let t=c,r=this.getNextItemIndex(i);if(!this.isInterstitial(n[r])){let e=this.primaryDetails?.fragments;if(s.snapOptions.in&&e){let i=na(null,e,c);i&&(t=Math.min(Math.max(n[r].start,_p(t,i)),n[r].end))}}if(this.log(kp(`live join (preroll)`,t)),this.timelinePos=t,r!==o&&(r||r===0)){this.advanceSchedule(r,e,void 0,i,a);return}}this.advanceSchedule(o,e,t,i,a)}return}}this.advanceSchedule(e,n,t,i,a)}advanceSchedule(e,t,n,r,i){let a=this.schedule;if(!a)return;let o=t[e]||null,s=this.primaryMedia,c=this.playerQueue;if(c.length&&c.forEach(t=>{let n=t.interstitial,r=a.findEventIndex(n.identifier);(r<e||r>e+1)&&this.clearInterstitial(n,o)}),this.isInterstitial(o)){this.timelinePos=Math.min(Math.max(this.timelinePos,o.start),o.end);let i=o.event;if(n===void 0){n=i.cue.pre?0:a.findAssetIndex(i,this.timelinePos);let t=bp(i,n-1);if(i.isAssetPastPlayoutLimit(t)||i.appendInPlace&&this.timelinePos===o.end){this.advanceAfterAssetEnded(i,e,n);return}n=t}let c=this.waitingItem;this.assetsBuffered(o,s)||this.setBufferingItem(o);let l=this.preloadAssets(i,n);if(this.eventItemsMatch(o,c||r)||(this.waitingItem=o,this.log(`INTERSTITIAL_STARTED ${Ep(o)} ${i.appendInPlace?`append in place`:``}`),i.hasPlayed=!1,this.hls.trigger(L.INTERSTITIAL_STARTED,{event:i,schedule:t.slice(0),scheduleIndex:e})),!i.assetListLoaded){this.log(`Waiting for ASSET-LIST to complete loading ${i}`);return}if(i.assetListLoader&&=(i.assetListLoader.destroy(),void 0),!s){this.log(`Waiting for attachMedia to start Interstitial ${i}`);return}this.waitingItem=this.endedItem=null,this.playingItem=o;let u=i.assetList[n];if(!u){this.advanceAfterAssetEnded(i,e,n||0);return}if(l||=this.getAssetPlayer(u.identifier),l===null||l.destroyed){let e=i.assetList.length;this.warn(`asset ${n+1}/${e} player destroyed ${i}`),l=this.createAssetPlayer(i,u,n),l.loadSource()}if(!this.eventItemsMatch(o,this.bufferingItem)&&i.appendInPlace&&this.isAssetBuffered(u))return;this.startAssetPlayer(l,n,t,e,s),this.shouldPlay&&Op(l.media)}else o?(this.resumePrimary(o,e,r),this.shouldPlay&&Op(this.hls.media)):i&&this.isInterstitial(r)&&(this.endedItem=null,this.playingItem=r,r.event.appendInPlace||this.attachPrimary(a.durations.primary,null))}get playbackDisabled(){return this.hls.config.enableInterstitialPlayback===!1}get primaryDetails(){return this.mediaSelection?.main.details}get primaryLive(){var e;return!!((e=this.primaryDetails)!=null&&e.live)}resumePrimary(e,t,n){var r;this.playingItem=e,this.playingAsset=this.endedAsset=null,this.waitingItem=null,this.bufferedToItem(e),this.endedItem=null,this.log(`resuming ${Ep(e)}`);let i=this.timelinePos;if((r=this.detachedData)!=null&&r.mediaSource?this.primaryLive&&this.startLoadingPrimaryAt(i):((i<e.start||i>=e.end||i<this.seekableStart)&&(i=this.getPrimaryResumption(e,t),this.log(kp(`resumePrimary`,i)),this.timelinePos=i),this.attachPrimary(i,e)),!n)return;let a=this.schedule?.items;a&&(this.log(`INTERSTITIALS_PRIMARY_RESUMED ${Ep(e)}`),this.hls.trigger(L.INTERSTITIALS_PRIMARY_RESUMED,{schedule:a.slice(0),scheduleIndex:t}),this.checkBuffer())}get seekableStart(){return this.primaryLive&&this.primaryDetails?.fragmentStart||0}getPrimaryResumption(e,t,n){let r=e.start;if(this.primaryLive){if(t===0)return this.hls.startPosition;let e=this.endedItem||this.playingItem,i=e!=null&&e.event?this.livePrerollResumption(e.event,n):void 0;if(i!==void 0)return i;let a=this.primaryDetails;if(a){let{fragmentStart:e,edge:t}=a;if(r<e||r>t&&!n){let n=this.hls.liveSyncPosition;return this.log(`primary resumption out of bounds (${r} [${e}-${t}]) snapping to liveSync ${n}`),n||e}}}return this.log(`primary resumption itemStart: ${r}`),r}getLiveStartPos(){let e=this.hls.startPosition,t=this.hls.liveSyncPosition||0,n=(this.primaryDetails?.targetduration||10)*3;return e===-1||t&&t-e<n?t||0:e}isAssetBuffered(e){let t=this.getAssetPlayer(e.identifier);return t!=null&&t.hls?t.hls.bufferedToEnd:J.bufferInfo(this.primaryMedia,this.timelinePos,0).end+1>=e.timelineStart+(e.duration||0)}attachPrimary(e,t,n){t?this.setBufferingItem(t):this.bufferingItem=this.playingItem,this.bufferingAsset=null;let r=this.primaryMedia;if(!r)return;let i=this.hls;i.media?this.checkBuffer():(this.transferMediaTo(i,r),n&&this.startLoadingPrimaryAt(e,n)),n||(this.log(kp(`attachPrimary`,e)),this.timelinePos=e,this.startLoadingPrimaryAt(e,n))}startLoadingPrimaryAt(e,t){let n=this.hls,{loadingEnabled:r,bufferingEnabled:i,startPosition:a}=n,o=n.hasEnoughToStart;if(this.log(`Start loading primary @${e} bufferedPos: ${this.bufferedPos} startPosition: ${a} skip seek: ${t} has enough ${o} loadingEnabled: ${r} bufferingEnabled: ${i}`),!t&&o||!r||Math.abs(a-e)>.1){let r=this.primaryDetails;if(r!=null&&r.live&&e+.5>=r.edge){let t=this.bufferingItem;this.log(`Resume primary loading when live passes ${e} buffering item: ${t?Ep(t):null}`),n.pauseBuffering(),this.bufferPastEdge=!0;return}n.startLoad(e,t)}else i||n.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(L.BUFFER_CODECS,this.onBufferCodecs,this),this.hls.on(L.BUFFER_CODECS,this.onBufferCodecs,this)}onLevelUpdated(e,t){if(t.level===-1||!this.schedule)return;let n=this.hls.levels[t.level];if(!n.details)return;let r=H(H({},this.mediaSelection||this.altSelection),{},{main:n});this.mediaSelection=r;let i=this.hls.startPosition;if(this.schedule.parseInterstitialDateRanges(r,this.hls.config.interstitialAppendInPlace,i===-1?0:i),this.schedule.items){if(!this.effectivePlayingItem)this.checkStart();else if(this.bufferPastEdge){let e=this.primaryDetails,t=this.bufferedPos;if(e!=null&&e.live&&t+.5<e.edge){this.bufferPastEdge=!1;let n=this.bufferingItem;if(this.log(`Live edge ${e.edge} passed buffer: ${t} buffering item: ${n?Ep(n):null}`),n?.end===1/0){let e=this.playingItem,r=this.isInterstitial(e)&&e.event.appendInPlace;this.hls.startLoad(Math.max(t,n.start),r)}else{let e=this.getBufferingPlayer();e&&e.bufferedInPlaceToEnd(this.primaryMedia,e.currentTime)&&e.hls&&e.hls.trigger(L.BUFFERED_TO_END,void 0)}}}}}onAudioTrackUpdated(e,t){let n=this.hls.audioTracks[t.id],r=this.mediaSelection;if(!r){this.altSelection=H(H({},this.altSelection),{},{audio:n});return}let i=H(H({},r),{},{audio:n});this.mediaSelection=i}onSubtitleTrackUpdated(e,t){let n=this.hls.subtitleTracks[t.id],r=this.mediaSelection;if(!r){this.altSelection=H(H({},this.altSelection),{},{subtitles:n});return}let i=H(H({},r),{},{subtitles:n});this.mediaSelection=i}onAudioTrackSwitching(e,t){let n=Vi(t);this.playerQueue.forEach(({hls:e})=>e&&(e.setAudioOption(t)||e.setAudioOption(n)))}onSubtitleTrackSwitch(e,t){let n=Vi(t);this.playerQueue.forEach(({hls:e})=>e&&(e.setSubtitleOption(t)||t.id!==-1&&e.setSubtitleOption(n)))}onBufferCodecs(e,t){let n=t.tracks;n&&(this.requiredTracks=n)}onBufferAppended(e,t){this.checkBuffer()}onBufferFlushed(e,t){let n=this.playingItem;if(n&&!this.itemsMatch(n,this.bufferingItem)&&!this.isInterstitial(n)){let e=this.timelinePos;this.bufferedPos=e,this.checkBuffer()}}onBufferedToEnd(e){if(!this.schedule)return;let t=this.schedule.events;if(this.bufferedPos<Number.MAX_VALUE&&t){for(let e=0;e<t.length;e++){let n=t[e];if(n.cue.post){let e=this.getEventItem(n.identifier);e&&this.eventItemsMatch(e,this.bufferingItem)&&this.bufferedToItem(e,0);break}}this.bufferedPos=Number.MAX_VALUE}}onMediaEnded(e){let t=this.playingItem;if(!this.playingLastItem&&t){let e=this.findItemIndex(t);this.setSchedulePosition(e+1)}else this.shouldPlay=!1}updateItem(e,t){let n=this.schedule?.items;return e&&n&&n[this.findItemIndex(e,t)]||null}trimInPlace(e,t){if(this.isInterstitial(e)&&e.event.appendInPlace&&t.end-e.end>.25){e.event.assetList.forEach((t,n)=>{e.event.isAssetPastPlayoutLimit(n)&&this.clearAssetPlayer(t.identifier,null)});let n=e.end+.25,r=J.bufferInfo(this.primaryMedia,n,0);(r.end>n||(r.nextStart||0)>n)&&(this.log(`trim buffered interstitial ${Ep(e)} (was ${Ep(t)})`),this.attachPrimary(n,null,!0),this.flushFrontBuffer(n))}}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){return!!t&&(e===t||e.event.identifier===t.event?.identifier)}findEventIndex(e){return this.schedule?this.schedule.findEventIndex(e):-1}getEventItem(e){if(this.schedule){let t=this.schedule.items?.[this.findEventIndex(e)];if(this.isInterstitial(t)&&t.event.identifier===e)return t}}findItemIndex(e,t){return e&&this.schedule?this.schedule.findItemIndex(e,t):-1}updateSchedule(e=!1){var t;let n=this.mediaSelection;if(!n)return;let r=this.hls?.liveSyncPosition||0;(t=this.schedule)==null||t.updateSchedule(n,[],r,e)}checkBuffer(e){let t=this.schedule?.items;if(!t)return;let n=J.bufferInfo(this.primaryMedia,this.timelinePos,0);e&&(this.bufferedPos=this.timelinePos),e||=n.len<1,this.updateBufferedPos(n.end,t,e)}updateBufferedPos(e,t,n){let r=this.schedule,i=this.bufferingItem;if(this.bufferedPos>e||!r)return;if(t.length===1&&this.itemsMatch(t[0],i)){this.bufferedPos=e;return}let a=this.playingItem,o=this.findItemIndex(a),s=r.findItemIndexAtTime(e);if(this.bufferedPos<e){var c;let n=this.findItemIndex(i),r=Math.min(n+1,t.length-1),a=t[r];if((s===-1&&i&&e>=i.end||(c=a.event)!=null&&c.appendInPlace&&e+.01>=a.start)&&(s=r),this.isInterstitial(i)){let e=i.event;if(r-o>1&&e.appendInPlace===!1||e.assetList.length===0&&e.assetListLoader)return}if(this.bufferedPos=e,s>n&&s>o)this.bufferedToItem(a);else{let t=this.primaryDetails;this.primaryLive&&t&&e>t.edge-t.targetduration&&a.start<t.edge+this.hls.config.interstitialLiveLookAhead&&this.isInterstitial(a)&&this.preloadAssets(a.event,0)}}else n&&a&&!this.itemsMatch(a,i)&&(s===o?this.bufferedToItem(a):s===o+1&&this.bufferedToItem(t[s]))}assetsBuffered(e,t){return e.event.assetList.length!==0&&!e.event.assetList.some(e=>{let n=this.getAssetPlayer(e.identifier);return!(n!=null&&n.bufferedInPlaceToEnd(t))})}setBufferingItem(e){let t=this.bufferingItem,n=this.schedule;if(!this.itemsMatch(e,t)&&n){let{items:r,events:i}=n;if(!r||!i)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 s=o?o.remaining:t?t.end-this.timelinePos:0;if(this.log(`INTERSTITIALS_BUFFERED_TO_BOUNDARY ${Ep(e)}`+(t?` (${s.toFixed(2)} remaining)`:``)),!this.playbackDisabled){if(a){let t=n.findAssetIndex(e.event,this.bufferedPos);e.event.assetList.forEach((e,n)=>{let r=this.getAssetPlayer(e.identifier);r&&(n===t&&r.loadSource(),r.resumeBuffering())})}else this.hls.resumeBuffering(),this.playerQueue.forEach(e=>e.pauseBuffering())}this.hls.trigger(L.INTERSTITIALS_BUFFERED_TO_BOUNDARY,{events:i.slice(0),schedule:r.slice(0),bufferingIndex:this.findItemIndex(e),playingIndex:this.findItemIndex(this.playingItem)})}else this.bufferingItem!==e&&(this.bufferingItem=e);return t}bufferedToItem(e,t=0){let n=this.setBufferingItem(e);if(!this.playbackDisabled){if(this.isInterstitial(e))this.bufferedToEvent(e,t);else if(n!==null){this.bufferingAsset=null;let t=this.getPrimaryResumption(e,this.findItemIndex(e),!0),n=this.bufferedPos=Math.max(t,Math.min(this.bufferedPos,e.end),this.timelinePos,e.start),r=this.detachedData;if(r)r.mediaSource?this.attachPrimary(n,e,!0):this.startLoadingPrimaryAt(n);else{let e=this.playingItem,t=this.isInterstitial(e)&&e.event.appendInPlace;this.startLoadingPrimaryAt(n,t)}}}}bufferedToEvent(e,t){let n=e.event,r=n.assetList.length===0&&!n.assetListLoader,i=n.cue.once;if(r||!i){let e=this.preloadAssets(n,t);if(e!=null&&e.interstitial.appendInPlace){let t=this.primaryMedia;t&&this.bufferAssetPlayer(e,t)}}}preloadAssets(e,t){let n=e.assetUrl,r=e.assetList.length,i=r===0&&!e.assetListLoader,a=e.cue.once;if(i){let i=e.timelineStart,a=this.playingItem,s=this.getBufferingPlayer();if(e.appendInPlace){var o;!this.isInterstitial(a)&&(a==null||(o=a.nextEvent)==null?void 0:o.identifier)===e.identifier&&this.flushFrontBuffer(i+.25)}let c,l=0;if((!s||s.interstitial.cue.pre)&&this.primaryLive&&(l=this.getLiveStartPos(),s&&(l+=s.remaining)),l&&!(e.cue.pre||e.cue.post)){let e=l-i;e>0&&(c=Math.round(e*1e3)/1e3)}if(this.log(`Load interstitial asset ${t+1}/${n?1:r} ${e}${l?` live-start: ${l} start-offset: ${c} (timeline-start: ${i})`:``}`),n)return this.createAsset(e,0,0,i,e.duration,n);let u=this.assetListLoader.loadAssetList(e,c);u&&(e.assetListLoader=u)}else if(!a&&r){for(let n=t;n<r;n++){let t=e.assetList[n],r=this.getAssetPlayerQueueIndex(t.identifier);(r===-1||this.playerQueue[r].destroyed)&&!t.error&&this.createAssetPlayer(e,t,n)}let n=e.assetList[t];if(n){let e=this.getAssetPlayer(n.identifier);return e&&e.loadSource(),e}}return null}flushFrontBuffer(e){let t=this.requiredTracks;if(!t)return;let n=this.primaryDetails;n&&e>=n.edge||(this.log(`Removing front buffer starting at ${e}`),Object.keys(t).forEach(t=>{this.hls.trigger(L.BUFFER_FLUSHING,{startOffset:e,endOffset:1/0,type:t})}))}getAssetPlayerQueueIndex(e){let t=this.playerQueue;for(let n=0;n<t.length;n++)if(e===t[n].assetId)return n;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 n=0;n<e.length;n++)if(e[n].media===t)return e[n]}return null}createAsset(e,t,n,r,i,a){let o={parentIdentifier:e.identifier,identifier:hp(e,a,t),duration:i,startOffset:n,timelineStart:r,uri:a};return this.createAssetPlayer(e,o,t)}createAssetPlayer(e,t,n){let r=this.hls,i=r.userConfig,a=Zi(r.loadLevelObj||r.levels[r.currentLevel],i.videoPreference),o=r.audioTracks[r.audioTrack],s=r.subtitleTracks[r.subtitleTrack],c=0;if(this.primaryLive||e.appendInPlace){let e=this.timelinePos-t.timelineStart;if(e>=0){let n=t.duration;n&&e<n&&(c=e)}}let l=t.identifier,u=H(H({},i),{},{maxMaxBufferLength:Math.min(15,r.config.maxMaxBufferLength),autoStartLoad:!0,startFragPrefetch:!0,primarySessionId:r.sessionId,assetPlayerId:l,abrEwmaDefaultEstimate:r.bandwidthEstimate,interstitialsController:void 0,startPosition:c,liveDurationInfinity:!1,testBandwidth:!1,videoPreference:a,audioPreference:o||i.audioPreference,subtitlePreference:s||i.subtitlePreference});e.appendInPlace&&(e.appendInPlaceStarted=!0,t.timelineStart&&(u.timelineOffset=t.timelineStart));let d=u.cmcd;d!=null&&d.sessionId&&d.contentId&&(u.cmcd=V({},d,{contentId:uf(t.uri)})),this.getAssetPlayer(l)&&this.warn(`Duplicate date range identifier ${e} and asset ${l}`);let f=new Cp(this.HlsPlayerClass,u,e,t);this.playerQueue.push(f),e.assetList[n]=t;let p=!0,m=r=>{if(r.live){let t=Error(`Interstitials MUST be VOD assets ${e}`),r={fatal:!0,type:F.OTHER_ERROR,details:I.INTERSTITIAL_ASSET_ITEM_ERROR,error:t},i=this.findEventIndex(e.identifier);this.handleAssetItemError(r,e,i,n,t.message);return}let i=r.edge-r.fragmentStart,a=t.duration;(p||a===null||i>a)&&(p=!1,this.log(`Interstitial asset "${l}" duration change ${a} > ${i}`),t.duration=i,this.updateSchedule())};f.on(L.LEVEL_UPDATED,(e,{details:t})=>m(t)),f.on(L.LEVEL_PTS_UPDATED,(e,{details:t})=>m(t)),f.on(L.EVENT_CUE_ENTER,()=>this.onInterstitialCueEnter());let h=(e,t)=>{let n=this.getAssetPlayer(l);if(n&&t.tracks){n.off(L.BUFFER_CODECS,h),n.tracks=t.tracks;let e=this.primaryMedia;this.bufferingAsset===n.assetItem&&e&&!n.media&&this.bufferAssetPlayer(n,e)}};f.on(L.BUFFER_CODECS,h),f.on(L.BUFFERED_TO_END,()=>{let t=this.getAssetPlayer(l);if(this.log(`buffered to end of asset ${t}`),!t||!this.schedule)return;let n=this.getEventItem(e.identifier);n&&this.advanceAssetBuffering(n,t.assetItem)});let g=t=>()=>{if(!this.getAssetPlayer(l)||!this.schedule)return;this.shouldPlay=!0;let n=this.findEventIndex(e.identifier);this.advanceAfterAssetEnded(e,n,t)};return f.once(L.MEDIA_ENDED,g(n)),f.once(L.PLAYOUT_LIMIT_REACHED,g(1/0)),f.on(L.ERROR,(t,r)=>{if(!this.schedule)return;let i=this.getAssetPlayer(l);if(r.details===I.BUFFER_STALLED_ERROR){if(i!=null&&i.appendInPlace){this.handleInPlaceStall(e);return}this.onTimeupdate(),this.checkBuffer(!0);return}r.details!==I.BUFFER_SEEK_OVER_HOLE&&this.handleAssetItemError(r,e,this.findEventIndex(e.identifier),n,`Asset player error ${r.error} ${e}`)}),f.on(L.DESTROYING,()=>{if(!this.getAssetPlayer(l)||!this.schedule)return;let t=Error(`Asset player destroyed unexpectedly ${l}`),r={fatal:!0,type:F.OTHER_ERROR,details:I.INTERSTITIAL_ASSET_ITEM_ERROR,error:t};this.handleAssetItemError(r,e,this.findEventIndex(e.identifier),n,t.message)}),this.log(`INTERSTITIAL_ASSET_PLAYER_CREATED ${Sp(t)}`),this.hls.trigger(L.INTERSTITIAL_ASSET_PLAYER_CREATED,{asset:t,assetListIndex:n,event:e,player:f}),f}clearInterstitial(e,t){this.clearAssetPlayers(e,t),e.reset()}clearAssetPlayers(e,t){e.assetList.forEach(e=>{this.clearAssetPlayer(e.identifier,t)})}resetAssetPlayer(e){let t=this.getAssetPlayerQueueIndex(e);if(t!==-1){this.log(`reset asset player "${e}" after error`);let n=this.playerQueue[t];this.transferMediaFromPlayer(n,null),n.resetDetails()}}clearAssetPlayer(e,t){let n=this.getAssetPlayerQueueIndex(e);if(n!==-1){let e=this.playerQueue[n];this.log(`clear ${e} toSegment: ${t&&Ep(t)}`),this.transferMediaFromPlayer(e,t),this.playerQueue.splice(n,1),e.destroy()}}emptyPlayerQueue(){let e;for(;e=this.playerQueue.pop();)e.destroy();this.playerQueue=[]}startAssetPlayer(e,t,n,r,i){let{interstitial:a,assetItem:o,assetId:s}=e,c=a.assetList.length,l=this.playingAsset;this.endedAsset=null,this.playingAsset=o,l?.identifier!==s&&(l&&(this.clearAssetPlayer(l.identifier,n[r]),delete l.error),this.log(`INTERSTITIAL_ASSET_STARTED ${t+1}/${c} ${Sp(o)}`),this.hls.trigger(L.INTERSTITIAL_ASSET_STARTED,{asset:o,assetListIndex:t,event:a,schedule:n.slice(0),scheduleIndex:r,player:e})),this.bufferAssetPlayer(e,i)}bufferAssetPlayer(e,t){if(!this.schedule)return;let{interstitial:n,assetItem:r}=e,i=this.getEventItem(n.identifier);if(!i)return;if(e.loadSource(),this.setBufferingItem(i),this.bufferingAsset=r,e.bufferedInPlaceToEnd(this.primaryMedia,e.currentTime)){this.advanceAssetBuffering(i,r);return}let a=this.getBufferingPlayer();if(a===e)return;let o=n.appendInPlace;if(o&&a?.interstitial.appendInPlace===!1)return;let s=a?.tracks||this.detachedData?.tracks||this.requiredTracks;if(o&&r!==this.playingAsset){if(!e.tracks){this.log(`Waiting for track info before buffering ${e}`);return}if(s&&!sn(s,e.tracks)){let t=Error(`Asset ${Sp(r)} SourceBuffer tracks ('${Object.keys(e.tracks)}') are not compatible with primary content tracks ('${Object.keys(s)}')`),i={fatal:!0,type:F.OTHER_ERROR,details:I.INTERSTITIAL_ASSET_ITEM_ERROR,error:t},a=n.findAssetIndex(r);this.handleAssetItemError(i,n,this.findEventIndex(n.identifier),a,t.message);return}}this.transferMediaTo(e,t)}handleInPlaceStall(e){let t=this.schedule,n=this.primaryMedia;if(!t||!n)return;let r=n.currentTime,i=t.findAssetIndex(e,r),a=e.assetList[i];if(a){let o=this.getAssetPlayer(a.identifier);if(o){let s=o.currentTime||r-a.timelineStart,c=o.duration-s;if(this.warn(`Stalled at ${s} of ${s+c} in ${o} ${e} (media.currentTime: ${r})`),s&&(c/n.playbackRate<.5||o.bufferedInPlaceToEnd(n,o.currentTime))&&o.hls){let n=t.findEventIndex(e.identifier);this.advanceAfterAssetEnded(e,n,i)}}}}advanceInPlace(e){let t=this.primaryMedia;if(t&&t.currentTime<e){let n=`advance currentTime to ${e}, duration: ${t.duration}`;t.duration>e?(this.log(n),t.currentTime=e):this.log(`Cannot ${n}`)}}handleAssetItemError(e,t,n,r,i){if(e.details===I.BUFFER_STALLED_ERROR)return;let a=t.assetList[r]||null;if(this.warn(`INTERSTITIAL_ASSET_ERROR ${a&&Sp(a)} ${e.error}`),!this.schedule)return;let o=a?.identifier||``,s=this.getAssetPlayerQueueIndex(o),c=this.playerQueue[s]||null,l=this.schedule.items,u=V({},e,{fatal:!1,errorAction:pa(!0),asset:a,assetListIndex:r,event:t,schedule:l,scheduleIndex:n,player:c});if(this.hls.trigger(L.INTERSTITIAL_ASSET_ERROR,u),!e.fatal)return;let d=this.playingAsset,f=this.bufferingAsset,p=Error(i);if(a&&(this.clearAssetPlayer(o,null),a.error=p),!t.assetList.some(e=>!e.error))t.error=p;else for(let e=r;e<t.assetList.length;e++)this.resetAssetPlayer(t.assetList[e].identifier);this.updateSchedule(!0),t.error?this.primaryFallback(t):d?.identifier===o?this.advanceAfterAssetEnded(t,n,r):f?.identifier===o&&this.isInterstitial(this.bufferingItem)&&this.advanceAssetBuffering(this.bufferingItem,f)}primaryFallback(e){let t=e.timelineStart,n=this.effectivePlayingItem,r=this.playingItem,i=this.seekableStart,a=this.hls.startPosition,o=this.timelinePos;if(this.isInterstitial(n)){this.log(`Fallback to primary from event "${e.identifier}" start: ${t} pos: ${o} playing: ${Ep(n)} startPosition: ${a} seekableStart: ${i} error: ${e.error}`),o===-1&&(o=a),o=Math.max(o,i);let r=this.updateItem(n,o);this.itemsMatch(n,r)&&this.clearInterstitial(e,null),e.appendInPlace&&(this.attachPrimary(t,null),this.flushFrontBuffer(t))}else if(o===-1){this.checkStart();return}if(!this.schedule||r&&!this.isInterstitial(r))return;let s=this.schedule.findItemIndexAtTime(o);this.setSchedulePosition(s)}onAssetListLoaded(e,t){var n;let r=t.event,i=r.identifier,a=t.assetListResponse.ASSETS;if(!((n=this.schedule)!=null&&n.hasEvent(i)))return;let o=r.timelineStart,s=r.duration,c=0;a.forEach((e,t)=>{let n=parseFloat(e.DURATION);this.createAsset(r,t,c,o+c,n,e.URI),c+=n}),r.duration=c,this.log(`Loaded asset-list with duration: ${c} (was: ${s}) ${r}`);let l=this.waitingItem?.event.identifier===i;this.updateSchedule();let u=this.bufferingItem?.event;if(l){let e=this.findEventIndex(i),t=this.getEventItem(i);if(t){if(!this.playingItem&&this.timelinePos>t.end&&this.schedule.findItemIndexAtTime(this.timelinePos)!==e){r.error=Error(`Interstitial ${a.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(t)}this.setSchedulePosition(e)}else if(u?.identifier===i){let e=r.assetList[0];if(e){let t=this.getAssetPlayer(e.identifier);if(u.appendInPlace){let e=this.primaryMedia;t&&e&&this.bufferAssetPlayer(t,e)}else t&&t.loadSource()}}}onError(e,t){if(this.schedule)switch(t.details){case I.ASSET_LIST_PARSING_ERROR:case I.ASSET_LIST_LOAD_ERROR:case I.ASSET_LIST_LOAD_TIMEOUT:{let e=t.interstitial;e&&(this.updateSchedule(!0),this.primaryFallback(e));break}case I.BUFFER_STALLED_ERROR:{let e=this.endedItem||this.waitingItem||this.playingItem;if(this.isInterstitial(e)&&e.event.appendInPlace){this.handleInPlaceStall(e.event);return}let t=this.primaryMedia;this.log(`Primary player stall @${this.timelinePos} currentTime: ${t?.currentTime} bufferedPos: ${this.bufferedPos}`),this.onTimeupdate(),this.checkBuffer(!0);break}}}},jp=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 e;let{media:t}=this,n=this.levelDetails;if(!t||!n||!this.hls)return;this.currentTime=t.currentTime;let r=this.hls.config,i=this.computeLatency();if(i===null)return;this._latency=i;let{lowLatencyMode:a,maxLiveSyncPlaybackRate:o}=r;if(!a||o===1||!n.live)return;let s=this.targetLatency;if(s===null)return;let c=i-s,l=c<Math.min(this.maxLatency,s+n.targetduration),u=Os(r)&&!!((e=this.hls.interstitialsManager)!=null&&(e=e.playingItem)!=null&&e.event);if(l&&c>.05&&this.forwardBufferLength>1&&!u){let e=Math.min(2,Math.max(1,o)),n=Math.round(2/(1+Math.exp(-.75*c-this.edgeStalled))*20)/20,r=Math.min(e,Math.max(1,n));this.changeMediaPlaybackRate(t,r)}else t.playbackRate!==1&&t.playbackRate!==0&&this.changeMediaPlaybackRate(t,1)},this.hls=e,this.registerListeners()}get levelDetails(){return this.hls?.latestLevelDetails||null}get latency(){return this._latency||0}get maxLatency(){let e=this.hls?.config;if(!e)return 0;if(e.liveMaxLatencyDuration!==void 0)return e.liveMaxLatencyDuration;let t=this.levelDetails;return t?e.liveMaxLatencyDurationCount*t.targetduration:0}get targetLatency(){let e=this.levelDetails;if(e===null||!this.hls)return null;let t=this.hls.config,{holdBack:n,partHoldBack:r,targetduration:i}=e,{liveSyncDuration:a,liveSyncDurationCount:o,lowLatencyMode:s}=t,c=this.hls.userConfig,l=s&&r||n;(this._targetLatencyUpdated||c.liveSyncDuration||c.liveSyncDurationCount||l===0)&&(l=a===void 0?o*i:a);let u=i;return l+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 n=this.levelDetails;if(n===null)return null;let r=n.edge,i=e-t-this.edgeStalled,a=r-n.totalduration,o=r-(this.hls.config.lowLatencyMode&&n.partTarget||n.targetduration);return Math.min(Math.max(a,i),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 n=e.buffered.length;return(n?e.buffered.end(n-1):t.edge)-this.currentTime}destroy(){this.unregisterListeners(),this.onMediaDetaching(),this.hls=null}registerListeners(){let{hls:e}=this;e&&(e.on(L.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(L.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(L.MANIFEST_LOADING,this.onManifestLoading,this),e.on(L.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(L.ERROR,this.onError,this),e.on(L.INTERSTITIAL_ASSET_STARTED,this.onAssetStarted,this))}unregisterListeners(){let{hls:e}=this;e&&(e.off(L.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(L.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(L.MANIFEST_LOADING,this.onManifestLoading,this),e.off(L.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(L.ERROR,this.onError,this),e.off(L.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),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 n;let r=this.hls,i=this.media||t.event.appendInPlace&&(r==null||(n=r.interstitialsManager)==null?void 0:n.playerQueue.reduce((e,t)=>e||t.media,null));r&&i&&i.playbackRate>1&&i.playbackRate<=r.config.maxLiveSyncPlaybackRate&&this.changeMediaPlaybackRate(i,1)}onError(e,t){var n;t.details===I.BUFFER_STALLED_ERROR&&(this.stallCount++,this.hls&&(n=this.levelDetails)!=null&&n.live&&this.hls.logger.warn(`[latency-controller]: Stall detected, adjusting target latency`))}changeMediaPlaybackRate(e,t){var n;e.playbackRate!==t&&((n=this.hls)==null||n.logger.debug(`[latency-controller]: latency=${this.latency.toFixed(3)}, targetLatency=${this.targetLatency?.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}},Mp=500,Np=1e-6,Pp=class extends Es{constructor(e,t,n){super(e,t,n,`subtitle-stream-controller`,z.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(L.LEVEL_LOADED,this.onLevelLoaded,this),e.on(L.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(L.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.on(L.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(L.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.on(L.BUFFER_FLUSHING,this.onBufferFlushing,this)}unregisterListeners(){super.unregisterListeners();let{hls:e}=this;e.off(L.LEVEL_LOADED,this.onLevelLoaded,this),e.off(L.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(L.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.off(L.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(L.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.off(L.BUFFER_FLUSHING,this.onBufferFlushing,this)}startLoad(e,t){this.stopLoad(),this.state=$.IDLE,this.setInterval(Mp),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 n,r;let{frag:i,part:a,success:o}=t;if(!o)return;let s=(n=this.tracksBuffered)[r=i.level]||(n[r]=[]);if(!s)return;let c,l=(a||i).start;for(let e=0;e<s.length;e++)if(l>=s[e].start&&l<=s[e].end){c=s[e];break}let u=l+(a||i).duration;if(c?c.end=u:(c={start:l,end:u},s.push(c)),!a||u>=i.end-Np){let e=this.fragmentTracker.fragBuffered(i);a&&e&&(e.range.subs={time:[{startPTS:i.start,endPTS:u}],partial:!0}),Tt(i)&&!this.fragContextChanged(i)&&(this.fragPrevious=i),this.fragBufferedComplete(i,a),this.media&&this.tickImmediate()}}onBufferFlushing(e,t){let{startOffset:n,endOffset:r}=t;if(n===0&&r!==1/0){let e=r-1;if(e<=0)return;t.endOffsetSubtitles=Math.max(0,e),this.tracksBuffered.forEach(t=>{if(t)for(let n=0;n<t.length;){if(t[n].end<=e){t.shift();continue}if(t[n].start<e)t[n].start=e;else break;n++}}),this.fragmentTracker.removeFragmentsInRange(n,e,z.SUBTITLE)}}onError(e,t){let n=t.frag;n?.type===z.SUBTITLE&&(t.details===I.FRAG_GAP&&this.fragmentTracker.addAsGap(n),this.fragCurrent&&this.fragCurrent.abortRequests(),this.state!==$.STOPPED&&(this.state=$.IDLE))}onSubtitleTracksUpdated(e,{subtitleTracks:t}){if(this.levels&&Nl(this.levels,t)){this.levels=t.map(e=>new Mi(e));return}this.tracksBuffered=[],this.levels=t.map(e=>new Mi(e)),this.fragmentTracker.removeFragmentsInRange(0,1/0,z.SUBTITLE),this.fragPrevious=null,this.mediaBuffer=null}onSubtitleTrackSwitch(e,t){var n;if(this.currentTrackId=t.id,this.abortCurrentFrag(),!((n=this.levels)!=null&&n.length)||this.currentTrackId===-1){this.clearInterval();return}let r=this.levels[this.currentTrackId];if(!(r!=null&&r.details)){this.mediaBuffer=null;return}this.mediaBuffer=this.mediaBufferTimeRanges,this.state!==$.STOPPED&&this.setInterval(Mp)}onSubtitleTrackLoaded(e,t){var n;let{currentTrackId:r,levels:i}=this,{details:a,id:o}=t;if(!i){this.warn(`Subtitle tracks were reset while loading level ${o}`);return}let s=i[o];if(o>=i.length||!s)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,l=0;if(a.live||(n=s.details)!=null&&n.live){if(a.deltaUpdateFailed)return;if(!c){this.startFragRequested=!1;return}s.details&&(l=this.alignPlaylists(a,s.details,this.levelLastLoaded?.details)),a.alignedSliding||(Cs(c,a,this),l=a.fragmentStart)}s.details=a,this.levelLastLoaded=s,c&&!this.startFragRequested&&this.setStartPosition(c,l),o===r&&(this.hls.trigger(L.SUBTITLE_TRACK_UPDATED,{details:a,id:o,groupId:t.groupId}),this.tickImmediate())}_handleFragmentLoadProgress(e){let{frag:t,part:n,payload:r}=e;n&&r!=null&&r.byteLength&&this.shouldDecrypt(t)&&this.decryptPayload(r,t,n)}_handleFragmentLoadComplete(e){let{frag:t,payload:n}=e;!this.fragContextChanged(t)&&n!=null&&n.byteLength&&this.shouldDecrypt(t)&&this.decryptPayload(n,t,null)}shouldDecrypt(e){let t=e.decryptdata;return!!(t!=null&&t.key&&t.iv&&ho(t.method))}decryptPayload(e,t,n){let r=t.decryptdata,i=performance.now();this.decrypter.decrypt(new Uint8Array(e),r.key.buffer,r.iv.buffer,go(r.method)).then(e=>{this.fragContextChanged(t)||this.hls.trigger(L.FRAG_DECRYPTED,{frag:t,part:n,payload:e,stats:{tstart:i,tdecrypt:performance.now()}})}).catch(e=>{this.hls.trigger(L.ERROR,{type:F.MEDIA_ERROR,details:I.FRAG_DECRYPT_ERROR,fatal:!1,error:e,reason:e.message,frag:t,part:n}),n||(this.warn(`${e.name}: ${e.message}`),this.state=$.IDLE)})}doTick(){if(this.state===$.IDLE&&this.levels){if(!this.media&&!this.primaryPrefetch&&(this.startFragRequested||!this.config.startFragPrefetch))return;let{currentTrackId:t,levels:n}=this,r=n[t],i=r?.details;if(!i||this.waitForLive(r)||this.waitForCdnTuneIn(i)){this.startFragRequested=!1;return}let{config:a}=this,o=this.playhead,s=J.bufferedInfo(this.tracksBuffered[t]||[],o,a.maxBufferHole),{end:c,len:l}=s;if(l>Math.max(this.hls.maxBufferLength+i.levelTargetDuration,this.hls.mainForwardBufferInfo?.len||0)||l&&!this.buffering)return;let u=this.getNextFragment(c,i);if(!u)return;if(Tt(u)){var e;if(u.end===s.end)return;let t=u.sn-i.startSN,n=i.fragments[t-1];u.cc===n?.cc&&!((e=i.partList)!=null&&e.length)&&this.fragmentTracker.getState(n)===Z.NOT_LOADED&&(u=n)}this.loadFragment(u,r,c)}}loadFragment(e,t,n){let r=this.fragmentTracker.getState(e);(r===Z.NOT_LOADED||r===Z.PARTIAL)&&super.loadFragment(e,t,n)}get mediaBufferTimeRanges(){return new Fp(this.tracksBuffered[this.currentTrackId]||[])}},Fp=class{constructor(e){this.buffered=void 0;let t=(t,n,r)=>{if(n>>>=0,n>r-1)throw new DOMException(`Failed to execute '${t}' on 'TimeRanges': The index provided (${n}) is greater than the maximum bound (${r})`);return e[n][t]};this.buffered={get length(){return e.length},end(n){return t(`end`,n,e.length)},start(n){return t(`start`,n,e.length)}}}},Ip={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},Lp=e=>String.fromCharCode(Ip[e]||e),Rp=15,zp=42,Bp={17:1,18:3,21:5,22:7,23:9,16:11,19:12,20:14},Vp={17:2,18:4,21:6,22:8,23:10,19:13,20:15},Hp={25:1,26:3,29:5,30:7,31:9,24:11,27:12,28:14},Up={25:2,26:4,29:6,30:8,31:10,27:13,28:15},Wp=[`white`,`green`,`blue`,`cyan`,`red`,`yellow`,`magenta`,`black`,`transparent`],Gp=class{constructor(){this.time=null,this.verboseLevel=0}log(e,t){if(this.verboseLevel>=e){let n=typeof t==`function`?t():t;U.log(`${this.time} [${e}] ${n}`)}}},Kp=function(e){let t=[];for(let n=0;n<e.length;n++)t.push(e[n].toString(16));return t},qp=Object.freeze({foreground:`white`,underline:!1,italics:!1,background:`black`,flash:!1}),Jp=class{constructor(){this.styles=qp}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=qp}setStyles(e){let t=this.styles,n=Object.prototype.hasOwnProperty;this.styles={foreground:n.call(e,`foreground`)?e.foreground:t.foreground,underline:n.call(e,`underline`)?e.underline:t.underline,italics:n.call(e,`italics`)?e.italics:t.italics,background:n.call(e,`background`)?e.background:t.background,flash:n.call(e,`flash`)?e.flash:t.flash}}toString(){return`color=`+this.foreground+`, underline=`+this.underline+`, italics=`+this.italics+`, background=`+this.background+`, flash=`+this.flash}},Yp=class{constructor(){this.uchar=` `,this.penState=new Jp}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}},Xp=class{constructor(e){this.chars=[],this.pos=0,this.currPenState=new Jp,this.cueStartTime=null,this.logger=void 0;for(let e=0;e<zp;e++)this.chars.push(new Yp);this.logger=e}equals(e){let t=this.chars,n=e.chars;for(let e=0;e<zp;e++){let r=t[e],i=n[e];if(r.uchar!==i.uchar)return!1;let a=r.penState.styles,o=i.penState.styles;if(a!==o&&(a.foreground!==o.foreground||a.underline!==o.underline||a.italics!==o.italics||a.background!==o.background||a.flash!==o.flash))return!1}return!0}copy(e){for(let t=0;t<zp;t++)this.chars[t].copy(e.chars[t])}isEmpty(){let e=this.chars;for(let t=0;t<zp;t++){let n=e[t];if(n.uchar!==` `)return!1;let r=n.penState.styles;if(r!==qp&&(r.foreground!==`white`||r.underline||r.italics||r.background!==`black`||r.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>=zp&&(this.logger.log(3,`Too large cursor position `+this.pos),this.pos=41)}moveCursor(e){let t=Math.min(this.pos+e,zp);if(e>1)for(let e=this.pos+1;e<t;e++)this.chars[e].setPenState(this.currPenState);this.setCursor(t)}backSpace(){this.moveCursor(-1),this.chars[this.pos].setChar(` `,this.currPenState)}insertChar(e){e>=144&&this.backSpace();let t=Lp(e);if(this.pos>=zp){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<zp;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 n=0;n<zp;n++){let r=this.chars[n].uchar;r!==` `&&(t=!1),e.push(r)}return t?``:e.join(``)}setPenStyles(e){this.currPenState.setStyles(e),this.chars[this.pos].setPenState(this.currPenState)}},Zp=class{constructor(e){this.rows=[],this.currRow=14,this.nrRollUpRows=null,this.lastOutputScreen=null,this.logger=void 0;for(let t=0;t<Rp;t++)this.rows.push(new Xp(e));this.logger=e}reset(){for(let e=0;e<Rp;e++)this.rows[e].clear();this.currRow=14}equals(e){let t=!0;for(let n=0;n<Rp;n++)if(!this.rows[n].equals(e.rows[n])){t=!1;break}return t}copy(e){for(let t=0;t<Rp;t++){let n=this.rows[t].chars,r=e.rows[t].chars;for(let e=0;e<zp;e++){let t=n[e],i=r[e];t.uchar=i.uchar,t.penState.styles=i.penState.styles}}}isEmpty(){let e=!0;for(let t=0;t<Rp;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 = `+q(e));let t=e.row-1;if(this.nrRollUpRows&&t<this.nrRollUpRows-1&&(t=this.nrRollUpRows-1),this.nrRollUpRows&&this.currRow!==t){for(let e=0;e<Rp;e++)this.rows[e].clear();let e=this.currRow+1-this.nrRollUpRows,n=this.lastOutputScreen;if(n){let r=n.rows[e].cueStartTime,i=this.logger.time;if(r!==null&&i!==null&&r<i)for(let r=0;r<this.nrRollUpRows;r++)this.rows[t-this.nrRollUpRows+r+1].copy(n.rows[e+r])}}this.currRow=t;let n=this.rows[this.currRow];if(e.indent!==null){let t=e.indent,r=Math.max(t-1,0);n.setCursor(e.indent),e.color=n.chars[r].penState.foreground}let r={foreground:e.color,underline:e.underline,italics:e.italics,background:`black`,flash:!1};this.setPen(r)}setBkgData(e){this.logger.log(2,()=>`bkgData = `+q(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||=!1;let t=[],n=``,r=-1;for(let n=0;n<Rp;n++){let i=this.rows[n].getTextString();i&&(r=n+1,e?t.push(`Row `+r+`: '`+i+`'`):t.push(i.trim()))}return t.length>0&&(n=e?`[`+t.join(` | `)+`]`:t.join(`
|
|
46
|
-
`)),n}getTextAndFormat(){return this.rows}},Qp=class{constructor(e,t,n){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 Zp(n),this.nonDisplayedMemory=new Zp(n),this.lastOutputScreen=new Zp(n),this.currRollUpRow=this.displayedMemory.rows[14],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null,this.logger=n}reset(){this.mode=null,this.displayedMemory.reset(),this.nonDisplayedMemory.reset(),this.lastOutputScreen.reset(),this.outputFilter.reset(),this.currRollUpRow=this.displayedMemory.rows[14],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null}getHandler(){return this.outputFilter}setHandler(e){this.outputFilter=e}setPAC(e){this.writeScreen.setPAC(e)}setBkgData(e){this.writeScreen.setBkgData(e)}setMode(e){e!==this.mode&&(this.mode=e,this.logger.log(2,()=>`MODE=`+e),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 t=0;t<e.length;t++)this.writeScreen.insertChar(e[t]);let t=this.writeScreen===this.displayedMemory?`DISP`:`NON_DISP`;this.logger.log(2,()=>t+`: `+this.writeScreen.getDisplayText(!0)),(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};t.underline=e%2==1,t.italics=e>=46,t.foreground=t.italics?`white`:[`white`,`green`,`blue`,`cyan`,`red`,`yellow`,`magenta`][Math.floor(e/2)-16],this.logger.log(2,`MIDROW: `+q(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))}},$p=class{constructor(e,t,n){this.channels=[null,null,null],this.currentChannel=0,this.cmdHistory=nm(),this.logger=void 0,this.field=void 0,this.outputFilters=void 0,this.logger=new Gp,this.field=e,this.outputFilters=[null,t,n]}getHandler(e){return this.outputFilters[e]}setHandler(e,t){var n;this.outputFilters[e]=t,(n=this.channels[e])==null||n.setHandler(t)}getChannel(e){let t=this.channels[e];return t||=this.channels[e]=new Qp(this.field+e-1,this.outputFilters[e],this.logger),t}addData(e,t){this.logger.time=e;for(let e=0;e<t.length;e+=2){let n=t[e]&127,r=t[e+1]&127,i=!1,a=null;if(n===0&&r===0)continue;this.logger.log(3,()=>`[`+Kp([t[e],t[e+1]])+`] -> (`+Kp([n,r])+`)`);let o=this.cmdHistory;if(n>=16&&n<=31){if(tm(n,r,o)){em(null,null,o),this.logger.log(3,()=>`Repeated command (`+Kp([n,r])+`) is dropped`);continue}em(n,r,this.cmdHistory),i=this.parseCmd(n,r),i||=this.parseMidrow(n,r),i||=this.parsePAC(n,r),i||=this.parseBackgroundAttributes(n,r)}else em(null,null,o);if(!i&&(a=this.parseChars(n,r),a)){let e=this.currentChannel;e&&e>0?this.getChannel(e).insertChars(a):this.logger.log(2,`No channel found yet. TEXT-MODE?`)}!i&&!a&&this.logger.log(2,()=>`Couldn't parse cleaned data `+Kp([n,r])+` orig: `+Kp([t[e],t[e+1]]))}}parseCmd(e,t){if(!((e===20||e===28||e===21||e===29)&&t>=32&&t<=47||(e===23||e===31)&&t>=33&&t<=35))return!1;let n=e===20||e===21||e===23?1:2,r=this.getChannel(n);return e===20||e===21||e===28||e===29?t===32?r.ccRCL():t===33?r.ccBS():t===34?r.ccAOF():t===35?r.ccAON():t===36?r.ccDER():t===37?r.ccRU(2):t===38?r.ccRU(3):t===39?r.ccRU(4):t===40?r.ccFON():t===41?r.ccRDC():t===42?r.ccTR():t===43?r.ccRTD():t===44?r.ccEDM():t===45?r.ccCR():t===46?r.ccENM():t===47&&r.ccEOC():r.ccTO(t-32),this.currentChannel=n,!0}parseMidrow(e,t){let n=0;if((e===17||e===25)&&t>=32&&t<=47){if(n=e===17?1:2,n!==this.currentChannel)return this.logger.log(0,`Mismatch channel in midrow parsing`),!1;let r=this.channels[n];return r?(r.ccMIDROW(t),this.logger.log(3,()=>`MIDROW (`+Kp([e,t])+`)`),!0):!1}return!1}parsePAC(e,t){let n;if(!((e>=17&&e<=23||e>=25&&e<=31)&&t>=64&&t<=127||(e===16||e===24)&&t>=64&&t<=95))return!1;let r=e<=23?1:2;return n=t>=64&&t<=95?r===1?Bp[e]:Hp[e]:r===1?Vp[e]:Up[e],this.getChannel(r).setPAC(this.interpretPAC(n,t)),this.currentChannel=r,!0}interpretPAC(e,t){let n,r={color:null,italics:!1,indent:null,underline:!1,row:e};return n=t>95?t-96:t-64,r.underline=(n&1)==1,n<=13?r.color=[`white`,`green`,`blue`,`cyan`,`red`,`yellow`,`magenta`,`white`][Math.floor(n/2)]:n<=15?(r.italics=!0,r.color=`white`):r.indent=Math.floor((n-16)/2)*4,r}parseChars(e,t){let n,r=null,i=null;if(e>=25?(n=2,i=e-8):(n=1,i=e),i>=17&&i<=19){let e;e=i===17?t+80:i===18?t+112:t+144,this.logger.log(2,()=>`Special char '`+Lp(e)+`' in channel `+n),r=[e]}else e>=32&&e<=127&&(r=t===0?[e]:[e,t]);return r&&this.logger.log(3,()=>`Char codes = `+Kp(r).join(`,`)),r}parseBackgroundAttributes(e,t){if(!((e===16||e===24)&&t>=32&&t<=47||(e===23||e===31)&&t>=45&&t<=47))return!1;let n,r={};e===16||e===24?(n=Math.floor((t-32)/2),r.background=Wp[n],t%2==1&&(r.background+=`_semi`)):t===45?r.background=`transparent`:(r.foreground=`black`,t===47&&(r.underline=!0));let i=e<=23?1:2;return this.getChannel(i).setBkgData(r),!0}reset(){for(let e=0;e<Object.keys(this.channels).length;e++){let t=this.channels[e];t&&t.reset()}em(null,null,this.cmdHistory)}cueSplitAtTime(e){for(let t=0;t<this.channels.length;t++){let n=this.channels[t];n&&n.cueSplitAtTime(e)}}};function em(e,t,n){n.a=e,n.b=t}function tm(e,t,n){return n.a===e&&n.b===t}function nm(){return{a:null,b:null}}var rm=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,n){(this.startTime===null||this.startTime>e)&&(this.startTime=e),this.endTime=t,this.screen=n,this.timelineController.createCaptionsTrack(this.trackName)}reset(){this.cueRanges=[],this.startTime=null}},im=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=om(),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(L.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(L.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(L.MANIFEST_LOADING,this.onManifestLoading,this),e.on(L.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(L.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(L.FRAG_LOADING,this.onFragLoading,this),e.on(L.FRAG_LOADED,this.onFragLoaded,this),e.on(L.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.on(L.FRAG_DECRYPTED,this.onFragDecrypted,this),e.on(L.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(L.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.on(L.BUFFER_APPENDED,this.onBufferAppended,this),e.on(L.BUFFER_FLUSHING,this.onBufferFlushing,this)}destroy(){let{hls:e}=this;e.off(L.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(L.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(L.MANIFEST_LOADING,this.onManifestLoading,this),e.off(L.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(L.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(L.FRAG_LOADING,this.onFragLoading,this),e.off(L.FRAG_LOADED,this.onFragLoaded,this),e.off(L.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.off(L.FRAG_DECRYPTED,this.onFragDecrypted,this),e.off(L.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(L.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.off(L.BUFFER_APPENDED,this.onBufferAppended,this),e.off(L.BUFFER_FLUSHING,this.onBufferFlushing,this),this.hls=this.config=this.media=null,this.cea608Parser1=this.cea608Parser2=void 0}initCea608Parsers(){let e=new rm(this,`textTrack1`),t=new rm(this,`textTrack2`),n=new rm(this,`textTrack3`),r=new rm(this,`textTrack4`);this.cea608Parser1=new $p(1,e,t),this.cea608Parser2=new $p(3,n,r)}addCues(e,t,n,r,i){let a=!1;for(let e=i.length;e--;){let r=i[e],o=am(r[0],r[1],t,n);if(o>=0&&(r[0]=Math.min(r[0],t),r[1]=Math.max(r[1],n),a=!0,o/(n-t)>.5))return}if(a||i.push([t,n]),this.config.renderTextTracksNatively){let i=this.cueCache[e];if(i){let e=this.Cues.newCue(null,t,n,r);e.length&&i.push.apply(i,e)}else{let i=this.captionsTracks[e].track;this.Cues.newCue(i,t,n,r)}}else{let i=this.Cues.newCue(null,t,n,r),a=this.captionsProperties[e]?.media;this.hls.trigger(L.CUES_PARSED,{type:`captions`,cues:i,track:e,closedCaptions:a})}}onInitPtsFound(e,{id:t,timestampOffsets:n}){let{unparsedFrags:r}=this;t===z.MAIN&&(this.initPTS=n),r.length&&(this.unparsedFrags=[],r.forEach(e=>{this.initPTS[e.frag.cc]?this.onFragLoaded(L.FRAG_LOADED,e):this.hls.trigger(L.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:e.frag,part:null,error: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:n,cueCache:r,media:i}=this,{label:a,languageCode:o}=t[e];i&&(r[e]=[],n[e]=jf(i,`captions`,a,o,`hidden`))}createNonNativeTrack(e){if(this.nonNativeCaptionsTracks[e])return;let t=this.captionsProperties[e];if(!t)return;let n={_id:e,label:t.label,kind:`captions`,default:t.media?!!t.media.default:!1,closedCaptions:t.media};this.nonNativeCaptionsTracks[e]=n,this.hls.trigger(L.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:[n]})}onMediaAttaching(e,t){this.media=t.media}onMediaDetaching(e,t){let n=!!t.transferMedia;if(this.media=null,!n){if(this.config.renderTextTracksNatively){let{captionsTracks:e,cueCache:t}=this;for(let n in e)e[n].remove(),delete t[n]}this.cueCache={},this.captionsTracks={},this.nonNativeCaptionsTracks={}}}onManifestLoading(){this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs=om(),this.tracks=[],this.captionsTracks={},this.nonNativeCaptionsTracks={},this.unparsedFrags=[],this.initPTS=[],this.cea608Parser1&&this.cea608Parser2&&(this.cea608Parser1.reset(),this.cea608Parser2.reset())}onSubtitleTracksUpdated(e,t){let n=t.subtitleTracks||[];if(n.length&&!this.config.renderTextTracksNatively&&!Nl(this.tracks,n)){let e=n.map(e=>({label:e.name,kind:e.type.toLowerCase(),default:e.default,subtitleTrack:e}));this.hls.trigger(L.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:e})}this.tracks=n}onManifestLoaded(e,t){this.config.enableCEA708Captions&&t.captions&&t.captions.forEach(e=>{let t=/(?:CC|SERVICE)([1-4])/.exec(e.instreamId);if(!t)return;let n=`textTrack${t[1]}`,r=this.captionsProperties[n];r&&(r.label=e.name,e.lang&&(r.languageCode=e.lang),r.media=e)})}closedCaptionsForLevel(e){return this.hls.levels[e.level]?.attrs[`CLOSED-CAPTIONS`]}onFragLoading(e,t){if(this.enabled&&t.frag.type===z.MAIN){let{cea608Parser1:e,cea608Parser2:n,lastSn:r}=this,{cc:i,sn:a}=t.frag,o=t.part?.index??-1;e&&n&&(a!==r+1||a===r&&o!==this.lastPartIndex+1||i!==this.lastCc)&&(e.reset(),n.reset()),this.lastCc=i,this.lastSn=a,this.lastPartIndex=o}}onFragLoaded(e,t){let{frag:n,payload:r}=t;if(n.level<this.tracks.length&&n.type===z.SUBTITLE){var i;if(r.byteLength||(i=n.initSegment)!=null&&(i=i.data)!=null&&i.byteLength){let e=n.decryptdata,r=`stats`in t;if(e==null||!e.encrypted||r){let e=this.tracks[n.level],r=this.vttCCs;r[n.cc]||(r[n.cc]={start:n.start,prevCC:this.prevCC,new:!0},this.prevCC=n.cc),e?.textCodec===hf?this._parseIMSC1(t):this._parseVTTs(t)}}else{let e=`part`in t?t.part:null;this.hls.trigger(L.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:n,part:e,error:Error(`Empty subtitle payload`)})}}}_parseIMSC1(e){let{frag:t,payload:n}=e,r=`part`in e?e.part:null;if(!this.initPTS[t.cc]){this.unparsedFrags.push(e);return}let i=this.hls;yf(n,this.initPTS[t.cc],e=>{this._appendCues(e,t.level),i.trigger(L.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:t,part:r})},e=>{i.logger.log(`Cannot parse IMSC1 (sn: ${t.sn} @${t.start}): ${e}`),i.trigger(L.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:t,part:r,error:e})})}_parseVTTs(e){let{frag:t,payload:n}=e,r=`part`in e?e.part:null,{initPTS:i,unparsedFrags:a}=this,o=i.length-1;if(!i[t.cc]&&o===-1){a.push(e);return}let s=this.hls,c=t.initSegment?.data;mf(c?Tr(c,new Uint8Array(n)).buffer:n,this.initPTS[t.cc],this.vttCCs,t.cc,(r&&!c?r:t).start,e=>{this._appendCues(e,t.level),s.trigger(L.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:t,part:r})},n=>{let i=n.message.startsWith(`Missing initPTS`);if(s.logger.log(`${i?`Deferred parsing of`:`Cannot parse`} VTT cue (sn: ${t.sn} @${t.start}): ${n}`),i){a.push(e);return}this.config.enableIMSC1&&this._fallbackToIMSC1(e),s.trigger(L.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:t,part:r,error:n})})}_fallbackToIMSC1(e){let{frag:t,payload:n}=e,r=this.tracks[t.level];r.textCodec||yf(n,this.initPTS[t.cc],()=>{r.textCodec=hf,this._parseIMSC1(e)},()=>{r.textCodec=`wvtt`})}_appendCues(e,t){let n=this.hls;if(this.config.renderTextTracksNatively){let n=this.tracks[t].trackNode?.track;if(!n||n.mode===`disabled`)return;e.forEach(e=>Nf(n,e))}else{let r=this.tracks[t];if(!r)return;let i=r.default?`default`:`subtitles`+t;n.trigger(L.CUES_PARSED,{type:`subtitles`,cues:e,track:i,subtitleTrack:r})}}onFragDecrypted(e,t){let{frag:n}=t;n.type===z.SUBTITLE&&this.onFragLoaded(L.FRAG_LOADED,t)}onSubtitleTracksCleared(){this.tracks=[],this.captionsTracks={}}onFragParsingUserdata(e,t){if(!this.enabled||!this.config.enableCEA708Captions)return;let{frag:n,samples:r}=t;if(n.type!==z.MAIN||this.closedCaptionsForLevel(n)!==`NONE`)for(let e=0;e<r.length;e++){let t=r[e].bytes;if(t){this.cea608Parser1||this.initCea608Parsers();let n=this.extractCea608Data(t);this.cea608Parser1.addData(r[e].pts,n[0]),this.cea608Parser2.addData(r[e].pts,n[1])}}}onBufferAppended(e,t){if(this.config.renderTextTracksNatively){var n;let{type:e,timeRanges:r}=t;if(e===`video`&&(n=r[e])!=null&&n.length){let{captionsTracks:e,cueCache:t}=this;Object.keys(t).forEach(n=>{let r=e[n]?.track;if(r){let e=t[n];for(let t=0;t<e.length;t++)Nf(r,e[t])}delete t[n]})}}}onBufferFlushing(e,t){let{startOffset:n,endOffset:r,endOffsetSubtitles:i,type:a}=t,{media:o}=this;if(!(!o||o.currentTime<r)){if(!a||a===`video`){let{captionsTracks:e,cueCache:t}=this;Object.keys(e).forEach(t=>Pf(e[t].track,n,r)),Object.keys(t).forEach(e=>{let i=t[e];for(let e=i.length;e--;){let t=i[e];t.startTime>=n&&t.endTime<=r&&i.splice(e,1)}})}this.config.renderTextTracksNatively&&n===0&&i!==void 0&&this.tracks.forEach(e=>{let t=e.trackNode?.track;t&&Pf(t,n,i)})}}extractCea608Data(e){let t=[[],[]],n=e[0]&31,r=2;for(let i=0;i<n;i++){let n=e[r++],i=127&e[r++],a=127&e[r++];if((i!==0||a!==0)&&4&n){let e=3&n;(e===0||e===1)&&(t[e].push(i),t[e].push(a))}}return t}};function am(e,t,n,r){return Math.min(t,r)-Math.max(e,n)}function om(){return{ccOffset:0,presentationOffset:0,0:{start:0,prevCC:-1,new:!0}}}var sm=/\s/,cm={newCue(e,t,n,r){let i=[],a,o,s,c,l,u=self.VTTCue||self.TextTrackCue;for(let f=0;f<r.rows.length;f++)if(a=r.rows[f],s=!0,c=0,l=``,!a.isEmpty()){var d;for(let e=0;e<a.chars.length;e++)sm.test(a.chars[e].uchar)&&s?c++:(l+=a.chars[e].uchar,s=!1);a.cueStartTime=t,t===n&&(n+=1e-4),c>=16?c--:c++;let r=cf(l.trim()),p=pf(t,n,r);e!=null&&(d=e.cues)!=null&&d.getCueById(p)||(o=new u(t,n,r),o.id=p,o.line=f+1,o.align=`left`,o.position=10+Math.min(80,Math.floor(c*8/32)*10),i.push(o))}return e&&i.length&&(i.sort((e,t)=>e.line===`auto`||t.line===`auto`?0:e.line>8&&t.line>8?t.line-e.line:e.line-t.line),i.forEach(t=>Nf(e,t))),i}},lm=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 Ct}destroy(){this.callbacks=this.context=this.config=null,this.abortInternal(),this.stats=null}load(e,t,n){let r=this.stats;if(r.loading.start)throw Error(`Loader can only be used once.`);r.loading.start=self.performance.now(),this.context=e,this.config=t,this.callbacks=n,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(Wt(e,t,!0))this.retry(e);else{U.warn(`timeout while loading ${this.context?.url}`);let e=this.callbacks;e&&(this.abortInternal(),e.onTimeout(this.stats,this.context,this.getNetworkDetails()))}}retry(e){let{context:t,stats:n}=this;this.retryDelay=Ht(e,n.retry),n.retry++,U.warn(`${status?`HTTP Status `+status:`Timeout`} while loading ${t?.url}, retrying ${n.retry}/${e.maxNumRetry} in ${this.retryDelay}ms`),this.abortInternal(),this.resetInternalLoader(),self.clearTimeout(this.retryTimeout),this.retryTimeout=self.setTimeout(()=>this.loadInternal(),this.retryDelay)}};function um(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch{}return!1}var dm=/(\d+)-(\d+)\/(\d+)/,fm=class extends lm{constructor(e){super(),this.fetchSetup=void 0,this.request=null,this.response=null,this.controller=null,this.fetchSetup=e.fetchSetup||gm}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:n}=this;if(!e||!t)return;n.loading.first=0,n.loaded=0,n.aborted=!1,this.controller=new self.AbortController;let r=pm(t,this.controller.signal),i=t.responseType===`arraybuffer`,a=i?`byteLength`:`length`,{maxTimeToFirstByteMs:o,maxLoadTimeMs:s}=e.loadPolicy;this.request=this.fetchSetup(t,r),self.clearTimeout(this.requestTimeout),e.timeout=o&&P(o)?o:s,this.requestTimeout=self.setTimeout(()=>{this.loadtimeout()},e.timeout),(Tl(this.request)?this.request.then(self.fetch):self.fetch(this.request)).then(r=>{this.response=r;let a=Math.max(self.performance.now(),n.loading.start);if(self.clearTimeout(this.requestTimeout),e.timeout=s,this.requestTimeout=self.setTimeout(()=>{this.loadtimeout()},s-(a-n.loading.start)),!r.ok){let{status:e,statusText:t}=r;throw new _m(t||`fetch, bad network response`,e,r)}n.loading.first=a,n.total=hm(r.headers)||n.total;let o=this.callbacks?.onProgress;return o&&P(e.highWaterMark)?this.loadProgressively(r,n,t,e.highWaterMark,o):i?r.arrayBuffer():t.responseType===`json`?r.json():r.text()}).then(r=>{var i;let o=this.response;if(!o)throw Error(`loader destroyed`);self.clearTimeout(this.requestTimeout),n.loading.end=Math.max(self.performance.now(),n.loading.first);let s=r[a];s&&(n.loaded=n.total=s);let c={url:o.url,data:r,code:o.status},l=this.callbacks?.onProgress;l&&!P(e.highWaterMark)&&l(n,t,r,o),(i=this.callbacks)==null||i.onSuccess(c,n,t,o)}).catch(r=>{if(self.clearTimeout(this.requestTimeout),n.aborted)return;let i=r&&r.code||0,a=r?r.message:null,o=e.loadPolicy.errorRetry,s=n.retry;if(Wt(o,s,!1,{url:t.url,data:void 0,code:i}))this.retry(o);else{var c;U.error(`${i} while loading ${t.url}`),(c=this.callbacks)==null||c.onError({code:i,text:a},t,r?r.details:null,n)}})}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,n,r=0,i){let a=new ks,o=e.body.getReader(),s=()=>o.read().then(o=>{if(o.done)return a.dataLength&&i(t,n,a.flush().buffer,e),Promise.resolve(new ArrayBuffer(0));let c=o.value,l=c.length;return t.loaded+=l,l<r||a.dataLength?(a.push(c),a.dataLength>=r&&i(t,n,a.flush().buffer,e)):i(t,n,c.buffer,e),s()}).catch(()=>Promise.reject());return s()}};function pm(e,t){let n={method:`GET`,mode:`cors`,credentials:`same-origin`,signal:t,headers:new self.Headers(V({},e.headers))};return e.rangeEnd&&n.headers.set(`Range`,`bytes=`+e.rangeStart+`-`+String(e.rangeEnd-1)),n}function mm(e){let t=dm.exec(e);if(t)return parseInt(t[2])-parseInt(t[1])+1}function hm(e){let t=e.get(`Content-Range`);if(t){let e=mm(t);if(P(e))return e}let n=e.get(`Content-Length`);if(n)return parseInt(n)}function gm(e,t){return new self.Request(e.url,t)}var _m=class extends Error{constructor(e,t,n){super(e),this.code=void 0,this.details=void 0,this.code=t,this.details=n}},vm=(e,t,n)=>Math.max(t,Math.min(e,n)),ym=/^age:\s*[\d.]+\s*$/im,bm=class extends lm{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 n=this.loader=new self.XMLHttpRequest,r=this.stats;r.loading.first=0,r.loaded=0,r.aborted=!1;let i=this.xhrSetup;i?Promise.resolve().then(()=>{if(!(this.loader!==n||this.stats.aborted))return i.call(this,n,t.url,t)}).catch(e=>{if(!(this.loader!==n||this.stats.aborted))return n.open(`GET`,t.url,!0),i.call(this,n,t.url,t)}).then(()=>{this.loader!==n||this.stats.aborted||this.openAndSendXhr(n,t,e)}).catch(e=>{var i;(i=this.callbacks)==null||i.onError({code:n.status,text:e.message},t,n,r)}):this.openAndSendXhr(n,t,e)}openAndSendXhr(e,t,n){e.readyState||e.open(`GET`,t.url,!0);let r=t.headers,{maxTimeToFirstByteMs:i,maxLoadTimeMs:a}=n.loadPolicy;if(r)for(let t in r)e.setRequestHeader(t,r[t]);t.rangeEnd&&e.setRequestHeader(`Range`,`bytes=${t.rangeStart}-${t.rangeEnd-1}`),e.onreadystatechange=this.readystatechange.bind(this),e.onprogress=this.loadprogress.bind(this),e.responseType=t.responseType,self.clearTimeout(this.requestTimeout),n.timeout=i&&P(i)?i:a,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),n.timeout),e.send()}readystatechange(){let{context:e,loader:t,stats:n}=this;if(!e||!t)return;let r=t.readyState,i=this.config;if(!n.aborted&&r>=2&&(n.loading.first===0&&(n.loading.first=Math.max(self.performance.now(),n.loading.start),i.timeout!==i.loadPolicy.maxLoadTimeMs&&(self.clearTimeout(this.requestTimeout),i.timeout=i.loadPolicy.maxLoadTimeMs,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),i.loadPolicy.maxLoadTimeMs-(n.loading.first-n.loading.start)))),r===4)){self.clearTimeout(this.requestTimeout),t.onreadystatechange=null,t.onprogress=null;let r=t.status,s=t.responseType===`text`?t.responseText:null;if(r>=200&&r<300){let i=s??t.response;if(i!=null){var a;n.loading.end=Math.max(self.performance.now(),n.loading.first);let o=t.responseType===`arraybuffer`?i.byteLength:i.length;n.loaded=n.total=o,n.bwEstimate=n.total*8e3/(n.loading.end-n.loading.first);let s=this.callbacks?.onProgress;s&&s(n,e,i,t);let c={url:t.responseURL,data:i,code:r};e.rangeEnd&&o!==e.rangeEnd-e.rangeStart&&U.warn(`Payload length ${o} does not match requested Range: bytes=${e.rangeStart}-${e.rangeEnd-1}`),(a=this.callbacks)==null||a.onSuccess(c,n,e,t);return}}let c=i.loadPolicy.errorRetry,l=n.retry;if(Wt(c,l,!1,{url:e.url,data:void 0,code:r}))this.retry(c);else{var o;U.error(`${r} while loading ${e.url}`),(o=this.callbacks)==null||o.onError({code:r,text:t.statusText},e,t,n)}}}loadprogress(e){let t=this.stats;t.loaded=e.loaded,e.lengthComputable&&(t.total=e.total)}getCacheAge(){let e=null;if(this.loader&&ym.test(this.loader.getAllResponseHeaders())){let t=this.loader.getResponseHeader(`age`);e=t?parseFloat(t):null}return e}getResponseHeader(e){return this.loader&&RegExp(`^${e}:\\s*[\\d.]+\\s*$`,`im`).test(this.loader.getAllResponseHeaders())?this.loader.getResponseHeader(e):null}},xm=H(H({autoStartLoad:!0,startPosition:-1,defaultAudioCodec:void 0,debug:!1,capLevelOnFPSDrop:!1,capLevelToPlayerSize:!1,ignoreDevicePixelRatio:!1,maxDevicePixelRatio:1/0,preferManagedMediaSource:!1,initialLiveManifestSize:1,maxBufferLength:30,backBufferLength:1/0,frontBufferFlushThreshold:1/0,loopBackBufferFlush:void 0,startOnSegmentBoundary:!1,nextAudioTrackBufferFlushForwardOffset:.25,maxBufferSize:6e7,maxFragLookUpTolerance:.25,maxBufferHole:.1,detectStallWithCurrentTimeMs:1250,highBufferWatchdogPeriod:2,nudgeOffset:.1,nudgeMaxRetry:3,nudgeOnVideoHole:!0,skipBufferHolePadding:.1,liveSyncMode:`edge`,liveSyncDurationCount:3,liveSyncOnStallIncrease:1,liveMaxLatencyDurationCount:1/0,liveMaxUnchangedPlaylistRefresh:1/0,liveSyncDuration:void 0,liveMaxLatencyDuration:void 0,maxLiveSyncPlaybackRate:1,liveDurationInfinity:!1,liveBackBufferLength:null,maxMaxBufferLength:600,enableWorker:!0,workerPath:null,enableSoftwareAES:!0,startLevel:void 0,startFragPrefetch:!1,fpsDroppedMonitoringPeriod:5e3,fpsDroppedMonitoringThreshold:.2,appendErrorMaxRetry:3,appendTimeout:1/0,ignorePlaylistParsingErrors:!1,loader:bm,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:Do,requireKeySystemAccessOnStart:!1,reuseKeySessions:!1,testBandwidth:!0,progressive:!1,lowLatencyMode:!0,cmcd:void 0,enableDateRangeMetadataCues:!0,enableEmsgMetadataCues:!0,enableEmsgKLVMetadata:!1,enableID3MetadataCues:!0,emsgKLVSchemaUri:void 0,enableInterstitialPlayback:!0,interstitialAppendInPlace:!0,interstitialLiveLookAhead:10,iframeCacheLimit:2097152,useMediaCapabilities:!0,preserveManualLevelOnError:!1,errorPenaltyExpireMs:0,certLoadPolicy:{default:{maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:null,errorRetry:null}},keyLoadPolicy:{default:{maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:2e4,backoff:`linear`},errorRetry:{maxNumRetry:8,retryDelayMs:1e3,maxRetryDelayMs:2e4,backoff:`linear`}}},manifestLoadPolicy:{default:{maxTimeToFirstByteMs:1/0,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},playlistLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:2,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},fragLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:12e4,timeoutRetry:{maxNumRetry:4,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:6,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},steeringManifestLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},interstitialAssetListLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:3e4,timeoutRetry:{maxNumRetry:0,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:0,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},manifestLoadingTimeOut:1e4,manifestLoadingMaxRetry:1,manifestLoadingRetryDelay:1e3,manifestLoadingMaxRetryTimeout:64e3,levelLoadingTimeOut:1e4,levelLoadingMaxRetry:4,levelLoadingRetryDelay:1e3,levelLoadingMaxRetryTimeout:64e3,fragLoadingTimeOut:2e4,fragLoadingMaxRetry:6,fragLoadingRetryDelay:1e3,fragLoadingMaxRetryTimeout:64e3,streamController:np,abrController:Qi,bufferController:wa,capLevelController:Il,errorController:ua,fpsController:Qd,id3TrackController:Yf,gapController:Bf,latencyController:jp},Sm()),{},{subtitleStreamController:Pp,subtitleTrackController:Lf,timelineController:im,audioStreamController:jl,audioTrackController:Fl,emeController:Kd,cmcdController:zd,contentSteeringController:Vd,iframeController:up,interstitialsController:Ap});function Sm(){return{cueHandler:cm,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 Cm(e,t,n){if((t.liveSyncDurationCount||t.liveMaxLatencyDurationCount)&&(t.liveSyncDuration||t.liveMaxLatencyDuration))throw Error(`Illegal hls.js config: don't mix up liveSyncDurationCount/liveMaxLatencyDurationCount and liveSyncDuration/liveMaxLatencyDuration`);if(t.liveMaxLatencyDurationCount!==void 0&&(t.liveSyncDurationCount===void 0||t.liveMaxLatencyDurationCount<=t.liveSyncDurationCount))throw Error(`Illegal hls.js config: "liveMaxLatencyDurationCount" must be greater than "liveSyncDurationCount"`);if(t.liveMaxLatencyDuration!==void 0&&(t.liveSyncDuration===void 0||t.liveMaxLatencyDuration<=t.liveSyncDuration))throw Error(`Illegal hls.js config: "liveMaxLatencyDuration" must be greater than "liveSyncDuration"`);if(t.liveMaxUnchangedPlaylistRefresh!==void 0){let e=t.liveMaxUnchangedPlaylistRefresh,r=vm(e,2,1/0);r!==e&&n.warn(`hls.js config: "liveMaxUnchangedPlaylistRefresh" clamped from ${e} to ${r}.`),t.liveMaxUnchangedPlaylistRefresh=r}let r=wm(e),i=[`manifest`,`level`,`frag`],a=[`TimeOut`,`MaxRetry`,`RetryDelay`,`MaxRetryTimeout`];return i.forEach(e=>{let i=`${e===`level`?`playlist`:e}LoadPolicy`,o=t[i]===void 0,s=[];a.forEach(n=>{let a=`${e}Loading${n}`,c=t[a];if(c!==void 0&&o){s.push(a);let e=r[i].default;switch(t[i]={default:e},n){case`TimeOut`:e.maxLoadTimeMs=c,e.maxTimeToFirstByteMs=c;break;case`MaxRetry`:e.errorRetry.maxNumRetry=c,e.timeoutRetry.maxNumRetry=c;break;case`RetryDelay`:e.errorRetry.retryDelayMs=c,e.timeoutRetry.retryDelayMs=c;break;case`MaxRetryTimeout`:e.errorRetry.maxRetryDelayMs=c,e.timeoutRetry.maxRetryDelayMs=c}}}),s.length&&n.warn(`hls.js config: "${s.join(`", "`)}" setting(s) are deprecated, use "${i}": ${q(t[i])}`)}),H(H({},r),t)}function wm(e){return e&&typeof e==`object`?Array.isArray(e)?e.map(wm):Object.keys(e).reduce((t,n)=>(t[n]=wm(e[n]),t),{}):e}function Tm(e,t){let n=e.loader;n!==fm&&n!==bm?(t.log(`[config]: Custom loader detected, cannot enable progressive streaming`),e.progressive=!1):um()&&(e.loader=fm,e.progressive=!0,e.enableSoftwareAES=!0,t.log(`[config]: Progressive streaming enabled, using FetchLoader`))}var Em=class extends Ml{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(L.MANIFEST_LOADING,this.onManifestLoading,this),e.on(L.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(L.LEVEL_LOADED,this.onLevelLoaded,this),e.on(L.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(L.FRAG_BUFFERED,this.onFragBuffered,this),e.on(L.ERROR,this.onError,this)}_unregisterListeners(){let{hls:e}=this;e.off(L.MANIFEST_LOADING,this.onManifestLoading,this),e.off(L.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(L.LEVEL_LOADED,this.onLevelLoaded,this),e.off(L.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(L.FRAG_BUFFERED,this.onFragBuffered,this),e.off(L.ERROR,this.onError,this)}destroy(){this._unregisterListeners(),this.steering=null,this.resetLevels(),super.destroy()}stopLoad(){this._levels.forEach(e=>{e.loadError=0,e.fragmentError=0}),super.stopLoad()}resetLevels(){this._startLevel=void 0,this.manualLevelIndex=-1,this.currentLevelIndex=-1,this.currentLevel=null,this._levels=[],this._maxAutoLevel=-1,this._iframeVariants=[]}onManifestLoading(e,t){this.resetLevels()}onManifestLoaded(e,t){let n=this.hls.config.preferManagedMediaSource,r=[],i={},a={},o=!1,s=!1,c=!1,l=!1;t.levels.forEach(e=>{let t=e.attrs,u=km(e,n),{audioCodec:d,videoCodec:f,imageCodec:p,width:m,height:h}=e;if(!u){this.log(`Some or all CODECS not supported "${t.CODECS}"`);return}o||=!!(m&&h),s||=!!f,c||=!!d,l||=!!p;let{CODECS:g,"FRAME-RATE":_,"HDCP-LEVEL":v,"PATHWAY-ID":y,RESOLUTION:b,"VIDEO-RANGE":x}=t,S=`${`${y||`.`}-`}${e.bitrate}-${b}-${_}-${g}-${x}-${v}`;if(!i[S]){let t=this.createLevel(e);i[S]=t,a[S]=1,r.push(t)}else if(i[S].uri!==e.url&&!e.attrs[`PATHWAY-ID`]){let t=a[S]+=1;e.attrs[`PATHWAY-ID`]=Array(t+1).join(`.`);let n=this.createLevel(e);i[S]=n,r.push(n)}else e.iframes||(i[S].addGroupId(`audio`,t.AUDIO),i[S].addGroupId(`text`,t.SUBTITLES))}),this.filterAndSortMediaOptions(r,t,o,s,c,l)}createLevel(e){let t=new Mi(e),n=e.supplemental;if(n!=null&&n.videoCodec&&!Om(n.videoCodec,this.hls.config.preferManagedMediaSource)){let e=Error(`SUPPLEMENTAL-CODECS not supported "${n.videoCodec}"`);this.log(e.message),t.supportedResult=gi(e,[])}return t}filterAndSortMediaOptions(e,t,n,r,i,a){let o=[],s=[],c=e,l=t.stats?.parsing||{},u=this.hls.config.preferManagedMediaSource;if((n||r)&&i&&(c=c.filter(({videoCodec:e,videoRange:t,width:n,height:r})=>(!!e||!!(n&&r))&&Oi(t))),r&&a&&(c=c.filter(e=>!e.imageCodec)),c.length===0){Promise.resolve().then(()=>{if(this.hls){let e=`no level with compatible codecs found in manifest`,n=e;t.levels.length&&(n=`one or more CODECS in variant not supported: ${q(t.levels.map(e=>e.attrs.CODECS).filter((e,t,n)=>n.indexOf(e)===t))}`,this.warn(n),e+=` (${n})`);let r=Error(e);this.hls.trigger(L.ERROR,{type:F.MEDIA_ERROR,details:I.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:t.url,error:r,reason:n})}}),l.end=performance.now();return}t.audioTracks&&(o=t.audioTracks.filter(e=>!e.audioCodec||Dm(e.audioCodec,u)),Am(o)),t.subtitles&&(s=t.subtitles,Am(s));let d=c.slice(0);c.sort((e,t)=>{if(e.attrs[`HDCP-LEVEL`]!==t.attrs[`HDCP-LEVEL`])return(e.attrs[`HDCP-LEVEL`]||``)>(t.attrs[`HDCP-LEVEL`]||``)?1:-1;if(n&&e.height!==t.height)return e.height-t.height;if(e.frameRate!==t.frameRate)return e.frameRate-t.frameRate;if(e.videoRange!==t.videoRange)return Di.indexOf(e.videoRange)-Di.indexOf(t.videoRange);if(e.videoCodec!==t.videoCodec){let n=ei(e.videoCodec),r=ei(t.videoCodec);if(n!==r)return r-n}if(e.uri===t.uri&&e.codecSet!==t.codecSet){let n=ti(e.codecSet),r=ti(t.codecSet);if(n!==r)return r-n}return e.averageBitrate===t.averageBitrate?0:e.averageBitrate-t.averageBitrate});let f=d[0];if(this.steering&&(c=this.steering.filterParsedLevels(c),c.length!==d.length)){for(let e=0;e<d.length;e++)if(d[e].pathwayId===c[0].pathwayId){f=d[e];break}}this._levels=c;for(let e=0;e<c.length;e++)if(c[e]===f){this._firstLevel=e;let t=f.bitrate,n=this.hls.bandwidthEstimate;if(this.log(`manifest loaded, ${c.length} level(s) found, first bitrate: ${t}`),this.hls.userConfig?.abrEwmaDefaultEstimate===void 0){let e=Math.min(t,this.hls.config.abrEwmaDefaultEstimateMax);e>n&&n===this.hls.abrEwmaDefaultEstimate&&(this.hls.bandwidthEstimate=e)}break}let p=t.iframeVariants.filter(e=>km(e,u));this._iframeVariants=p;let m=i&&!r,h=this.hls.config,g=!!(h.audioStreamController&&h.audioTrackController),_={levels:c,audioTracks:o,subtitleTracks:s,iframeVariants:p,sessionData:t.sessionData,sessionKeys:t.sessionKeys,firstLevel:this._firstLevel,stats:t.stats,audio:i,video:r,altAudio:g&&!m&&o.some(e=>!!e.url)};l.end=performance.now(),this.hls.trigger(L.MANIFEST_PARSED,_)}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 n=Error(`invalid level idx`),r=e<0;if(this.hls.trigger(L.ERROR,{type:F.OTHER_ERROR,details:I.LEVEL_SWITCH_ERROR,level:e,fatal:r,error:n,reason:n.message}),r)return;e=Math.min(e,t.length-1)}let n=this.currentLevelIndex,r=this.currentLevel,i=r?r.attrs[`PATHWAY-ID`]:void 0,a=t[e],o=a.attrs[`PATHWAY-ID`];if(this.currentLevelIndex=e,this.currentLevel=a,n===e&&r&&i===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 ${n}${i?` with Pathway `+i:``}`);let s={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(L.LEVEL_SWITCHING,s);let c=a.details;if(!c||c.live){let e=this.switchParams(a.uri,r?.details,c);this.loadPlaylist(e)}}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?this.hls.firstAutoLevel:e}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(),n=e.filter(e=>t.indexOf(e)!==-1);if(e.length<1){this.warn(`pathwayPriority ${e} should contain at least one pathway from list: ${t}`);return}this.steering.pathwayPriority=n}}onError(e,t){!t.fatal&&t.context&&t.context.type===R.LEVEL&&t.context.level===this.level&&this.checkRetry(t)}onFragBuffered(e,{frag:t}){if(t.type===z.MAIN){let e=t.elementaryStreams;if(!Object.keys(e).some(t=>!!e[t]))return;let n=this._levels[t.level];n!=null&&n.loadError&&(this.log(`Resetting level error count of ${n.loadError} on frag buffered`),n.loadError=0)}}onLevelLoaded(e,t){var n;let{level:r,details:i}=t,a=t.levelInfo;if(!a){var o;this.warn(`Invalid level index ${r}`),(o=t.deliveryDirectives)!=null&&o.skip&&(i.deltaUpdateFailed=!0);return}if(a===this.currentLevel||t.withoutMultiVariant){a.fragmentError===0&&(a.loadError=0);let e=a.details;e===t.details&&e.advanced&&(e=void 0),this.playlistLoaded(r,t,e)}else(n=t.deliveryDirectives)!=null&&n.skip&&(i.deltaUpdateFailed=!0)}loadPlaylist(e){super.loadPlaylist(),this.shouldLoadPlaylist(this.currentLevel)&&this.scheduleLoading(this.currentLevel,e)}loadingPlaylist(e,t){super.loadingPlaylist(e,t);let n=this.getUrlWithDirectives(e.uri,t),r=this.currentLevelIndex,i=e.attrs[`PATHWAY-ID`],a=e.details,o=a?.age;this.log(`Loading level index ${r}${t?.msn===void 0?``:` at sn `+t.msn+` part `+t.part}${i?` Pathway `+i:``}${o&&a.live?` age `+o.toFixed(1)+(a.type&&` `+a.type||``):``} ${n}`),this.hls.trigger(L.LEVEL_LOADING,{url:n,level:r,levelInfo:e,pathwayId:e.attrs[`PATHWAY-ID`],id:0,deliveryDirectives:t||null})}get nextLoadLevel(){return this.manualLevelIndex===-1?this.hls.nextAutoLevel:this.manualLevelIndex}set nextLoadLevel(e){let t=this.currentLevelIndex;if(this.manualLevelIndex===-1&&e!==t&&e!==-1){let n=this.hls.config.abrSwitchInterval;if(n>0){let r=performance.now(),i=r-this.lastABRSwitchTime,a=n*1e3;if(this.lastABRSwitchTime>-1&&i<a){this.warn(`Preventing ABR level switch: ${t} -> ${e} (${Math.round(i)}ms < ${a}ms / ${n}s)`);return}this.lastABRSwitchTime=r,this.log(`Allowing ABR level switch: ${t} -> ${e} (${Math.round(i)}ms >= ${a}ms / ${n}s)`)}}this.level=e,this.manualLevelIndex===-1&&(this.hls.nextAutoLevel=e)}removeLevel(e){var t;if(this._levels.length===1)return;let n=this._levels.filter((t,n)=>n!==e||(this.steering&&this.steering.removeLevel(t),t===this.currentLevel&&(this.currentLevel=null,this.currentLevelIndex=-1,t.details&&t.details.fragments.forEach(e=>e.level=-1)),!1));gs(n),this._levels=n,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 r=n.length-1;this._firstLevel=Math.min(this._firstLevel,r),this._startLevel&&=Math.min(this._startLevel,r),this.hls.trigger(L.LEVELS_UPDATED,{levels:n})}onLevelsUpdated(e,{levels:t}){this._levels=t}checkMaxAutoUpdated(){let{autoLevelCapping:e,maxAutoLevel:t,maxHdcpLevel:n}=this.hls;this._maxAutoLevel!==t&&(this._maxAutoLevel=t,this.hls.trigger(L.MAX_AUTO_LEVEL_UPDATED,{autoLevelCapping:e,levels:this.levels,maxAutoLevel:t,minAutoLevel:this.hls.minAutoLevel,maxHdcpLevel:n}))}};function Dm(e,t){return Zr(e,`audio`,t)}function Om(e,t){return Zr(e,`video`,t)}function km(e,t){let{audioCodec:n,videoCodec:r}=e;n&&(e.audioCodec=n=ai(n,t)||void 0),r&&=e.videoCodec=li(r);let{unknownCodecs:i}=e;return!(i?.length||n&&!Dm(n,t)||r&&!Om(r,t))}function Am(e){let t={};e.forEach(e=>{let n=e.groupId||``;e.id=t[n]=t[n]||0,t[n]++})}var jm=class extends Xt{constructor(e,t){super(`key-loader`,t),this.config=void 0,this.keyLoaderInfo={},this.emeController=null,this.config=e}abort(e){for(let t in this.keyLoaderInfo){let n=this.keyLoaderInfo[t].loader;if(n){if(e&&e!==n.context?.frag.type)return;n.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,n){return this.emeController?this.emeController.loadClear(e,t,n):null}load(e,t){return!e.decryptdata&&e.encrypted&&this.emeController&&this.config.emeEnabled?this.emeController.selectKeySystemFormat(e).then(n=>this.loadInternal(e,t,n)):this.loadInternal(e,t)}loadInternal(e,t,n){n&&e.setKeyFormat(n);let r=e.decryptdata;if(!r){let t=Error(n?`Expected frag.decryptdata to be defined after setting format ${n}`:`Missing decryption data on fragment in onKeyLoading (emeEnabled with controller: ${this.emeController&&this.config.emeEnabled})`);return Promise.reject(Mm(e,I.KEY_LOAD_ERROR,t))}let i=e;switch(r.method){case`SAMPLE-AES`:case`SAMPLE-AES-CENC`:case`SAMPLE-AES-CTR`:return r.keyFormat===`identity`?this.loadKeyHTTP(i):t?t.then(()=>this.loadKeyEME(i)):this.loadKeyEME(i);case`AES-128`:case`AES-256`:case`AES-256-CTR`:return this.loadKeyHTTP(i);default:return Promise.reject(Mm(e,I.KEY_LOAD_ERROR,Error(`Key supplied with unsupported METHOD: "${r.method}"`)))}}loadKeyEME(e){if(this.emeController&&this.config.emeEnabled){var t;if(!e.decryptdata.keyId&&(t=e.initSegment)!=null&&t.data){let t=hr(e.initSegment.data);if(t.length){let n=t[0],r=e.decryptdata.uri;if(n.some(e=>e!==0))this.log(`Using keyId found in init segment ${Hn(n)} keyUri: ${r}`),No.setKeyIdForUri(r,n);else{let e=No.addKeyIdForUri(r);this.log(`Patching empty keyId with ${Hn(e)} keyUri: ${r}`),n=e}e.decryptdata.keyId=n}}return this.emeController.loadKey(e).then(()=>({frag:e,keyInfo:{decryptdata:e.decryptdata}}))}return Promise.reject(Mm(e,I.KEY_LOAD_ERROR,Error(`emeEnabled with controller: ${this.emeController&&this.config.emeEnabled})`)))}loadKeyHTTP(e){let t=e.decryptdata,n=t.uri;if(!n)return Promise.reject(Mm(e,I.KEY_LOAD_ERROR,Error(`Invalid key URI: "${n}"`)));let r=this.keyLoaderInfo[n];if(r){if(r.decryptdata.key)return t.key=r.decryptdata.key,r.keyLoadPromise=null,Promise.resolve({frag:e,keyInfo:r});if(r.keyLoadPromise)return r.keyLoadPromise.then(n=>(t.key=r.decryptdata.key,H(H({},n),{},{frag:e})))}this.log(`Loading${t.keyId?` keyId: `+Hn(t.keyId):``} URI: ${t.uri} from ${e.type} ${e.level}`);let i=this.config,a=i.loader,o=new a(i);e.keyLoader=o;let s=this.keyLoaderInfo[n]={decryptdata:t,keyLoadPromise:null,loader:o};return s.keyLoadPromise=new Promise((t,r)=>{let a={type:R.KEY,keyInfo:s,frag:e,responseType:`arraybuffer`,url:n},c=i.keyLoadPolicy.default,l={loadPolicy:c,timeout:c.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0};o.load(a,l,{onSuccess:(e,n,i,a)=>{let{frag:o,keyInfo:s,url:c}=i;if(!o.decryptdata||s!==this.keyLoaderInfo[c])return this.resetLoader(i),r(Mm(o,I.KEY_LOAD_ERROR,Error(`after key load, decryptdata unset or changed`),a));s.decryptdata.key=o.decryptdata.key=new Uint8Array(e.data),o.keyLoader=s.loader=s.keyLoadPromise=null,t({frag:o,keyInfo:s})},onError:(t,i,a,o)=>{this.resetLoader(i),r(Mm(e,I.KEY_LOAD_ERROR,Error(`HTTP Error ${t.code} loading key ${t.text}`),a,H({url:n,data:void 0},t)))},onTimeout:(t,n,i)=>{this.resetLoader(n),r(Mm(e,I.KEY_LOAD_TIMEOUT,Error(`key loading timed out`),i))},onAbort:(t,n,i)=>{this.resetLoader(n),r(Mm(e,I.INTERNAL_ABORTED,Error(`key loading aborted`),i))}})})}resetLoader(e){let{frag:t,keyInfo:n,url:r}=e,i=n.loader;t.keyLoader===i&&(t.keyLoader=n.loader=n.keyLoadPromise=null),delete this.keyLoaderInfo[r],i&&i.destroy()}};function Mm(e,t=I.KEY_LOAD_ERROR,n,r,i){return new Xa({type:F.NETWORK_ERROR,details:t,fatal:!1,frag:e,response:i,error:n,networkDetails:r||null})}function Nm(e){let{type:t}=e;switch(t){case R.AUDIO_TRACK:return z.AUDIO;case R.SUBTITLE_TRACK:return z.SUBTITLE;default:return z.MAIN}}function Pm(e,t){let n=e.url;return(n===void 0||n.indexOf(`data:`)===0)&&(n=t.url),n}var Fm=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(L.MANIFEST_LOADING,this.onManifestLoading,this),e.on(L.LEVEL_LOADING,this.onLevelLoading,this),e.on(L.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.on(L.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),e.on(L.LEVELS_UPDATED,this.onLevelsUpdated,this)}unregisterListeners(){let{hls:e}=this;e.off(L.MANIFEST_LOADING,this.onManifestLoading,this),e.off(L.LEVEL_LOADING,this.onLevelLoading,this),e.off(L.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.off(L.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),e.off(L.LEVELS_UPDATED,this.onLevelsUpdated,this)}createInternalLoader(e){let t=this.hls.config,n=t.pLoader,r=t.loader,i=new(n||r)(t);return this.loaders[e.type]=i,i}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:n}=t;this.variableList=null,this.load({id:null,level:0,responseType:`text`,type:R.MANIFEST,url:n,deliveryDirectives:null,levelOrTrack:null})}onLevelLoading(e,t){let{id:n,level:r,pathwayId:i,url:a,deliveryDirectives:o,levelInfo:s}=t;this.load({id:n,level:r,pathwayId:i,responseType:`text`,type:R.LEVEL,url:a,deliveryDirectives:o,levelOrTrack:s})}onAudioTrackLoading(e,t){let{id:n,groupId:r,url:i,deliveryDirectives:a,track:o}=t;this.load({id:n,groupId:r,level:null,responseType:`text`,type:R.AUDIO_TRACK,url:i,deliveryDirectives:a,levelOrTrack:o})}onSubtitleTrackLoading(e,t){let{id:n,groupId:r,url:i,deliveryDirectives:a,track:o}=t;this.load({id:n,groupId:r,level:null,responseType:`text`,type:R.SUBTITLE_TRACK,url:i,deliveryDirectives:a,levelOrTrack:o})}onLevelsUpdated(e,t){let n=this.loaders[R.LEVEL];if(n){let e=n.context;e&&!t.levels.some(t=>t===e.levelOrTrack)&&(n.abort(),delete this.loaders[R.LEVEL])}}load(e){let t=this.hls.config,n=this.getInternalLoader(e);if(n){let t=this.hls.logger,r=n.context;if(r?.levelOrTrack===e.levelOrTrack&&(r.url===e.url||r.deliveryDirectives&&!e.deliveryDirectives)){r.url===e.url?t.log(`[playlist-loader]: ignore ${e.url} ongoing request`):t.log(`[playlist-loader]: ignore ${e.url} in favor of ${r.url}`);return}t.log(`[playlist-loader]: aborting previous loader for type: ${e.type}`),n.abort()}let r;if(r=e.type===R.MANIFEST?t.manifestLoadPolicy.default:V({},t.playlistLoadPolicy.default,{timeoutRetry:null,errorRetry:null}),n=this.createInternalLoader(e),P(e.deliveryDirectives?.part)){let t;if(e.type===R.LEVEL&&e.level!==null?t=this.hls.levels[e.level].details:e.type===R.AUDIO_TRACK&&e.id!==null?t=this.hls.audioTracks[e.id].details:e.type===R.SUBTITLE_TRACK&&e.id!==null&&(t=this.hls.subtitleTracks[e.id].details),t){let e=t.partTarget,n=t.targetduration;if(e&&n){let t=Math.max(e*3,n*.8)*1e3;r=V({},r,{maxTimeToFirstByteMs:Math.min(t,r.maxTimeToFirstByteMs),maxLoadTimeMs:Math.min(t,r.maxTimeToFirstByteMs)})}}}let i=r.errorRetry||r.timeoutRetry||{},a={loadPolicy:r,timeout:r.maxLoadTimeMs,maxRetry:i.maxNumRetry||0,retryDelay:i.retryDelayMs||0,maxRetryDelay:i.maxRetryDelayMs||0};n.load(e,a,{onSuccess:(e,t,n,r)=>{let i=this.getInternalLoader(n);this.resetInternalLoader(n.type);let a=e.data;t.parsing.start=performance.now(),Ho.isMediaPlaylist(a)||n.type!==R.MANIFEST?this.handleTrackOrLevelPlaylist(e,t,n,r||null,i):this.handleMasterPlaylist(e,t,n,r)},onError:(e,t,n,r)=>{this.handleNetworkError(t,n,!1,e,r)},onTimeout:(e,t,n)=>{this.handleNetworkError(t,n,!0,void 0,e)}})}checkAutostartLoad(){if(!this.hls)return;let{config:{autoStartLoad:e,startPosition:t},forceStartLoad:n}=this.hls;(e||n)&&(this.hls.logger.log(`${e?`auto`:`force`} startLoad with configured startPosition ${t}`),this.hls.startLoad(t))}handleMasterPlaylist(e,t,n,r){let i=this.hls,a=e.data,o=Pm(e,n),s=Ho.parseMasterPlaylist(a,o);if(s.playlistParsingError){t.parsing.end=performance.now(),this.handleManifestParsingError(e,n,s.playlistParsingError,r,t);return}let{contentSteering:c,levels:l,iframeVariants:u,sessionData:d,sessionKeys:f,startTimeOffset:p,variableList:m}=s;this.variableList=m,l.forEach(e=>{let{unknownCodecs:t}=e;if(t){let{preferManagedMediaSource:n}=this.hls.config,{audioCodec:r,videoCodec:i}=e;for(let a=t.length;a--;){let o=t[a];Zr(o,`audio`,n)?(e.audioCodec=r=r?`${r},${o}`:o,Yr.audio[r.substring(0,4)]=2,t.splice(a,1)):Zr(o,`video`,n)&&(e.videoCodec=i=i?`${i},${o}`:o,Yr.video[i.substring(0,4)]=2,t.splice(a,1))}}});let{AUDIO:h=[],SUBTITLES:g,"CLOSED-CAPTIONS":_}=Ho.parseMasterPlaylistMedia(a,o,s);h.length&&!h.some(e=>!e.url)&&l[0].audioCodec&&!l[0].attrs.AUDIO&&(this.hls.logger.log(`[playlist-loader]: audio codec signaled in quality level, but no embedded audio track signaled, create one`),h.unshift({type:`main`,name:`main`,groupId:`main`,default:!1,autoselect:!1,forced:!1,id:-1,attrs:new so({}),bitrate:0,url:``})),i.trigger(L.MANIFEST_LOADED,{levels:l,audioTracks:h,subtitles:g,iframeVariants:u,captions:_,contentSteering:c,url:o,stats:t,networkDetails:r,sessionData:d,sessionKeys:f,startTimeOffset:p,variableList:m})}handleTrackOrLevelPlaylist(e,t,n,r,i){let a=this.hls,{id:o,level:s,type:c}=n,l=Pm(e,n),u=P(s)?s:P(o)?o:0,d=Nm(n),f=Ho.parseLevelPlaylist(e.data,l,u,d,0,this.variableList);if(c===R.MANIFEST){let e={attrs:new so({}),bitrate:0,details:f,name:``,url:l};f.requestScheduled=t.loading.start+fs(f,0),a.trigger(L.MANIFEST_LOADED,{levels:[e],audioTracks:[],iframeVariants:[],url:l,stats:t,networkDetails:r,sessionData:null,sessionKeys:null,contentSteering:null,startTimeOffset:null,variableList:null})}t.parsing.end=performance.now(),n.levelDetails=f,this.handlePlaylistLoaded(f,e,t,n,r,i)}handleManifestParsingError(e,t,n,r,i){this.hls.trigger(L.ERROR,{type:F.NETWORK_ERROR,details:I.MANIFEST_PARSING_ERROR,fatal:t.type===R.MANIFEST,url:e.url,err:n,error:n,reason:n.message,response:e,context:t,networkDetails:r,stats:i})}handleNetworkError(e,t,n=!1,r,i){let a=`A network ${n?`timeout`:`error`+(r?` (status `+r.code+`)`:``)} occurred while loading ${e.type}`;e.type===R.LEVEL?a+=`: ${e.level} id: ${e.id}`:(e.type===R.AUDIO_TRACK||e.type===R.SUBTITLE_TRACK)&&(a+=` id: ${e.id} group-id: "${e.groupId}"`);let o=Error(a);this.hls.logger.warn(`[playlist-loader]: ${a}`);let s=I.UNKNOWN,c=!1,l=this.getInternalLoader(e);switch(e.type){case R.MANIFEST:s=n?I.MANIFEST_LOAD_TIMEOUT:I.MANIFEST_LOAD_ERROR,c=!0;break;case R.LEVEL:s=n?I.LEVEL_LOAD_TIMEOUT:I.LEVEL_LOAD_ERROR,c=!1;break;case R.AUDIO_TRACK:s=n?I.AUDIO_TRACK_LOAD_TIMEOUT:I.AUDIO_TRACK_LOAD_ERROR,c=!1;break;case R.SUBTITLE_TRACK:s=n?I.SUBTITLE_TRACK_LOAD_TIMEOUT:I.SUBTITLE_LOAD_ERROR,c=!1}l&&this.resetInternalLoader(e.type);let u={type:F.NETWORK_ERROR,details:s,fatal:c,url:e.url,loader:l,context:e,error:o,networkDetails:t,stats:i};if(r){let n=e.url;t&&`url`in t&&(n=t.url),u.response=H({url:n,data:void 0},r)}this.hls.trigger(L.ERROR,u)}handlePlaylistLoaded(e,t,n,r,i,a){let o=this.hls,{type:s,level:c,levelOrTrack:l,id:u,groupId:d,deliveryDirectives:f}=r,p=Pm(t,r),m=Nm(r),h=typeof r.level==`number`&&m===z.MAIN?c:void 0;l&&`iframes`in l&&l.iframes&&!e.iframesOnly&&(e.playlistParsingError=Error(`EXT-X-I-FRAME-STREAM-INF media playlist MUST contain an EXT-X-I-FRAMES-ONLY tag`),e.iframesOnly=!0);let g=e.playlistParsingError;if(g){if(this.hls.logger.warn(`${g} ${e.url}`),!o.config.ignorePlaylistParsingErrors){o.trigger(L.ERROR,{type:F.NETWORK_ERROR,details:I.LEVEL_PARSING_ERROR,fatal:!1,url:p,error:g,reason:g.message,response:t,context:r,level:h,parent:m,networkDetails:i,stats:n});return}e.playlistParsingError=null}if(!e.fragments.length){let a=e.playlistParsingError=Error(`No Segments found in Playlist`);o.trigger(L.ERROR,{type:F.NETWORK_ERROR,details:I.LEVEL_EMPTY_ERROR,fatal:!1,url:p,error:a,reason:a.message,response:t,context:r,level:h,parent:m,networkDetails:i,stats:n});return}switch(e.live&&a&&(a.getCacheAge&&(e.ageHeader=a.getCacheAge()||0),(!a.getCacheAge||isNaN(e.ageHeader))&&(e.ageHeader=0)),s){case R.MANIFEST:case R.LEVEL:if(h){if(!l)h=0;else if(l!==o.levels[h]){let e=o.levels.indexOf(l);e>-1&&(h=e)}}o.trigger(L.LEVEL_LOADED,{details:e,levelInfo:l||o.levels[0],level:h||0,id:u||0,stats:n,networkDetails:i,deliveryDirectives:f,withoutMultiVariant:s===R.MANIFEST,context:r});break;case R.AUDIO_TRACK:o.trigger(L.AUDIO_TRACK_LOADED,{details:e,track:l,id:u||0,groupId:d||``,stats:n,networkDetails:i,deliveryDirectives:f,context:r});break;case R.SUBTITLE_TRACK:o.trigger(L.SUBTITLE_TRACK_LOADED,{details:e,track:l,id:u||0,groupId:d||``,stats:n,networkDetails:i,deliveryDirectives:f,context:r})}}},Im=class e{static get version(){return Fs}static isMSESupported(){return Zf()}static isSupported(){return Qf()}static getMediaSource(){return an()}static get Events(){return L}static get MetadataSchema(){return $s}static get ErrorTypes(){return F}static get ErrorDetails(){return I}static get DefaultConfig(){return e.defaultConfig?e.defaultConfig:xm}static set DefaultConfig(t){e.defaultConfig=t}constructor(t={}){this.config=void 0,this.userConfig=void 0,this.logger=void 0,this._url=null,this.streamController=void 0,this.coreComponents=void 0,this.networkControllers=void 0,this._emitter=new Ps,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 n=this.logger=rn(t.debug||!1,`Hls instance`,t.loggerId||t.assetPlayerId),r=this.config=Cm(e.DefaultConfig,t,n);this.userConfig=t,r.progressive&&Tm(r,n);let{streamController:i,abrController:a,bufferController:o,capLevelController:s,errorController:c,fpsController:l,id3TrackController:u,iframeController:d,gapController:f}=r,p=new c(this),m=this.abrController=new a(this),h=new Ma(this),g=r.interstitialsController,_=g?this.interstitialsController=new g(this,e):null,v=o?this.bufferController=new o(this,h):null,y=s?this.capLevelController=new s(this):null,b=l?new l(this):null,x=r.cmcdController,S=x?this.cmcdController=new x(this):null,C=new Fm(this),w=r.contentSteeringController,T=w?new w(this):null,E=this.levelController=new Em(this,T),D=u?new u(this):void 0,O=new jm(this.config,this.logger),k=this.streamController=new i(this,h,O),A=this.gapController=f?new f(this,h):void 0;y&&y.setStreamController(k);let j=[C,E,k];_&&j.splice(1,0,_),T&&j.splice(1,0,T),this.networkControllers=j;let M=[m];v&&M.push(v),A&&M.push(A),y&&M.push(y),b&&(b.setStreamController(k),M.push(b)),D&&M.push(D),M.push(h),this.audioTrackController=this.createController(r.audioTrackController,j);let N=r.audioStreamController;N&&j.push(this.audioStreamController=new N(this,h,O)),this.subtitleTrackController=this.createController(r.subtitleTrackController,j);let ee=r.subtitleStreamController;ee&&j.push(this.subtititleStreamController=new ee(this,h,O)),this.createController(r.timelineController,M),O.emeController=this.emeController=this.createController(r.emeController,M),S&&M.push(S),this.latencyController=this.createController(r.latencyController,M),this.coreComponents=M,this.iframeController=d?new d(this,e):void 0,j.push(p);let te=p.onErrorOut;typeof te==`function`&&this.on(L.ERROR,te,p),this.on(L.MANIFEST_LOADED,C.onManifestLoaded,C)}createController(e,t){if(e){let n=new e(this);return t&&t.push(n),n}return null}on(e,t,n=this){this._emitter.on(e,t,n)}once(e,t,n=this){this._emitter.once(e,t,n)}removeAllListeners(e){this._emitter.removeAllListeners(e)}off(e,t,n=this,r){this._emitter.off(e,t,n,r)}listeners(e){return this._emitter.listeners(e)}emit(e,t,n){return this._emitter.emit(e,t,n)}trigger(e,t){if(this.config.debug)return this.emit(e,e,t);try{return this.emit(e,e,t)}catch(t){if(this.logger.error(`An internal error happened while handling event `+e+`. Error message: "`+t.message+`". Here is a stacktrace:`,t),!this.triggeringException){this.triggeringException=!0;let n=e===L.ERROR;this.trigger(L.ERROR,{type:F.OTHER_ERROR,details:I.INTERNAL_EXCEPTION,fatal:n,event:e,error:t}),this.triggeringException=!1}}return!1}listenerCount(e){return this._emitter.listenerCount(e)}destroy(){this.logger.log(`destroy`),this.trigger(L.DESTROYING,void 0),this.detachMedia(),this.removeAllListeners(),this._autoLevelCapping=-1,this._url=null,this.networkControllers.forEach(e=>e.destroy()),this.networkControllers.length=0,this.coreComponents.forEach(e=>e.destroy()),this.coreComponents.length=0,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 t=Error(`attachMedia failed: invalid argument (${e})`);this.trigger(L.ERROR,{type:F.OTHER_ERROR,details:I.ATTACH_MEDIA_ERROR,fatal:!0,error:t});return}this.logger.log(`attachMedia`),this._media&&(this.logger.warn(`media must be detached before attaching`),this.detachMedia());let t=`media`in e,n=t?e.media:e,r=t?e:{media:n};this._media=n,this.trigger(L.MEDIA_ATTACHING,r)}detachMedia(){this.logger.log(`detachMedia`);let e={};this.trigger(L.MEDIA_DETACHING,e),this._media=null,this.trigger(L.MEDIA_DETACHED,e)}transferMedia(){this._media=null;let e=this.bufferController?.transferMedia()||null,t={transferMedia:e};return this.trigger(L.MEDIA_DETACHING,t),this.trigger(L.MEDIA_DETACHED,t),e}loadSource(e){var t;this.stopLoad();let n=this.media,r=this._url,i=this._url=St.buildAbsoluteURL(self.location.href,e,{alwaysNormalize:!0});this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.logger.log(`loadSource:${i}`),n&&r&&(r!==i||(t=this.bufferController)!=null&&t.hasSourceTypes())&&(this.detachMedia(),this.attachMedia(n)),this.trigger(L.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 n=0;n<this.networkControllers.length&&(this.networkControllers[n].startLoad(e,t),this.started&&this.networkControllers);n++);}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!==$.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={[z.MAIN]:this.streamController.inFlightFrag};return this.audioStreamController&&(e[z.AUDIO]=this.audioStreamController.inFlightFrag),this.subtititleStreamController&&(e[z.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,n=e?.currentTime;this.detachMedia(),e&&(this.attachMedia(e),t&&(n?this.startLoad(n):this.config.autoStartLoad||this.startLoad()))}removeLevel(e){this.levelController.removeLevel(e)}get sessionId(){let e=this._sessionId;return e||=this._sessionId=vn(),e}get levels(){return this.levelController.levels||[]}get latestLevelDetails(){return this.streamController.getLevelDetails()||null}get loadLevelObj(){return this.levelController.loadLevelObj}get currentLevel(){return this.streamController.currentLevel}set currentLevel(e){this.logger.log(`set currentLevel:${e}`),this.levelController.manualLevel=e,this.streamController.immediateLevelSwitch()}get nextLevel(){return this.streamController.nextLevel}set nextLevel(e){this.logger.log(`set nextLevel:${e}`),this.levelController.manualLevel=e,this.streamController.nextLevelSwitch()}get loadLevel(){return this.levelController.level}set loadLevel(e){this.logger.log(`set loadLevel:${e}`),this.levelController.manualLevel=e}get nextLoadLevel(){return this.levelController.nextLoadLevel}set nextLoadLevel(e){this.levelController.nextLoadLevel=e}get firstLevel(){return Math.max(this.levelController.firstLevel,this.minAutoLevel)}set firstLevel(e){this.logger.log(`set firstLevel:${e}`),this.levelController.firstLevel=e}get startLevel(){let e=this.levelController.startLevel;return 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,n=!!e;t&&n!==this.config.capLevelToPlayerSize&&(n?t.startCapping():(t.stopCapping(),this.autoLevelCapping=-1,this.streamController.nextLevelSwitch()),this.config.capLevelToPlayerSize=n)}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){Ei(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 n=e.length;for(let r=0;r<n;r++)if(e[r].maxBitrate>=t)return r;return 0}get maxAutoLevel(){let{levels:e,autoLevelCapping:t,maxHdcpLevel:n}=this,r;if(r=t===-1&&e!=null&&e.length?e.length-1:t,n)for(let t=r;t--;){let r=e[t].attrs[`HDCP-LEVEL`];if(r&&r<=n)return t}return r}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(){return this.audioStreamController?.getFwdBufferInfo()||null}get maxBufferLength(){return this.streamController.maxBufferLength}setAudioOption(e){return this.audioTrackController?.setAudioOption(e)||null}setSubtitleOption(e){return this.subtitleTrackController?.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(){return this.audioStreamController?.nextAudioTrack??-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(){return this.latencyController?.liveSyncPosition??null}get latency(){return this.latencyController?.latency||0}get maxLatency(){return this.latencyController?.maxLatency||0}get targetLatency(){return this.latencyController?.targetLatency||null}set targetLatency(e){this.latencyController&&(this.latencyController.targetLatency=e)}get drift(){return this.latencyController?.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(){return this.levelController.iframeVariants||[]}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){return vi(e,zi(t),navigator.mediaCapabilities)}};Im.defaultConfig=void 0;var Lm={droppedFrames:0};function Rm(e){try{return new URL(e).host}catch{return``}}var zm=/\.(m3u8|ts|m4s|mp4|cmfv|cmfa)(\?|$)/i;function Bm(e){if(typeof performance>`u`||typeof performance.getEntriesByType!=`function`)return``;let t=``,n=-1,r=performance.getEntriesByType(`resource`);for(let i of r)if(!(i.startTime<e)&&(i.initiatorType===`video`||i.initiatorType===`audio`||zm.test(i.name))&&i.startTime>=n){let e=Rm(i.name);e&&(t=e,n=i.startTime)}return t}function Vm(e){let t=e.getVideoPlaybackQuality?.();return{dropped:t?.droppedVideoFrames??0,totalFrames:t?.totalVideoFrames??0}}var Hm=class{constructor(e){i(this,`video`,void 0),i(this,`baseFrames`,0),i(this,`baseDropped`,0),i(this,`lastFrames`,0),i(this,`lastDropped`,0),this.video=e}read(){let e=Vm(this.video);return e.totalFrames<this.lastFrames&&(this.baseFrames+=this.lastFrames),e.dropped<this.lastDropped&&(this.baseDropped+=this.lastDropped),this.lastFrames=e.totalFrames,this.lastDropped=e.dropped,{dropped:this.baseDropped+e.dropped,totalFrames:this.baseFrames+e.totalFrames}}attach(){let e=()=>void this.read();return this.video.addEventListener(`timeupdate`,e),this.video.addEventListener(`seeking`,e),()=>{this.video.removeEventListener(`timeupdate`,e),this.video.removeEventListener(`seeking`,e)}}};function Um(e,t){let n=[[`playing`,()=>t(`playing`)],[`waiting`,()=>t(`buffering`)],[`stalled`,()=>t(`buffering`)],[`pause`,()=>{e.ended||t(`paused`)}],[`ended`,()=>t(`ended`)]];for(let[t,r]of n)e.addEventListener(t,r);return()=>{for(let[t,r]of n)e.removeEventListener(t,r)}}var Wm=2e3,Gm=3,Km=500,qm=6e3,Jm=.25,Ym=250,Xm=.05,Zm=4,Qm=12e3,$m=.25,eh=1e3;function th(e){try{let t=new TextDecoder(`utf-8`).decode(new Uint8Array(e));return/^skd:\/\/[0-9a-fA-F-]{36}:([0-9a-fA-F]{32})$/.exec(t)?.[1]}catch{return}}function nh(e){return!!(e??(typeof document<`u`?document.createElement(`video`):void 0))?.canPlayType(`application/vnd.apple.mpegurl`)}function rh(){if(typeof window>`u`)return!1;let e=`WebKitMediaKeys`in window||typeof HTMLMediaElement<`u`&&`webkitSetMediaKeys`in HTMLMediaElement.prototype,t=typeof navigator<`u`&&/Apple/i.test(navigator.vendor??``);return e||t}function ih(){if(typeof navigator>`u`||!rh())return!1;let e=navigator.userAgent??``;return/iPhone|iPad|iPod/.test(e)?!0:/Macintosh/.test(e)&&typeof navigator.maxTouchPoints==`number`&&navigator.maxTouchPoints>1}var ah=class{constructor(e){i(this,`name`,`native`),i(this,`deps`,void 0),i(this,`onLoaded`,void 0),i(this,`onError`,void 0),i(this,`onEncrypted`,void 0),i(this,`fairplayLicenseUrl`,void 0),i(this,`keySession`,null),i(this,`fairplayArmed`,!1),i(this,`onVisibility`,null),i(this,`onPageShow`,null),i(this,`hiddenSince`,null),i(this,`refocusTimer`,null),i(this,`edgeTimer`,null),i(this,`onEdgeReset`,null),i(this,`lastBufferedEnd`,null),i(this,`bufferedAdvancedAt`,null),i(this,`lastSeekableEnd`,null),i(this,`edgeStampedAt`,null),i(this,`lastTickAt`,null),i(this,`endedEmitted`,!1),i(this,`fairplayKeyIV`,void 0),i(this,`loadStarted`,void 0),i(this,`preloadTouched`,!1),i(this,`savedPreload`,null),i(this,`cdnHost`,``),i(this,`builtAt`,void 0),i(this,`frameCounter`,void 0),i(this,`detachFrames`,null),this.deps=e,this.frameCounter=new Hm(e.video),this.loadStarted=e.deferLoad!==!0,this.builtAt=typeof performance<`u`?performance.now():0}async load(){this.detachFrames??=this.frameCounter.attach();let{video:e,descriptor:t,emit:n}=this.deps;if(this.endedEmitted=!1,this.watchRefocus(),this.watchBufferedEnd(),this.loadStarted||(this.preloadTouched=!0,this.savedPreload=e.getAttribute(`preload`),e.preload=`none`),t.drmEnabled){if(!t.drm?.fairplay){n({type:`error`,error:new a(`DRM_CLIENT`,0,`native HLS engine cannot satisfy this DRM (Widevine requires the hls.js engine); use engine "auto"/"hls" on a Widevine-capable browser`),fatal:!0});return}this.armFairPlay()}let r=!this.loadStarted;this.onLoaded=r?void 0:()=>n({type:`ready`}),this.onError=()=>n({type:`error`,error:new a(`INTERNAL`,0,`native HLS playback error`),fatal:!0}),this.onLoaded&&e.addEventListener(`loadedmetadata`,this.onLoaded,{once:!0}),e.addEventListener(`error`,this.onError),e.src=ch(t.manifestUrl,t.analytics?.sid),e.load()}startLoad(){this.loadStarted||(this.loadStarted=!0,this.restorePreload())}restorePreload(){if(!this.preloadTouched)return;this.preloadTouched=!1;let{video:e}=this.deps;this.savedPreload===null?e.removeAttribute(`preload`):e.setAttribute(`preload`,this.savedPreload)}armFairPlay(){let{video:e,descriptor:t,credential:n,deviceId:r,userId:i,emit:o}=this.deps,l=t.drm?.fairplay;if(!l)return;this.fairplayLicenseUrl=l.licenseUrl;let u=(e,t,n,r)=>o({type:`error`,error:new a(c(t,r),t,e,r?{serverCode:r}:void 0),fatal:n}),d=async e=>{try{return await e.text()}catch{return``}};this.onEncrypted=a=>{let o=a;o.initData&&!this.fairplayArmed&&(this.fairplayArmed=!0,this.fairplayKeyIV=th(o.initData),(async()=>{try{let a=await(await navigator.requestMediaKeySystemAccess(`com.apple.fps`,[{initDataTypes:[o.initDataType],videoCapabilities:[{contentType:`application/vnd.apple.mpegurl`,robustness:``}],distinctiveIdentifier:`not-allowed`,persistentState:`not-allowed`,sessionTypes:[`temporary`]}])).createMediaKeys(),c=await fetch(l.certificateUrl,{headers:{"x-api-key":n.apiKey}});if(!c.ok){this.fairplayArmed=!1,u(`FairPlay certificate request failed: ${c.status}`,c.status,!0);return}await a.setServerCertificate(await c.arrayBuffer()),await e.setMediaKeys(a);let f=a.createSession();this.keySession=f,f.addEventListener(`message`,e=>{(async()=>{try{let a=await fetch(this.fairplayLicenseUrl??l.licenseUrl,{method:`POST`,body:e.message,headers:{"x-api-key":n.apiKey,"X-Match-Urn":t.matchUrn,"X-Device-Id":r,...i?{"X-User-Id":i}:{},...this.fairplayKeyIV?{"X-Key-Iv":this.fairplayKeyIV}:{}}});if(!a.ok){let e=a.status===403?s(await d(a)):void 0;u(`FairPlay license request failed: ${a.status}`,a.status,!0,e);return}await f.update(new Uint8Array(await a.arrayBuffer()))}catch(e){u(`FairPlay license request failed: ${String(e)}`,0,!0)}})()}),await f.generateRequest(o.initDataType,o.initData)}catch(e){this.fairplayArmed=!1,u(`FairPlay key session failed: ${String(e)}`,0,!0)}})())},e.addEventListener(`encrypted`,this.onEncrypted)}setLicenseUrls(e){e.fairplay&&(this.fairplayLicenseUrl=e.fairplay)}getQualityLevels(){return[]}getCurrentQuality(){return-1}setQuality(e){}setMaxBitrate(e){}getAudioTracks(){let e=this.deps.video.audioTracks;return e?Array.from({length:e.length},(t,n)=>{let r=e[n];return{id:n,name:r.label||r.language||`Audio ${n+1}`,lang:r.language||void 0,default:r.enabled}}):[]}setAudioTrack(e){let t=this.deps.video.audioTracks;if(t)for(let n=0;n<t.length;n+=1)t[n].enabled=n===e}getTextTracks(){let e=this.deps.video.textTracks;return Array.from({length:e.length},(t,n)=>{let r=e[n];return{id:n,name:r.label||r.language||`Text ${n+1}`,lang:r.language||void 0}})}setTextTrack(e){let t=this.deps.video.textTracks;for(let n=0;n<t.length;n+=1)t[n].mode=n===e?`showing`:`disabled`}seekToLive(){let e=this.deps.video,t=this.liveEnd();t==null||t<=e.currentTime||(e.currentTime=t)}getStats(){let e=this.deps.video,t=this.frameCounter.read(),n={droppedFrames:t.dropped,decodedFrames:t.totalFrames};if(this.cdnHost||=Bm(this.builtAt),this.cdnHost&&(n.cdnHost=this.cdnHost),this.deps.descriptor.drmEnabled&&(n.keySystem=`fairplay`),e.duration===1/0){n.isLive=!0;let t=this.liveEdgeEstimate(),r=t==null?NaN:t-e.currentTime;Number.isFinite(r)&&(n.atLiveEdge=r<=Zm,!e.paused&&r>=0&&(n.latencySeconds=r))}else Number.isFinite(e.duration)&&e.duration>0&&(n.isLive=!1);return n}stop(){this.unwatchBufferedEnd();try{this.deps.video.pause()}catch{}}watchRefocus(){this.deps.snapToLiveOnRefocus===!1||typeof document>`u`||this.onVisibility||(this.onVisibility=()=>{let e=oh();if(document.visibilityState===`hidden`){this.hiddenSince=e,this.cancelRefocus();return}let t=this.hiddenSince;this.hiddenSince=null,t!=null&&e-t>=Wm&&this.armRefocus()},this.onPageShow=e=>{e.persisted&&this.armRefocus()},document.addEventListener(`visibilitychange`,this.onVisibility),typeof window<`u`&&window.addEventListener(`pageshow`,this.onPageShow))}armRefocus(){if(this.cancelRefocus(),Number.isFinite(this.deps.video.duration))return;let e=this.liveEnd(),t=oh,n=t(),r=0,i=()=>{if(this.refocusTimer=null,Number.isFinite(this.deps.video.duration))return;r+=Km;let a=this.liveEnd(),o=a!=null&&(e==null||a>=e+Jm),s=Math.max(r,t()-n)>=qm;if(o||s&&a!=null){this.snapToLive();return}this.refocusTimer=setTimeout(i,Km)};this.refocusTimer=setTimeout(i,Km)}cancelRefocus(){this.refocusTimer!=null&&clearTimeout(this.refocusTimer),this.refocusTimer=null}watchBufferedEnd(){if(this.edgeTimer!=null)return;let{video:e}=this.deps;this.onEdgeReset=e=>{this.lastBufferedEnd=null,this.bufferedAdvancedAt=null,e.type===`emptied`&&this.resetEndStale()},e.addEventListener(`seeking`,this.onEdgeReset),e.addEventListener(`emptied`,this.onEdgeReset),this.edgeTimer=setInterval(()=>{if(e.duration!==1/0)return;this.checkEndStale();let t=sh(e,e.currentTime);t!=null&&((this.lastBufferedEnd==null||Math.abs(t-this.lastBufferedEnd)>=Xm)&&(this.bufferedAdvancedAt=oh()),this.lastBufferedEnd=t)},Ym)}checkEndStale(){if(this.endedEmitted)return;let e=oh(),t=this.lastTickAt==null?0:e-this.lastTickAt;this.lastTickAt=e;let n=this.liveEnd();if(n==null)return;let r=this.lastSeekableEnd==null||Math.abs(n-this.lastSeekableEnd)>=$m;this.lastSeekableEnd=n;let i=this.deps.video,a=typeof document<`u`&&document.visibilityState===`hidden`;if(r||t>eh||a||i.paused){this.edgeStampedAt=e;return}e-(this.edgeStampedAt??e)>Qm&&(this.endedEmitted=!0,this.deps.emit({type:`ended`,reason:`stalled`}))}resetEndStale(){this.lastSeekableEnd=null,this.edgeStampedAt=null,this.lastTickAt=null}unwatchBufferedEnd(){this.edgeTimer!=null&&clearInterval(this.edgeTimer),this.edgeTimer=null,this.onEdgeReset&&=(this.deps.video.removeEventListener(`seeking`,this.onEdgeReset),this.deps.video.removeEventListener(`emptied`,this.onEdgeReset),null),this.resetEndStale(),this.lastBufferedEnd=null,this.bufferedAdvancedAt=null}liveEdgeEstimate(){let e=this.deps.video;if(e.duration!==1/0)return null;let t=this.liveEnd(),n=sh(e,e.currentTime)??this.lastBufferedEnd;if(n!=null){let e=this.bufferedAdvancedAt,r=n+(e==null?0:Math.max(0,(oh()-e)/1e3));(t==null||r>t)&&(t=r)}return t!=null&&Number.isFinite(t)?t:null}liveEnd(){let e=this.deps.video;if(e.duration!==1/0||e.seekable.length===0)return null;let t=e.seekable.end(e.seekable.length-1);return Number.isFinite(t)?t:null}snapToLive(){let e=this.deps.video,t=this.liveEnd();if(t==null)return;let n=e.seekable.start(e.seekable.length-1),r=Math.min(e.currentTime,t),i=Math.max(n,t-Gm,r);try{e.currentTime=i}catch{}}destroy(){this.detachFrames?.(),this.detachFrames=null,this.cancelRefocus(),this.unwatchBufferedEnd(),this.onVisibility&&typeof document<`u`&&(document.removeEventListener(`visibilitychange`,this.onVisibility),this.onVisibility=null),this.onPageShow&&typeof window<`u`&&(window.removeEventListener(`pageshow`,this.onPageShow),this.onPageShow=null);let{video:e}=this.deps;this.onLoaded&&e.removeEventListener(`loadedmetadata`,this.onLoaded),this.onError&&e.removeEventListener(`error`,this.onError),this.onEncrypted&&e.removeEventListener(`encrypted`,this.onEncrypted),this.keySession?.close().catch(()=>{}),this.keySession=null,this.fairplayArmed=!1,this.fairplayKeyIV=void 0;try{e.pause()}catch{}e.removeAttribute(`src`),this.restorePreload();try{e.load()}catch{}}};function oh(){return typeof performance<`u`?performance.now():Date.now()}function sh(e,t){let n=e.buffered;if(!n||!Number.isFinite(t))return null;for(let e=0;e<n.length;e+=1)if(n.start(e)<=t+.1&&n.end(e)>t){let t=n.end(e);return Number.isFinite(t)?t:null}return null}function ch(e,t){return t?`${e}${e.includes(`?`)?`&`:`?`}CMCD=${encodeURIComponent(`sid="${t}"`)}`:e}function lh(e,t=Date.now()){if(!e)return!1;let n;try{n=new URL(e).searchParams.get(`exp`)}catch{return!1}return!n||!/^\d+$/.test(n)?!1:Number(n)*1e3<=t}var uh=4096;function dh(e){if(!e||typeof e!=`object`)return;let{response:t}=e;if(typeof t==`string`)return t;let n;if(Object.prototype.toString.call(t)===`[object ArrayBuffer]`?n=new Uint8Array(t):ArrayBuffer.isView(t)&&(n=new Uint8Array(t.buffer,t.byteOffset,t.byteLength)),!(!n||n.byteLength===0||n.byteLength>uh))try{return new TextDecoder().decode(n)}catch{return}}var fh=15e3,ph=5e3,mh=6;function hh(e){try{let t=new URL(e);return t.searchParams.delete(`CMCD`),t.toString()}catch{return e}}var gh=class{constructor(e={}){i(this,`cmcd`,void 0),i(this,`entries`,new Map),i(this,`keyed`,new Set),i(this,`perTrack`,new Map),i(this,`stats`,{started:0,served:0,missed:0,failed:0,expired:0}),this.cmcd=e}keyUsable(e){this.keyed.add(e)}isActive(e){return!this.keyed.has(e)}prefetch(e,t,n){if(!this.isActive(t))return;let r=hh(e);if(this.entries.has(r))return;let i=this.perTrack.get(t)??0;if(i>=mh)return;this.perTrack.set(t,i+1);let a=new AbortController,o={started:performance.now(),first:0,bytes:Promise.resolve(null),abort:a};o.bytes=fetch(this.withCmcd(e,t,n),{credentials:`omit`,mode:`cors`,signal:a.signal}).then(async e=>(o.first=performance.now(),e.ok?e.arrayBuffer():null)).catch(()=>null),this.entries.set(r,o),this.stats.started+=1,setTimeout(()=>{this.entries.get(r)===o&&(this.entries.delete(r),a.abort(),this.stats.expired+=1)},fh)}take(e){let t=hh(e),n=this.entries.get(t);return n&&this.entries.delete(t),n}destroy(){for(let e of this.entries.values())e.abort.abort();this.entries.clear()}withCmcd(e,t,n){let{sessionId:r,contentId:i}=this.cmcd;if(!r&&!i)return e;let a=[];i&&a.push(`cid="${i}"`),a.push(`ot=${n===`init`?`i`:t===`audio`?`a`:`v`}`),a.push(`sf=h`),r&&a.push(`sid="${r}"`),a.push(`st=ll`);try{let t=new URL(e);return t.searchParams.set(`CMCD`,a.join(`,`)),t.toString()}catch{return e}}};function _h(e){let t=Im.DefaultConfig?.loader;if(typeof t!=`function`)return;class n extends t{constructor(...e){super(...e),i(this,`served`,!1),i(this,`cancelled`,!1),i(this,`stats`,vh())}load(t,n,r){let i=t.rangeEnd?void 0:e.take(t.url);if(!i){super.load(t,n,r);return}this.served=!0;let a=performance.now(),o=n?.loadPolicy?.maxTimeToFirstByteMs||ph,s=setTimeout(()=>{!this.cancelled&&this.served&&(i.abort.abort(),e.stats.failed+=1,this.served=!1,super.load(t,n,r))},o);i.bytes.then(o=>{if(clearTimeout(s),this.cancelled||!this.served)return;if(!o){e.stats.failed+=1,this.served=!1,super.load(t,n,r);return}e.stats.served+=1;let c=this.stats;c.loading.start=a,c.loading.first=Math.max(a,i.first||a),c.loading.end=performance.now(),c.loaded=c.total=o.byteLength,r.onSuccess({url:t.url,data:o},c,t,null)})}abort(){if(this.served){this.cancelled=!0,this.stats.aborted=!0;return}super.abort()}}return n}function vh(){return{aborted:!1,loaded:0,retry:0,total:0,chunkCount:0,bwEstimate:0,loading:{start:0,first:0,end:0},parsing:{start:0,end:0},buffering:{start:0,first:0,end:0}}}function yh(e){return e===`audio`?`audio`:`main`}function bh(e,t){let n=[];t.initSegment?.url&&!t.initSegment.data&&n.push({url:t.initSegment.url,kind:`init`});let r=((t.type===`audio`?e.audioTracks?.[e.audioTrack]?.details:typeof t.level==`number`?e.levels?.[t.level]?.details:void 0)?.partList??[]).filter(e=>e.fragment.sn===t.sn);if(r.length)for(let e of r)e.url&&n.push({url:e.url,kind:`media`});else t.url&&n.push({url:t.url,kind:`media`});return n}function xh(e,t){return e.length===0?0:e[Math.min(e.length,Math.max(1,Math.ceil(t/100*e.length)))-1]??0}function Sh(){return Im.isSupported()}var Ch=1e6,wh=20,Th=1e4,Eh=3,Dh=5,Oh=3,kh=1e4,Ah=3e4,jh=12e3,Mh=3e3,Nh=.02,Ph=6e3,Fh=.5,Ih=3,Lh=.5,Rh=1.1,zh=.25,Bh=5e3,Vh=4e3,Hh=2,Uh=5,Wh=2,Gh=2,Kh=4,qh=4,Jh=2e3,Yh=3e4,Xh=1,Zh=2;function Qh(e,t,n){if(n<=0||t<0||t>=e.length)return t;let r=(t,n)=>e[t].width===e[n].width&&e[t].height===e[n].height,i=t=>{for(;t+1<e.length&&r(t+1,t);)t++;return t},a=i(t);for(let t=0;t<n&&a+1<e.length;t++)a=i(a+1);return a}var $h=.2,eg=30,tg=2,ng=2,rg=2,ig=9,ag=.5,og=64,sg=1e4,cg=8,lg=.6,ug=.4,dg=.4,fg=2,pg=6e4,mg=.5,hg=3.5,gg=300;function _g(e){return(e?.part??e?.frag)?.stats}function vg(){if(typeof navigator>`u`)return 0;try{let e=navigator.connection?.rtt;return typeof e==`number`&&Number.isFinite(e)&&e>0?e:0}catch{return 0}}function yg(e){if(e.liveSyncDurationCount!=null||e.liveMaxLatencyDurationCount!=null){delete e.liveSyncDuration,delete e.liveMaxLatencyDuration;return}e.liveSyncDuration??=rg;let t=Math.max(12,e.liveSyncDuration+ig);(e.liveMaxLatencyDuration==null||e.liveMaxLatencyDuration<=e.liveSyncDuration)&&(e.liveMaxLatencyDuration=t),bg(e,e.liveSyncDuration)}function bg(e,t){let n=(e,t,n)=>Math.min(n,Math.max(t,e));e.maxStarvationDelay??=n(t/2,.5,4),e.maxLoadingDelay??=n(t,1,4),e.abrEwmaFastLive??=n(t/2,1,3)}var xg=class{constructor(e){i(this,`name`,`hls`),i(this,`hls`,null),i(this,`deps`,void 0),i(this,`licenseUrl`,void 0),i(this,`detectedLowLatency`,!1),i(this,`bytesLoaded`,0),i(this,`prefetch`,null),i(this,`reportedFirstPlaylist`,!1),i(this,`reportedFirstBytes`,!1),i(this,`reportedDrmReady`,!1),i(this,`playlistBytesLoaded`,0),i(this,`renditionSwitches`,0),i(this,`licenseTimeMs`,0),i(this,`licenseRequested`,!1),i(this,`upshifts`,0),i(this,`downshifts`,0),i(this,`lastLevelIndex`,-1),i(this,`requestCount`,0),i(this,`requestErrors`,0),i(this,`requestTimesMs`,[]),i(this,`cdnHost`,``),i(this,`ladderHeights`,void 0),i(this,`ladderTopBitrateKbps`,0),i(this,`mediaRecoveries`,0),i(this,`networkRecoveries`,0),i(this,`licenseRecoveries`,0),i(this,`recoveryResetTimer`,null),i(this,`networkRetryTimer`,null),i(this,`licenseRetryTimer`,null),i(this,`onVisibility`,null),i(this,`onSeeking`,null),i(this,`onPause`,null),i(this,`onPlay`,null),i(this,`pauseSuspendTimer`,null),i(this,`loadSuspended`,!1),i(this,`stopped`,!1),i(this,`sawLive`,!1),i(this,`lastEndSN`,-1),i(this,`lastAdvanceMs`,0),i(this,`endWatchdog`,null),i(this,`endedEmitted`,!1),i(this,`lastFragLoadingMs`,0),i(this,`starvedTicks`,0),i(this,`starvationKicks`,0),i(this,`kickPending`,!1),i(this,`kickTicks`,0),i(this,`starvationRebuilds`,0),i(this,`kickKind`,null),i(this,`starvedFrames`,0),i(this,`deadTicks`,0),i(this,`mainFragsSinceTick`,0),i(this,`bwFragsLoaded`,0),i(this,`bwSavedAt`,0),i(this,`recentMainFrags`,[]),i(this,`chaseSuspended`,!1),i(this,`savedLiveMaxLatency`,void 0),i(this,`savedMaxSyncRate`,void 0),i(this,`chaseLatency`,-1),i(this,`catchUpRate`,1),i(this,`catchUpEngaged`,!1),i(this,`onTimeUpdate`,null),i(this,`chaseTicks`,0),i(this,`liveRetargets`,0),i(this,`holdBackEnabled`,void 0),i(this,`holdBackSamples`,[]),i(this,`holdBackBase`,-1),i(this,`holdBackStepCount`,0),i(this,`holdBackApplied`,0),i(this,`holdBackSlowTicks`,0),i(this,`holdBackFastSince`,0),i(this,`holdBackSteps`,0),i(this,`holdBackPriorChecked`,!1),i(this,`capObserver`,null),i(this,`capTimer`,null),i(this,`sizeCapLevel`,null),i(this,`bitrateCapLevel`,-1),i(this,`pushedCapLevel`,-1),i(this,`pushedCapReason`,null),i(this,`fpsCapBitrate`,null),i(this,`fpsCapFailedHeight`,null),i(this,`fpsCapManaged`,!0),i(this,`fpsLastFrames`,-1),i(this,`fpsLastDropped`,-1),i(this,`fpsBadTicks`,0),i(this,`fpsGraceTicks`,0),i(this,`fpsDownCaps`,0),i(this,`sizeCapManaged`,!0),i(this,`dprMedia`,null),i(this,`onDprChange`,null),i(this,`loadStarted`,void 0),i(this,`frameCounter`,void 0),i(this,`detachFrames`,null),this.deps=e,this.holdBackEnabled=e.adaptiveHoldBack!==!1,this.frameCounter=new Hm(e.video),this.licenseUrl=e.descriptor.drm?.widevine?.licenseUrl,this.loadStarted=e.deferLoad!==!0}async load(){this.detachFrames??=this.frameCounter.attach();let{descriptor:e,snapToLiveOnRefocus:t,video:n,emit:r}=this.deps,i=nh(n)&&rh(),o=!!e.drm?.widevine?.licenseUrl&&!i;if(e.drmEnabled&&!o){r({type:`error`,error:new a(`DRM_CLIENT`,0,e.drm?.fairplay?.licenseUrl&&i?`FairPlay cannot be played on the hls.js engine (WebKit binds keys via the media sinf box); use engine "auto" or "native"`:`DRM is required but none of the stream’s key systems is usable on this platform (WebKit takes FairPlay only; other browsers take Widevine only)`),fatal:!0});return}e.drmEnabled&&o&&!this.deps.hlsConfig?.requestMediaKeySystemAccessFunc&&(Xe(n),rt()),this.startHls(),t!==!1&&typeof document<`u`&&(this.onVisibility=()=>{let e=this.hls;if(document.visibilityState!==`visible`||!e)return;let t=e.liveSyncPosition;if(typeof t!=`number`)return;let r=typeof e.targetLatency==`number`&&e.targetLatency>0?e.targetLatency:3;t-n.currentTime>Math.max(r*3,8)&&(n.currentTime=t)},document.addEventListener(`visibilitychange`,this.onVisibility)),this.onSeeking=()=>{this.clampOverSeek(),this.loadSuspended&&(this.resumeLoading(),this.schedulePauseSuspend())},n.addEventListener(`seeking`,this.onSeeking),this.onTimeUpdate=()=>this.updateCatchUpBand(),n.addEventListener(`timeupdate`,this.onTimeUpdate),this.onPause=()=>this.schedulePauseSuspend(),this.onPlay=()=>this.resumeLoading(),n.addEventListener(`pause`,this.onPause),n.addEventListener(`play`,this.onPlay),this.sizeCapManaged&&typeof ResizeObserver<`u`&&(this.capObserver=new ResizeObserver(()=>this.onMediaResize()),this.capObserver.observe(n),this.watchDprChanges())}schedulePauseSuspend(){this.pauseSuspendTimer||this.loadSuspended||this.stopped||!this.loadStarted||(this.pauseSuspendTimer=setTimeout(()=>{this.pauseSuspendTimer=null;let{video:e}=this.deps;if(e.paused&&!e.ended&&!this.stopped&&this.hls){try{this.hls.stopLoad()}catch{return}this.loadSuspended=!0}},Bh))}resumeLoading(){if(this.pauseSuspendTimer&&=(clearTimeout(this.pauseSuspendTimer),null),this.resetChaseWindow(),this.resetFrameDropWindow(),this.loadSuspended&&(this.loadSuspended=!1,!this.stopped&&this.hls)){this.lastAdvanceMs=Date.now(),this.lastFragLoadingMs=0,this.resetStarvationWindow(),this.resetChaseWindow(),this.clearKick();try{this.hls.startLoad(-1)}catch{}}}startLoad(){this.loadStarted||(this.loadStarted=!0,this.deps.video.paused&&this.schedulePauseSuspend(),this.hls?.startLoad(-1))}watchDprChanges(){if(typeof matchMedia!=`function`)return;this.unwatchDprChanges();let e=typeof self<`u`&&self.devicePixelRatio||1,t=matchMedia(`(resolution: ${e}dppx)`);if(typeof t.addEventListener!=`function`)return;let n=()=>{this.onMediaResize(),this.watchDprChanges()};t.addEventListener(`change`,n),this.dprMedia=t,this.onDprChange=n}unwatchDprChanges(){this.dprMedia&&this.onDprChange&&this.dprMedia.removeEventListener(`change`,this.onDprChange),this.dprMedia=null,this.onDprChange=null}clampOverSeek(){let e=this.hls;if(!e||this.chaseSuspended||(e.levels[e.currentLevel]??e.levels[e.loadLevel])?.details?.live!==!0)return;let t=e.liveSyncPosition;if(typeof t!=`number`||!Number.isFinite(t))return;let{video:n}=this.deps;n.currentTime<=t+ag||(n.currentTime=t)}reanchorPartTimeline(e,t){let{frag:n,part:r}=t;if(!r||r.index!==0||n.type!==`main`||typeof n.sn!=`number`)return;let i=e.levels[n.level]?.details;if(!i?.live)return;let a=r.elementaryStreams.video??r.elementaryStreams.audiovideo??r.elementaryStreams.audio;if(!a)return;let o=n.sn,s=i.fragments.find(e=>e&&e.sn===o)??(i.fragmentHint?.sn===o?i.fragmentHint:void 0);if(!s)return;let c=a.startPTS-s.start;if(!(!Number.isFinite(c)||Math.abs(c)<Nh)){for(let e of i.fragments)e&&e.setStart(e.start+c);i.fragmentHint?.setStart(i.fragmentHint.start+c),this.deps.debug===!0&&console.info(`havik-player: LL-HLS timeline re-anchored by ${c>=0?`+`:``}${c.toFixed(3)}s at sn ${n.sn} (level ${n.level})`)}}startHls(){let{video:e,descriptor:t,credential:n,deviceId:r,userId:i,lowLatency:a,debug:o,hlsConfig:s,emit:c}=this.deps;this.clearKick(),this.resetStarvationWindow(),this.resetChaseWindow(),this.resetFrameDropWindow(),this.lastFragLoadingMs=0,this.lastEndSN=-1,this.lastAdvanceMs=0;let l=t.drmEnabled&&!!(t.drm?.widevine?.licenseUrl||t.drm?.fairplay?.licenseUrl),u=nh(this.deps.video)&&rh(),d={debug:o===!0,enableWorker:!a,lowLatencyMode:a,backBufferLength:90,liveDurationInfinity:!0,maxBufferHole:.5,maxLiveSyncPlaybackRate:u?1:1.1,abrEwmaDefaultEstimate:this.startEstimate(),capLevelToPlayerSize:!1,...this.loadStarted?{}:{autoStartLoad:!1},...l?{emeEnabled:!0,drmSystems:{...this.licenseUrl?{"com.widevine.alpha":{licenseUrl:this.licenseUrl}}:{}},drmSystemOptions:{videoRobustness:Ye.video,audioRobustness:Ye.audio,videoEncryptionScheme:Ye.scheme,audioEncryptionScheme:Ye.scheme},...We()?{requestMediaKeySystemAccessFunc:Je(e)}:{},licenseXhrSetup:(e,a)=>{let o=performance.now(),s=()=>{e.open(`POST`,this.licenseUrl??a,!0),e.setRequestHeader(`x-api-key`,n.apiKey),e.setRequestHeader(`X-Match-Urn`,t.matchUrn),e.setRequestHeader(`X-Device-Id`,r),i&&e.setRequestHeader(`X-User-Id`,i),this.licenseRequested=!0,e.addEventListener(`loadend`,()=>{this.licenseTimeMs===0&&(this.licenseTimeMs=Math.max(1,Math.round(performance.now()-o)))})},{freshLicenseUrl:c}=this.deps;if(!c||!lh(this.licenseUrl)){s();return}let l=this.hls,u,d=new Promise(e=>{u=setTimeout(()=>e(void 0),kh)});return Promise.race([c().catch(()=>void 0),d]).finally(()=>clearTimeout(u)).then(e=>{if(!this.hls||this.hls!==l)throw Error(`havik-player: engine torn down during refresh`);e&&(this.licenseUrl=e),s()})}}:{},...t.analytics?.sid?{cmcd:{sessionId:t.analytics.sid,contentId:t.matchUrn,useHeaders:!1}}:{},...s};if(this.prefetch?.destroy(),this.prefetch=null,l&&this.deps.mediaDuringKey!==!1&&!d.fLoader){let e=new gh({sessionId:t.analytics?.sid,contentId:t.matchUrn}),n=_h(e);n&&(this.prefetch=e,d.fLoader=n)}yg(d),this.catchUpRate=typeof d.maxLiveSyncPlaybackRate==`number`?d.maxLiveSyncPlaybackRate:1,this.catchUpEngaged=!1,this.catchUpRate>1&&(d.maxLiveSyncPlaybackRate=1),this.sizeCapManaged=d.capLevelToPlayerSize!==!0,this.fpsCapManaged=!(s&&`capLevelOnFPSDrop`in s),this.loadStarted=d.autoStartLoad!==!1;let f=new Im(d);if(this.hls=f,this.armHoldBack(f,d),f.on(Im.Events.FRAG_PARSED,(e,t)=>this.reanchorPartTimeline(f,t)),f.on(Im.Events.MANIFEST_PARSED,()=>{this.mediaRecoveries=0,this.networkRecoveries=0,l&&!this.deps.hlsConfig?.requestMediaKeySystemAccessFunc&&this.dropLevelsWidevineCannotPlay(f),this.measureLadder(f),this.applySizeCap(),this.loadSuspended=!1,e.paused&&this.schedulePauseSuspend(),c({type:`ready`})}),f.on(Im.Events.FRAG_BUFFERED,(e,t)=>{t?.frag?.type===`main`&&(this.kickKind!==`dead`&&this.clearKick(),(this.mediaRecoveries>0||this.networkRecoveries>0||this.licenseRecoveries>0||this.starvationKicks>0||this.starvationRebuilds>0)&&!this.recoveryResetTimer&&(this.recoveryResetTimer=setTimeout(()=>{this.mediaRecoveries=0,this.networkRecoveries=0,this.licenseRecoveries=0,this.starvationKicks=0,this.starvationRebuilds=0,this.recoveryResetTimer=null},Ah)))}),f.on(Im.Events.FRAG_LOADING,(e,t)=>{t?.frag?.type===`main`&&(this.lastFragLoadingMs=Date.now())}),f.on(Im.Events.FRAG_LOADED,(e,t)=>{t?.frag?.type===`main`&&(this.mainFragsSinceTick+=1,this.bwFragsLoaded+=1,this.maybeRememberBandwidth(!1));let n=t?.frag,r=_g(t),i=r?.loaded;typeof i==`number`&&(this.bytesLoaded+=i),!this.reportedFirstBytes&&typeof i==`number`&&i>0&&(this.reportedFirstBytes=!0,c({type:`firstBytes`}));let a=r?.loading;a&&a.end>0&&a.start>0&&(this.requestCount+=1,this.requestTimesMs.push(Math.max(0,Math.round(a.end-a.start))),this.requestTimesMs.length>og&&this.requestTimesMs.shift()),this.sampleHoldBack(t);let o=n?.url;if(o){let e=Rm(o);e&&(this.cdnHost=e)}}),f.on(Im.Events.LEVEL_LOADED,(e,t)=>{let n=t?.stats?.loaded;if(typeof n==`number`&&(this.playlistBytesLoaded+=n),this.reportedFirstPlaylist||(this.reportedFirstPlaylist=!0,c({type:`firstPlaylist`})),this.detectedLowLatency)return;let r=t.details;(r?.partList?.length||(r?.partTarget??0)>0)&&(this.detectedLowLatency=!0,c({type:`lowLatencyDetected`,value:!0}))}),f.on(Im.Events.LEVEL_LOADED,(e,t)=>this.trackEnd(t)),this.prefetch){let e=this.prefetch;f.on(Im.Events.KEY_LOADING,(t,n)=>{let r=n?.frag,i=yh(r?.type);if(r&&e.isActive(i))for(let t of bh(f,r))e.prefetch(t.url,i,t.kind)}),f.on(Im.Events.KEY_LOADED,(t,n)=>e.keyUsable(yh(n?.frag?.type)))}f.on(Im.Events.KEY_LOADED,()=>{l&&!this.reportedDrmReady&&(this.reportedDrmReady=!0,c({type:`drmReady`}))}),this.endWatchdog&&clearInterval(this.endWatchdog),this.endWatchdog=setInterval(()=>{this.checkEndStale(),this.checkStarvation(),this.updateCatchUpBand(),this.checkFutileChase(),this.adaptHoldBack(),this.checkFrameDrops()},Mh),f.on(Im.Events.LEVEL_SWITCHED,(e,t)=>{this.renditionSwitches+=1;let n=this.lastLevelIndex>=0?f.levels[this.lastLevelIndex]:void 0,r=f.levels[t.level];n&&r&&r.bitrate!==n.bitrate&&(r.bitrate>n.bitrate?this.upshifts+=1:this.downshifts+=1),this.lastLevelIndex=t.level,this.armFrameDropGrace(),c({type:`qualitychange`,index:t.level})}),f.on(Im.Events.AUDIO_TRACK_SWITCHED,(e,t)=>c({type:`audiotrackchange`,id:t.id})),f.on(Im.Events.SUBTITLE_TRACK_SWITCH,(e,t)=>c({type:`texttrackchange`,id:t.id})),f.on(Im.Events.ERROR,(e,t)=>this.onError(t)),f.loadSource(t.manifestUrl),f.attachMedia(e)}getQualityLevels(){return this.hls?this.hls.levels.map((e,t)=>({index:t,width:e.width||void 0,height:e.height||void 0,bitrate:e.bitrate,codecs:e.videoCodec||e.codecSet||void 0})):[]}getCurrentQuality(){return this.hls?this.hls.autoLevelEnabled?-1:this.hls.currentLevel:-1}setQuality(e){this.hls&&(this.hls.currentLevel=e)}setMaxBitrate(e){let t=this.hls;if(t){if(e==null)this.bitrateCapLevel=-1;else{let n=-1;t.levels.forEach((t,r)=>{t.bitrate<=e&&(n=r)}),this.bitrateCapLevel=n}this.pushCap()}}computeSizeCapTarget(){let e=this.hls;if(!e||e.levels.length===0)return null;let{video:t}=this.deps,n=t.getBoundingClientRect(),r=n.width,i=n.height;if(!r&&!i&&(r=t.width||0,i=t.height||0),!(r>0)||!(i>0))return null;let a=e.config??{},o=typeof self<`u`&&self.devicePixelRatio>0?self.devicePixelRatio:1,s=a.ignoreDevicePixelRatio?1:o;s=Math.min(s,a.maxDevicePixelRatio??1/0);let c=Il.getMaxLevelByMediaSize(e.levels,r*s,i*s),l=this.deps.sizeCapHeadroom;if(l==null&&o>=Zh)return c;let u=l??Xh,d=Number.isNaN(u)?Xh:u===1/0?e.levels.length:Math.max(0,Math.floor(u));return Qh(e.levels,c,d)}onMediaResize(){if(!this.sizeCapManaged)return;let e=this.computeSizeCapTarget();if(e==null)return;if(this.sizeCapLevel==null){this.applySizeCap();return}if(e===this.sizeCapLevel){this.capTimer&&=(clearTimeout(this.capTimer),null);return}this.capTimer&&clearTimeout(this.capTimer);let t=e>this.sizeCapLevel?Jh:Yh;this.capTimer=setTimeout(()=>{this.capTimer=null,this.computeSizeCapTarget()===e?this.applySizeCap():this.onMediaResize()},t)}measureLadder(e){let t=e.levels.map(e=>e.height).filter(e=>!!e);this.ladderHeights=t.length?[...new Set(t)].sort((e,t)=>e-t):void 0,this.ladderTopBitrateKbps=e.levels.length?Math.round(Math.max(...e.levels.map(e=>e.bitrate))/1e3):0}dropLevelsWidevineCannotPlay(e){this.removeLevelsWhere(e,e=>it(e)!==!0);let t=new Set(e.levels.map(e=>e.videoCodec).filter(e=>!!e&&Ze(e)!==`avc`&&!!Ze(e)));for(let n of t)nt(n).then(t=>{t||this.hls!==e||this.removeLevelsWhere(e,e=>e===n)&&(this.measureLadder(e),this.applySizeCap())})}removeLevelsWhere(e,t){let n=e.levels??[],r=[],i=new Set;if(n.forEach((e,n)=>{let a=e.videoCodec;a&&Ze(a)&&t(a)&&(r.push(n),i.add(a))}),!r.length)return!1;let a=[...i].join(`, `);if(!n.some((e,t)=>r.includes(t)?!1:!Ze(e.videoCodec)||it(e.videoCodec)===!0))return console.warn(`havik-player: every rendition is ${a}, which Widevine may not play on this browser; keeping them`),!1;for(let t=r.length-1;t>=0;--t)e.removeLevel(r[t]);return console.info(`havik-player: skipped ${r.length} rendition(s) Widevine cannot play on this browser (${a})`),!0}applySizeCap(){if(!this.sizeCapManaged)return;this.capTimer&&=(clearTimeout(this.capTimer),null);let e=this.computeSizeCapTarget();e!=null&&(this.sizeCapLevel=e,this.pushCap())}pushCap(){let e=this.hls;if(!e)return;let t=[[`size`,this.sizeCapLevel??-1],[`bitrate`,this.bitrateCapLevel],[`fps`,this.fpsCapLevel(e)]],n=-1,r=null;for(let[e,i]of t)i>=0&&(n<0||i<n)&&(n=i,r=e);e.autoLevelCapping=n,this.pushedCapLevel=n,this.pushedCapReason=r}getAudioTracks(){return this.hls?this.hls.audioTracks.map(e=>({id:e.id,name:e.name,lang:e.lang||void 0,default:!!e.default})):[]}setAudioTrack(e){this.hls&&(this.hls.audioTrack=e)}getTextTracks(){return this.hls?this.hls.subtitleTracks.map(e=>({id:e.id,name:e.name,lang:e.lang||void 0})):[]}setTextTrack(e){let t=this.hls;t&&(e<0?(t.subtitleTrack=-1,t.subtitleDisplay=!1):(t.subtitleTrack=e,t.subtitleDisplay=!0))}seekToLive(){let e=this.hls;e&&typeof e.liveSyncPosition==`number`&&(this.deps.video.currentTime=e.liveSyncPosition)}setLicenseUrls(e){e.widevine&&(this.licenseUrl=e.widevine)}getStats(){let e=this.hls,t=this.frameCounter.read(),n={droppedFrames:t.dropped,decodedFrames:t.totalFrames,lowLatency:this.detectedLowLatency,bytesLoaded:this.bytesLoaded,playlistBytesLoaded:this.playlistBytesLoaded,renditionSwitches:this.renditionSwitches,liveRetargets:this.liveRetargets,holdBackSteps:this.holdBackSteps,fpsDownCaps:this.fpsDownCaps,licenseTimeMs:this.licenseTimeMs,upshifts:this.upshifts,downshifts:this.downshifts,requestCount:this.requestCount,requestErrors:this.requestErrors,requestTimesMs:[...this.requestTimesMs],ladderHeights:this.ladderHeights,ladderTopBitrateKbps:this.ladderTopBitrateKbps||void 0};if(this.cdnHost&&(n.cdnHost=this.cdnHost),this.licenseRequested&&(n.keySystem=`widevine`,n.drmSecurityLevel=`L3`),e){n.qualityPinned=!e.autoLevelEnabled,typeof e.latency==`number`&&(n.latencySeconds=e.latency),typeof e.targetLatency==`number`&&e.targetLatency>0&&(n.targetLatencySeconds=e.targetLatency),typeof e.bandwidthEstimate==`number`&&(n.bandwidthKbps=Math.round(e.bandwidthEstimate/1e3));let t=e.currentLevel>=0?e.levels[e.currentLevel]:void 0;t&&(n.levelHeight=t.height);let r=e.autoLevelCapping,i=r>=0?e.levels[r]:void 0;if(i&&i.height>0){n.maxLevelHeight=i.height;let t=e.config??{};t.capLevelToPlayerSize!==!0&&t.capLevelOnFPSDrop!==!0&&r===this.pushedCapLevel&&this.pushedCapReason&&(n.capReason=this.pushedCapReason)}t?.videoCodec&&(n.videoCodec=t.videoCodec),t?.audioCodec&&(n.audioCodec=t.audioCodec),t&&typeof t.bitrate==`number`&&(n.renditionBitrateKbps=Math.round(t.bitrate/1e3)),typeof t?.details?.live==`boolean`&&(n.isLive=t.details.live,typeof e.liveSyncPosition==`number`&&(n.atLiveEdge=this.deps.video.currentTime>=e.liveSyncPosition-1.5))}return n}trackEnd(e){let t=e.details;if(t){if(t.live===!0){let e=!this.sawLive;this.sawLive=!0,e&&this.applyHoldBackPrior();let n=t.endSN??-1;n!==this.lastEndSN&&(this.lastEndSN=n,this.lastAdvanceMs=Date.now(),this.chaseSuspended&&this.resumeChasing());return}this.sawLive&&this.emitEnded(`endlist`)}}checkEndStale(){if(this.endedEmitted||!this.sawLive||this.lastAdvanceMs===0)return;if(typeof document<`u`&&document.hidden){this.lastAdvanceMs=Date.now();return}if(this.loadSuspended){this.lastAdvanceMs=Date.now();return}let e=Date.now()-this.lastAdvanceMs;!this.chaseSuspended&&e>Ph&&this.suspendChasing(),e>jh&&this.emitEnded(`stalled`)}resetStarvationWindow(){this.starvedTicks=0,this.deadTicks=0,this.mainFragsSinceTick=0,this.recentMainFrags=[]}clearKick(){this.kickPending=!1,this.kickTicks=0,this.kickKind=null}checkStarvation(){let e=this.hls,{video:t}=this.deps;if(!e||this.endedEmitted||!this.sawLive||this.chaseSuspended)return;if(typeof document<`u`&&document.hidden||this.loadSuspended){this.resetStarvationWindow();return}let n=Date.now(),r=this.lastAdvanceMs!==0&&n-this.lastAdvanceMs<Ph,i=this.lastFragLoadingMs!==0&&n-this.lastFragLoadingMs>Vh,a=t.readyState<HTMLMediaElement.HAVE_FUTURE_DATA&&!t.paused,{totalFrames:o,dropped:s}=Vm(t),c=o-s,l=c!==this.starvedFrames;if(this.starvedFrames=c,!a||l){(t.readyState>=HTMLMediaElement.HAVE_FUTURE_DATA||l)&&this.clearKick(),this.resetStarvationWindow();return}if(!r){this.resetStarvationWindow();return}if(this.kickPending&&(this.kickKind===`dead`||i)&&(this.kickTicks+=1),this.starvedTicks=i?this.starvedTicks+1:0,this.deadTicks+=1,this.recentMainFrags.push(this.mainFragsSinceTick),this.mainFragsSinceTick=0,this.recentMainFrags.length>Kh&&this.recentMainFrags.shift(),this.clearRecoveryReset(),this.kickPending&&this.kickTicks>=Wh&&(this.clearKick(),this.starvationRebuilds<Gh)){this.starvationRebuilds+=1,this.resetStarvationWindow(),this.clearRecoveryReset(),console.warn(`havik-player: restarting the load did not resume video (the wedge is in hls.js state that only a rebuild clears) — rebuilding the player`),this.rebuildInstance(`starvation rebuild`);return}let u=i&&this.starvedTicks>=Hh,d=!i&&this.deadTicks>=Kh&&this.recentMainFrags.reduce((e,t)=>e+t,0)>=qh;if((u||d)&&(this.resetStarvationWindow(),!(this.starvationKicks>=Uh))){this.starvationKicks+=1,this.kickPending=!0,this.kickTicks=0,this.kickKind=d?`dead`:`quiet`,this.clearRecoveryReset(),console.warn(d?`havik-player: video starved while hls.js keeps loading media it never plays (dead pipeline at the live edge) — restarting the load`:`havik-player: video starved while the live playlist advances (wedged hls.js fragment pipeline) — restarting the load`);try{e.stopLoad(),e.startLoad(-1)}catch(e){console.warn(`havik-player: starvation kick failed`,e)}}}updateCatchUpBand(){let e=this.hls;if(!e||this.catchUpRate<=1||this.chaseSuspended||this.loadSuspended)return;let t=e.latency,n=e.targetLatency;if(typeof t!=`number`||typeof n!=`number`||!Number.isFinite(t))return;let r=t-n;!this.catchUpEngaged&&r>Fh?this.catchUpEngaged=!0:this.catchUpEngaged&&r<=Fh&&this.deps.video.playbackRate===1&&(this.catchUpEngaged=!1);let i=this.catchUpEngaged?this.catchUpRate:1;e.config.maxLiveSyncPlaybackRate!==i&&(e.config.maxLiveSyncPlaybackRate=i)}fpsCapLevel(e){if(this.fpsCapBitrate==null)return-1;let t=this.fpsCapFailedHeight,n=-1;return e.levels.forEach((e,r)=>{let i=t==null||!(e.height>0)||e.height<t;e.bitrate<=this.fpsCapBitrate&&i&&(n=r)}),n<0?0:n}armFrameDropGrace(){this.fpsGraceTicks>0||(this.fpsGraceTicks=ng,this.fpsBadTicks=0)}resetFrameDropWindow(){this.fpsLastFrames=-1,this.fpsLastDropped=-1,this.fpsBadTicks=0}checkFrameDrops(){let e=this.hls,{video:t}=this.deps;if(!e||!this.fpsCapManaged||this.loadSuspended||t.paused||!e.autoLevelEnabled||typeof document<`u`&&document.hidden){this.resetFrameDropWindow();return}let{totalFrames:n,dropped:r}=Vm(t),i=this.fpsLastFrames<0,a=n-this.fpsLastFrames,o=r-this.fpsLastDropped;if(this.fpsLastFrames=n,this.fpsLastDropped=r,i||a<eg||o<0){this.fpsBadTicks=0;return}if(this.fpsGraceTicks>0){--this.fpsGraceTicks,this.fpsBadTicks=0;return}if(o<=$h*a){this.fpsBadTicks=0;return}if(this.fpsBadTicks+=1,this.fpsBadTicks<tg)return;this.fpsBadTicks=0;let s=e.levels,c=s[e.currentLevel];if(!c)return;let l=s.filter(e=>e.height>0&&e.height<c.height),u=(l.length?l:s.filter(e=>e.bitrate<c.bitrate)).map(e=>e.bitrate).sort((e,t)=>t-e)[0];u!=null&&(this.fpsCapBitrate!=null&&u>=this.fpsCapBitrate||(this.fpsCapBitrate=u,l.length&&(this.fpsCapFailedHeight=c.height),this.fpsDownCaps+=1,console.warn(`havik-player: dropping ${Math.round(100*o/a)}% of frames at ${c.height}p — capping quality below it`),this.pushCap()))}resetChaseWindow(){this.chaseLatency=-1,this.chaseTicks=0}checkFutileChase(){let e=this.hls,{video:t}=this.deps;if(!e||this.endedEmitted||!this.sawLive||this.chaseSuspended||this.loadSuspended||typeof document<`u`&&document.hidden){this.resetChaseWindow();return}let n=e.latency,r=t.playbackRate,i=e.config.maxLiveSyncPlaybackRate;if(!(!t.paused&&typeof i==`number`&&i>1&&r>=Math.min(Rh,i)&&r<=i&&typeof n==`number`&&Number.isFinite(n))){this.resetChaseWindow();return}if(this.chaseLatency<0||this.chaseLatency-n>=Lh){this.chaseLatency=n,this.chaseTicks=0;return}if(this.chaseTicks+=1,this.chaseTicks<Ih)return;this.resetChaseWindow();let a=typeof e.config.liveMaxLatencyDuration==`number`?e.config.liveMaxLatencyDuration:e.maxLatency;if(!(a>1))return;let o=e.targetLatency;if(typeof o!=`number`||!(o>0))return;let s=Math.min(n,a-1);s<o+zh||(console.warn(`havik-player: catch-up at ${r}x not gaining on the live edge (latency ${n.toFixed(1)}s); holding at ${s.toFixed(1)}s`),this.liveRetargets+=1,e.targetLatency=s,this.deps.emit({type:`livetargetchange`,change:{targetSeconds:s,previousSeconds:o,reason:`futile-chase`}}))}armHoldBack(e,t){this.holdBackEnabled&&(this.holdBackSlowTicks=0,this.holdBackFastSince=0,this.holdBackSamples=[],this.holdBackBase<0&&typeof t.liveSyncDuration==`number`&&(this.holdBackBase=t.liveSyncDuration),this.holdBackApplied>0&&(e.targetLatency=this.holdBackApplied))}applyHoldBackPrior(){let e=this.hls;if(!this.holdBackEnabled||this.holdBackPriorChecked||!e||(this.holdBackPriorChecked=!0,this.holdBackApplied>0||this.holdBackStepCount>0))return;let t=e.targetLatency;if(this.holdBackBase<0&&typeof t==`number`&&t>0&&(this.holdBackBase=t),this.holdBackBase<0)return;let n=vg();if(!(n>=gg))return;let r=typeof t==`number`&&t>0?t:this.holdBackBase,i=Math.min(this.holdBackCeiling(e),this.holdBackBase+mg);i>r&&(this.holdBackStepCount=1,this.moveHoldBack(e,r,i,`connection-rtt`,`connection rtt ${n} ms`))}holdBackCeiling(e){let t=this.deps.adaptiveHoldBackCeiling,n=typeof t==`number`&&Number.isFinite(t)?t:hg,r=typeof e.config.liveMaxLatencyDuration==`number`?e.config.liveMaxLatencyDuration:e.maxLatency;return r>1?Math.min(n,r-1):n}sampleHoldBack(e){if(!this.holdBackEnabled||typeof document<`u`&&document.hidden)return;let t=e.frag?.type;if(t!==`main`&&t!==`audio`)return;let n=e.part?e.part.duration:this.detectedLowLatency?0:e.frag?.duration;if(typeof n!=`number`||!(n>0))return;let r=_g(e)?.loading;if(!r||!(r.start>0)||!(r.end>0))return;let i=r.first>r.start?r.first:r.end,a=Math.max(0,i-r.start)/(n*1e3);this.holdBackSamples.push({t:Date.now(),ratio:a}),this.holdBackSamples.length>256&&this.holdBackSamples.shift()}adaptHoldBack(){if(!this.holdBackEnabled)return;let e=this.hls;if(!e||this.endedEmitted||!this.sawLive||this.chaseSuspended||this.loadSuspended||typeof document<`u`&&document.hidden){this.holdBackSlowTicks=0,this.holdBackFastSince=0,this.holdBackSamples=[];return}let t=Date.now(),n=t-sg,r=this.holdBackSamples,i=0;for(;i<r.length&&r[i].t<n;)i+=1;i>0&&r.splice(0,i);let a=e.targetLatency;if(typeof a!=`number`||!(a>0))return;this.holdBackBase<0&&(this.holdBackBase=a);let o=this.holdBackBase,s=this.holdBackCeiling(e);if(r.length<cg){this.holdBackSlowTicks=0;return}let c=r.map(e=>e.ratio).sort((e,t)=>e-t),l=xh(c,95),u=xh(c,50),d=Math.round(l*1e3);if(l>=lg&&u>=ug){if(this.holdBackFastSince=0,this.holdBackSlowTicks+=1,this.holdBackSlowTicks<fg)return;this.holdBackSlowTicks=0;let t=Math.ceil((s-o)/mg),n=Math.ceil((a-o)/mg-1e-9);if(n>this.holdBackStepCount&&(this.holdBackStepCount=n),this.holdBackStepCount>=t)return;this.holdBackStepCount+=1;let r=Math.min(s,o+this.holdBackStepCount*mg);if(r<=a)return;this.moveHoldBack(e,a,r,`slow-fetches`,`part fetches slow (first byte p50 ${Math.round(u*1e3)} / p95 ${d} ms per 1 s of media)`);return}if(this.holdBackSlowTicks=0,l>=dg){this.holdBackFastSince=0;return}if(this.holdBackFastSince===0){this.holdBackFastSince=t;return}if(t-this.holdBackFastSince<pg||(this.holdBackFastSince=t,this.holdBackStepCount===0||a!==this.holdBackApplied))return;--this.holdBackStepCount;let f=Math.max(o,o+this.holdBackStepCount*mg);f>=a||this.moveHoldBack(e,a,f,`fast-fetches`,`part fetches fast again (p95 first byte ${d} ms per 1 s of media)`)}moveHoldBack(e,t,n,r,i){console.info(`havik-player: ${i}; live target ${t.toFixed(1)}s → ${n.toFixed(1)}s`),this.holdBackApplied=n,this.holdBackSteps+=1,e.targetLatency=n,this.deps.emit({type:`livetargetchange`,change:{targetSeconds:n,previousSeconds:t,reason:r}})}suspendChasing(){let e=this.hls;if(!e)return;this.chaseSuspended=!0,this.savedLiveMaxLatency=e.config.liveMaxLatencyDuration,this.savedMaxSyncRate=e.config.maxLiveSyncPlaybackRate,e.config.liveMaxLatencyDuration=2**53-1,e.config.maxLiveSyncPlaybackRate=1;let{video:t}=this.deps,n=this.savedMaxSyncRate;t.playbackRate>1&&typeof n==`number`&&t.playbackRate<=n&&(t.playbackRate=1)}resumeChasing(){this.chaseSuspended=!1;let e=this.hls;e&&(e.config.liveMaxLatencyDuration=this.savedLiveMaxLatency,e.config.maxLiveSyncPlaybackRate=this.savedMaxSyncRate)}emitEnded(e){this.endedEmitted||(this.endedEmitted=!0,this.endWatchdog&&=(clearInterval(this.endWatchdog),null),this.deps.emit({type:`ended`,reason:e}))}stop(){this.endWatchdog&&=(clearInterval(this.endWatchdog),null),this.clearKick(),this.stopped=!0,this.loadSuspended=!1,this.pauseSuspendTimer&&=(clearTimeout(this.pauseSuspendTimer),null);try{this.hls?.stopLoad()}catch{}try{this.deps.video.pause()}catch{}}startEstimate(){return this.deps.rememberBandwidth===!1?Ch:ze()??Ch}maybeRememberBandwidth(e){if(this.deps.rememberBandwidth===!1||this.bwFragsLoaded<wh)return;let t=Date.now();if(!e&&t-this.bwSavedAt<Th)return;let n=this.hls?.bandwidthEstimate;typeof n!=`number`||!Number.isFinite(n)||n<=0||(this.bwSavedAt=t,Be(n))}destroy(){if(this.maybeRememberBandwidth(!0),this.detachFrames?.(),this.detachFrames=null,this.prefetch?.destroy(),this.prefetch=null,this.clearRecoveryReset(),this.capTimer&&=(clearTimeout(this.capTimer),null),this.capObserver&&=(this.capObserver.disconnect(),null),this.unwatchDprChanges(),this.endWatchdog&&=(clearInterval(this.endWatchdog),null),this.onVisibility&&typeof document<`u`&&(document.removeEventListener(`visibilitychange`,this.onVisibility),this.onVisibility=null),this.onSeeking&&=(this.deps.video.removeEventListener(`seeking`,this.onSeeking),null),this.onTimeUpdate&&=(this.deps.video.removeEventListener(`timeupdate`,this.onTimeUpdate),null),this.onPause&&=(this.deps.video.removeEventListener(`pause`,this.onPause),null),this.onPlay&&=(this.deps.video.removeEventListener(`play`,this.onPlay),null),this.pauseSuspendTimer&&=(clearTimeout(this.pauseSuspendTimer),null),this.networkRetryTimer&&=(clearTimeout(this.networkRetryTimer),null),this.licenseRetryTimer&&=(clearTimeout(this.licenseRetryTimer),null),this.hls){try{this.hls.destroy()}catch(e){console.warn(`havik-player: hls.js destroy() threw during teardown`,e)}this.hls=null}}clearRecoveryReset(){this.recoveryResetTimer&&=(clearTimeout(this.recoveryResetTimer),null)}scheduleLicenseRetry(e){if(e.details!==Im.ErrorDetails.KEY_SYSTEM_LICENSE_REQUEST_FAILED&&e.details!==Im.ErrorDetails.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED)return!1;let t=e.response?.code??0;if(!(t===0||t===408||t===429||t>=500)||this.licenseRecoveries>=Oh)return!1;this.licenseRecoveries+=1;let n=Math.min(8e3,500*2**(this.licenseRecoveries-1));return this.licenseRetryTimer=setTimeout(()=>{this.licenseRetryTimer=null,this.rebuildInstance(`license retry`)},n),!0}rebuildInstance(e){if(this.hls){try{this.hls.destroy()}catch(t){console.warn(`havik-player: hls.js destroy() threw during ${e}`,t)}this.hls=null,this.startHls(),this.armFrameDropGrace()}}onError(e){if(e.type===Im.ErrorTypes.NETWORK_ERROR&&String(e.details??``).startsWith(`frag`)&&(this.requestErrors+=1),!e.fatal)return;let t=this.hls;if(t){if(this.clearRecoveryReset(),e.type===Im.ErrorTypes.KEY_SYSTEM_ERROR){if(this.scheduleLicenseRetry(e))return;this.deps.emit({type:`error`,error:this.toError(e,`DRM`),fatal:!0,detail:e.details});return}if(e.type===Im.ErrorTypes.NETWORK_ERROR){if(this.networkRecoveries<Dh){this.networkRecoveries+=1;let e=Math.min(8e3,1e3*2**(this.networkRecoveries-1));this.networkRetryTimer=setTimeout(()=>{this.networkRetryTimer=null,this.hls&&this.hls.startLoad()},e);return}this.deps.emit({type:`error`,error:this.toError(e,`NETWORK`),fatal:!0,detail:e.details});return}if(e.type===Im.ErrorTypes.MEDIA_ERROR){if(this.mediaRecoveries<Eh){this.mediaRecoveries+=1,t.recoverMediaError();return}this.deps.emit({type:`error`,error:this.toError(e),fatal:!0,detail:e.details});return}this.deps.emit({type:`error`,error:this.toError(e),fatal:!0,detail:e.details})}}toError(e,t=`PLAYBACK`){let n=e.response?.code??0,r=e.details??e.type,i=e.reason??e.error?.message??``,o=t===`DRM`&&n===403&&e.details===Im.ErrorDetails.KEY_SYSTEM_LICENSE_REQUEST_FAILED?s(dh(e.networkDetails)):void 0;return new a(t===`DRM`?c(n,o):n===401?`UNAUTHORIZED`:n===403?`FORBIDDEN`:`INTERNAL`,n,`${t} error: ${r}${i?` (${i})`:``}`,o?{serverCode:o}:void 0)}},Sg=15e3,Cg=6e5,wg=3e5,Tg=100,Eg=1,Dg=1e3,Og=3e4,kg=1e3,Ag={inline:`PRESENTATION_INLINE`,fullscreen:`PRESENTATION_FULLSCREEN`,pip:`PRESENTATION_PIP`},jg={widevine:`KEY_SYSTEM_WIDEVINE`,fairplay:`KEY_SYSTEM_FAIRPLAY`,none:`KEY_SYSTEM_NONE`},Mg=new Set([`INVALID_URN`,`NOT_FOUND`,`GEO_DENIED`,`GONE`,`TOO_EARLY`,`UNAVAILABLE`,`UNAUTHORIZED`,`FORBIDDEN`,`RATE_LIMITED`,`TIMEOUT`]),Ng={idle:`PLAYER_STATE_IDLE`,waiting:`PLAYER_STATE_WAITING`,loading:`PLAYER_STATE_LOADING`,playing:`PLAYER_STATE_PLAYING`,buffering:`PLAYER_STATE_BUFFERING`,paused:`PLAYER_STATE_PAUSED`,ended:`PLAYER_STATE_ENDED`,error:`PLAYER_STATE_ERROR`};function Pg(e){try{let t=new URL(e),[n,...r]=t.hostname.split(`.`);return!n||r.length===0||n!==`feed`&&!n.startsWith(`feed-`)?void 0:(t.hostname=[n.replace(/^feed/,`beacons`),...r].join(`.`),t.pathname=``,t.search=``,t.origin)}catch{return}}var Fg=(e,t)=>e.replace(/\/$/,``).toLowerCase()===t.replace(/\/$/,``).toLowerCase(),Ig=new Set,Lg=new Set,Rg=new Set,zg=e=>`this page's Content-Security-Policy blocks QoE beacons. Add ${e} to connect-src; until then none are sent.`;function Bg(e){if(e.disposition!==`enforce`||e.effectiveDirective!==`connect-src`)return;let t;try{let n=new URL(e.blockedURI);t=n.origin+n.pathname}catch{return}if(Ig.has(t)&&!Lg.has(t)){Lg.add(t),b(zg(new URL(t).origin));for(let e of Rg)e.noteCspBlocked()}}function Vg(e,t){return b(t,e),{disabledReason:t}}function Hg(e,t,n){if(n)return t&&!Fg(t,n)&&b(`analytics.endpoint "${t}" ignored; the server named "${n}".`),{endpoint:n};if(t)return{endpoint:t};if(t!==void 0)return Vg(`empty-endpoint`,`analytics is disabled: no QoE beacons will be sent. analytics.endpoint was supplied but empty. Pass a real beacons origin, analytics: { endpoint: 'https://beacons[-dev].<domain>' }, or omit the option to derive it from baseUrl (or analytics: false to opt out).`);let r=Pg(e);if(r)return{endpoint:r};let i;try{i=new URL(e).hostname||e}catch{i=e}return Vg(i,`analytics is disabled: no QoE beacons will be sent. The beacons endpoint cannot be derived from the baseUrl host "${i}" — the convention is feed[-dev].<domain> → beacons[-dev].<domain>. Pass an explicit endpoint, analytics: { endpoint: 'https://beacons[-dev].<domain>' }, to createPlayer (or analytics: false to opt out deliberately).`)}var Ug=class{constructor(e){i(this,`opts`,void 0),i(this,`url`,void 0),i(this,`cspKey`,void 0),i(this,`now`,void 0),i(this,`seq`,0),i(this,`pending`,[]),i(this,`timer`,null),i(this,`endedFlag`,!1),i(this,`lastBytes`,0),i(this,`lastPlaylistBytes`,0),i(this,`lastDropped`,0),i(this,`lastSwitches`,0),i(this,`playingSinceMs`,null),i(this,`hiddenSinceMs`,null),i(this,`playingTotalMs`,0),i(this,`hiddenTotalMs`,0),i(this,`lastHbPlayingMs`,0),i(this,`lastHbHiddenMs`,0),i(this,`lastHbRebufferMs`,0),i(this,`lastHbRebufferCount`,0),i(this,`lastHbActiveMs`,0),i(this,`rebufferCount`,0),i(this,`rebufferTotalMs`,0),i(this,`bufferingSinceMs`,null),i(this,`isBuffering`,!1),i(this,`errorCount`,0),i(this,`seekCount`,0),i(this,`pauseCount`,0),i(this,`isPlaying`,!1),i(this,`isHidden`,!1),i(this,`isMuted`,!1),i(this,`activeSinceMs`,null),i(this,`activeTotalMs`,0),i(this,`mutedSinceMs`,null),i(this,`mutedTotalMs`,0),i(this,`lastHbMutedMs`,0),i(this,`volumeChanges`,0),i(this,`muteChanges`,0),i(this,`presentation`,`inline`),i(this,`presentationSinceMs`,void 0),i(this,`fullscreenTotalMs`,0),i(this,`pipTotalMs`,0),i(this,`waitingSinceMs`,null),i(this,`waitingTotalMs`,0),i(this,`firstAudioMs`,0),i(this,`timeToFirstStallMs`,0),i(this,`lastStallMs`,0),i(this,`lastErrorMs`,0),i(this,`lastSeekMs`,-1),i(this,`stallIsSeekInduced`,!1),i(this,`lastErrorStage`,null),i(this,`sawFirstBytes`,!1),i(this,`mediaInfoSignature`,``),i(this,`lastUpshifts`,0),i(this,`lastDownshifts`,0),i(this,`lastDecoded`,0),i(this,`lastRequestCount`,0),i(this,`lastRequestErrors`,0),i(this,`pendingStart`,null),i(this,`firstFlushTimer`,null),i(this,`idleTimer`,null),i(this,`lastTickMs`,0),i(this,`bornMs`,void 0),i(this,`startupAnchorMs`,void 0),i(this,`startupTimeMs`,0),i(this,`manifestLoadMs`,0),i(this,`firstFragLoadMs`,0),i(this,`firstPlaylistMs`,0),i(this,`drmSetupMs`,0),i(this,`onPagehide`,()=>this.end(`END_REASON_PAGEHIDE`)),i(this,`cspBlockedNoted`,!1),i(this,`onFreeze`,()=>{this.endedFlag||this.flush(!0)}),i(this,`onResume`,()=>this.checkSuspension(this.now())),i(this,`onVisibility`,()=>{typeof document>`u`||(document.visibilityState===`hidden`?(this.hiddenSinceMs===null&&(this.hiddenSinceMs=this.now()),this.isHidden=!0):(this.hiddenSinceMs!==null&&(this.hiddenTotalMs+=this.now()-this.hiddenSinceMs,this.hiddenSinceMs=null),this.isHidden=!1),this.syncActive(),this.syncBuffering())}),this.opts={...e,heartbeatMs:e.heartbeatMs??Sg,idleMs:e.idleMs??Cg},this.url=`${e.endpoint.replace(/\/$/,``)}/v1/beacons`;try{let e=new URL(this.url);this.cspKey=e.origin+e.pathname}catch{this.cspKey=void 0}this.now=e.now??(()=>Date.now()),this.bornMs=this.now(),this.presentationSinceMs=this.bornMs,this.startupAnchorMs=this.bornMs}start(){if(this.endedFlag)return;let e={player:this.opts.player,sdkVersion:this.opts.sdkVersion,...this.opts.environment};this.pendingStart=e,this.enqueue({sessionStart:e}),this.firstFlushTimer=setTimeout(()=>this.flush(),Dg),this.lastTickMs=this.now(),this.timer=setInterval(()=>this.heartbeat(),this.opts.heartbeatMs),typeof window<`u`&&window.addEventListener(`pagehide`,this.onPagehide),typeof document<`u`&&(document.addEventListener(`visibilitychange`,this.onVisibility),document.addEventListener(`freeze`,this.onFreeze),document.addEventListener(`resume`,this.onResume),this.cspKey&&Ig.add(this.cspKey),document.addEventListener(`securitypolicyviolation`,Bg),Rg.add(this),this.noteCspBlocked(),this.onVisibility())}checkSuspension(e){if(this.endedFlag||!this.opts.idleMs)return!1;let t=Math.max(this.opts.idleMs,wg);return this.lastTickMs>0&&e-this.lastTickMs>=t?(this.endIdle(this.lastTickMs),!0):(this.lastTickMs=e,!1)}syncIdle(e){e===`paused`&&this.opts.idleMs?this.idleTimer===null&&(this.idleTimer=setTimeout(()=>{this.idleTimer=null,this.endIdle()},this.opts.idleMs)):this.idleTimer!==null&&(clearTimeout(this.idleTimer),this.idleTimer=null)}endIdle(e){this.endedFlag||(this.end(`END_REASON_IDLE`,e),this.opts.onIdle?.())}noteStateChange(e,t,n,r){if(this.endedFlag||e===t)return;let i=this.now();if(t===`playing`?(this.playingSinceMs===null&&(this.playingSinceMs=i),this.startupTimeMs===0&&(this.startupTimeMs=Math.max(Eg,i-this.startupAnchorMs)),this.firstAudioMs===0&&!this.isMuted&&(this.firstAudioMs=Math.max(Eg,i-this.startupAnchorMs)),this.isMuted&&this.mutedSinceMs===null&&(this.mutedSinceMs=i)):this.playingSinceMs!==null&&(this.playingTotalMs+=i-this.playingSinceMs,this.playingSinceMs=null,this.mutedSinceMs!==null&&(this.mutedTotalMs+=i-this.mutedSinceMs,this.mutedSinceMs=null)),this.isPlaying=t===`playing`,this.syncActive(),t===`waiting`?this.waitingSinceMs=i:this.waitingSinceMs!==null&&(this.waitingTotalMs+=i-this.waitingSinceMs,this.waitingSinceMs=null),t===`buffering`&&e===`playing`){this.stallIsSeekInduced=this.seekInduced(i);let e=!this.isHidden&&!this.stallIsSeekInduced;e&&(this.rebufferCount+=1),this.isBuffering=!0,this.lastStallMs=i,e&&this.timeToFirstStallMs===0&&(this.timeToFirstStallMs=Math.max(Eg,Math.round(this.playingTotalMs)))}else e===`buffering`&&(this.isBuffering=!1,this.stallIsSeekInduced=!1);this.syncBuffering(),t===`paused`&&(this.pauseCount+=1),this.syncIdle(t);let a={fromState:Ng[e]??`PLAYER_STATE_UNSPECIFIED`,toState:Ng[t]??`PLAYER_STATE_UNSPECIFIED`,presentation:Ag[this.presentation]},o=this.causeOf(e,t,i);o&&(a.cause=o),n>0&&(a.positionMs=Math.round(n)),r&&(a.renditionHeight=r),this.enqueue({stateChange:a})}seekInduced(e){return this.lastSeekMs>=0&&e-this.lastSeekMs<kg}causeOf(e,t,n){if(t===`error`)return`TRANSITION_CAUSE_ERROR`;if(t===`buffering`)return this.seekInduced(n)?`TRANSITION_CAUSE_SEEK`:`TRANSITION_CAUSE_NETWORK_STALL`;if(t===`paused`||t===`playing`&&e===`paused`)return`TRANSITION_CAUSE_USER`}syncActive(e=this.now()){let t=this.isPlaying&&!this.isHidden&&!this.isMuted;t&&this.activeSinceMs===null?this.activeSinceMs=e:!t&&this.activeSinceMs!==null&&(this.activeTotalMs+=e-this.activeSinceMs,this.activeSinceMs=null)}syncBuffering(){let e=this.isBuffering&&!this.isHidden&&!this.stallIsSeekInduced;e&&this.bufferingSinceMs===null?this.bufferingSinceMs=this.now():!e&&this.bufferingSinceMs!==null&&(this.rebufferTotalMs+=this.now()-this.bufferingSinceMs,this.bufferingSinceMs=null)}closePresentation(e=this.now()){let t=e-this.presentationSinceMs;this.presentation===`fullscreen`?this.fullscreenTotalMs+=t:this.presentation===`pip`&&(this.pipTotalMs+=t),this.presentationSinceMs=e}noteAutoplay(e){this.pendingStart&&(this.pendingStart.autoplay=e)}noteEnvironment(e){this.pendingStart&&Object.assign(this.pendingStart,e)}seedVolume(e,t){this.endedFlag||(this.isMuted=e||t===0,this.isMuted&&this.isPlaying&&this.mutedSinceMs===null&&(this.mutedSinceMs=this.now()),this.syncActive())}noteVolume(e,t){if(this.endedFlag)return;let n=e||t===0;if(n===this.isMuted){this.volumeChanges+=1;return}this.muteChanges+=1;let r=this.now();n?this.isPlaying&&this.mutedSinceMs===null&&(this.mutedSinceMs=r):(this.mutedSinceMs!==null&&(this.mutedTotalMs+=r-this.mutedSinceMs,this.mutedSinceMs=null),this.firstAudioMs===0&&this.isPlaying&&(this.firstAudioMs=Math.max(Eg,r-this.startupAnchorMs))),this.isMuted=n,this.syncActive()}notePresentation(e){this.endedFlag||e===this.presentation||(this.closePresentation(),this.presentation=e)}notePlayIntent(){this.endedFlag||this.startupTimeMs>0||(this.startupAnchorMs=this.now(),this.manifestLoadMs>0&&(this.manifestLoadMs=Eg),this.firstPlaylistMs>0&&(this.firstPlaylistMs=Eg),this.firstFragLoadMs>0&&(this.firstFragLoadMs=Eg),this.drmSetupMs>0&&(this.drmSetupMs=Eg))}noteReady(){this.manifestLoadMs===0&&(this.manifestLoadMs=Math.max(Eg,this.now()-this.startupAnchorMs))}noteFirstPlaylist(){this.firstPlaylistMs===0&&(this.firstPlaylistMs=Math.max(Eg,this.now()-this.startupAnchorMs))}noteDrmReady(){this.drmSetupMs===0&&(this.drmSetupMs=Math.max(Eg,this.now()-this.startupAnchorMs))}noteFirstBytes(){this.sawFirstBytes=!0,this.firstFragLoadMs===0&&(this.firstFragLoadMs=Math.max(Eg,this.now()-this.startupAnchorMs))}noteSeek(){this.endedFlag||(this.seekCount+=1,this.lastSeekMs=this.now())}noteError(e,t,n,r,i,a){if(this.endedFlag)return;this.errorCount+=1,this.lastErrorMs=this.now();let o={code:e};t&&(o.detail=t),n&&(o.fatal=!0),r>0&&(o.httpStatus=r),i>0&&(o.positionMs=Math.round(i));let s=this.stageOf(e,t,a);o.stage=s,this.lastErrorStage=s;let c=this.safeSample()?.cdnHost;c&&(o.cdnHost=c),this.enqueue({error:o}),this.flush()}stageOf(e,t,n){let r=n??``;if(r!==``)return/^fragLoad/i.test(r)?this.sawFirstBytes?`ERROR_STAGE_SEGMENT`:`ERROR_STAGE_FIRST_SEGMENT`:/^(manifest|level|audioTrack|subtitleTrack)/i.test(r)?`ERROR_STAGE_MANIFEST`:/key|licen[cs]e/i.test(r)?`ERROR_STAGE_DRM`:/parsing|append|buffer|remux|decrypt|media/i.test(r)?`ERROR_STAGE_DECODE`:`ERROR_STAGE_OTHER`;if(e===`DRM_CLIENT`||e===`DRM_DEVICE_REVOKED`)return`ERROR_STAGE_DRM`;if(Mg.has(e))return`ERROR_STAGE_RESOLVE`;let i=t??``;return/frag|segment/i.test(i)?this.sawFirstBytes?`ERROR_STAGE_SEGMENT`:`ERROR_STAGE_FIRST_SEGMENT`:/manifest|level|playlist/i.test(i)?`ERROR_STAGE_MANIFEST`:/key|licen[cs]e/i.test(i)?`ERROR_STAGE_DRM`:/buffer|decode|media|append/i.test(i)?`ERROR_STAGE_DECODE`:`ERROR_STAGE_OTHER`}noteEnded(){this.end(`END_REASON_ENDED`)}noteDestroyed(){this.end(`END_REASON_STOPPED`)}noteFatal(){this.end(`END_REASON_FATAL_ERROR`)}heartbeat(){if(this.endedFlag)return;let e=this.now();if(this.checkSuspension(e)||this.cspBlocked())return;let t=this.opts.sample(),n=this.playingTotalMs;this.playingSinceMs!==null&&(n+=e-this.playingSinceMs);let r=this.hiddenTotalMs;this.hiddenSinceMs!==null&&(r+=e-this.hiddenSinceMs);let i=this.rebufferTotalMs;this.bufferingSinceMs!==null&&(i+=e-this.bufferingSinceMs);let a=this.activeTotalMs;this.activeSinceMs!==null&&(a+=e-this.activeSinceMs);let o={},s=t.bytesLoaded??0;s>this.lastBytes&&(o.bytesDownloadedDelta=s-this.lastBytes),this.lastBytes=s;let c=t.playlistBytesLoaded??0;c>this.lastPlaylistBytes&&(o.playlistBytesDelta=c-this.lastPlaylistBytes),this.lastPlaylistBytes=c;let l=t.droppedFrames??0;l>this.lastDropped&&(o.droppedFramesDelta=l-this.lastDropped),this.lastDropped=l;let u=t.renditionSwitches??0;u>this.lastSwitches&&(o.renditionSwitchesDelta=u-this.lastSwitches),this.lastSwitches=u,n>this.lastHbPlayingMs&&(o.playingMsDelta=Math.round(n-this.lastHbPlayingMs)),this.lastHbPlayingMs=n,r>this.lastHbHiddenMs&&(o.hiddenMsDelta=Math.round(r-this.lastHbHiddenMs)),this.lastHbHiddenMs=r,i>this.lastHbRebufferMs&&(o.rebufferMsDelta=Math.round(i-this.lastHbRebufferMs)),this.lastHbRebufferMs=i,this.rebufferCount>this.lastHbRebufferCount&&(o.rebufferCountDelta=this.rebufferCount-this.lastHbRebufferCount),this.lastHbRebufferCount=this.rebufferCount,a>this.lastHbActiveMs&&(o.activeMsDelta=Math.round(a-this.lastHbActiveMs)),this.lastHbActiveMs=a,typeof t.latencySeconds==`number`&&(o.latencyMs=Math.round(t.latencySeconds*1e3)),typeof t.targetLatencySeconds==`number`&&(o.targetLatencyMs=Math.round(t.targetLatencySeconds*1e3)),typeof t.bandwidthKbps==`number`&&(o.bandwidthEstKbps=t.bandwidthKbps),typeof t.levelHeight==`number`&&(o.renditionHeight=t.levelHeight),typeof t.renditionBitrateKbps==`number`&&(o.renditionBitrateKbps=t.renditionBitrateKbps),t.atLiveEdge===!0&&(o.atLiveEdge=!0),typeof t.bufferedMs==`number`&&t.bufferedMs>0&&(o.bufferedMs=Math.round(t.bufferedMs)),o.playerState=Ng[t.state]??`PLAYER_STATE_UNSPECIFIED`;let d=this.mutedTotalMs;this.mutedSinceMs!==null&&(d+=e-this.mutedSinceMs),d>this.lastHbMutedMs&&(o.mutedMsDelta=Math.round(d-this.lastHbMutedMs)),this.lastHbMutedMs=d;let f=t.upshifts??0;f>this.lastUpshifts&&(o.upshiftsDelta=f-this.lastUpshifts),this.lastUpshifts=f;let p=t.downshifts??0;p>this.lastDownshifts&&(o.downshiftsDelta=p-this.lastDownshifts),this.lastDownshifts=p;let m=t.decodedFrames??0;m>this.lastDecoded&&(o.decodedFramesDelta=m-this.lastDecoded),this.lastDecoded=m;let h=t.requestErrors??0;h>this.lastRequestErrors&&(o.requestErrorsDelta=h-this.lastRequestErrors),this.lastRequestErrors=h;let g=t.requestCount??0,_=g-this.lastRequestCount;if(this.lastRequestCount=g,_>0){o.requestCountDelta=_;let e=t.requestTimesMs??[],n=e.slice(Math.max(0,e.length-_)).sort((e,t)=>e-t);n.length>0&&(o.requestTimeP50Ms=xh(n,50),o.requestTimeP95Ms=xh(n,95))}typeof t.latencySeconds==`number`&&typeof t.targetLatencySeconds==`number`&&(o.driftMs=Math.round((t.latencySeconds-t.targetLatencySeconds)*1e3)),typeof t.playbackRate==`number`&&t.playbackRate>0&&(o.playbackRate=t.playbackRate),t.qualityPinned===!0&&(o.qualityPinned=!0),t.cdnHost&&(o.cdnHost=t.cdnHost),this.maybeEmitMediaInfo(t),this.enqueue({heartbeat:o}),this.flush(),s>0&&this.noteFirstBytes()}maybeEmitMediaInfo(e){if(!(e.videoCodec??e.keySystem??e.ladderHeights))return;let t={};e.videoCodec&&(t.videoCodec=e.videoCodec),e.audioCodec&&(t.audioCodec=e.audioCodec),e.keySystem&&(t.keySystem=jg[e.keySystem]),e.drmSecurityLevel&&(t.drmSecurityLevel=e.drmSecurityLevel),e.ladderHeights?.length&&(t.ladderHeights=e.ladderHeights),e.ladderTopBitrateKbps&&(t.ladderTopBitrateKbps=e.ladderTopBitrateKbps),e.lowLatency&&(t.lowLatency=!0);let n=JSON.stringify(t);n!==this.mediaInfoSignature&&(this.mediaInfoSignature=n,this.enqueue({mediaInfo:t}))}end(e,t){if(this.endedFlag)return;this.endedFlag=!0,Rg.delete(this);let n=t??this.now();this.playingSinceMs!==null&&(this.playingTotalMs+=n-this.playingSinceMs,this.playingSinceMs=null),this.hiddenSinceMs!==null&&(this.hiddenTotalMs+=n-this.hiddenSinceMs,this.hiddenSinceMs=null),this.bufferingSinceMs!==null&&(this.rebufferTotalMs+=n-this.bufferingSinceMs,this.bufferingSinceMs=null),this.mutedSinceMs!==null&&(this.mutedTotalMs+=n-this.mutedSinceMs,this.mutedSinceMs=null),this.waitingSinceMs!==null&&(this.waitingTotalMs+=n-this.waitingSinceMs,this.waitingSinceMs=null),this.isPlaying=!1,this.syncActive(n),this.closePresentation(n),this.firstFlushTimer&&=(clearTimeout(this.firstFlushTimer),null),this.timer&&=(clearInterval(this.timer),null),this.idleTimer&&=(clearTimeout(this.idleTimer),null),typeof window<`u`&&window.removeEventListener(`pagehide`,this.onPagehide),typeof document<`u`&&(document.removeEventListener(`visibilitychange`,this.onVisibility),document.removeEventListener(`freeze`,this.onFreeze),document.removeEventListener(`resume`,this.onResume));let r=this.safeSample();r&&this.maybeEmitMediaInfo(r);let i={reason:e},a=r?.bytesLoaded??this.lastBytes;a>0&&(i.bytesDownloadedTotal=a),this.playingTotalMs>0&&(i.watchTimeMs=Math.round(this.playingTotalMs)),this.rebufferCount>0&&(i.rebufferCount=this.rebufferCount),this.rebufferTotalMs>0&&(i.rebufferTimeMs=Math.round(this.rebufferTotalMs)),this.startupTimeMs>0&&(i.startupTimeMs=Math.round(this.startupTimeMs)),this.manifestLoadMs>0&&(i.manifestLoadMs=Math.round(this.manifestLoadMs)),this.firstPlaylistMs>0&&(i.firstPlaylistMs=Math.round(this.firstPlaylistMs)),this.firstFragLoadMs>0&&(i.firstFragLoadMs=Math.round(this.firstFragLoadMs)),this.drmSetupMs>0&&(i.drmSetupMs=Math.round(this.drmSetupMs));let o=r?.licenseTimeMs??0;o>0&&(i.licenseTimeMs=Math.round(o));let s=r?.droppedFrames??this.lastDropped;s>0&&(i.droppedFramesTotal=s),this.errorCount>0&&(i.errorCount=this.errorCount),this.hiddenTotalMs>0&&(i.hiddenTimeMs=Math.round(this.hiddenTotalMs)),this.seekCount>0&&(i.seekCount=this.seekCount),this.pauseCount>0&&(i.pauseCount=this.pauseCount),this.firstAudioMs>0&&(i.firstAudioMs=Math.round(this.firstAudioMs)),this.waitingTotalMs>0&&(i.waitingForLiveMs=Math.round(this.waitingTotalMs)),this.timeToFirstStallMs>0&&(i.timeToFirstStallMs=Math.round(this.timeToFirstStallMs));let c=r?.positionMs??0;c>0&&(i.exitPositionMs=Math.round(c)),this.activeTotalMs>0&&(i.activeWatchTimeMs=Math.round(this.activeTotalMs)),this.mutedTotalMs>0&&(i.mutedTimeMs=Math.round(this.mutedTotalMs));let l=e!==`END_REASON_ENDED`;l&&this.lastStallMs>0&&n-this.lastStallMs<=Og&&(i.abandonAfterStallMs=Math.max(Eg,Math.round(n-this.lastStallMs))),l&&this.lastErrorMs>0&&n-this.lastErrorMs<=Og&&(i.abandonAfterErrorMs=Math.max(Eg,Math.round(n-this.lastErrorMs))),this.fullscreenTotalMs>0&&(i.fullscreenTimeMs=Math.round(this.fullscreenTotalMs)),this.pipTotalMs>0&&(i.pipTimeMs=Math.round(this.pipTotalMs)),this.volumeChanges>0&&(i.volumeChanges=this.volumeChanges),this.muteChanges>0&&(i.muteChanges=this.muteChanges);let u=r?.decodedFrames??this.lastDecoded;u>0&&(i.decodedFramesTotal=u),e===`END_REASON_STOPPED`&&this.startupTimeMs===0&&this.lastErrorStage===null&&(e=`END_REASON_ABORTED`,i.reason=e),this.startupTimeMs===0&&e!==`END_REASON_ABORTED`&&(i.failedStage=this.lastErrorStage??(this.manifestLoadMs===0?`ERROR_STAGE_MANIFEST`:this.firstFragLoadMs===0?`ERROR_STAGE_FIRST_SEGMENT`:`ERROR_STAGE_OTHER`)),this.pending.push(this.wrap({sessionEnd:i})),this.flush(e===`END_REASON_PAGEHIDE`)}safeSample(){try{return this.opts.sample()}catch{return null}}wrap(e){return this.seq+=1,{sid:this.opts.sid,clientTime:new Date(this.now()).toISOString(),seq:this.seq,...e}}noteCspBlocked(){this.cspBlockedNoted||this.endedFlag||!this.cspBlocked()||(this.cspBlockedNoted=!0,this.opts.onBlocked?.(zg(new URL(this.url).origin)))}cspBlocked(){return!!this.cspKey&&Lg.has(this.cspKey)}enqueue(e){if(!this.cspBlocked())for(this.pending.push(this.wrap(e));this.pending.length>Tg;){let e=this.pending.findIndex(e=>e.heartbeat||e.stateChange);this.pending.splice(e>=0?e:0,1)}}flush(e=!1){if(this.firstFlushTimer&&=(clearTimeout(this.firstFlushTimer),null),this.pendingStart=null,this.pending.length===0)return;if(this.cspBlocked()){this.pending=[];return}let t=JSON.stringify({beacons:this.pending});if(this.pending=[],e){let e=this.opts.sendBeacon??(typeof navigator<`u`&&navigator.sendBeacon?navigator.sendBeacon.bind(navigator):void 0);if(e&&e(this.url,t))return}let n=this.opts.fetchFn??(typeof fetch<`u`?fetch:void 0);n&&n(this.url,{method:`POST`,headers:{"content-type":`application/json`},body:t,keepalive:!0}).catch(()=>{})}};function Wg(){if(typeof window>`u`)return{integration:`INTEGRATION_KIND_SDK`};let e;try{e=window.top!==window.self}catch{e=!0}let t=window.location?.origin;if(!e)return{host:t&&t!==`null`?t:void 0,integration:`INTEGRATION_KIND_SDK`};let n;try{let e=window.location.ancestorOrigins;e&&e.length>0&&(n=e[e.length-1]??void 0),!n&&typeof document<`u`&&document.referrer&&(n=new URL(document.referrer).origin)}catch{n=void 0}return n===`null`&&(n=void 0),{host:n,integration:`INTEGRATION_KIND_IFRAME`}}function Gg(){if(typeof navigator>`u`)return`DEVICE_CLASS_OTHER`;let e=navigator.userAgentData,t=e?.platform??``;if(/tv|tizen|webos/i.test(t))return`DEVICE_CLASS_TV`;let n=typeof screen<`u`?Math.min(screen.width,screen.height):0;return e?.mobile??(typeof navigator.maxTouchPoints==`number`&&navigator.maxTouchPoints>1&&n>0&&n<900)?n>=600?`DEVICE_CLASS_TABLET`:`DEVICE_CLASS_PHONE`:e||n>=900||/mac|win|linux|chrome os/i.test(t)?`DEVICE_CLASS_DESKTOP`:`DEVICE_CLASS_OTHER`}function Kg(){let e=typeof navigator<`u`?navigator.connection:void 0;if(!e)return{connectionType:`CONNECTION_TYPE_UNKNOWN`};let t={wifi:`CONNECTION_TYPE_WIFI`,cellular:`CONNECTION_TYPE_CELLULAR`,ethernet:`CONNECTION_TYPE_ETHERNET`},n={"slow-2g":`RADIO_ACCESS_ESTIMATED_SLOW_2G`,"2g":`RADIO_ACCESS_ESTIMATED_2G`,"3g":`RADIO_ACCESS_ESTIMATED_3G`,"4g":`RADIO_ACCESS_ESTIMATED_4G`},r=(e,t)=>Object.prototype.hasOwnProperty.call(e,t)?e[t]:void 0,i={connectionType:e.type?r(t,e.type)??`CONNECTION_TYPE_OTHER`:`CONNECTION_TYPE_UNKNOWN`};if(e.effectiveType){let t=r(n,e.effectiveType);t&&(i.radioAccess=t)}return typeof e.downlink==`number`&&e.downlink>0&&(i.downlinkKbps=Math.round(e.downlink*1e3)),typeof e.rtt==`number`&&e.rtt>0&&(i.rttMs=Math.round(e.rtt)),e.saveData&&(i.saveData=!0),i}function qg(e){let t=Wg(),n={deviceClass:Gg(),integration:t.integration,...Kg()};t.host&&(n.host=t.host),typeof screen<`u`&&screen.width>0&&(n.screenWidth=screen.width,n.screenHeight=screen.height),typeof window<`u`&&window.devicePixelRatio>0&&(n.devicePixelRatio=Math.round(window.devicePixelRatio*100)/100);let r=e.getBoundingClientRect?.();return r&&r.width>0&&(n.viewportWidth=Math.round(r.width),n.viewportHeight=Math.round(r.height)),n}async function Jg(){let e=typeof navigator<`u`?navigator.userAgentData:void 0;if(!e?.getHighEntropyValues)return{};try{let t=await e.getHighEntropyValues([`model`,`platformVersion`]),n={};return t.model&&(n.deviceModel=t.model),t.platformVersion&&(n.osVersion=t.platformVersion),n}catch{return{}}}var Yg=`2.23.4`,Xg={accent:`#E1B600`,accentText:`#1B1C23`,background:`#0e0f13`,surface:`#1B1C23`,surfaceMuted:`#2a2c36`,text:`#ffffff`,textMuted:`#9aa0ad`,border:`rgba(255, 255, 255, 0.1)`,radius:`8px`,fontFamily:`ui-sans-serif, system-ui, -apple-system, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif`},Zg={accent:`--havik-accent`,accentText:`--havik-accent-text`,background:`--havik-bg`,surface:`--havik-surface`,surfaceMuted:`--havik-surface-muted`,text:`--havik-text`,textMuted:`--havik-text-muted`,border:`--havik-border`,radius:`--havik-radius`,fontFamily:`--havik-font`};function Qg(e,t){let n={...Xg,...t};for(let t of Object.keys(Zg))e.style.setProperty(Zg[t],n[t]);n.logoUrl&&e.style.setProperty(`--havik-logo`,`url("${n.logoUrl}")`)}var $g=`havik-player-styles`,e_=`
|
|
43
|
+
`):n}function Tf(e,t){return[].slice.call(e.childNodes).reduce((e,n,r)=>{var i;return n.nodeName===`br`&&r?e+`
|
|
44
|
+
`:(i=n.childNodes)!=null&&i.length?e+Tf(n,t):e+(t?n.textContent.replace(/\s+/g,` `):n.textContent)},``)}function Ef(e,t,n){let r=`http://www.w3.org/ns/ttml#styling`,i=null,a=[`displayAlign`,`textAlign`,`color`,`backgroundColor`,`fontSize`,`fontFamily`],o=e!=null&&e.hasAttribute(`style`)?e.getAttribute(`style`):null;return o&&n.hasOwnProperty(o)&&(i=n[o]),a.reduce((n,a)=>{let o=Df(t,r,a)||Df(e,r,a)||Df(i,r,a);return o&&(n[a]=o),n},{})}function Df(e,t,n){return e&&e.hasAttributeNS(t,n)?e.getAttributeNS(t,n):null}function Of(e){return Error(`Could not parse ttml timestamp ${e}`)}function kf(e,t){if(!e)return null;if(_f.test(e))return Af(e,t);let n=nf(e);return n===null&&vf.test(e)&&(n=jf(e,t)),n}function Af(e,t){let n=_f.exec(e),r=(n[4]|0)+(n[5]|0)/t.subFrameRate;return(n[1]|0)*3600+(n[2]|0)*60+(n[3]|0)+r/t.frameRate}function jf(e,t){let n=vf.exec(e),r=Number(n[1]);switch(n[2]){case`h`:return r*3600;case`m`:return r*60;case`ms`:return r/1e3;case`f`:return r/t.frameRate;case`t`:return r/t.tickRate}return r}function Mf(e,t,n,r=``,i=`disabled`){let a=e.ownerDocument.createElement(`track`);return a.kind=t,a.label=n,r&&(a.srclang=r),a.src=`data:,WEBVTT`,a.track.mode=i,e.appendChild(a),a}function Nf(e){return e.forced&&qr()?`forced`:e.characteristics&&/transcribes-spoken-dialog/gi.test(e.characteristics)&&/describes-music-and-sound/gi.test(e.characteristics)?`captions`:`subtitles`}function Pf(e,t){let n=e.mode;if(n===`disabled`&&(e.mode=`hidden`),e.cues&&!e.cues.getCueById(t.id))try{if(e.addCue(t),!e.cues.getCueById(t.id))throw Error(`addCue is failed for: ${t}`)}catch(n){U.debug(`[texttrack-utils]: ${n}`);try{let n=new self.TextTrackCue(t.startTime,t.endTime,t.text);n.id=t.id,e.addCue(n)}catch(e){U.debug(`[texttrack-utils]: Legacy TextTrackCue fallback failed: ${e}`)}}n===`disabled`&&(e.mode=n)}function Ff(e,t,n,r){let i=e.mode;if(i===`disabled`&&(e.mode=`hidden`),e.cues&&e.cues.length>0){let i=Lf(e.cues,t,n);for(let t=0;t<i.length;t++)(!r||r(i[t]))&&e.removeCue(i[t])}i===`disabled`&&(e.mode=i)}function If(e,t){if(t<=e[0].startTime)return 0;let n=e.length-1;if(t>e[n].endTime)return-1;let r=0,i=n,a;for(;r<=i;)if(a=Math.floor((i+r)/2),t<e[a].startTime)i=a-1;else if(t>e[a].startTime&&r<n)r=a+1;else return a;return e[r].startTime-t<t-e[i].startTime?r:i}function Lf(e,t,n){let r=[],i=If(e,t);if(i>-1)for(let a=i,o=e.length;a<o;a++){let i=e[a];if(i.startTime>=t&&i.endTime<=n)r.push(i);else if(i.startTime>n)return r}return r}var Rf=class extends Nl{constructor(e){super(e,`subtitle-track-controller`),this.media=null,this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0,this.queuedDefaultTrack=-1,this.useTextTrackPolling=!1,this.subtitlePollingInterval=-1,this._subtitleDisplay=!0,this.asyncPollTrackChange=()=>this.pollTrackChange(0),this.onTextTracksChanged=()=>{if(this.useTextTrackPolling||self.clearInterval(this.subtitlePollingInterval),!this.media||!this.hls.config.renderTextTracksNatively)return;let e=-1,t=!1;if(this.currentTrack){let n=this.currentTrack.trackNode?.track.mode;n===`showing`?(e=this.trackId,t=!0):n===`hidden`&&(e=this.trackId)}if(!t)for(let t=0;t<this.tracksInGroup.length;t++){let n=this.tracksInGroup[t].trackNode?.track.mode;if(n===`showing`){e=t;break}e<0&&n===`hidden`&&(e=t)}e>-1&&(this._subtitleDisplay=this.tracksInGroup[e].trackNode?.track.mode===`showing`),this.setSubtitleTrack(e,!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(L.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(L.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(L.MANIFEST_LOADING,this.onManifestLoading,this),e.on(L.MANIFEST_PARSED,this.onManifestParsed,this),e.on(L.LEVEL_LOADING,this.onLevelLoading,this),e.on(L.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(L.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(L.ERROR,this.onError,this)}unregisterListeners(){let{hls:e}=this;e.off(L.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(L.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(L.MANIFEST_LOADING,this.onManifestLoading,this),e.off(L.MANIFEST_PARSED,this.onManifestParsed,this),e.off(L.LEVEL_LOADING,this.onLevelLoading,this),e.off(L.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(L.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(L.ERROR,this.onError,this)}createTracksInGroup(){var e;if(!this.media||!this.hls.config.renderTextTracksNatively)return;this.tracksInGroup.forEach(e=>{e.trackNode||=Mf(this.media,Nf(e),e.name,e.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 n=t.media;this.media=n;let r=this.trackId;this.queuedDefaultTrack>-1&&(r=this.queuedDefaultTrack,this.queuedDefaultTrack=-1),this.setSubtitleTrack(r),this.createTracksInGroup(),this.useTextTrackPolling=!(n.textTracks&&`onchange`in n.textTracks),this.useTextTrackPolling?this.pollTrackChange(500):n.textTracks.addEventListener(`change`,this.asyncPollTrackChange)}pollTrackChange(e){self.clearInterval(this.subtitlePollingInterval),this.subtitlePollingInterval=self.setInterval(this.onTextTracksChanged,e)}onMediaDetaching(e,t){let n=this.media;if(!n)return;let r=!!t.transferMedia;self.clearInterval(this.subtitlePollingInterval),this.useTextTrackPolling||n.textTracks.removeEventListener(`change`,this.asyncPollTrackChange),this.trackId>-1&&(this.queuedDefaultTrack=this.trackId,this.setSubtitleTrack(-1)),this.media=null,!r&&this.hls.config.renderTextTracksNatively&&this.tracksInGroup.forEach(e=>{let t=e.trackNode;t&&(t.track.mode=`hidden`,t.remove(),e.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:n,groupId:r,details:i}=t,a=this.tracksInGroup[n];if(!a||a.groupId!==r){this.warn(`Subtitle track with id:${n} and group:${r} not found in active group ${a?.groupId}`);return}let o=a.details;a.details=t.details,this.log(`Subtitle track ${n} "${a.name}" lang:${a.lang} group:${r} loaded [${i.startSN}-${i.endSN}]`),n===this.trackId&&this.playlistLoaded(n,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 n=t.subtitleGroups||null,r=this.groupIds,i=this.currentTrack;if(!n||r?.length!==n?.length||n!=null&&n.some(e=>r?.indexOf(e)===-1)){this.groupIds=n;let e=[];if(this.tracks.forEach(t=>{(t.textCodec===gf?this.hls.config.enableIMSC1:this.hls.config.enableWebVTT)&&(!n||n.indexOf(t.groupId)>-1?(t.id=e.length,e.push(t)):t.trackNode&&=(t.trackNode.remove(),void 0))}),e.length===this.tracksInGroup.length){let t=!1;for(let n=0;n<e.length;n++)if(e[n]!==this.tracksInGroup[n]){t=!0;break}if(!t)return}e.length&&this.selectDefaultTrack&&!e.some(e=>e.default)&&(this.selectDefaultTrack=!1),this.tracksInGroup=e,this.trackId=-1,this.currentTrack=null;let t=this.hls.config.subtitlePreference;if(!i&&t){this.selectDefaultTrack=!1;let n=Hi(t,e);if(n>-1)i=e[n];else{let e=Hi(t,this.tracks);i=this.tracks[e]}}let r=this.findTrackId(i);r===-1&&i&&(r=this.findTrackId(null));let a={subtitleTracks:e};this.log(`Updating subtitle tracks, ${e.length} track(s) found in "${n?.join(`,`)}" group-id`),this.hls.trigger(L.SUBTITLE_TRACKS_UPDATED,a),this.setSubtitleTrack(r),this.createTracksInGroup()}}findTrackId(e){let t=this.tracksInGroup,n=this.selectDefaultTrack;for(let r=0;r<t.length;r++){let i=t[r];if(!(n&&!i.default||!n&&!e)&&(!e||Ui(i,e)))return r}if(e){for(let n=0;n<t.length;n++){let r=t[n];if(Fl(e.attrs,r.attrs,[`LANGUAGE`,`ASSOC-LANGUAGE`,`CHARACTERISTICS`]))return n}for(let n=0;n<t.length;n++){let r=t[n];if(Fl(e.attrs,r.attrs,[`LANGUAGE`]))return n}}return-1}onError(e,t){!t.fatal&&t.context&&t.context.type===R.SUBTITLE_TRACK&&t.context.id===this.trackId&&Xi(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 n=this.currentTrack;if(n&&Ui(e,n))return n;let r=Hi(e,this.tracksInGroup);if(r>-1){let e=this.tracksInGroup[r];return this.setSubtitleTrack(r,!0),e}if(n)return null;{let n=Hi(e,t);if(n>-1)return t[n]}}}return null}loadPlaylist(e){super.loadPlaylist(),this.shouldLoadPlaylist(this.currentTrack)&&this.scheduleLoading(this.currentTrack,e)}loadingPlaylist(e,t){super.loadingPlaylist(e,t);let n=e.id,r=e.groupId,i=this.getUrlWithDirectives(e.url,t),a=e.details,o=a?.age;this.log(`Loading subtitle ${n} "${e.name}" lang:${e.lang} group:${r}${t?.msn===void 0?``:` at sn `+t.msn+` part `+t.part}${o&&a.live?` age `+o.toFixed(1)+(a.type&&` `+a.type||``):``} ${i}`),this.hls.trigger(L.SUBTITLE_TRACK_LOADING,{url:i,id:n,groupId:r,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 n=t===e?this._subtitleDisplay?`showing`:`hidden`:`disabled`,r=t.trackNode.track;r.mode!==n&&(r.mode=n)}})}setSubtitleTrack(e,t=!1){let n=this.tracksInGroup;if(this.media||(this.queuedDefaultTrack=e),e<-1||e>=n.length||!P(e)){this.warn(`Invalid subtitle track id: ${e}`);return}let r=this.currentTrack,i=n[e]||null;if(this.trackId=e,this.currentTrack=i,t&&this.toggleTrackModes(),!i){r&&this.hls.trigger(L.SUBTITLE_TRACK_SWITCH,{id:e});return}let a=!!i.details&&!i.details.live;if(i===r&&a)return;this.log(`Switching to subtitle-track ${e}`+(i?` "${i.name}" lang:${i.lang} group:${i.groupId}`:``));let{id:o,groupId:s=``,name:c,type:l,url:u}=i;this.hls.trigger(L.SUBTITLE_TRACK_SWITCH,{id:o,groupId:s,name:c,type:l,url:u});let d=this.switchParams(i.url,r?.details,i.details);this.loadPlaylist(d)}},zf=2,Bf=100,Vf=class extends Za{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 e;(e=this.media)!=null&&e.seeking||(this.waiting=self.performance.now(),this.tick())},this.onMediaEnded=()=>{this.hls&&(this.ended=this.media?.currentTime||1,this.hls.trigger(L.MEDIA_ENDED,{stalled:!1}))},this.hls=e,this.fragmentTracker=t,this.lastCurrentTime=this.getCurrentTime(),this.registerListeners()}registerListeners(){let{hls:e}=this;e&&(e.on(L.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(L.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(L.BUFFER_APPENDED,this.onBufferAppended,this))}unregisterListeners(){let{hls:e}=this;e&&(e.off(L.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(L.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(L.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(Bf),this.mediaSource=t.mediaSource;let n=this.media=t.media;Y(n,`playing`,this.onMediaPlaying),Y(n,`waiting`,this.onMediaWaiting),Y(n,`ended`,this.onMediaEnded)}onMediaDetaching(e,t){this.clearInterval();let{media:n}=this;n&&(X(n,`playing`,this.onMediaPlaying),X(n,`waiting`,this.onMediaWaiting),X(n,`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(){let e=this.hls?.config.timelineOffset||0;return this.media?Math.max(this.media.currentTime,e):e}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){let n=this.hls?.config;if(!n)return;let r=this.media;if(!r)return;let{seeking:i}=r,a=this.seeking&&!i,o=!this.seeking&&i,s=r.paused&&!i||r.ended||r.playbackRate===0;if(this.seeking=i,e!==t){t&&(this.ended=0),this.moved=!0,i||(this.skipRetry=this.nudgeRetry=0,n.nudgeOnVideoHole&&!s&&e>t&&this.nudgeOnVideoHole(e,t)),this.waiting===0&&this.stallResolved(e);return}if(o||a){a&&this.stallResolved(e);return}if(s){this.skipRetry=this.nudgeRetry=0,this.stallResolved(e),!this.ended&&r.ended&&this.hls&&(this.ended=e||1,this.hls.trigger(L.MEDIA_ENDED,{stalled:!1}));return}if(!J.getBuffered(r).length){this.skipRetry=this.nudgeRetry=0;return}let c=J.bufferInfo(r,e,0),l=this.fragmentTracker;l&&this.hls&&Gf(c,e,l,this.hls);let u=c.nextStart||0;if(i&&l&&this.hls){let t=Hf(this.hls.inFlightFragments,e),n=c.len>zf,r=!u||t||u-e>zf&&!l.getPartialFragment(e);if(n||r)return;this.moved=!1}let d=this.hls?.latestLevelDetails;if(!this.moved&&this.stalled!==null&&l){if(!(c.len>0)&&!u)return;let t=Math.max(u,c.start||0)-e,n=d!=null&&d.live?d.targetduration*2:zf,i=Wf(e,l);if(t>0&&(t<=n||i)){r.paused||this._trySkipBufferHole(i);return}}let f=n.detectStallWithCurrentTimeMs,p=self.performance.now(),m=this.waiting,h=this.stalled;if(h===null){if(m>0&&p-m<f)h=this.stalled=m;else{this.stalled=p;return}}let g=p-h;if(!i&&(g>=f||m&&this.moved)&&this.hls){if(this.mediaSource?.readyState===`ended`&&!(d!=null&&d.live)&&Math.abs(e-(d?.edge||0))<1){if(this.ended)return;this.ended=e||1,this.hls.trigger(L.MEDIA_ENDED,{stalled:!0});return}if(this._reportStall(c),!this.media||!this.hls)return;if(r.currentTime!==e){let t=e;e=r.currentTime,this.moved=!0,this.log(`currentTime changed ${t} > ${e}`);return}}let _=J.bufferInfo(r,e,n.maxBufferHole);this._tryFixBufferStall(_,g,e)}stallResolved(e){let t=this.stalled;if(t&&this.hls&&(this.stalled=null,this.stallReported)){let n=self.performance.now()-t;this.log(`playback not stuck anymore @${e}, after ${Math.round(n)}ms`),this.stallReported=!1,this.waiting=0,this.hls.trigger(L.STALL_RESOLVED,{})}}nudgeOnVideoHole(e,t){var n;let r=this.buffered.video;if(this.hls&&this.media&&this.fragmentTracker&&(n=this.buffered.audio)!=null&&n.length&&r&&r.length>1&&e>r.end(0)){let n=J.bufferedInfo(J.timeRangesToArray(this.buffered.audio),e,0);if(n.len>1&&t>=n.start){let n=J.timeRangesToArray(r),i=J.bufferedInfo(n,t,0).bufferedIndex;if(i>-1&&i<n.length-1){let t=J.bufferedInfo(n,e,0).bufferedIndex,r=n[i].end,a=n[i+1].start;if((t===-1||t>i)&&a-r<1&&e-r<2){let n=Error(`nudging playhead to flush pipeline after video hole. currentTime: ${e} hole: ${r} -> ${a} buffered index: ${t}`);this.warn(n.message),this.media.currentTime+=1e-6;let i=Wf(e,this.fragmentTracker);i&&`fragment`in i?i=i.fragment:i||=void 0;let o=J.bufferInfo(this.media,e,0);this.hls.trigger(L.ERROR,{type:F.MEDIA_ERROR,details:I.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:n,reason:n.message,frag:i,buffer:o.len,bufferInfo:o})}}}}}_tryFixBufferStall(e,t,n){let{fragmentTracker:r,media:i}=this,a=this.hls?.config;if(!i||!r||!a)return;let o=this.hls?.latestLevelDetails,s=Wf(n,r);if((s||o!=null&&o.live&&n<o.fragmentStart)&&(this._trySkipBufferHole(s)||!this.media))return;let c=e.buffered,l=this.adjacentTraversal(e,n);(c&&c.length>1&&e.len>a.maxBufferHole||e.nextStart&&(e.nextStart-n<a.maxBufferHole||l))&&(t>a.highBufferWatchdogPeriod*1e3||this.waiting)&&(this.warn(`Trying to nudge playhead over buffer-hole`),this._tryNudgeBuffer(e))}adjacentTraversal(e,t){let n=this.fragmentTracker,r=e.nextStart;if(n&&r){let e=n.getFragAtPos(t,z.MAIN),i=n.getFragAtPos(r,z.MAIN);if(e&&i)return i.sn-e.sn<2}return!1}_reportStall(e){let{hls:t,media:n,stallReported:r,stalled:i}=this;if(!r&&i!==null&&n&&t){this.stallReported=!0;let r=Error(`Playback stalling at @${n.currentTime} due to low buffer (${q(e)})`);this.warn(r.message),t.trigger(L.ERROR,{type:F.MEDIA_ERROR,details:I.BUFFER_STALLED_ERROR,fatal:!1,error:r,buffer:e.len,bufferInfo:e,stalled:{start:i}})}}_trySkipBufferHole(e){let{fragmentTracker:t,media:n,hls:r}=this,i=r?.config;if(!n||!t||!i)return 0;let a=n.currentTime,o=J.bufferInfo(n,a,0);Gf(o,a,t,r);let s=a<o.start?o.start:o.nextStart;if(s){let l=o.len<=i.maxBufferHole,u=o.len>0&&o.len<1&&n.readyState<3,d=s-a;if(d>0&&(l||u)){if(d>i.maxBufferHole){let n=!1;if(a===0){let e=t.getAppendedFrag(0,z.MAIN);e&&s<e.end&&(n=!0)}if(!n&&e){var c;if(!((c=r.loadLevelObj)!=null&&c.details)||Hf(r.inFlightFragments,s))return 0;let n=!1,i=e.end;for(;i<s;){let e=Wf(i,t),r=e?e.duration:0;if(r>0)i+=r;else{n=!0;break}}if(n)return 0}}let{nudgeMaxRetry:l,skipBufferHolePadding:u}=i,f=++this.skipRetry>l,p=Math.max(s,a)+u;if(f||(this.warn(`skipping hole, adjusting currentTime from ${a} to ${p}`),this.moved=!0,n.currentTime=p),!(e!=null&&e.gap)||f){let t=Error(f?`Playhead still not moving after seeking over buffer hole from ${a} to ${p} after ${i.nudgeMaxRetry} attempts.`:`fragment loaded with buffer holes, seeking from ${a} to ${p}`),n={type:F.MEDIA_ERROR,details:I.BUFFER_SEEK_OVER_HOLE,fatal:f,error:t,reason:t.message,buffer:o.len,bufferInfo:o};e&&(`fragment`in e?n.part=e:n.frag=e),r.trigger(L.ERROR,n)}return p}}return 0}_tryNudgeBuffer(e){let{hls:t,media:n,nudgeRetry:r}=this,i=t?.config;if(!n||!i)return 0;let a=n.currentTime;if(this.nudgeRetry++,r<i.nudgeMaxRetry){let o=a+(r+1)*i.nudgeOffset,s=Error(`Nudging 'currentTime' from ${a} to ${o}`);this.warn(s.message),n.currentTime=o,t.trigger(L.ERROR,{type:F.MEDIA_ERROR,details:I.BUFFER_NUDGE_ON_STALL,error:s,fatal:!1,buffer:e.len,bufferInfo:e})}else{let n=Error(`Playhead still not moving while enough data buffered @${a} after ${i.nudgeMaxRetry} nudges`);this.error(n.message),t.trigger(L.ERROR,{type:F.MEDIA_ERROR,details:I.BUFFER_STALLED_ERROR,error:n,fatal:!0,buffer:e.len,bufferInfo:e})}}};function Hf(e,t){let n=Uf(e.main);if(n&&n.start<=t)return n;let r=Uf(e.audio);return r&&r.start<=t?r:null}function Uf(e){if(!e)return null;switch(e.state){case Q.IDLE:case Q.STOPPED:case Q.ENDED:case Q.ERROR:return null}return e.frag}function Wf(e,t){return t.getAppendedFrag(e,z.MAIN)||t.getPartialFragment(e)}function Gf(e,t,n,r){let i=r.latestLevelDetails,a=Wf(t,n);if(ks(r.config)&&!e.nextStart&&i&&a&&r.interstitialsManager){let n=`type`in a?a:a.fragment,o=sa(i,n.sn);o?.level===n.level&&Os(o,r.interstitialsManager.playerQueue,t)&&(e.nextStart=o.start)}}var Kf=.25;function qf(){if(!(typeof self>`u`))return self.VTTCue||self.TextTrackCue}function Jf(e,t,n,r,i){let a=new e(t,n,``);try{a.value=r,i&&(a.type=i)}catch{a=new e(t,n,q(i?H({type:i},r):r))}return a}var Yf=(()=>{let e=qf();try{e&&new e(0,1/0,``)}catch{return Number.MAX_VALUE}return 1/0})(),Xf=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(L.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(L.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(L.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(L.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(L.MANIFEST_LOADING,this.onManifestLoading,this),e.on(L.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.on(L.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(L.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(L.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))}_unregisterListeners(){let{hls:e}=this;e&&(e.off(L.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(L.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(L.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(L.MANIFEST_LOADING,this.onManifestLoading,this),e.off(L.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.off(L.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(L.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(L.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))}onMediaAttaching(e,t){this.media=t.media}onMediaAttached(){let e=this.hls?.latestLevelDetails;e&&this.updateDateRangeCues(e)}onMediaDetaching(e,t){this.media=null,!t.transferMedia&&(this.id3Track&&=(this.id3Track.remove(),null),this.dateRangeCuesAppended={})}onManifestLoading(){this.dateRangeCuesAppended={}}createTrack(e){return Mf(e,`metadata`,`id3`,``,`hidden`)}onFragParsingMetadata(e,t){if(!this.media||!this.hls)return;let{enableEmsgMetadataCues:n,enableID3MetadataCues:r}=this.hls.config;if(!n&&!r)return;let{samples:i}=t;this.id3Track||=this.createTrack(this.media);let a=qf();if(a)for(let e=0;e<i.length;e++){let t=i[e].type;if(t===ec.emsg&&!n||!r)continue;let o=Rn(i[e].data),s=i[e].pts,c=s+i[e].duration;c>Yf&&(c=Yf),c-s<=0&&(c=s+Kf);for(let e=0;e<o.length;e++){let n=o[e];if(!zn(n)){this.updateId3CueEnds(s,t);let e=Jf(a,s,c,n,t);e&&this.id3Track.track.addCue(e)}}}}updateId3CueEnds(e,t){let n=this.id3Track?.track.cues;if(n)for(let r=n.length;r--;){let i=n[r];i.type===t&&i.startTime<e&&i.endTime===Yf&&(i.endTime=e)}}onBufferFlushing(e,{startOffset:t,endOffset:n,type:r}){let{id3Track:i,hls:a}=this;if(!a)return;let{config:{enableEmsgMetadataCues:o,enableID3MetadataCues:s}}=a;if(i&&(o||s)){let e;e=r===`audio`?e=>e.type===ec.audioId3&&s:r===`video`?e=>e.type===ec.emsg&&o:e=>e.type===ec.audioId3&&s||e.type===ec.emsg&&o,Ff(i.track,t,n,e)}}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:n,timelineOffset:r,enableDateRangeMetadataCues:i,interstitialsController:a}=this.hls.config;if(!i)return;let o=qf();if(n&&r&&!a){let{fragmentStart:t,fragmentEnd:r}=e,i=this.assetCue;i?(i.startTime=t,i.endTime=r):o&&(i=this.assetCue=Jf(o,t,r,{assetPlayerId:this.hls.config.assetPlayerId},`hlsjs.interstitial.asset`),i&&(i.id=n,this.id3Track||=this.createTrack(this.media),this.id3Track.track.addCue(i),i.addEventListener(`enter`,this.onEventCueEnter)))}if(!e.hasProgramDateTime)return;let{id3Track:s}=this,{dateRanges:c}=e,l=Object.keys(c),u=this.dateRangeCuesAppended;if(s&&t){var d;if((d=s.track.cues)!=null&&d.length){let e=Object.keys(u).filter(e=>l.indexOf(e)===-1);for(let t=e.length;t--;){let n=e[t],r=u[n]?.cues;delete u[n],r&&Object.keys(r).forEach(e=>{let t=r[e];if(t){t.removeEventListener(`enter`,this.onEventCueEnter);try{s.track.removeCue(t)}catch{}}})}}else u=this.dateRangeCuesAppended={}}let f=e.fragments[e.fragments.length-1];if(l.length!==0&&P(f?.programDateTime)){this.id3Track||=this.createTrack(this.media);for(let e=0;e<l.length;e++){let t=l[e],n=c[t],r=n.startTime,i=u[t],s=i?.cues||{},d=i?.durationKnown||!1,f=Yf,{duration:p,endDate:m}=n;if(m&&p!==null)f=r+p,d=!0;else if(n.endOnNext&&!d){let e=l.reduce((e,t)=>{if(t!==n.id){let r=c[t];if(r.class===n.class&&r.startDate>n.startDate&&(!e||n.startDate<e.startDate))return r}return e},null);e&&(f=e.startTime,d=!0)}let h=Object.keys(n.attr);for(let e=0;e<h.length;e++){let c=h[e];if(!lo(c))continue;let l=s[c];if(l)d&&!(i!=null&&i.durationKnown)?l.endTime=f:Math.abs(l.startTime-r)>.01&&(l.startTime=r,l.endTime=f);else if(o){let e=n.attr[c];uo(c)&&(e=Un(e));let i=Jf(o,r,f,{key:c,data:e},ec.dateRange);i&&(i.id=t,this.id3Track.track.addCue(i),s[c]=i,a&&(c===`X-ASSET-LIST`||c===`X-ASSET-URL`)&&i.addEventListener(`enter`,this.onEventCueEnter))}}u[t]={cues:s,dateRange:n,durationKnown:d}}}}};function Zf(){return self.SourceBuffer||self.WebKitSourceBuffer}function Qf(){if(!an())return!1;let e=Zf();return!e||e.prototype&&typeof e.prototype.appendBuffer==`function`&&typeof e.prototype.remove==`function`}function $f(){if(!Qf())return!1;let e=an();return typeof e?.isTypeSupported==`function`&&([`avc1.42E01E,mp4a.40.2`,`av01.0.01M.08`,`vp09.00.50.08`].some(t=>e.isTypeSupported($r(t,`video`)))||[`mp4a.40.2`,`fLaC`].some(t=>e.isTypeSupported($r(t,`audio`))))}function ep(){var e;let t=Zf();return typeof(t==null||(e=t.prototype)==null?void 0:e.changeType)==`function`}var tp={DISABLED:0,SWITCHING:1,SWITCHED:2},np=100,rp=class extends Ds{constructor(e,t,n){super(e,t,n,`stream-controller`,z.MAIN),this.audioCodecSwap=!1,this.level=-1,this._forceStartLoad=!1,this._hasEnoughToStart=!1,this.altAudio=tp.DISABLED,this.audioOnly=!1,this._couldBacktrack=!1,this._backtrackFragment=void 0,this.audioCodecSwitch=!1,this.videoBuffer=null,this.onMediaPlaying=()=>{this.tick()},this.onMediaSeeked=()=>{let e=this.media,t=e?e.currentTime:null;if(t===null||!P(t)||(this.log(`Media seeked to ${t}`),!this.getBufferedFrag(t)))return;let n=this.getFwdBufferInfoAtPos(e,t,z.MAIN,0);if(!n||n.len===0){this.log(`Main buffer empty at ${t} on "seeked" event: ${n&&n.len}`);return}this.tick()},this.registerListeners()}registerListeners(){super.registerListeners();let{hls:e}=this;e.on(L.MANIFEST_PARSED,this.onManifestParsed,this),e.on(L.LEVEL_LOADING,this.onLevelLoading,this),e.on(L.LEVEL_LOADED,this.onLevelLoaded,this),e.on(L.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.on(L.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(L.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.on(L.BUFFER_CREATED,this.onBufferCreated,this),e.on(L.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(L.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(L.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){super.unregisterListeners();let{hls:e}=this;e.off(L.MANIFEST_PARSED,this.onManifestParsed,this),e.off(L.LEVEL_LOADED,this.onLevelLoaded,this),e.off(L.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.off(L.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(L.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.off(L.BUFFER_CREATED,this.onBufferCreated,this),e.off(L.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(L.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(L.FRAG_BUFFERED,this.onFragBuffered,this)}onHandlerDestroying(){this.onMediaPlaying=this.onMediaSeeked=null,this.unregisterListeners(),super.onHandlerDestroying()}startLoad(e,t){if(this.levels){let{lastCurrentTime:n,hls:r}=this;if(this.stopLoad(),this.setInterval(np),this.level=-1,!this.startFragRequested){let e=r.startLevel;e===-1&&(r.config.testBandwidth&&this.levels.length>1?(e=0,this.bitrateTest=!0):e=r.firstAutoLevel),r.nextLoadLevel=e,this.level=r.loadLevel,this._hasEnoughToStart=!!t}n>0&&e===-1&&!t&&this.initPTS.length&&(this.log(`Override startPosition with lastCurrentTime @${n}`),e=n),this.state=Q.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=Q.STOPPED}stopLoad(){this._forceStartLoad=!1,super.stopLoad()}doTick(){switch(this.state){case Q.WAITING_LEVEL:{let{levels:e,level:t}=this,n=e?.[t],r=n?.details;if(r&&(!r.live||this.levelLastLoaded===n&&!this.waitForLive(n))){if(this.waitForCdnTuneIn(r))break;this.state=Q.IDLE;break}if(this.hls.nextLoadLevel!==this.level){this.state=Q.IDLE;break}break}case Q.FRAG_LOADING_WAITING_RETRY:this.checkRetryDate()}this.state===Q.IDLE&&this.doTickIdle(),this.onTickEnd()}onTickEnd(){super.onTickEnd(),this.checkFragmentChanged()}doTickIdle(){let{hls:e,levelLastLoaded:t,levels:n,media:r}=this;if(t===null||!r&&!this.primaryPrefetch&&(this.startFragRequested||!e.config.startFragPrefetch)||this.altAudio&&this.audioOnly)return;let i=this.buffering?e.nextLoadLevel:e.loadLevel;if(!(n!=null&&n[i]))return;let a=n[i],o=this.getMainFwdBufferInfo();if(o===null)return;let s=this.getLevelDetails();if(s&&this._streamEnded(o,s)&&this.altAudio!==tp.SWITCHING){let e={type:this.targetBufferType()};this.hls.trigger(L.BUFFER_EOS,e),this.state=Q.ENDED;return}if(!this.buffering)return;e.loadLevel!==i&&e.manualLevel===-1&&this.log(`Adapting to level ${i} from level ${this.level}`),this.level=e.nextLoadLevel=i;let c=a.details;if(!c||this.state===Q.WAITING_LEVEL||this.waitForLive(a)){this.level=i,this.state=Q.WAITING_LEVEL,this.startFragRequested=!1;return}let l=o.len,u=this.getMaxBufferLength(a.maxBitrate);if(l>=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&&Tt(f)&&this.fragmentTracker.getState(f)!==Z.OK){let e=(this.backtrackFragment??f).sn-c.startSN,t=c.fragments[e-1];t&&f.cc===t.cc&&(f=t,this.fragmentTracker.removeFragment(t))}else this.backtrackFragment&&o.len&&(this.backtrackFragment=void 0);if(f&&this.isLoopLoading(f,d)){if(!f.gap){let e=this.audioOnly&&!this.altAudio?B.AUDIO:B.VIDEO,t=(e===B.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;t&&this.afterBufferFlushed(t,e)}f=this.getNextFragmentLoopLoading(f,c,o,z.MAIN,u)}f&&(this.exceedsMaxBuffer(o,u,f)||this.loadFragment(f,a,d))}loadFragment(e,t,n){let r=this.fragmentTracker.getState(e);r===Z.NOT_LOADED||r===Z.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,n):this.clearTrackerIfNeeded(e)}immediateLevelSwitch(){this.abortCurrentFrag(),this.flushMainBuffer(0,1/0),this.altAudio!==tp.DISABLED&&(this.getLevelDetails()?.fragmentStart||0)>this.lastCurrentTime&&super.flushMainBuffer(0,1/0,`audio`)}getBufferOutput(){return this.mediaBuffer&&this.altAudio===tp.SWITCHED?this.mediaBuffer:this.media}checkFragmentChanged(){let e=this.fragPlaying;if(!this.checkFragPlaying())return!1;let t=this.fragPlaying;if(t){let n=t.level;this.hls.trigger(L.FRAG_CHANGED,{frag:t,previousFrag:e}),e?.level!==n&&this.hls.trigger(L.LEVEL_SWITCHED,{level:n})}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===tp.SWITCHED&&!this.audioOnly?`video`:null}onMediaAttached(e,t){super.onMediaAttached(e,t);let n=t.media;Y(n,`playing`,this.onMediaPlaying),Y(n,`seeked`,this.onMediaSeeked)}onMediaDetaching(e,t){let{media:n}=this;n&&(X(n,`playing`,this.onMediaPlaying),X(n,`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(L.BUFFER_RESET,void 0),this.couldBacktrack=!1,this.backtrackFragment=void 0,this.altAudio=tp.DISABLED,this.audioOnly=!1}onManifestParsed(e,t){let n=!1,r=!1;for(let e=0;e<t.levels.length;e++){let i=t.levels[e].audioCodec;i&&(n||=i.indexOf(`mp4a.40.2`)!==-1,r||=i.indexOf(`mp4a.40.5`)!==-1)}this.audioCodecSwitch=n&&r&&!ep(),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:n}=this;if(!n||this.state!==Q.IDLE)return;let r=t.levelInfo;(!r.details||r.details.live&&(this.levelLastLoaded!==r||r.details.expired)||this.waitForCdnTuneIn(r.details))&&(this.state=Q.WAITING_LEVEL)}onLevelLoaded(e,t){var n;let{levels:r,startFragRequested:i}=this,a=t.level,o=t.details,s=o.totalduration;if(!r){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:${s}`);let c=t.levelInfo,l=this.fragCurrent;l&&(this.state===Q.FRAG_LOADING||this.state===Q.FRAG_LOADING_WAITING_RETRY)&&l.level!==t.level&&l.loader&&this.abortCurrentFrag();let u=0;if(o.live||(n=c.details)!=null&&n.live){if(this.checkLiveUpdate(o),o.deltaUpdateFailed)return;u=this.alignPlaylists(o,c.details,this.levelLastLoaded?.details)}if(c.details=o,this.levelLastLoaded=c,i||this.setStartPosition(o,u),this.hls.trigger(L.LEVEL_UPDATED,{details:o,level:a}),this.state===Q.WAITING_LEVEL){if(this.waitForCdnTuneIn(o))return;this.state=Q.IDLE}i&&o.live&&this.synchronizeToLiveEdge(o),this.initPTS.some((e,t)=>{if(t>=o.startCC)return!0;delete this.initPTS[t]}),this.tick()}synchronizeToLiveEdge(e){let{config:t,media:n}=this;if(!n)return;let r=this.hls.liveSyncPosition,i=this.playhead,a=e.fragmentStart,o=e.edge,s=i>=a-t.maxFragLookUpTolerance&&i<=o;if(r!==null&&n.duration>r&&(i<r||!s)){let a=t.liveMaxLatencyDuration===void 0?t.liveMaxLatencyDurationCount*e.targetduration:t.liveMaxLatencyDuration;if((!s&&n.readyState<4||i<o-a)&&(this._hasEnoughToStart||(this.nextLoadPosition=r),n.readyState)){if(this.warn(`Playback: ${i} is located too far from the end of live sliding playlist: ${o}, reset currentTime to : ${r}`),this.config.liveSyncMode===`buffered`){var c;let e=J.bufferInfo(n,r,0);if(!((c=e.buffered)!=null&&c.length)){n.currentTime=r;return}if(e.start<=i){n.currentTime=r;return}let{nextStart:t}=J.bufferedInfo(e.buffered,i,0);t&&(n.currentTime=t)}else n.currentTime=r}}}_handleFragmentLoadProgress(e){let t=e.frag,{part:n,payload:r}=e,{levels:i}=this;if(!i){this.warn(`Levels were reset while fragment load was in progress. Fragment ${t.sn} of level ${t.level} will not be buffered`);return}let a=i[t.level];if(!a){this.warn(`Level ${t.level} not found on progress`);return}let o=a.details;if(!o){this.warn(`Dropping fragment ${t.sn} of level ${t.level} after level details were reset`),this.fragmentTracker.removeFragment(t);return}let s=a.videoCodec,c=o.PTSKnown||!o.live,l=t.initSegment?.data,u=this._getAudioCodec(a),d=this.transmuxer=this.transmuxer||new Al(this.hls,z.MAIN,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)),f=n?n.index:-1,p=f!==-1,{decryptRange:m,byteRange:h}=qa(t,n,this.iframesOnly),g=new Qa(t.level,t.sn,t.stats.chunkCount,h?h.end-h.start:r.byteLength,f,p,t.duration,this.iframesOnly,m),_=this.initPTS[t.cc];d.push(r,l,u,s,t,n,o.totalduration,c,g,_)}onAudioTrackSwitching(e,t){let n=this.hls,r=this.altAudio!==tp.DISABLED;if(Yi(t.url,n))this.altAudio=tp.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 e=this.fragCurrent;e&&(this.log(`Switching to main audio track, cancel main fragment load`),e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.resetTransmuxer(),this.resetLoadingState()}else this.audioOnly&&this.resetTransmuxer();if(r){this.altAudio=tp.DISABLED,this.fragmentTracker.removeAllFragments(),n.once(L.BUFFER_FLUSHED,()=>{this.hls&&this.hls.trigger(L.AUDIO_TRACK_SWITCHED,t)}),n.trigger(L.BUFFER_FLUSHING,{startOffset:0,endOffset:1/0,type:null});return}n.trigger(L.AUDIO_TRACK_SWITCHED,t)}}onAudioTrackSwitched(e,t){let n=Yi(t.url,this.hls);if(n){let e=this.videoBuffer;e&&this.mediaBuffer!==e&&(this.log(`Switching on alternate audio, use video.buffered to schedule main fragment loading`),this.mediaBuffer=e)}this.altAudio=n?tp.SWITCHED:tp.DISABLED,this.tick()}onBufferCreated(e,t){let n=t.tracks,r,i,a=!1;for(let e in n){let t=n[e];if(t.id===`main`){if(i=e,r=t,e===`video`){let t=n[e];t&&(this.videoBuffer=t.buffer)}}else a=!0}a&&r?(this.log(`Alternate track found, use ${i}.buffered to schedule main fragment loading`),this.mediaBuffer=r.buffer):this.mediaBuffer=this.media}onFragBuffered(e,t){let{frag:n,part:r}=t,i=n.type===z.MAIN;if(i){if(this.fragContextChanged(n)){this.warn(`Fragment ${n.sn}${r?` p: `+r.index:``} of level ${n.level} finished buffering, but was aborted. state: ${this.state}`),this.state===Q.PARSED&&(this.state=Q.IDLE);return}let e=!1;if(Tt(n)&&(e=!!n.gap&&!n.tagList.some(e=>e[0]===`GAP`)),this.fragBufferedComplete(n,r),e){n.stats.retry++;let e=this.levels?.[n.level];e&&e.fragmentError++}}let a=this.media;a&&(!this._hasEnoughToStart&&J.getBuffered(a).length&&(this.seekToStartPos(),this._hasEnoughToStart=!0),i&&this.tick())}get hasEnoughToStart(){return this._hasEnoughToStart}onError(e,t){if(t.fatal){this.state=Q.ERROR;return}switch(t.details){case I.FRAG_GAP:case I.FRAG_PARSING_ERROR:case I.FRAG_DECRYPT_ERROR:case I.FRAG_LOAD_ERROR:case I.FRAG_LOAD_TIMEOUT:case I.KEY_LOAD_ERROR:case I.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(z.MAIN,t);break;case I.LEVEL_LOAD_ERROR:case I.LEVEL_LOAD_TIMEOUT:case I.LEVEL_PARSING_ERROR:!t.levelRetry&&this.state===Q.WAITING_LEVEL&&t.context?.type===R.LEVEL&&(this.state=Q.IDLE);break;case I.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 I.MEDIA_SOURCE_REQUIRES_RESET:this.onSourceBufferError(z.MAIN,t);break;case I.BUFFER_ADD_CODEC_ERROR:case I.BUFFER_APPEND_ERROR:if(t.parent!==`main`)return;this.reduceLengthAndFlushBuffer(t)&&this.resetLoadingState();break;case I.BUFFER_FULL_ERROR:if(t.parent!==`main`)return;this.reduceLengthAndFlushBuffer(t)&&(!this.config.interstitialsController&&this.config.assetPlayerId?this._hasEnoughToStart=!0:this.flushMainBuffer(0,1/0));break;case I.INTERNAL_EXCEPTION:this.recoverWorkerError(t)}}onFragLoadEmergencyAborted(){this.state=Q.IDLE,this._hasEnoughToStart||(this.startFragRequested=!1,this.nextLoadPosition=this.lastCurrentTime),this.tickImmediate()}onBufferFlushed(e,{type:t}){if(t!==B.AUDIO||!this.altAudio){let e=(t===B.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;e&&(this.afterBufferFlushed(e,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,n=this.startPosition;if(n>=0&&t<n){if(e.seeking){this.log(`could not seek to ${n}, already seeking at ${t}`);return}let r=this.timelineOffset;r&&n&&(n+=r);let i=this.getLevelDetails(),a=J.getBuffered(e),o=a.length?a.start(0):0,s=o-n,c=Math.max(this.config.maxBufferHole,this.config.maxFragLookUpTolerance);(this.config.startOnSegmentBoundary||s>0&&(s<c||this.loadingParts&&s<2*(i?.partTarget||0)))&&(this.log(`adjusting start position by ${s} to match buffer start`),n+=s,this.startPosition=n),t<n&&(this.log(`seek to target start position ${n} from current time ${t} buffer start ${o}`),e.currentTime=n)}}_getAudioCodec(e){let t=this.config.defaultAudioCodec||e.audioCodec;return this.audioCodecSwap&&t&&(this.log(`Swapping audio codec`),t=t.indexOf(`mp4a.40.5`)===-1?`mp4a.40.5`:`mp4a.40.2`),t}_loadBitrateTestFrag(e,t){e.bitrateTest=!0,this._doFragLoad(e,t).then(e=>{let{hls:n}=this,r=e?.frag;if(!r||this.fragContextChanged(r))return;t.fragmentError=0,this.state=Q.IDLE,this.startFragRequested=!1,this.bitrateTest=!1;let i=r.stats;i.parsing.start=i.parsing.end=i.buffering.start=i.buffering.end=self.performance.now(),n.trigger(L.FRAG_LOADED,e),r.bitrateTest=!1}).catch(t=>{this.state!==Q.STOPPED&&this.state!==Q.ERROR&&(this.warn(t),this.resetFragmentLoading(e))})}_handleTransmuxComplete(e){let t=this.playlistType,{hls:n}=this,{remuxResult:r,chunkMeta:i}=e,a=this.getCurrentContext(i);if(!a){this.resetWhenMissingContext(i);return}let{frag:o,part:s,level:c}=a,{video:l,text:u,id3:d,initSegment:f}=r,{details:p}=c,m=this.altAudio?void 0:r.audio;if(this.fragContextChanged(o)){this.fragmentTracker.removeFragment(o);return}if(this.state=Q.PARSING,f){let e=f.tracks;if(e){let r=o.initSegment||o;if(this.unhandledEncryptionError(f,o))return;this._bufferInitSegment(c,e,r,i),n.trigger(L.FRAG_PARSING_INIT_SEGMENT,{frag:r,id:t,tracks:e})}let r=f.initPTS,a=f.timescale,s=this.initPTS[o.cc];if(P(r)&&(!s||s.baseTime!==r||s.timescale!==a)){let e=f.trackId;this.initPTS[o.cc]={baseTime:r,timescale:a,trackId:e};let i=this.initPTS.slice(0);n.trigger(L.INIT_PTS_FOUND,{timestampOffsets:i,frag:o,id:t,initPTS:r,timescale:a,trackId:e})}}if(l&&p){m&&l.type===`audiovideo`&&this.logMuxedErr(o);let e=p.fragments[o.sn-1-p.startSN],t=o.sn===p.startSN,n=!e||o.cc>e.cc;if(r.independent!==!1){let{startPTS:e,endPTS:r,startDTS:a,endDTS:c}=l;if(s)s.elementaryStreams[l.type]={startPTS:e,endPTS:r,startDTS:a,endDTS:c};else if(l.firstKeyFrame&&l.independent&&i.id===1&&!n&&(this.couldBacktrack=!0),l.dropped&&l.independent){let i=this.getMainFwdBufferInfo(),a=(i?i.end:this.getLoadPosition())+this.config.maxBufferHole,s=l.firstKeyFramePTS?l.firstKeyFramePTS:e;if(!t&&a<s-this.config.maxBufferHole&&!n){this.backtrack(o);return}n&&(o.gap=!0),o.setElementaryStreamInfo(l.type,o.start,r,o.start,c,!0)}else t&&e-(p.appliedTimelineOffset||0)>zf&&(o.gap=!0);o.setElementaryStreamInfo(l.type,e,r,a,c),this.backtrackFragment&&=o,this.bufferFragmentData(l,o,s,i,t||n)}else if(t||n)o.gap=!0;else{this.backtrack(o);return}}if(m){let{startPTS:e,endPTS:t,startDTS:n,endDTS:r}=m;s&&(s.elementaryStreams[B.AUDIO]={startPTS:e,endPTS:t,startDTS:n,endDTS:r}),o.setElementaryStreamInfo(B.AUDIO,e,t,n,r),this.bufferFragmentData(m,o,s,i)}if(p&&d!=null&&d.samples.length){let e={id:t,frag:o,details:p,samples:d.samples};n.trigger(L.FRAG_PARSING_METADATA,e)}if(p&&u){let e={id:t,frag:o,details:p,samples:u.samples};n.trigger(L.FRAG_PARSING_USERDATA,e)}}logMuxedErr(e){this.warn(`${Tt(e)?`Media`:`Init`} segment with muxed audiovideo where only video expected: ${e.url}`)}_bufferInitSegment(e,t,n,r){if(this.state!==Q.PARSING)return;this.audioOnly=!!t.audio&&!t.video,this.altAudio&&!this.audioOnly&&(delete t.audio,t.audiovideo&&this.logMuxedErr(n));let{audio:i,video:a,audiovideo:o}=t;if(i){let n=e.audioCodec,r=si(i.codec,n);if(r===`mp4a`&&(r=`mp4a.40.5`),this.audioCodecSwitch){r&&=r.indexOf(`mp4a.40.5`)===-1?`mp4a.40.5`:`mp4a.40.2`;let e=i.metadata;e&&`channelCount`in e&&(e.channelCount||1)!==1&&!Gr()&&(r=`mp4a.40.5`)}r&&r.indexOf(`mp4a.40.5`)!==-1&&Jr()&&i.container!==`audio/mpeg`&&(r=`mp4a.40.2`,this.log(`Android: force audio codec to ${r}`)),n&&n!==r&&this.log(`Swapping manifest audio codec "${n}" for "${r}"`),i.levelCodec=r,i.id=z.MAIN,this.log(`Init audio buffer, container:${i.container}, codecs[selected/level/parsed]=[${r||``}/${n||``}/${i.codec}]`),delete t.audiovideo}if(a){a.levelCodec=e.videoCodec,a.id=z.MAIN;let n=a.codec;if(n?.length===4)switch(n){case`hvc1`:case`hev1`:a.codec=`hvc1.1.6.L120.90`;break;case`av01`:a.codec=`av01.0.04M.08`;break;case`avc1`:a.codec=`avc1.42e01e`}this.log(`Init video buffer, container:${a.container}, codecs[level/parsed]=[${e.videoCodec||``}/${n}]${a.codec===n?``:` parsed-corrected=`+a.codec}${a.supplemental?` supplemental=`+a.supplemental:``}`),delete t.audiovideo}o&&(this.iframesOnly&&this.logMuxedErr(n),this.log(`Init audiovideo buffer, container:${o.container}, codecs[level/parsed]=[${e.codecs}/${o.codec}]`),delete t.video,delete t.audio);let s=Object.keys(t);if(s.length){if(this.hls.trigger(L.BUFFER_CODECS,t),!this.hls)return;s.forEach(e=>{let i=t[e].initSegment;i!=null&&i.byteLength&&this.hls.trigger(L.BUFFER_APPENDING,{type:e,data:i,frag:n,part:null,chunkMeta:r,parent:n.type})})}this.tickImmediate()}getMainFwdBufferInfo(){let e=this.getBufferOutput();return this.getFwdBufferInfo(e,z.MAIN)}get maxBufferLength(){let{levels:e,level:t}=this,n=e?.[t];return n?this.getMaxBufferLength(n.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=Q.IDLE}get nextLevel(){let e=this.nextBufferedFrag;return e?e.level:-1}get currentFrag(){if(this.fragPlaying)return this.fragPlaying;let e=this.media?.currentTime||this.lastCurrentTime;return P(e)?this.getAppendedFrag(e):null}get currentProgramDateTime(){let e=this.media?.currentTime||this.lastCurrentTime;if(P(e)){let t=this.getLevelDetails(),n=this.currentFrag||(t?na(null,t.fragments,e):null);if(n){let t=n.programDateTime;if(t!==null){let r=t+(e-n.start)*1e3;return new Date(r)}}}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}},ip=class extends rp{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 e=this.media;e!=null&&e.seeking&&(e.currentTime=e.currentTime)},this.onMediaSeeking=()=>{}}setInitPts(e){this.initPTS=e.slice()}loadMediaAt(e,t){if(!this.hls)return;let{seekOnAppend:n}=t,r=e+this.timelineOffset;switch(this.nextLoadPosition=this.lastCurrentTime=r,this.startPosition=e,this.state){case Q.STOPPED:case Q.ENDED:case Q.ERROR:this.state=Q.IDLE}this.state===Q.IDLE?(this.hls.resumeBuffering(),this.tick(),this.currentOp=[r,t]):this.nextOp=[r,t],this.hls.off(L.BUFFERED_TO_END,this.onBufferedToEnd);let i=this.media;n&&i&&this.seekTo(r)&&(this.currentOp=[r,t],this.nextOp=void 0,this.flushPipeline(r,!0))}seekTo(e){let t=this.media;if(t){let n=this.getLevelDetails()?.edge,r=n===void 0?t.duration:n;if(e>=r&&(e=r-.01),J.bufferInfo(t,e,0).len>0&&this.getBufferedAt(e))return t.currentTime=e,!0}return!1}getBufferedAt(e){return this.fragmentTracker.getBufferedFrag(e,z.MAIN)}cacheSet(e,t){if(!this.hls)return;e.data=t;let n=this.cached;n.push(e),this.cachedSize+=t.buffer.byteLength;let r=this.hls.config.iframeCacheLimit;for(;this.cachedSize>r&&n.length>1;){let e=n.shift();if(e.data)this.cachedSize-=e.data.byteLength,e.data=void 0;else{this.cached=n.filter(e=>!!e.data),this.cachedSize=n.reduce((e,{data:t})=>t?t.buffer.byteLength:0,0);break}}}onHandlerDestroying(){this.cached.length=0,this.cachedSize=0,super.onHandlerDestroying()}_handleFragmentLoadProgress(e){let t=e.frag,{part:n,payload:r}=e;this.cacheFragmentData&&!n&&r!=null&&r.byteLength&&!t.data&&Tt(t)&&this.cacheSet(t,new Uint8Array(r.slice(0))),super._handleFragmentLoadProgress(e)}loadFragment(e,t,n){let r=this.fragmentTracker.getState(e);if((r===Z.NOT_LOADED||r===Z.PARTIAL)&&this.canReplayCached(e)){this.replayCachedFragment(e);return}super.loadFragment(e,t,n)}canReplayCached(e){var t;if(!this.cacheFragmentData||!((t=e.data)!=null&&t.byteLength))return!1;let n=e.decryptdata;return n?.keyFormat!==`identity`||!!n.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 n=e.stats=new Ct;n.loading.start=n.loading.first=n.loading.end=self.performance.now(),n.loaded=n.total=t.byteLength,n.chunkCount=1,this.state=Q.FRAG_LOADING;let r={frag:e,part:null,payload:t,networkDetails:null};this._handleFragmentLoadProgress(r),this.hls.trigger(L.FRAG_LOADED,r),this._handleFragmentLoadComplete(r)}fragBufferedComplete(e,t){super.fragBufferedComplete(e,t);let{currentOp:n,nextOp:r}=this;this.currentOp=this.nextOp=void 0,this.state=Q.STOPPED,n!=null&&n[1].seekOnAppend&&(this.flushPipeline(n[0],!r),this.seekTo(n[0])||this.log(`Could not seek to ${n[0]} after fragment buffered (superseded or flushed) buffer: ${this.media?_a(J.getBuffered(this.media)):`none`}`)),r&&this.loadMediaAt.apply(this,r)}flushPipeline(e,t){if(t){let t=this.media;if(t){let n=J.bufferInfo(t,e,0),r=n.len?n.nextStart:0;r&&(this.fragmentTracker.removeFragmentsInRange(r,1/0,z.MAIN),this.flushMainBuffer(r,1/0))}this.hls.once(L.BUFFERED_TO_END,this.onBufferedToEnd)}this.hls.trigger(L.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,n){let r=this.initDetails;return this.initDetails=null,super.alignPlaylists(e,t,n||r||void 0)}getMainFwdBufferInfo(){let e=this.playhead,t=this.getBufferedAt(e);if(t){let n=t.duration;return{len:n,start:e,end:e+n,bufferedIndex:-1}}return{len:0,start:e,end:e,bufferedIndex:-1}}_streamEnded(){let e=this.playhead,t=this.fragmentTracker.getBufferedFrag(e,z.MAIN);return!!(t!=null&&t.endList)}},ap=class extends ip{constructor(...e){super(...e),this._img=void 0,this.queued=void 0,this.cacheFragmentData=!1}get image(){return this._img}set image(e){let t=this._img?.src;t&&self.URL.revokeObjectURL(t),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 Q.STOPPED:case Q.ENDED:case Q.ERROR:this.state=Q.IDLE}if(this.state===Q.IDLE){if(this.hls.resumeBuffering(),this.media||={},this.tick(),this.state===Q.IDLE){let t=this.getBufferedAt(e);t&&(this.fragCurrent=t,this.updateImage(t,null))}}else{let n=this.fragCurrent;(!n||e>=n.start&&e<n.end)&&(this.queued=[t])}}updateImage(e,t,n){let r=e.data;r||this.fragmentTracker.removeFragment(e);let i=this._img;if(i&&r){let a=self.performance.now(),o=t?t.stats:e.stats;o.buffering.start=e.stats.buffering.start=a,i.onload=()=>{if(!this.hls)return;let r=this.hls.levels[e.level];r!=null&&r.fragmentError&&(r.fragmentError=0,e.stats.retry=0);let i=self.performance.now(),a=t?t.stats:e.stats;a.buffering.end=e.stats.buffering.end=i,this.hls.trigger(L.FRAG_BUFFERED,{frag:e,part:t,stats:a,id:e.type,chunkMeta:n})},i.onerror=()=>{this.handleError(`Image decode error`,e,t,n)};let s=i.src;s&&self.URL.revokeObjectURL(s);let c=new Blob([r],{type:`image/jpeg`});i.src=self.URL.createObjectURL(c)}else this.state=Q.STOPPED,this.processQueued()}processQueued(){let e=this.queued;this.queued=void 0,e&&this.loadMediaAt.apply(this,e)}handleError(e,t,n,r){if(!this.hls)return;let i=Error(e);this.hls.trigger(L.ERROR,{type:F.MEDIA_ERROR,details:I.FRAG_PARSING_ERROR,chunkMeta:r,frag:t,part:n,fatal:!1,error:i,err:i})}_bufferInitSegment(){}bufferFragmentData(e,t,n,r){super.bufferFragmentData(e,t,n,r,!0);let i=K(new Uint8Array(e.data1),[`mdat`]);if(i.length===0){this.handleError(`Could not find I-Frame mdat`,t,n,r);return}let a=t;this.cacheSet(a,i[0]),this.updateImage(a,n,r)}fragBufferedComplete(e,t){this.fragmentTracker.fragBuffered(e,!0),super.fragBufferedComplete(e,t),this.processQueued()}checkFragPlaying(){let e=this.fragPrevious?.start;if(e!==void 0){let t=this.getAppendedFrag(e);if(t&&!Et(t,this.fragPlaying))return this.fragPlaying=t,!0}return!1}getMainFwdBufferInfo(){return{len:0,start:this.playhead,end:this.playhead,bufferedIndex:-1}}},op=10,sp=`Image I-Frame player does not accept HTMLMediaElements`,cp={seekOnAppend:!0},lp,up,dp=class extends Xt{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,lp||=fp(t),up||=pp(lp),this.hls=e,this.iframeInstances=[],this.registerListeners()}registerListeners(){let e=this.hls;e&&(e.on(L.MANIFEST_LOADING,this.clearAsset,this),e.on(L.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(L.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(L.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(L.FRAG_BUFFERED,this.onFragBuffered,this),e.on(L.DESTROYING,this.onDestroying,this))}unregisterListeners(){let e=this.hls;e&&(e.off(L.MANIFEST_LOADING,this.clearAsset,this),e.off(L.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(L.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(L.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(L.FRAG_BUFFERED,this.onFragBuffered,this),e.off(L.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}){let n=this.hls?.pathwayPriority;t.length&&n&&this.iframeInstances.forEach(e=>{e.pathwayPriority=n})}onInitPtsFound(e,{id:t,timestampOffsets:n}){t===z.MAIN&&(this.initPTS=n)}onFragBuffered(e,t){let n=this.hls;n&&n.hasEnoughToStart&&(n.mainForwardBufferInfo?.len||0)>op&&this.iframeInstances.forEach(e=>{if(!e.loadingEnabled){var t;e.startLoad(((t=this.hls)==null||(t=t.media)==null?void 0:t.currentTime)||0)}})}createIFramePlayer(e){return this.createInstance(lp,this.hls?.iframeVariants,e)}createImageIFramePlayer(e){let t=this.hls?.iframeVariants.filter(e=>e.imageCodec);return this.createInstance(up,t,e,`image-`)}createInstance(e,t,n,r){let{hls:i}=this;if(!i)return null;let{url:a,userConfig:o,latestLevelDetails:s,loadLevelObj:c,loadLevel:l,bandwidthEstimate:u,sessionId:d}=i,{stats:f,variableList:p}=this;if(!(t!=null&&t.length)||!f||!a)return null;let m=`${r||``}iframe-player-${this.instanceCounter++}`,h=i.levels,g=c||h[l],_=Zi(g,o.videoPreference),v=g?.pathwayId||`.`,y=new e(H(H({},o),{},{loggerId:m,primarySessionId:d,videoPreference:_,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},n),a,this.initPTS,s);return this.iframeInstances=this.iframeInstances.filter(e=>!e.url),this.iframeInstances.push(y),y.trigger(L.MANIFEST_LOADED,{levels:t,contentSteering:{uri:``,pathwayId:v},sessionKeys:null,audioTracks:[],iframeVariants:[],sessionData:null,startTimeOffset:null,stats:f,networkDetails:null,url:a,variableList:p}),y}};function fp(e){return class extends e{constructor(e,t,n,r){e.streamController||=ip,super(e),this._url=t,this.streamController.setInitPts(n),this.streamController.initDetails=r}loadSource(){}loadMediaAt(e,t=cp){if(e<0)return;let n=H(H({},cp),t);this.loadingEnabled||this.startLoad(e),this.streamController.loadMediaAt(e,n)}}}function pp(e){return class extends e{constructor(e,t,n,r){e.cmcdController=void 0,e.emeController=void 0,e.streamController||=ap,e.capLevelController=void 0,e.bufferController=void 0,super(e,t,n,r)}attachImage(e){this.streamController.image=e}detachImage(){this.streamController.image=void 0}loadSource(){}attachMedia(){throw Error(sp)}detachMedia(){}recoverMediaError(){}transferMedia(){return null}loadMediaAt(e){if(e<0)return null;this.loadingEnabled||this.startLoad(e),this.streamController.loadMediaAt(e)}}}var mp=.025,hp=function(e){return e[e.Point=0]=`Point`,e[e.Range=1]=`Range`,e}({});function gp(e,t,n){return`${e.identifier}-${n+1}-${df(t)}`}var _p=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){if(e>0&&e>=this.assetList.length)return!0;let t=this.playoutLimit;return e<=0||isNaN(t)?!1:t===0||(this.assetList[e]?.startOffset||0)>t}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 yp(t,e)?vp(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;return t-vp(t,e)<.1}return!1}get resumptionOffset(){let e=this.resumeOffset,t=P(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 yp(t,e)?vp(e,t):e}return e}get appendInPlace(){return this.appendInPlaceStarted?!0:!this.appendInPlaceDisabled&&!!(!this.cue.once&&!this.cue.pre&&this.startIsAligned&&(isNaN(this.playoutLimit)&&isNaN(this.resumeOffset)||this.resumeOffset&&this.duration&&Math.abs(this.resumeOffset-this.duration)<mp))}set appendInPlace(e){if(this.appendInPlaceStarted){this.resetOnResume=!e;return}this.appendInPlaceDisabled=!e}get timelineStart(){return this._timelineStart===null?this.startTime:this._timelineStart}set timelineStart(e){this._timelineStart=e}get duration(){let e=this.playoutLimit,t;return t=this._duration===null?this.dateRange.duration?this.dateRange.duration:this.dateRange.plannedDuration||0:this._duration,!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`?hp.Range:hp.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 Sp(this)}};function vp(e,t){return e-t.start<t.duration/2&&!(Math.abs(e-(t.start+t.duration))<mp)?t.start:t.start+t.duration}function yp(e,t){return t>e.start-mp&&t<e.start+e.duration+mp}function bp(e,t,n){let r=new self.URL(e,n);return r.protocol!==`data:`&&wi(r,`_HLS_primary_id`,t),r}function xp(e,t){for(;(n=e.assetList[++t])!=null&&n.error;)var n;return t}function Sp(e){return`["${e.identifier}" ${e.cue.pre?`<pre>`:e.cue.post?`<post>`:``}${e.timelineStart.toFixed(2)}-${e.resumeTime.toFixed(2)}]`}function Cp(e){let t=e.timelineStart,n=e.duration||0;return`["${e.identifier}" ${t.toFixed(2)}-${(t+n).toFixed(2)}]`}var wp=class{constructor(e,t,n,r){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(L.PLAYOUT_LIMIT_REACHED,{})};let i=this.hls=new e(t);this.interstitial=n,this.assetItem=r;let a=()=>{this.hasDetails=!0};i.once(L.LEVEL_LOADED,a),i.once(L.AUDIO_TRACK_LOADED,a),i.once(L.SUBTITLE_TRACK_LOADED,a),i.on(L.MEDIA_ATTACHING,(e,{media:t})=>{this.removeMediaListeners(),this.mediaAttached=t,this.interstitial.playoutLimit&&(t.addEventListener(`timeupdate`,this.checkPlayout),this.appendInPlace&&i.on(L.BUFFER_APPENDED,()=>{let e=this.bufferedEnd;this.reachedPlayout(e)&&(this._bufferedEosTime=e,i.trigger(L.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=bp(t,e.config.primarySessionId||``).href}catch{}e.loadSource(t)}}}bufferedInPlaceToEnd(e,t){var n;if(!this.appendInPlace)return!1;if((n=this.hls)!=null&&n.bufferedToEnd)return!0;if(!e)return!1;let r=Math.min(this._bufferedEosTime||1/0,this.duration),i=this.timelineOffset+(t||0),a=J.bufferInfo(e,i,.02);return this.getAssetTime(a.end)>=r-.02}reachedPlayout(e){let t=this.interstitial.playoutLimit;return this.startOffset+e>=t}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(){return this.hls?.media||null}get bufferedEnd(){let e=this.media||this.mediaAttached;if(!e)return this._bufferedEosTime?this._bufferedEosTime:this.currentTime;let t=J.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 n=t-this.startOffset;if(n>0&&n<e)return n}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(){return this.hls?.config.timelineOffset||0}set timelineOffset(e){let t=this.timelineOffset;if(e!==t){let n=e-t;if(Math.abs(n)>1/9e4&&this.hls){if(this.hasDetails)throw Error(`Cannot set timelineOffset after playlists are loaded`);this.hls.config.timelineOffset=e}}}getAssetTime(e){let t=this.timelineOffset,n=this.duration;return Math.min(Math.max(0,e-t),n)}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(){return this.bufferSnapShot(),this.hls?.transferMedia()||null}resetDetails(){let e=this.hls;if(e&&this.hasDetails){e.stopLoad();let t=e=>delete e.details;e.levels.forEach(t),e.allAudioTracks.forEach(t),e.allSubtitleTracks.forEach(t),this.hasDetails=!1}}on(e,t,n){var r;(r=this.hls)==null||r.on(e,t)}once(e,t,n){var r;(r=this.hls)==null||r.once(e,t)}off(e,t,n){var r;(r=this.hls)==null||r.off(e,t)}toString(){return`HlsAssetPlayer: ${Cp(this.assetItem)} ${this.hls?.sessionId} ${this.appendInPlace?`append-in-place`:``}`}},Tp=.033,Ep=class extends Xt{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((n,r)=>e<=r.startOffset&&t>r.startOffset?(delete r.error,n+1):n,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 n=-1;e.nextEvent?n=this.findEventIndex(e.nextEvent.identifier)-1:e.previousEvent&&(n=this.findEventIndex(e.previousEvent.identifier)+1);let r=this.items;if(r)for(r[n]||(t===void 0&&(t=e.start),n=this.findItemIndexAtTime(t));n>=0&&(i=r[n])!=null&&i.event;){var i;n--}return n}findItemIndexAtTime(e,t){let n=this.items;if(n)for(let r=0;r<n.length;r++){let i=n[r];t&&t!==`primary`&&(i=i[t]);let a=i.start,o=n[r].event,s=o!=null&&o.cue.pre?o.duration:i.end;if(e===a||e>a&&e<s)return r}return-1}findJumpRestrictedIndex(e,t){let n=this.items;if(n)for(let r=e;r<=t&&n[r];r++){let e=n[r].event;if(e!=null&&e.restrictions.jump&&!e.appendInPlace)return r}return-1}findEventIndex(e){let t=this.items;if(t){for(let n=t.length;n--;)if(t[n].event?.identifier===e)return n}return-1}findAssetIndex(e,t){let n=e.assetList,r=n.length;if(r>1)for(let e=0;e<r;e++){let i=n[e];if(!i.error){let n=i.timelineStart;if(t===n||t>n&&(t<n+(i.duration||0)||e===r-1))return e}}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 e=t.assetList,n=e[e.length-1];if(n)return n.identifier}return null}parseInterstitialDateRanges(e,t,n=0){let r=e.main.details,{dateRanges:i}=r,a=this.events,o=this.parseDateRanges(i,{url:r.url},t),s=Object.keys(i),c=a?a.filter(e=>s.indexOf(e.identifier)===-1):[];o.length&&o.sort((e,t)=>{let n=e.cue.pre,r=e.cue.post,i=t.cue.pre,a=t.cue.post;if(n&&!i)return-1;if(i&&!n||r&&!a)return 1;if(a&&!r)return-1;if(!n&&!i&&!r&&!a){let n=e.startTime,r=t.startTime;if(n!==r)return n-r}return e.dateRange.tagOrder-t.dateRange.tagOrder}),this.events=o,c.forEach(e=>{this.removeEvent(e)}),this.updateSchedule(e,c,n)}updateSchedule(e,t=[],n=0,r=!1){let i=this.events||[];if(i.length||t.length||this.length<2){let a=this.items,o=this.parseSchedule(i,e,n);(r||t.length||a?.length!==o.length||o.some((e,t)=>Math.abs(e.playout.start-a[t].playout.start)>.005||Math.abs(e.playout.end-a[t].playout.end)>.005))&&(this.items=o,this.onScheduleUpdate(t,a))}}parseDateRanges(e,t,n){let r=[],i=Object.keys(e);for(let a=0;a<i.length;a++){let o=i[a],s=e[o];if(s.isInterstitial){let e=this.eventMap[o];e?e.setDateRange(s):(e=new _p(s,t),this.eventMap[o]=e,n===!1&&(e.appendInPlace=n)),r.push(e)}}return r}parseSchedule(e,t,n=0){let r=[],i=t.main.details,a=i.live?1/0:i.edge,o=0;if(e=e.filter(e=>!e.error&&!(e.cue.once&&e.hasPlayed)),e.length){this.resolveOffsets(e,t);let s=0,c=0;if(e.forEach((t,l)=>{let u=t.cue.pre,d=t.cue.post,f=e[l-1]||null,p=t.appendInPlace,m=d?a:t.startOffset,h=t.duration,g=t.timelineOccupancy===hp.Range?h:0,_=u&&i.live?n+(t.resumeOffset||0):0,v=_||t.resumptionOffset,y=f?.startTime===m,b=m+t.cumulativeDuration,x=p?b+h:m+v;if(u||!d&&m<=0){let e=c;c+=g,t.timelineStart=b;let n=o;o+=h,r.push({event:t,start:b,end:x,playout:{start:n,end:o},integrated:{start:e,end:c}})}else if(m<=a){if(!y){let n=m-s;if(n>Tp){let i=s,a=c;c+=n;let u=o;o+=n;let d={previousEvent:e[l-1]||null,nextEvent:t,start:i,end:i+n,playout:{start:u,end:o},integrated:{start:a,end:c}};r.push(d)}else n>0&&f&&(f.cumulativeDuration+=n,r[r.length-1].end=m)}d&&(x=b),t.timelineStart=b;let n=c;c+=g;let i=o;o+=h,r.push({event:t,start:b,end:x,playout:{start:i,end:o},integrated:{start:n,end:c}})}else return;let S=_||t.resumeTime;s=d||S>a?a:!u&&x&&t.appendInPlaceStarted&&S-x>Tp?x:S}),s<a){let e=s,t=c,n=a-s;c+=n;let i=o;o+=n,r.push({previousEvent:r[r.length-1]?.event||null,nextEvent:null,start:s,end:e+n,playout:{start:i,end:o},integrated:{start:t,end:c}})}this.setDurations(a,o,c)}else r.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 r}setDurations(e,t,n){this.durations={primary:e,playout:t,integrated:n}}resolveOffsets(e,t){let n=t.main.details,r=n.live?1/0:n.edge,i=0,a=-1;e.forEach((o,s)=>{let c=o.cue.pre,l=o.cue.post,u=c?0:l?r:o.startTime;this.updateAssetDurations(o),a===u?o.cumulativeDuration=i:(i=0,a=u),!l&&o.snapOptions.in&&(o.resumeAnchor=na(null,n.fragments,o.startOffset+o.resumptionOffset,0,0)||void 0),o.appendInPlace&&!o.appendInPlaceStarted&&(this.primaryCanResumeInPlaceAt(o,t)||(o.appendInPlace=!1)),!o.appendInPlace&&s+1<e.length&&e[s+1].startTime-e[s].resumeTime<Tp&&(e[s+1].appendInPlace=!1,e[s+1].appendInPlace&&this.warn(`Could not change append strategy for abutting event ${o}`));let d=P(o.resumeOffset)?o.resumeOffset:o.duration;i+=d})}primaryCanResumeInPlaceAt(e,t){let n=e.resumeTime,r=e.startTime+e.resumptionOffset;return Math.abs(n-r)>mp?(this.log(`"${e.identifier}" resumption ${n} not aligned with estimated timeline end ${r}`),!1):!Object.keys(t).some(r=>{let i=t[r].details,a=i.edge;if(n>=a)return this.log(`"${e.identifier}" resumption ${n} past ${r} playlist end ${a}`),!1;let o=na(null,i.fragments,n);if(!o)return this.log(`"${e.identifier}" resumption ${n} does not align with any fragments in ${r} playlist (${i.fragStart}-${i.fragmentEnd})`),!0;let s=r===`audio`?.175:0;return Math.abs(o.start-n)<mp+s||Math.abs(o.end-n)<mp+s?!1:(this.log(`"${e.identifier}" resumption ${n} not aligned with ${r} fragment bounds (${o.start}-${o.end} sn: ${o.sn} cc: ${o.cc})`),!0)})}updateAssetDurations(e){if(!e.assetListLoaded)return;let t=e.timelineStart,n=0,r=!1,i=!1;for(let a=0;a<e.assetList.length;a++){let o=e.assetList[a],s=t+n;o.startOffset=n,o.timelineStart=s,r||=o.duration===null,i||=!!o.error;let c=o.error?0:o.duration||0;n+=c}e.duration=r&&!i?Math.max(n,e.duration):n}removeEvent(e){e.reset(),delete this.eventMap[e.identifier]}};function Dp(e){return`[${e.event?`"`+e.event.identifier+`"`:`primary`}: ${e.start.toFixed(2)}-${e.end.toFixed(2)}]`}var Op=class{constructor(e){this.hls=void 0,this.hls=e}destroy(){this.hls=null}loadAssetList(e,t){let n=e.assetListUrl,r;try{r=bp(n,this.hls.sessionId,e.baseUrl)}catch(t){let r=this.assignAssetListError(e,I.ASSET_LIST_LOAD_ERROR,t,n);this.hls.trigger(L.ERROR,r);return}t&&r.protocol!==`data:`&&wi(r,`_HLS_start_offset`,``+t);let i=this.hls.config,a=i.loader,o=new a(i),s={type:R.INTERSTITIAL_ASSET_LIST,responseType:`json`,url:r.href},c=i.interstitialAssetListLoadPolicy.default,l={loadPolicy:c,timeout:c.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0};return o.load(s,l,{onSuccess:(t,n,r,i)=>{let a=t.data,o=a?.ASSETS;if(!Array.isArray(o)){let t=this.assignAssetListError(e,I.ASSET_LIST_PARSING_ERROR,Error(`Invalid interstitial asset list`),r.url,n,i);this.hls.trigger(L.ERROR,t);return}e.assetListResponse=a,this.hls.trigger(L.ASSET_LIST_LOADED,{event:e,assetListResponse:a,networkDetails:i})},onError:(t,n,r,i)=>{let a=this.assignAssetListError(e,I.ASSET_LIST_LOAD_ERROR,Error(`Error loading X-ASSET-LIST: HTTP status ${t.code} ${t.text} (${n.url})`),n.url,i,r);this.hls.trigger(L.ERROR,a)},onTimeout:(t,n,r)=>{let i=this.assignAssetListError(e,I.ASSET_LIST_LOAD_TIMEOUT,Error(`Timeout loading X-ASSET-LIST (${n.url})`),n.url,t,r);this.hls.trigger(L.ERROR,i)}}),this.hls.trigger(L.ASSET_LIST_LOADING,{event:e}),o}assignAssetListError(e,t,n,r,i,a){return e.error=n,{type:F.NETWORK_ERROR,details:t,fatal:!1,interstitial:e,url:r,error:n,networkDetails:a,stats:i}}};function kp(e){var t;e==null||(t=e.play())==null||t.catch(()=>{})}function Ap(e,t){return`[${e}] Advancing timeline position to ${t}`}var jp=class extends Xt{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 e=this.currentTime;if(e===void 0||this.playbackDisabled||!this.schedule)return;let t=e-this.timelinePos;if(Math.abs(t)<1/7056e5)return;let n=t<=-.01;this.timelinePos===-1&&!this.effectivePlayingItem&&this.checkStart(),this.timelinePos=e,this.bufferedPos=e;let r=this.playingItem;if(!r){this.checkBuffer();return}if(n&&this.schedule.resetErrorsInRange(e,e-t)&&this.updateSchedule(!0),this.checkBuffer(),n&&e<r.start||e>=r.end){var i;let t=this.findItemIndex(r),a=this.schedule.findItemIndexAtTime(e);if(a===-1&&(a=t+(n?-1:1),this.log(`seeked ${n?`back `:``}to position not covered by schedule ${e} (resolving from ${t} to ${a})`)),!this.isInterstitial(r)&&(i=this.media)!=null&&i.paused&&(this.shouldPlay=!1),!n&&a>t){let e=this.schedule.findJumpRestrictedIndex(t+1,a);if(e>t){this.setSchedulePosition(e);return}}this.setSchedulePosition(a);return}let a=this.playingAsset;if(!a){if(this.playingLastItem&&this.isInterstitial(r)){let t=r.event.assetList[0];t&&(this.endedItem=this.playingItem,this.playingItem=null,this.setScheduleToAssetAtTime(e,t))}return}let o=a.timelineStart,s=a.duration||0;if(n&&e<o||e>=o+s){var c;(c=r.event)!=null&&c.appendInPlace&&(this.clearAssetPlayers(r.event,r),this.flushFrontBuffer(e)),this.setScheduleToAssetAtTime(e,a)}},this.onTimeupdate=()=>{let e=this.currentTime;if(e===void 0||this.playbackDisabled)return;if(this.timelinePos===-1&&!this.effectivePlayingItem&&this.checkStart(),e>this.timelinePos)this.timelinePos=e,e>this.bufferedPos&&this.checkBuffer();else return;let t=this.playingItem;if(!t||this.playingLastItem)return;if(e>=t.end){this.timelinePos=t.end;let e=this.findItemIndex(t);this.setSchedulePosition(e+1)}let n=this.playingAsset;n&&e>=n.timelineStart+(n.duration||0)&&this.setScheduleToAssetAtTime(e,n)},this.onScheduleUpdate=(e,t)=>{let n=this.schedule;if(!n)return;let r=this.playingItem,i=n.events||[],a=n.items||[],o=n.durations,s=e.map(e=>e.identifier),c=!!(i.length||s.length);(c||t)&&this.log(`INTERSTITIALS_UPDATED (${i.length}): ${i}
|
|
45
|
+
Schedule: ${a.map(e=>Dp(e))} pos: ${this.timelinePos}`),s.length&&this.log(`Removed events ${s}`);let l=null,u=null;r&&(l=this.updateItem(r,this.timelinePos),this.itemsMatch(r,l)?this.playingItem=l:this.waitingItem=null);let d=this.waitingItem;d&&(this.waitingItem=this.updateItem(d),!this.waitingItem&&!r&&(this.log(`INTERSTITIAL_ENDED unresolved ${Dp(d)}`),this.hls.trigger(L.INTERSTITIAL_ENDED,{event:d.event,schedule:a.slice(0),scheduleIndex:-1})));let f=this.bufferingItem;if(f&&(u=this.updateItem(f,this.bufferedPos),this.itemsMatch(f,u)?this.bufferingItem=u:f.event&&(this.bufferingItem=this.playingItem,this.clearInterstitial(f.event,null))),e.forEach(e=>{e.assetList.forEach(e=>{this.clearAssetPlayer(e.identifier,null)})}),this.playerQueue.forEach(e=>{if(e.interstitial.appendInPlace){let t=e.assetItem.timelineStart,n=e.timelineOffset-t;if(n)try{e.timelineOffset=t}catch(r){Math.abs(n)>mp&&this.warn(`${r} ("${e.assetId}" ${e.timelineOffset}->${t})`)}}}),c||t){if(this.hls.trigger(L.INTERSTITIALS_UPDATED,{events:i.slice(0),schedule:a.slice(0),durations:o,removedIds:s}),this.isInterstitial(r)&&s.indexOf(r.event.identifier)>-1){this.warn(`Interstitial "${r.event.identifier}" removed while playing`),this.primaryFallback(r.event);return}r&&this.trimInPlace(l,r),f&&u!==l&&this.trimInPlace(u,f),this.checkBuffer()}},this.hls=e,this.HlsPlayerClass=t,this.assetListLoader=new Op(e),this.schedule=new Ep(this.onScheduleUpdate,e.logger),this.registerListeners()}registerListeners(){let e=this.hls;e&&(e.on(L.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(L.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(L.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(L.MANIFEST_LOADING,this.onManifestLoading,this),e.on(L.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(L.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(L.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),e.on(L.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.on(L.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),e.on(L.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),e.on(L.ASSET_LIST_LOADED,this.onAssetListLoaded,this),e.on(L.BUFFER_APPENDED,this.onBufferAppended,this),e.on(L.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(L.BUFFERED_TO_END,this.onBufferedToEnd,this),e.on(L.MEDIA_ENDED,this.onMediaEnded,this),e.on(L.ERROR,this.onError,this),e.on(L.DESTROYING,this.onDestroying,this))}unregisterListeners(){let e=this.hls;e&&(e.off(L.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(L.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(L.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(L.MANIFEST_LOADING,this.onManifestLoading,this),e.off(L.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(L.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(L.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),e.off(L.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.off(L.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),e.off(L.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),e.off(L.ASSET_LIST_LOADED,this.onAssetListLoaded,this),e.off(L.BUFFER_CODECS,this.onBufferCodecs,this),e.off(L.BUFFER_APPENDED,this.onBufferAppended,this),e.off(L.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(L.BUFFERED_TO_END,this.onBufferedToEnd,this),e.off(L.MEDIA_ENDED,this.onMediaEnded,this),e.off(L.ERROR,this.onError,this),e.off(L.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){X(e,`play`,this.onPlay),X(e,`pause`,this.onPause),X(e,`seeking`,this.onSeeking),X(e,`timeupdate`,this.onTimeupdate)}onMediaAttaching(e,t){let n=this.media=t.media;Y(n,`seeking`,this.onSeeking),Y(n,`timeupdate`,this.onTimeupdate),Y(n,`play`,this.onPlay),Y(n,`pause`,this.onPause)}onMediaAttached(e,t){let n=this.effectivePlayingItem,r=this.detachedData;if(this.detachedData=null,n===null)this.checkStart();else if(!r){this.clearScheduleState();let e=this.findItemIndex(n);this.setSchedulePosition(e)}}clearScheduleState(){this.log(`clear schedule state`),this.playingItem=this.bufferingItem=this.waitingItem=this.endedItem=this.playingAsset=this.endedAsset=this.bufferingAsset=null}onMediaDetaching(e,t){let n=!!t.transferMedia,r=this.media;if(this.media=null,!n&&(r&&this.removeMediaListeners(r),this.detachedData)){let e=this.getBufferingPlayer();e&&(this.log(`Removing schedule state for detachedData and ${e}`),this.playingAsset=this.endedAsset=this.bufferingAsset=this.bufferingItem=this.waitingItem=this.detachedData=null,e.detachMedia()),this.shouldPlay=!1}}get interstitialsManager(){if(!this.hls)return null;if(this.manager)return this.manager;let e=this,t=()=>e.bufferingItem||e.waitingItem,n=t=>t&&e.getAssetPlayer(t.identifier),r=(t,r,i,o,s)=>{if(t){let c=t[r].start,l=t.event;if(l){if(r===`playout`||l.timelineOccupancy!==hp.Point){let e=n(i);e?.interstitial===l&&(c+=e.assetItem.startOffset+e[s])}}else{let n=o===`bufferedPos`?a():e[o];c+=n-t.start}return c}return 0},i=(t,n)=>{var r;if(t!==0&&n!==`primary`&&(r=e.schedule)!=null&&r.length){let r=e.schedule.findItemIndexAtTime(t),i=e.schedule.items?.[r];if(i)return t+(i[n].start-i.start)}return t},a=()=>{let t=e.bufferedPos;return t===Number.MAX_VALUE?o(`primary`):Math.max(t,0)},o=t=>{var n;return(n=e.primaryDetails)!=null&&n.live?e.primaryDetails.edge:e.schedule?.durations[t]||0},s=(t,i)=>{var a;let o=e.effectivePlayingItem;if(o!=null&&(a=o.event)!=null&&a.restrictions.skip||!e.schedule)return;e.log(`seek to ${t} "${i}"`);let s=e.effectivePlayingItem,c=e.schedule.findItemIndexAtTime(t,i),l=e.schedule.items?.[c],u=e.getBufferingPlayer(),d=u?.interstitial?.appendInPlace,f=s&&e.itemsMatch(s,l);if(s&&(d||f)){let a=n(e.playingAsset),o=a?.media||e.primaryMedia;if(o){let n=i===`primary`?o.currentTime:r(s,i,e.playingAsset,`timelinePos`,`currentTime`),c=t-n,l=(d?n:o.currentTime)+c;if(l>=0&&(!a||d||l<=a.duration)){o.currentTime=l;return}}}if(l){let n=t;if(i!==`primary`){let e=t-l[i].start;n=l.start+e}let r=!e.isInterstitial(l);if((!e.isInterstitial(s)||s.event.appendInPlace)&&(r||l.event.appendInPlace)){let t=e.media||(d?u?.media:null);t&&(t.currentTime=n)}else if(s){let a=e.findItemIndex(s);if(c>a){let t=e.schedule.findJumpRestrictedIndex(a+1,c);if(t>a){e.setSchedulePosition(t);return}}let o=0;if(r)e.timelinePos=n,e.checkBuffer();else{let e=l.event.assetList,n=t-(l[i]||l).start;for(let t=e.length;t--;){let r=e[t];if(r.duration&&n>=r.startOffset&&n<r.startOffset+r.duration){o=t;break}}}e.setSchedulePosition(c,o)}}},c=()=>{let n=e.effectivePlayingItem;if(e.isInterstitial(n))return n;let r=t();return e.isInterstitial(r)?r:null},l={get bufferedEnd(){let n=t(),i=e.bufferingItem;return i&&i===n&&(r(i,`playout`,e.bufferingAsset,`bufferedPos`,`bufferedEnd`)-i.playout.start||e.bufferingAsset?.startOffset)||0},get currentTime(){let t=c(),n=e.effectivePlayingItem;return n&&n===t?r(n,`playout`,e.effectivePlayingAsset,`timelinePos`,`currentTime`)-n.playout.start:0},set currentTime(t){let n=c(),r=e.effectivePlayingItem;r&&r===n&&s(t+r.playout.start,`playout`)},get duration(){let e=c();return e?e.playout.end-e.playout.start:0},get assetPlayers(){let t=c()?.event.assetList;return t?t.map(t=>e.getAssetPlayer(t.identifier)):[]},get playingIndex(){let t=c()?.event;return t&&e.effectivePlayingAsset?t.findAssetIndex(e.effectivePlayingAsset):-1},get scheduleItem(){return c()}};return this.manager={get events(){var t;return((t=e.schedule)==null||(t=t.events)==null?void 0:t.slice(0))||[]},get schedule(){var t;return((t=e.schedule)==null||(t=t.items)==null?void 0:t.slice(0))||[]},get interstitialPlayer(){return c()?l:null},get playerQueue(){return e.playerQueue.slice(0)},get bufferingAsset(){return e.bufferingAsset},get bufferingItem(){return t()},get bufferingIndex(){let n=t();return e.findItemIndex(n)},get playingAsset(){return e.effectivePlayingAsset},get playingItem(){return e.effectivePlayingItem},get playingIndex(){let t=e.effectivePlayingItem;return e.findItemIndex(t)},primary:{get bufferedEnd(){return a()},get currentTime(){let t=e.timelinePos;return t>0?t:0},set currentTime(e){s(e,`primary`)},get duration(){return o(`primary`)},get seekableStart(){return e.seekableStart}},integrated:{get bufferedEnd(){return r(t(),`integrated`,e.bufferingAsset,`bufferedPos`,`bufferedEnd`)},get currentTime(){return r(e.effectivePlayingItem,`integrated`,e.effectivePlayingAsset,`timelinePos`,`currentTime`)},set currentTime(e){s(e,`integrated`)},get duration(){return o(`integrated`)},get seekableStart(){return i(e.seekableStart,`integrated`)}},skip:()=>{let t=e.effectivePlayingItem,n=t?.event;if(n&&!n.restrictions.skip){let r=e.findItemIndex(t);if(n.appendInPlace){let e=t.playout.start+t.event.duration;s(e+.001,`playout`)}else e.advanceAfterAssetEnded(n,r,1/0)}}}}get effectivePlayingItem(){return this.waitingItem||this.playingItem||this.endedItem}get effectivePlayingAsset(){return this.playingAsset||this.endedAsset}get playingLastItem(){let e=this.playingItem,t=this.schedule?.items;return!this.playbackStarted||!e||!t?!1:this.findItemIndex(e)===t.length-1}get playbackStarted(){return this.effectivePlayingItem!==null}get currentTime(){var e;if(this.mediaSelection===null)return;let t=this.waitingItem||this.playingItem;if(this.isInterstitial(t)&&!t.event.appendInPlace)return;let n=this.media;!n&&(e=this.bufferingItem)!=null&&(e=e.event)!=null&&e.appendInPlace&&(n=this.primaryMedia);let r=n?.currentTime;if(r!==void 0&&P(r))return r}get primaryMedia(){return this.media||this.detachedData?.media||null}isInterstitial(e){return!!(e!=null&&e.event)}retreiveMediaSource(e,t){let n=this.getAssetPlayer(e);n&&this.transferMediaFromPlayer(n,t)}transferMediaFromPlayer(e,t){let n=e.interstitial.appendInPlace,r=e.media;if(n&&r===this.primaryMedia){if(this.bufferingAsset=null,(!t||this.isInterstitial(t)&&!t.event.appendInPlace)&&t&&r){this.detachedData={media:r};return}let n=e.transferMedia();this.log(`transfer MediaSource from ${e} ${q(n)}`),this.detachedData=n}else t&&r&&(this.shouldPlay||=!r.paused)}transferMediaTo(e,t){if(e.media===t)return;let n=null,r=this.hls,i=e!==r,a=i&&e.interstitial.appendInPlace,o=this.detachedData?.mediaSource,s;if(r.media)a&&(n=r.transferMedia(),this.detachedData=n),s=`Primary`;else{let e=this.getBufferingPlayer();e?(n=e.transferMedia(),this.detachedData=n,s=`${e}`):s=o?`detached MediaSource`:`detached media`}if(!n){if(o)n=this.detachedData,this.log(`using detachedData: MediaSource ${q(n)}`);else if(!this.detachedData||r.media===t){let e=this.playerQueue;e.length>1&&e.forEach(e=>{if(i&&e.interstitial.appendInPlace!==a){let t=e.interstitial;this.clearInterstitial(e.interstitial,null),t.appendInPlace=!1,t.appendInPlace&&this.warn(`Could not change append strategy for queued assets ${t}`)}}),this.hls.detachMedia(),this.detachedData={media:t}}}let c=n&&`mediaSource`in n&&n.mediaSource?.readyState!==`closed`;if(this.log(`${c?`transfering MediaSource`:`attaching media`} to ${i?e:`Primary`} from ${s} (media.currentTime: ${t.currentTime})`),!c&&!i){e.attachMedia(t);return}let l=c&&n?H({},n):{media:t},u=this.schedule;if(u&&i){let t=e.assetId===u.assetIdAtEnd;l.overrides={duration:u.duration,endOfStream:t||e.appendInPlace===!1}}if(!c&&a){let t=e,n=t.assetItem.timelineStart;if(n){let e=t.hls,r=Math.max(this.timelinePos-n,2**-52);e.startPosition!==r&&(this.log(`Set ${t} startPosition: ${r}`),e.config.startPosition=r,e.loadingEnabled&&e.startLoad(r))}}e.attachMedia(l)}onInterstitialCueEnter(){this.onTimeupdate()}checkStart(){let e=this.schedule,t=e?.events,n=this.hls;if(!t||this.playbackDisabled||!this.media||!n)return;this.bufferedPos===-1&&(this.bufferedPos=0);let r=this.timelinePos,i=this.effectivePlayingItem;if(r===-1){if(!n.loadingEnabled){this.log(`waiting for startLoad( <startPosition> )`);return}let r=n.startPosition;if(this.timelinePos=r,t.length===0)this.setSchedulePosition(0);else if(t[0].cue.pre){this.log(Ap(`checkStart (preroll)`,r));let n=e.findEventIndex(t[0].identifier);this.setSchedulePosition(n)}else if(r>=0||!this.primaryLive){this.log(Ap(`checkStart`,r));let t=this.timelinePos=r>0?r:0,n=e.findItemIndexAtTime(t);this.setSchedulePosition(n)}else n.liveSyncPosition===0?this.setSchedulePosition(0):this.log(`[checkStart] waiting for live start`)}else if(i&&!this.playingItem){this.log(Ap(`checkStart (playing item)`,i.start));let t=e.findItemIndex(i);this.setSchedulePosition(t)}}advanceAssetBuffering(e,t){let n=e.event,r=xp(n,n.findAssetIndex(t));if(!n.isAssetPastPlayoutLimit(r))this.bufferedToEvent(e,r);else if(this.schedule){let t=this.getNextItemIndex(e,!0),n=this.schedule.items?.[t];n&&this.bufferedToItem(n)}}livePrerollResumption(e,t){if(e.cue.pre&&this.primaryLive&&!P(e.resumeOffset)&&this.hls){let e=this.getLiveStartPos();if(t){let t=this.getBufferingPlayer();return e+(t!=null&&t.interstitial.cue.pre?t.remaining:0)}return e}}getNextItemIndex(e,t){if(this.schedule){let n=this.livePrerollResumption(e.event,t);if(n!==void 0)return this.log(`find next item index @${n}`),this.schedule.findItemIndexAtTime(n)}return this.findItemIndex(e)+1}advanceAfterAssetEnded(e,t,n){let r=xp(e,n);if(!e.isAssetPastPlayoutLimit(r)){if(e.appendInPlace){let t=e.assetList[r];t&&this.advanceInPlace(t.timelineStart)}this.setSchedulePosition(t,r)}else if(this.schedule){let n=this.schedule.items;if(n){let r=n[t],i=r.event?this.getNextItemIndex(r):t+1;if(i>=n.length){this.setSchedulePosition(-1);return}let a=e.resumeTime;this.timelinePos<a&&(this.log(Ap(`advanceAfterAssetEnded`,a)),this.timelinePos=a,e.appendInPlace&&!n[i].event&&this.hls.startLoad(a+.01),this.checkBuffer(this.bufferedPos<a)),this.setSchedulePosition(i)}}}setScheduleToAssetAtTime(e,t){let n=this.schedule;if(!n)return;let r=t.parentIdentifier,i=n.getEvent(r);if(i){let t=n.findEventIndex(r),a=n.findAssetIndex(i,e);this.advanceAfterAssetEnded(i,t,a-1)}}setSchedulePosition(e,t){let n=this.schedule?.items;if(!n||this.playbackDisabled)return;let r=e>=0?n[e]:null;this.log(`setSchedulePosition ${e}, ${t} (${r&&Dp(r)}) pos: ${this.timelinePos}`);let i=this.waitingItem||this.playingItem,a=this.playingLastItem;if(this.isInterstitial(i)){let s=i.event,c=this.playingAsset,l=c?.identifier,u=l?this.getAssetPlayer(l):null;if(u&&l&&(!this.eventItemsMatch(i,r)||t!==void 0&&l!==s.assetList[t].identifier)){var o;let t=s.findAssetIndex(c);if(this.log(`INTERSTITIAL_ASSET_ENDED ${t+1}/${s.assetList.length} ${Cp(c)}`),this.endedAsset=c,this.playingAsset=null,this.hls.trigger(L.INTERSTITIAL_ASSET_ENDED,{asset:c,assetListIndex:t,event:s,schedule:n.slice(0),scheduleIndex:e,player:u}),i!==this.playingItem){this.itemsMatch(i,this.playingItem)&&!this.playingAsset&&this.advanceAfterAssetEnded(s,this.findItemIndex(this.playingItem),t);return}this.retreiveMediaSource(l,r),u.media&&!((o=this.detachedData)!=null&&o.mediaSource)&&u.detachMedia()}if(!this.eventItemsMatch(i,r)&&(this.endedItem=i,this.playingItem=this.waitingItem=null,this.log(`INTERSTITIAL_ENDED ${s} ${Dp(i)}`),s.hasPlayed=!0,this.hls.trigger(L.INTERSTITIAL_ENDED,{event:s,schedule:n.slice(0),scheduleIndex:e}),s.cue.once&&this.hls)){this.updateSchedule();let e=this.schedule?.items;if(r&&e){let o=this.findItemIndex(r),c=this.livePrerollResumption(s);if(c!==void 0){let t=c,r=this.getNextItemIndex(i);if(!this.isInterstitial(n[r])){let e=this.primaryDetails?.fragments;if(s.snapOptions.in&&e){let i=na(null,e,c);i&&(t=Math.min(Math.max(n[r].start,vp(t,i)),n[r].end))}}if(this.log(Ap(`live join (preroll)`,t)),this.timelinePos=t,r!==o&&(r||r===0)){this.advanceSchedule(r,e,void 0,i,a);return}}this.advanceSchedule(o,e,t,i,a)}return}}this.advanceSchedule(e,n,t,i,a)}advanceSchedule(e,t,n,r,i){let a=this.schedule;if(!a)return;let o=t[e]||null,s=this.primaryMedia,c=this.playerQueue;if(c.length&&c.forEach(t=>{let n=t.interstitial,r=a.findEventIndex(n.identifier);(r<e||r>e+1)&&this.clearInterstitial(n,o)}),this.isInterstitial(o)){this.timelinePos=Math.min(Math.max(this.timelinePos,o.start),o.end);let i=o.event;if(n===void 0){n=i.cue.pre?0:a.findAssetIndex(i,this.timelinePos);let t=xp(i,n-1);if(i.isAssetPastPlayoutLimit(t)||i.appendInPlace&&this.timelinePos===o.end){this.advanceAfterAssetEnded(i,e,n);return}n=t}let c=this.waitingItem;this.assetsBuffered(o,s)||this.setBufferingItem(o);let l=this.preloadAssets(i,n);if(this.eventItemsMatch(o,c||r)||(this.waitingItem=o,this.log(`INTERSTITIAL_STARTED ${Dp(o)} ${i.appendInPlace?`append in place`:``}`),i.hasPlayed=!1,this.hls.trigger(L.INTERSTITIAL_STARTED,{event:i,schedule:t.slice(0),scheduleIndex:e})),!i.assetListLoaded){this.log(`Waiting for ASSET-LIST to complete loading ${i}`);return}if(i.assetListLoader&&=(i.assetListLoader.destroy(),void 0),!s){this.log(`Waiting for attachMedia to start Interstitial ${i}`);return}this.waitingItem=this.endedItem=null,this.playingItem=o;let u=i.assetList[n];if(!u){this.advanceAfterAssetEnded(i,e,n||0);return}if(l||=this.getAssetPlayer(u.identifier),l===null||l.destroyed){let e=i.assetList.length;this.warn(`asset ${n+1}/${e} player destroyed ${i}`),l=this.createAssetPlayer(i,u,n),l.loadSource()}if(!this.eventItemsMatch(o,this.bufferingItem)&&i.appendInPlace&&this.isAssetBuffered(u))return;this.startAssetPlayer(l,n,t,e,s),this.shouldPlay&&kp(l.media)}else o?(this.resumePrimary(o,e,r),this.shouldPlay&&kp(this.hls.media)):i&&this.isInterstitial(r)&&(this.endedItem=null,this.playingItem=r,r.event.appendInPlace||this.attachPrimary(a.durations.primary,null))}get playbackDisabled(){return this.hls.config.enableInterstitialPlayback===!1}get primaryDetails(){return this.mediaSelection?.main.details}get primaryLive(){var e;return!!((e=this.primaryDetails)!=null&&e.live)}resumePrimary(e,t,n){var r;this.playingItem=e,this.playingAsset=this.endedAsset=null,this.waitingItem=null,this.bufferedToItem(e),this.endedItem=null,this.log(`resuming ${Dp(e)}`);let i=this.timelinePos;if((r=this.detachedData)!=null&&r.mediaSource?this.primaryLive&&this.startLoadingPrimaryAt(i):((i<e.start||i>=e.end||i<this.seekableStart)&&(i=this.getPrimaryResumption(e,t),this.log(Ap(`resumePrimary`,i)),this.timelinePos=i),this.attachPrimary(i,e)),!n)return;let a=this.schedule?.items;a&&(this.log(`INTERSTITIALS_PRIMARY_RESUMED ${Dp(e)}`),this.hls.trigger(L.INTERSTITIALS_PRIMARY_RESUMED,{schedule:a.slice(0),scheduleIndex:t}),this.checkBuffer())}get seekableStart(){return this.primaryLive&&this.primaryDetails?.fragmentStart||0}getPrimaryResumption(e,t,n){let r=e.start;if(this.primaryLive){if(t===0)return this.hls.startPosition;let e=this.endedItem||this.playingItem,i=e!=null&&e.event?this.livePrerollResumption(e.event,n):void 0;if(i!==void 0)return i;let a=this.primaryDetails;if(a){let{fragmentStart:e,edge:t}=a;if(r<e||r>t&&!n){let n=this.hls.liveSyncPosition;return this.log(`primary resumption out of bounds (${r} [${e}-${t}]) snapping to liveSync ${n}`),n||e}}}return this.log(`primary resumption itemStart: ${r}`),r}getLiveStartPos(){let e=this.hls.startPosition,t=this.hls.liveSyncPosition||0,n=(this.primaryDetails?.targetduration||10)*3;return e===-1||t&&t-e<n?t||0:e}isAssetBuffered(e){let t=this.getAssetPlayer(e.identifier);return t!=null&&t.hls?t.hls.bufferedToEnd:J.bufferInfo(this.primaryMedia,this.timelinePos,0).end+1>=e.timelineStart+(e.duration||0)}attachPrimary(e,t,n){t?this.setBufferingItem(t):this.bufferingItem=this.playingItem,this.bufferingAsset=null;let r=this.primaryMedia;if(!r)return;let i=this.hls;i.media?this.checkBuffer():(this.transferMediaTo(i,r),n&&this.startLoadingPrimaryAt(e,n)),n||(this.log(Ap(`attachPrimary`,e)),this.timelinePos=e,this.startLoadingPrimaryAt(e,n))}startLoadingPrimaryAt(e,t){let n=this.hls,{loadingEnabled:r,bufferingEnabled:i,startPosition:a}=n,o=n.hasEnoughToStart;if(this.log(`Start loading primary @${e} bufferedPos: ${this.bufferedPos} startPosition: ${a} skip seek: ${t} has enough ${o} loadingEnabled: ${r} bufferingEnabled: ${i}`),!t&&o||!r||Math.abs(a-e)>.1){let r=this.primaryDetails;if(r!=null&&r.live&&e+.5>=r.edge){let t=this.bufferingItem;this.log(`Resume primary loading when live passes ${e} buffering item: ${t?Dp(t):null}`),n.pauseBuffering(),this.bufferPastEdge=!0;return}n.startLoad(e,t)}else i||n.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(L.BUFFER_CODECS,this.onBufferCodecs,this),this.hls.on(L.BUFFER_CODECS,this.onBufferCodecs,this)}onLevelUpdated(e,t){if(t.level===-1||!this.schedule)return;let n=this.hls.levels[t.level];if(!n.details)return;let r=H(H({},this.mediaSelection||this.altSelection),{},{main:n});this.mediaSelection=r;let i=this.hls.startPosition;if(this.schedule.parseInterstitialDateRanges(r,this.hls.config.interstitialAppendInPlace,i===-1?0:i),this.schedule.items){if(!this.effectivePlayingItem)this.checkStart();else if(this.bufferPastEdge){let e=this.primaryDetails,t=this.bufferedPos;if(e!=null&&e.live&&t+.5<e.edge){this.bufferPastEdge=!1;let n=this.bufferingItem;if(this.log(`Live edge ${e.edge} passed buffer: ${t} buffering item: ${n?Dp(n):null}`),n?.end===1/0){let e=this.playingItem,r=this.isInterstitial(e)&&e.event.appendInPlace;this.hls.startLoad(Math.max(t,n.start),r)}else{let e=this.getBufferingPlayer();e&&e.bufferedInPlaceToEnd(this.primaryMedia,e.currentTime)&&e.hls&&e.hls.trigger(L.BUFFERED_TO_END,void 0)}}}}}onAudioTrackUpdated(e,t){let n=this.hls.audioTracks[t.id],r=this.mediaSelection;if(!r){this.altSelection=H(H({},this.altSelection),{},{audio:n});return}let i=H(H({},r),{},{audio:n});this.mediaSelection=i}onSubtitleTrackUpdated(e,t){let n=this.hls.subtitleTracks[t.id],r=this.mediaSelection;if(!r){this.altSelection=H(H({},this.altSelection),{},{subtitles:n});return}let i=H(H({},r),{},{subtitles:n});this.mediaSelection=i}onAudioTrackSwitching(e,t){let n=Vi(t);this.playerQueue.forEach(({hls:e})=>e&&(e.setAudioOption(t)||e.setAudioOption(n)))}onSubtitleTrackSwitch(e,t){let n=Vi(t);this.playerQueue.forEach(({hls:e})=>e&&(e.setSubtitleOption(t)||t.id!==-1&&e.setSubtitleOption(n)))}onBufferCodecs(e,t){let n=t.tracks;n&&(this.requiredTracks=n)}onBufferAppended(e,t){this.checkBuffer()}onBufferFlushed(e,t){let n=this.playingItem;if(n&&!this.itemsMatch(n,this.bufferingItem)&&!this.isInterstitial(n)){let e=this.timelinePos;this.bufferedPos=e,this.checkBuffer()}}onBufferedToEnd(e){if(!this.schedule)return;let t=this.schedule.events;if(this.bufferedPos<Number.MAX_VALUE&&t){for(let e=0;e<t.length;e++){let n=t[e];if(n.cue.post){let e=this.getEventItem(n.identifier);e&&this.eventItemsMatch(e,this.bufferingItem)&&this.bufferedToItem(e,0);break}}this.bufferedPos=Number.MAX_VALUE}}onMediaEnded(e){let t=this.playingItem;if(!this.playingLastItem&&t){let e=this.findItemIndex(t);this.setSchedulePosition(e+1)}else this.shouldPlay=!1}updateItem(e,t){let n=this.schedule?.items;return e&&n&&n[this.findItemIndex(e,t)]||null}trimInPlace(e,t){if(this.isInterstitial(e)&&e.event.appendInPlace&&t.end-e.end>.25){e.event.assetList.forEach((t,n)=>{e.event.isAssetPastPlayoutLimit(n)&&this.clearAssetPlayer(t.identifier,null)});let n=e.end+.25,r=J.bufferInfo(this.primaryMedia,n,0);(r.end>n||(r.nextStart||0)>n)&&(this.log(`trim buffered interstitial ${Dp(e)} (was ${Dp(t)})`),this.attachPrimary(n,null,!0),this.flushFrontBuffer(n))}}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){return!!t&&(e===t||e.event.identifier===t.event?.identifier)}findEventIndex(e){return this.schedule?this.schedule.findEventIndex(e):-1}getEventItem(e){if(this.schedule){let t=this.schedule.items?.[this.findEventIndex(e)];if(this.isInterstitial(t)&&t.event.identifier===e)return t}}findItemIndex(e,t){return e&&this.schedule?this.schedule.findItemIndex(e,t):-1}updateSchedule(e=!1){var t;let n=this.mediaSelection;if(!n)return;let r=this.hls?.liveSyncPosition||0;(t=this.schedule)==null||t.updateSchedule(n,[],r,e)}checkBuffer(e){let t=this.schedule?.items;if(!t)return;let n=J.bufferInfo(this.primaryMedia,this.timelinePos,0);e&&(this.bufferedPos=this.timelinePos),e||=n.len<1,this.updateBufferedPos(n.end,t,e)}updateBufferedPos(e,t,n){let r=this.schedule,i=this.bufferingItem;if(this.bufferedPos>e||!r)return;if(t.length===1&&this.itemsMatch(t[0],i)){this.bufferedPos=e;return}let a=this.playingItem,o=this.findItemIndex(a),s=r.findItemIndexAtTime(e);if(this.bufferedPos<e){var c;let n=this.findItemIndex(i),r=Math.min(n+1,t.length-1),a=t[r];if((s===-1&&i&&e>=i.end||(c=a.event)!=null&&c.appendInPlace&&e+.01>=a.start)&&(s=r),this.isInterstitial(i)){let e=i.event;if(r-o>1&&e.appendInPlace===!1||e.assetList.length===0&&e.assetListLoader)return}if(this.bufferedPos=e,s>n&&s>o)this.bufferedToItem(a);else{let t=this.primaryDetails;this.primaryLive&&t&&e>t.edge-t.targetduration&&a.start<t.edge+this.hls.config.interstitialLiveLookAhead&&this.isInterstitial(a)&&this.preloadAssets(a.event,0)}}else n&&a&&!this.itemsMatch(a,i)&&(s===o?this.bufferedToItem(a):s===o+1&&this.bufferedToItem(t[s]))}assetsBuffered(e,t){return e.event.assetList.length!==0&&!e.event.assetList.some(e=>{let n=this.getAssetPlayer(e.identifier);return!(n!=null&&n.bufferedInPlaceToEnd(t))})}setBufferingItem(e){let t=this.bufferingItem,n=this.schedule;if(!this.itemsMatch(e,t)&&n){let{items:r,events:i}=n;if(!r||!i)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 s=o?o.remaining:t?t.end-this.timelinePos:0;if(this.log(`INTERSTITIALS_BUFFERED_TO_BOUNDARY ${Dp(e)}`+(t?` (${s.toFixed(2)} remaining)`:``)),!this.playbackDisabled){if(a){let t=n.findAssetIndex(e.event,this.bufferedPos);e.event.assetList.forEach((e,n)=>{let r=this.getAssetPlayer(e.identifier);r&&(n===t&&r.loadSource(),r.resumeBuffering())})}else this.hls.resumeBuffering(),this.playerQueue.forEach(e=>e.pauseBuffering())}this.hls.trigger(L.INTERSTITIALS_BUFFERED_TO_BOUNDARY,{events:i.slice(0),schedule:r.slice(0),bufferingIndex:this.findItemIndex(e),playingIndex:this.findItemIndex(this.playingItem)})}else this.bufferingItem!==e&&(this.bufferingItem=e);return t}bufferedToItem(e,t=0){let n=this.setBufferingItem(e);if(!this.playbackDisabled){if(this.isInterstitial(e))this.bufferedToEvent(e,t);else if(n!==null){this.bufferingAsset=null;let t=this.getPrimaryResumption(e,this.findItemIndex(e),!0),n=this.bufferedPos=Math.max(t,Math.min(this.bufferedPos,e.end),this.timelinePos,e.start),r=this.detachedData;if(r)r.mediaSource?this.attachPrimary(n,e,!0):this.startLoadingPrimaryAt(n);else{let e=this.playingItem,t=this.isInterstitial(e)&&e.event.appendInPlace;this.startLoadingPrimaryAt(n,t)}}}}bufferedToEvent(e,t){let n=e.event,r=n.assetList.length===0&&!n.assetListLoader,i=n.cue.once;if(r||!i){let e=this.preloadAssets(n,t);if(e!=null&&e.interstitial.appendInPlace){let t=this.primaryMedia;t&&this.bufferAssetPlayer(e,t)}}}preloadAssets(e,t){let n=e.assetUrl,r=e.assetList.length,i=r===0&&!e.assetListLoader,a=e.cue.once;if(i){let i=e.timelineStart,a=this.playingItem,s=this.getBufferingPlayer();if(e.appendInPlace){var o;!this.isInterstitial(a)&&(a==null||(o=a.nextEvent)==null?void 0:o.identifier)===e.identifier&&this.flushFrontBuffer(i+.25)}let c,l=0;if((!s||s.interstitial.cue.pre)&&this.primaryLive&&(l=this.getLiveStartPos(),s&&(l+=s.remaining)),l&&!(e.cue.pre||e.cue.post)){let e=l-i;e>0&&(c=Math.round(e*1e3)/1e3)}if(this.log(`Load interstitial asset ${t+1}/${n?1:r} ${e}${l?` live-start: ${l} start-offset: ${c} (timeline-start: ${i})`:``}`),n)return this.createAsset(e,0,0,i,e.duration,n);let u=this.assetListLoader.loadAssetList(e,c);u&&(e.assetListLoader=u)}else if(!a&&r){for(let n=t;n<r;n++){let t=e.assetList[n],r=this.getAssetPlayerQueueIndex(t.identifier);(r===-1||this.playerQueue[r].destroyed)&&!t.error&&this.createAssetPlayer(e,t,n)}let n=e.assetList[t];if(n){let e=this.getAssetPlayer(n.identifier);return e&&e.loadSource(),e}}return null}flushFrontBuffer(e){let t=this.requiredTracks;if(!t)return;let n=this.primaryDetails;n&&e>=n.edge||(this.log(`Removing front buffer starting at ${e}`),Object.keys(t).forEach(t=>{this.hls.trigger(L.BUFFER_FLUSHING,{startOffset:e,endOffset:1/0,type:t})}))}getAssetPlayerQueueIndex(e){let t=this.playerQueue;for(let n=0;n<t.length;n++)if(e===t[n].assetId)return n;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 n=0;n<e.length;n++)if(e[n].media===t)return e[n]}return null}createAsset(e,t,n,r,i,a){let o={parentIdentifier:e.identifier,identifier:gp(e,a,t),duration:i,startOffset:n,timelineStart:r,uri:a};return this.createAssetPlayer(e,o,t)}createAssetPlayer(e,t,n){let r=this.hls,i=r.userConfig,a=Zi(r.loadLevelObj||r.levels[r.currentLevel],i.videoPreference),o=r.audioTracks[r.audioTrack],s=r.subtitleTracks[r.subtitleTrack],c=0;if(this.primaryLive||e.appendInPlace){let e=this.timelinePos-t.timelineStart;if(e>=0){let n=t.duration;n&&e<n&&(c=e)}}let l=t.identifier,u=H(H({},i),{},{maxMaxBufferLength:Math.min(15,r.config.maxMaxBufferLength),autoStartLoad:!0,startFragPrefetch:!0,primarySessionId:r.sessionId,assetPlayerId:l,abrEwmaDefaultEstimate:r.bandwidthEstimate,interstitialsController:void 0,startPosition:c,liveDurationInfinity:!1,testBandwidth:!1,videoPreference:a,audioPreference:o||i.audioPreference,subtitlePreference:s||i.subtitlePreference});e.appendInPlace&&(e.appendInPlaceStarted=!0,t.timelineStart&&(u.timelineOffset=t.timelineStart));let d=u.cmcd;d!=null&&d.sessionId&&d.contentId&&(u.cmcd=V({},d,{contentId:df(t.uri)})),this.getAssetPlayer(l)&&this.warn(`Duplicate date range identifier ${e} and asset ${l}`);let f=new wp(this.HlsPlayerClass,u,e,t);this.playerQueue.push(f),e.assetList[n]=t;let p=!0,m=r=>{if(r.live){let t=Error(`Interstitials MUST be VOD assets ${e}`),r={fatal:!0,type:F.OTHER_ERROR,details:I.INTERSTITIAL_ASSET_ITEM_ERROR,error:t},i=this.findEventIndex(e.identifier);this.handleAssetItemError(r,e,i,n,t.message);return}let i=r.edge-r.fragmentStart,a=t.duration;(p||a===null||i>a)&&(p=!1,this.log(`Interstitial asset "${l}" duration change ${a} > ${i}`),t.duration=i,this.updateSchedule())};f.on(L.LEVEL_UPDATED,(e,{details:t})=>m(t)),f.on(L.LEVEL_PTS_UPDATED,(e,{details:t})=>m(t)),f.on(L.EVENT_CUE_ENTER,()=>this.onInterstitialCueEnter());let h=(e,t)=>{let n=this.getAssetPlayer(l);if(n&&t.tracks){n.off(L.BUFFER_CODECS,h),n.tracks=t.tracks;let e=this.primaryMedia;this.bufferingAsset===n.assetItem&&e&&!n.media&&this.bufferAssetPlayer(n,e)}};f.on(L.BUFFER_CODECS,h),f.on(L.BUFFERED_TO_END,()=>{let t=this.getAssetPlayer(l);if(this.log(`buffered to end of asset ${t}`),!t||!this.schedule)return;let n=this.getEventItem(e.identifier);n&&this.advanceAssetBuffering(n,t.assetItem)});let g=t=>()=>{if(!this.getAssetPlayer(l)||!this.schedule)return;this.shouldPlay=!0;let n=this.findEventIndex(e.identifier);this.advanceAfterAssetEnded(e,n,t)};return f.once(L.MEDIA_ENDED,g(n)),f.once(L.PLAYOUT_LIMIT_REACHED,g(1/0)),f.on(L.ERROR,(t,r)=>{if(!this.schedule)return;let i=this.getAssetPlayer(l);if(r.details===I.BUFFER_STALLED_ERROR){if(i!=null&&i.appendInPlace){this.handleInPlaceStall(e);return}this.onTimeupdate(),this.checkBuffer(!0);return}r.details!==I.BUFFER_SEEK_OVER_HOLE&&this.handleAssetItemError(r,e,this.findEventIndex(e.identifier),n,`Asset player error ${r.error} ${e}`)}),f.on(L.DESTROYING,()=>{if(!this.getAssetPlayer(l)||!this.schedule)return;let t=Error(`Asset player destroyed unexpectedly ${l}`),r={fatal:!0,type:F.OTHER_ERROR,details:I.INTERSTITIAL_ASSET_ITEM_ERROR,error:t};this.handleAssetItemError(r,e,this.findEventIndex(e.identifier),n,t.message)}),this.log(`INTERSTITIAL_ASSET_PLAYER_CREATED ${Cp(t)}`),this.hls.trigger(L.INTERSTITIAL_ASSET_PLAYER_CREATED,{asset:t,assetListIndex:n,event:e,player:f}),f}clearInterstitial(e,t){this.clearAssetPlayers(e,t),e.reset()}clearAssetPlayers(e,t){e.assetList.forEach(e=>{this.clearAssetPlayer(e.identifier,t)})}resetAssetPlayer(e){let t=this.getAssetPlayerQueueIndex(e);if(t!==-1){this.log(`reset asset player "${e}" after error`);let n=this.playerQueue[t];this.transferMediaFromPlayer(n,null),n.resetDetails()}}clearAssetPlayer(e,t){let n=this.getAssetPlayerQueueIndex(e);if(n!==-1){let e=this.playerQueue[n];this.log(`clear ${e} toSegment: ${t&&Dp(t)}`),this.transferMediaFromPlayer(e,t),this.playerQueue.splice(n,1),e.destroy()}}emptyPlayerQueue(){let e;for(;e=this.playerQueue.pop();)e.destroy();this.playerQueue=[]}startAssetPlayer(e,t,n,r,i){let{interstitial:a,assetItem:o,assetId:s}=e,c=a.assetList.length,l=this.playingAsset;this.endedAsset=null,this.playingAsset=o,l?.identifier!==s&&(l&&(this.clearAssetPlayer(l.identifier,n[r]),delete l.error),this.log(`INTERSTITIAL_ASSET_STARTED ${t+1}/${c} ${Cp(o)}`),this.hls.trigger(L.INTERSTITIAL_ASSET_STARTED,{asset:o,assetListIndex:t,event:a,schedule:n.slice(0),scheduleIndex:r,player:e})),this.bufferAssetPlayer(e,i)}bufferAssetPlayer(e,t){if(!this.schedule)return;let{interstitial:n,assetItem:r}=e,i=this.getEventItem(n.identifier);if(!i)return;if(e.loadSource(),this.setBufferingItem(i),this.bufferingAsset=r,e.bufferedInPlaceToEnd(this.primaryMedia,e.currentTime)){this.advanceAssetBuffering(i,r);return}let a=this.getBufferingPlayer();if(a===e)return;let o=n.appendInPlace;if(o&&a?.interstitial.appendInPlace===!1)return;let s=a?.tracks||this.detachedData?.tracks||this.requiredTracks;if(o&&r!==this.playingAsset){if(!e.tracks){this.log(`Waiting for track info before buffering ${e}`);return}if(s&&!sn(s,e.tracks)){let t=Error(`Asset ${Cp(r)} SourceBuffer tracks ('${Object.keys(e.tracks)}') are not compatible with primary content tracks ('${Object.keys(s)}')`),i={fatal:!0,type:F.OTHER_ERROR,details:I.INTERSTITIAL_ASSET_ITEM_ERROR,error:t},a=n.findAssetIndex(r);this.handleAssetItemError(i,n,this.findEventIndex(n.identifier),a,t.message);return}}this.transferMediaTo(e,t)}handleInPlaceStall(e){let t=this.schedule,n=this.primaryMedia;if(!t||!n)return;let r=n.currentTime,i=t.findAssetIndex(e,r),a=e.assetList[i];if(a){let o=this.getAssetPlayer(a.identifier);if(o){let s=o.currentTime||r-a.timelineStart,c=o.duration-s;if(this.warn(`Stalled at ${s} of ${s+c} in ${o} ${e} (media.currentTime: ${r})`),s&&(c/n.playbackRate<.5||o.bufferedInPlaceToEnd(n,o.currentTime))&&o.hls){let n=t.findEventIndex(e.identifier);this.advanceAfterAssetEnded(e,n,i)}}}}advanceInPlace(e){let t=this.primaryMedia;if(t&&t.currentTime<e){let n=`advance currentTime to ${e}, duration: ${t.duration}`;t.duration>e?(this.log(n),t.currentTime=e):this.log(`Cannot ${n}`)}}handleAssetItemError(e,t,n,r,i){if(e.details===I.BUFFER_STALLED_ERROR)return;let a=t.assetList[r]||null;if(this.warn(`INTERSTITIAL_ASSET_ERROR ${a&&Cp(a)} ${e.error}`),!this.schedule)return;let o=a?.identifier||``,s=this.getAssetPlayerQueueIndex(o),c=this.playerQueue[s]||null,l=this.schedule.items,u=V({},e,{fatal:!1,errorAction:pa(!0),asset:a,assetListIndex:r,event:t,schedule:l,scheduleIndex:n,player:c});if(this.hls.trigger(L.INTERSTITIAL_ASSET_ERROR,u),!e.fatal)return;let d=this.playingAsset,f=this.bufferingAsset,p=Error(i);if(a&&(this.clearAssetPlayer(o,null),a.error=p),!t.assetList.some(e=>!e.error))t.error=p;else for(let e=r;e<t.assetList.length;e++)this.resetAssetPlayer(t.assetList[e].identifier);this.updateSchedule(!0),t.error?this.primaryFallback(t):d?.identifier===o?this.advanceAfterAssetEnded(t,n,r):f?.identifier===o&&this.isInterstitial(this.bufferingItem)&&this.advanceAssetBuffering(this.bufferingItem,f)}primaryFallback(e){let t=e.timelineStart,n=this.effectivePlayingItem,r=this.playingItem,i=this.seekableStart,a=this.hls.startPosition,o=this.timelinePos;if(this.isInterstitial(n)){this.log(`Fallback to primary from event "${e.identifier}" start: ${t} pos: ${o} playing: ${Dp(n)} startPosition: ${a} seekableStart: ${i} error: ${e.error}`),o===-1&&(o=a),o=Math.max(o,i);let r=this.updateItem(n,o);this.itemsMatch(n,r)&&this.clearInterstitial(e,null),e.appendInPlace&&(this.attachPrimary(t,null),this.flushFrontBuffer(t))}else if(o===-1){this.checkStart();return}if(!this.schedule||r&&!this.isInterstitial(r))return;let s=this.schedule.findItemIndexAtTime(o);this.setSchedulePosition(s)}onAssetListLoaded(e,t){var n;let r=t.event,i=r.identifier,a=t.assetListResponse.ASSETS;if(!((n=this.schedule)!=null&&n.hasEvent(i)))return;let o=r.timelineStart,s=r.duration,c=0;a.forEach((e,t)=>{let n=parseFloat(e.DURATION);this.createAsset(r,t,c,o+c,n,e.URI),c+=n}),r.duration=c,this.log(`Loaded asset-list with duration: ${c} (was: ${s}) ${r}`);let l=this.waitingItem?.event.identifier===i;this.updateSchedule();let u=this.bufferingItem?.event;if(l){let e=this.findEventIndex(i),t=this.getEventItem(i);if(t){if(!this.playingItem&&this.timelinePos>t.end&&this.schedule.findItemIndexAtTime(this.timelinePos)!==e){r.error=Error(`Interstitial ${a.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(t)}this.setSchedulePosition(e)}else if(u?.identifier===i){let e=r.assetList[0];if(e){let t=this.getAssetPlayer(e.identifier);if(u.appendInPlace){let e=this.primaryMedia;t&&e&&this.bufferAssetPlayer(t,e)}else t&&t.loadSource()}}}onError(e,t){if(this.schedule)switch(t.details){case I.ASSET_LIST_PARSING_ERROR:case I.ASSET_LIST_LOAD_ERROR:case I.ASSET_LIST_LOAD_TIMEOUT:{let e=t.interstitial;e&&(this.updateSchedule(!0),this.primaryFallback(e));break}case I.BUFFER_STALLED_ERROR:{let e=this.endedItem||this.waitingItem||this.playingItem;if(this.isInterstitial(e)&&e.event.appendInPlace){this.handleInPlaceStall(e.event);return}let t=this.primaryMedia;this.log(`Primary player stall @${this.timelinePos} currentTime: ${t?.currentTime} bufferedPos: ${this.bufferedPos}`),this.onTimeupdate(),this.checkBuffer(!0);break}}}},Mp=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 e;let{media:t}=this,n=this.levelDetails;if(!t||!n||!this.hls)return;this.currentTime=t.currentTime;let r=this.hls.config,i=this.computeLatency();if(i===null)return;this._latency=i;let{lowLatencyMode:a,maxLiveSyncPlaybackRate:o}=r;if(!a||o===1||!n.live)return;let s=this.targetLatency;if(s===null)return;let c=i-s,l=c<Math.min(this.maxLatency,s+n.targetduration),u=ks(r)&&!!((e=this.hls.interstitialsManager)!=null&&(e=e.playingItem)!=null&&e.event);if(l&&c>.05&&this.forwardBufferLength>1&&!u){let e=Math.min(2,Math.max(1,o)),n=Math.round(2/(1+Math.exp(-.75*c-this.edgeStalled))*20)/20,r=Math.min(e,Math.max(1,n));this.changeMediaPlaybackRate(t,r)}else t.playbackRate!==1&&t.playbackRate!==0&&this.changeMediaPlaybackRate(t,1)},this.hls=e,this.registerListeners()}get levelDetails(){return this.hls?.latestLevelDetails||null}get latency(){return this._latency||0}get maxLatency(){let e=this.hls?.config;if(!e)return 0;if(e.liveMaxLatencyDuration!==void 0)return e.liveMaxLatencyDuration;let t=this.levelDetails;return t?e.liveMaxLatencyDurationCount*t.targetduration:0}get targetLatency(){let e=this.levelDetails;if(e===null||!this.hls)return null;let t=this.hls.config,{holdBack:n,partHoldBack:r,targetduration:i}=e,{liveSyncDuration:a,liveSyncDurationCount:o,lowLatencyMode:s}=t,c=this.hls.userConfig,l=s&&r||n;(this._targetLatencyUpdated||c.liveSyncDuration||c.liveSyncDurationCount||l===0)&&(l=a===void 0?o*i:a);let u=i;return l+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 n=this.levelDetails;if(n===null)return null;let r=n.edge,i=e-t-this.edgeStalled,a=r-n.totalduration,o=r-(this.hls.config.lowLatencyMode&&n.partTarget||n.targetduration);return Math.min(Math.max(a,i),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 n=e.buffered.length;return(n?e.buffered.end(n-1):t.edge)-this.currentTime}destroy(){this.unregisterListeners(),this.onMediaDetaching(),this.hls=null}registerListeners(){let{hls:e}=this;e&&(e.on(L.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(L.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(L.MANIFEST_LOADING,this.onManifestLoading,this),e.on(L.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(L.ERROR,this.onError,this),e.on(L.INTERSTITIAL_ASSET_STARTED,this.onAssetStarted,this))}unregisterListeners(){let{hls:e}=this;e&&(e.off(L.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(L.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(L.MANIFEST_LOADING,this.onManifestLoading,this),e.off(L.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(L.ERROR,this.onError,this),e.off(L.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),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 n;let r=this.hls,i=this.media||t.event.appendInPlace&&(r==null||(n=r.interstitialsManager)==null?void 0:n.playerQueue.reduce((e,t)=>e||t.media,null));r&&i&&i.playbackRate>1&&i.playbackRate<=r.config.maxLiveSyncPlaybackRate&&this.changeMediaPlaybackRate(i,1)}onError(e,t){var n;t.details===I.BUFFER_STALLED_ERROR&&(this.stallCount++,this.hls&&(n=this.levelDetails)!=null&&n.live&&this.hls.logger.warn(`[latency-controller]: Stall detected, adjusting target latency`))}changeMediaPlaybackRate(e,t){var n;e.playbackRate!==t&&((n=this.hls)==null||n.logger.debug(`[latency-controller]: latency=${this.latency.toFixed(3)}, targetLatency=${this.targetLatency?.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}},Np=500,Pp=1e-6,Fp=class extends Ds{constructor(e,t,n){super(e,t,n,`subtitle-stream-controller`,z.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(L.LEVEL_LOADED,this.onLevelLoaded,this),e.on(L.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(L.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.on(L.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(L.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.on(L.BUFFER_FLUSHING,this.onBufferFlushing,this)}unregisterListeners(){super.unregisterListeners();let{hls:e}=this;e.off(L.LEVEL_LOADED,this.onLevelLoaded,this),e.off(L.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(L.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.off(L.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(L.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.off(L.BUFFER_FLUSHING,this.onBufferFlushing,this)}startLoad(e,t){this.stopLoad(),this.state=Q.IDLE,this.setInterval(Np),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 n,r;let{frag:i,part:a,success:o}=t;if(!o)return;let s=(n=this.tracksBuffered)[r=i.level]||(n[r]=[]);if(!s)return;let c,l=(a||i).start;for(let e=0;e<s.length;e++)if(l>=s[e].start&&l<=s[e].end){c=s[e];break}let u=l+(a||i).duration;if(c?c.end=u:(c={start:l,end:u},s.push(c)),!a||u>=i.end-Pp){let e=this.fragmentTracker.fragBuffered(i);a&&e&&(e.range.subs={time:[{startPTS:i.start,endPTS:u}],partial:!0}),Tt(i)&&!this.fragContextChanged(i)&&(this.fragPrevious=i),this.fragBufferedComplete(i,a),this.media&&this.tickImmediate()}}onBufferFlushing(e,t){let{startOffset:n,endOffset:r}=t;if(n===0&&r!==1/0){let e=r-1;if(e<=0)return;t.endOffsetSubtitles=Math.max(0,e),this.tracksBuffered.forEach(t=>{if(t)for(let n=0;n<t.length;){if(t[n].end<=e){t.shift();continue}if(t[n].start<e)t[n].start=e;else break;n++}}),this.fragmentTracker.removeFragmentsInRange(n,e,z.SUBTITLE)}}onError(e,t){let n=t.frag;n?.type===z.SUBTITLE&&(t.details===I.FRAG_GAP&&this.fragmentTracker.addAsGap(n),this.fragCurrent&&this.fragCurrent.abortRequests(),this.state!==Q.STOPPED&&(this.state=Q.IDLE))}onSubtitleTracksUpdated(e,{subtitleTracks:t}){if(this.levels&&Pl(this.levels,t)){this.levels=t.map(e=>new Mi(e));return}this.tracksBuffered=[],this.levels=t.map(e=>new Mi(e)),this.fragmentTracker.removeFragmentsInRange(0,1/0,z.SUBTITLE),this.fragPrevious=null,this.mediaBuffer=null}onSubtitleTrackSwitch(e,t){var n;if(this.currentTrackId=t.id,this.abortCurrentFrag(),!((n=this.levels)!=null&&n.length)||this.currentTrackId===-1){this.clearInterval();return}let r=this.levels[this.currentTrackId];if(!(r!=null&&r.details)){this.mediaBuffer=null;return}this.mediaBuffer=this.mediaBufferTimeRanges,this.state!==Q.STOPPED&&this.setInterval(Np)}onSubtitleTrackLoaded(e,t){var n;let{currentTrackId:r,levels:i}=this,{details:a,id:o}=t;if(!i){this.warn(`Subtitle tracks were reset while loading level ${o}`);return}let s=i[o];if(o>=i.length||!s)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,l=0;if(a.live||(n=s.details)!=null&&n.live){if(a.deltaUpdateFailed)return;if(!c){this.startFragRequested=!1;return}s.details&&(l=this.alignPlaylists(a,s.details,this.levelLastLoaded?.details)),a.alignedSliding||(ws(c,a,this),l=a.fragmentStart)}s.details=a,this.levelLastLoaded=s,c&&!this.startFragRequested&&this.setStartPosition(c,l),o===r&&(this.hls.trigger(L.SUBTITLE_TRACK_UPDATED,{details:a,id:o,groupId:t.groupId}),this.tickImmediate())}_handleFragmentLoadProgress(e){let{frag:t,part:n,payload:r}=e;n&&r!=null&&r.byteLength&&this.shouldDecrypt(t)&&this.decryptPayload(r,t,n)}_handleFragmentLoadComplete(e){let{frag:t,payload:n}=e;!this.fragContextChanged(t)&&n!=null&&n.byteLength&&this.shouldDecrypt(t)&&this.decryptPayload(n,t,null)}shouldDecrypt(e){let t=e.decryptdata;return!!(t!=null&&t.key&&t.iv&&ho(t.method))}decryptPayload(e,t,n){let r=t.decryptdata,i=performance.now();this.decrypter.decrypt(new Uint8Array(e),r.key.buffer,r.iv.buffer,go(r.method)).then(e=>{this.fragContextChanged(t)||this.hls.trigger(L.FRAG_DECRYPTED,{frag:t,part:n,payload:e,stats:{tstart:i,tdecrypt:performance.now()}})}).catch(e=>{this.hls.trigger(L.ERROR,{type:F.MEDIA_ERROR,details:I.FRAG_DECRYPT_ERROR,fatal:!1,error:e,reason:e.message,frag:t,part:n}),n||(this.warn(`${e.name}: ${e.message}`),this.state=Q.IDLE)})}doTick(){if(this.state===Q.IDLE&&this.levels){if(!this.media&&!this.primaryPrefetch&&(this.startFragRequested||!this.config.startFragPrefetch))return;let{currentTrackId:t,levels:n}=this,r=n[t],i=r?.details;if(!i||this.waitForLive(r)||this.waitForCdnTuneIn(i)){this.startFragRequested=!1;return}let{config:a}=this,o=this.playhead,s=J.bufferedInfo(this.tracksBuffered[t]||[],o,a.maxBufferHole),{end:c,len:l}=s;if(l>Math.max(this.hls.maxBufferLength+i.levelTargetDuration,this.hls.mainForwardBufferInfo?.len||0)||l&&!this.buffering)return;let u=this.getNextFragment(c,i);if(!u)return;if(Tt(u)){var e;if(u.end===s.end)return;let t=u.sn-i.startSN,n=i.fragments[t-1];u.cc===n?.cc&&!((e=i.partList)!=null&&e.length)&&this.fragmentTracker.getState(n)===Z.NOT_LOADED&&(u=n)}this.loadFragment(u,r,c)}}loadFragment(e,t,n){let r=this.fragmentTracker.getState(e);(r===Z.NOT_LOADED||r===Z.PARTIAL)&&super.loadFragment(e,t,n)}get mediaBufferTimeRanges(){return new Ip(this.tracksBuffered[this.currentTrackId]||[])}},Ip=class{constructor(e){this.buffered=void 0;let t=(t,n,r)=>{if(n>>>=0,n>r-1)throw new DOMException(`Failed to execute '${t}' on 'TimeRanges': The index provided (${n}) is greater than the maximum bound (${r})`);return e[n][t]};this.buffered={get length(){return e.length},end(n){return t(`end`,n,e.length)},start(n){return t(`start`,n,e.length)}}}},Lp={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},Rp=e=>String.fromCharCode(Lp[e]||e),zp=15,Bp=42,Vp={17:1,18:3,21:5,22:7,23:9,16:11,19:12,20:14},Hp={17:2,18:4,21:6,22:8,23:10,19:13,20:15},Up={25:1,26:3,29:5,30:7,31:9,24:11,27:12,28:14},Wp={25:2,26:4,29:6,30:8,31:10,27:13,28:15},Gp=[`white`,`green`,`blue`,`cyan`,`red`,`yellow`,`magenta`,`black`,`transparent`],Kp=class{constructor(){this.time=null,this.verboseLevel=0}log(e,t){if(this.verboseLevel>=e){let n=typeof t==`function`?t():t;U.log(`${this.time} [${e}] ${n}`)}}},qp=function(e){let t=[];for(let n=0;n<e.length;n++)t.push(e[n].toString(16));return t},Jp=Object.freeze({foreground:`white`,underline:!1,italics:!1,background:`black`,flash:!1}),Yp=class{constructor(){this.styles=Jp}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=Jp}setStyles(e){let t=this.styles,n=Object.prototype.hasOwnProperty;this.styles={foreground:n.call(e,`foreground`)?e.foreground:t.foreground,underline:n.call(e,`underline`)?e.underline:t.underline,italics:n.call(e,`italics`)?e.italics:t.italics,background:n.call(e,`background`)?e.background:t.background,flash:n.call(e,`flash`)?e.flash:t.flash}}toString(){return`color=`+this.foreground+`, underline=`+this.underline+`, italics=`+this.italics+`, background=`+this.background+`, flash=`+this.flash}},Xp=class{constructor(){this.uchar=` `,this.penState=new Yp}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}},Zp=class{constructor(e){this.chars=[],this.pos=0,this.currPenState=new Yp,this.cueStartTime=null,this.logger=void 0;for(let e=0;e<Bp;e++)this.chars.push(new Xp);this.logger=e}equals(e){let t=this.chars,n=e.chars;for(let e=0;e<Bp;e++){let r=t[e],i=n[e];if(r.uchar!==i.uchar)return!1;let a=r.penState.styles,o=i.penState.styles;if(a!==o&&(a.foreground!==o.foreground||a.underline!==o.underline||a.italics!==o.italics||a.background!==o.background||a.flash!==o.flash))return!1}return!0}copy(e){for(let t=0;t<Bp;t++)this.chars[t].copy(e.chars[t])}isEmpty(){let e=this.chars;for(let t=0;t<Bp;t++){let n=e[t];if(n.uchar!==` `)return!1;let r=n.penState.styles;if(r!==Jp&&(r.foreground!==`white`||r.underline||r.italics||r.background!==`black`||r.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>=Bp&&(this.logger.log(3,`Too large cursor position `+this.pos),this.pos=41)}moveCursor(e){let t=Math.min(this.pos+e,Bp);if(e>1)for(let e=this.pos+1;e<t;e++)this.chars[e].setPenState(this.currPenState);this.setCursor(t)}backSpace(){this.moveCursor(-1),this.chars[this.pos].setChar(` `,this.currPenState)}insertChar(e){e>=144&&this.backSpace();let t=Rp(e);if(this.pos>=Bp){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<Bp;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 n=0;n<Bp;n++){let r=this.chars[n].uchar;r!==` `&&(t=!1),e.push(r)}return t?``:e.join(``)}setPenStyles(e){this.currPenState.setStyles(e),this.chars[this.pos].setPenState(this.currPenState)}},Qp=class{constructor(e){this.rows=[],this.currRow=14,this.nrRollUpRows=null,this.lastOutputScreen=null,this.logger=void 0;for(let t=0;t<zp;t++)this.rows.push(new Zp(e));this.logger=e}reset(){for(let e=0;e<zp;e++)this.rows[e].clear();this.currRow=14}equals(e){let t=!0;for(let n=0;n<zp;n++)if(!this.rows[n].equals(e.rows[n])){t=!1;break}return t}copy(e){for(let t=0;t<zp;t++){let n=this.rows[t].chars,r=e.rows[t].chars;for(let e=0;e<Bp;e++){let t=n[e],i=r[e];t.uchar=i.uchar,t.penState.styles=i.penState.styles}}}isEmpty(){let e=!0;for(let t=0;t<zp;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 = `+q(e));let t=e.row-1;if(this.nrRollUpRows&&t<this.nrRollUpRows-1&&(t=this.nrRollUpRows-1),this.nrRollUpRows&&this.currRow!==t){for(let e=0;e<zp;e++)this.rows[e].clear();let e=this.currRow+1-this.nrRollUpRows,n=this.lastOutputScreen;if(n){let r=n.rows[e].cueStartTime,i=this.logger.time;if(r!==null&&i!==null&&r<i)for(let r=0;r<this.nrRollUpRows;r++)this.rows[t-this.nrRollUpRows+r+1].copy(n.rows[e+r])}}this.currRow=t;let n=this.rows[this.currRow];if(e.indent!==null){let t=e.indent,r=Math.max(t-1,0);n.setCursor(e.indent),e.color=n.chars[r].penState.foreground}let r={foreground:e.color,underline:e.underline,italics:e.italics,background:`black`,flash:!1};this.setPen(r)}setBkgData(e){this.logger.log(2,()=>`bkgData = `+q(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||=!1;let t=[],n=``,r=-1;for(let n=0;n<zp;n++){let i=this.rows[n].getTextString();i&&(r=n+1,e?t.push(`Row `+r+`: '`+i+`'`):t.push(i.trim()))}return t.length>0&&(n=e?`[`+t.join(` | `)+`]`:t.join(`
|
|
46
|
+
`)),n}getTextAndFormat(){return this.rows}},$p=class{constructor(e,t,n){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 Qp(n),this.nonDisplayedMemory=new Qp(n),this.lastOutputScreen=new Qp(n),this.currRollUpRow=this.displayedMemory.rows[14],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null,this.logger=n}reset(){this.mode=null,this.displayedMemory.reset(),this.nonDisplayedMemory.reset(),this.lastOutputScreen.reset(),this.outputFilter.reset(),this.currRollUpRow=this.displayedMemory.rows[14],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null}getHandler(){return this.outputFilter}setHandler(e){this.outputFilter=e}setPAC(e){this.writeScreen.setPAC(e)}setBkgData(e){this.writeScreen.setBkgData(e)}setMode(e){e!==this.mode&&(this.mode=e,this.logger.log(2,()=>`MODE=`+e),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 t=0;t<e.length;t++)this.writeScreen.insertChar(e[t]);let t=this.writeScreen===this.displayedMemory?`DISP`:`NON_DISP`;this.logger.log(2,()=>t+`: `+this.writeScreen.getDisplayText(!0)),(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};t.underline=e%2==1,t.italics=e>=46,t.foreground=t.italics?`white`:[`white`,`green`,`blue`,`cyan`,`red`,`yellow`,`magenta`][Math.floor(e/2)-16],this.logger.log(2,`MIDROW: `+q(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))}},em=class{constructor(e,t,n){this.channels=[null,null,null],this.currentChannel=0,this.cmdHistory=rm(),this.logger=void 0,this.field=void 0,this.outputFilters=void 0,this.logger=new Kp,this.field=e,this.outputFilters=[null,t,n]}getHandler(e){return this.outputFilters[e]}setHandler(e,t){var n;this.outputFilters[e]=t,(n=this.channels[e])==null||n.setHandler(t)}getChannel(e){let t=this.channels[e];return t||=this.channels[e]=new $p(this.field+e-1,this.outputFilters[e],this.logger),t}addData(e,t){this.logger.time=e;for(let e=0;e<t.length;e+=2){let n=t[e]&127,r=t[e+1]&127,i=!1,a=null;if(n===0&&r===0)continue;this.logger.log(3,()=>`[`+qp([t[e],t[e+1]])+`] -> (`+qp([n,r])+`)`);let o=this.cmdHistory;if(n>=16&&n<=31){if(nm(n,r,o)){tm(null,null,o),this.logger.log(3,()=>`Repeated command (`+qp([n,r])+`) is dropped`);continue}tm(n,r,this.cmdHistory),i=this.parseCmd(n,r),i||=this.parseMidrow(n,r),i||=this.parsePAC(n,r),i||=this.parseBackgroundAttributes(n,r)}else tm(null,null,o);if(!i&&(a=this.parseChars(n,r),a)){let e=this.currentChannel;e&&e>0?this.getChannel(e).insertChars(a):this.logger.log(2,`No channel found yet. TEXT-MODE?`)}!i&&!a&&this.logger.log(2,()=>`Couldn't parse cleaned data `+qp([n,r])+` orig: `+qp([t[e],t[e+1]]))}}parseCmd(e,t){if(!((e===20||e===28||e===21||e===29)&&t>=32&&t<=47||(e===23||e===31)&&t>=33&&t<=35))return!1;let n=e===20||e===21||e===23?1:2,r=this.getChannel(n);return e===20||e===21||e===28||e===29?t===32?r.ccRCL():t===33?r.ccBS():t===34?r.ccAOF():t===35?r.ccAON():t===36?r.ccDER():t===37?r.ccRU(2):t===38?r.ccRU(3):t===39?r.ccRU(4):t===40?r.ccFON():t===41?r.ccRDC():t===42?r.ccTR():t===43?r.ccRTD():t===44?r.ccEDM():t===45?r.ccCR():t===46?r.ccENM():t===47&&r.ccEOC():r.ccTO(t-32),this.currentChannel=n,!0}parseMidrow(e,t){let n=0;if((e===17||e===25)&&t>=32&&t<=47){if(n=e===17?1:2,n!==this.currentChannel)return this.logger.log(0,`Mismatch channel in midrow parsing`),!1;let r=this.channels[n];return r?(r.ccMIDROW(t),this.logger.log(3,()=>`MIDROW (`+qp([e,t])+`)`),!0):!1}return!1}parsePAC(e,t){let n;if(!((e>=17&&e<=23||e>=25&&e<=31)&&t>=64&&t<=127||(e===16||e===24)&&t>=64&&t<=95))return!1;let r=e<=23?1:2;return n=t>=64&&t<=95?r===1?Vp[e]:Up[e]:r===1?Hp[e]:Wp[e],this.getChannel(r).setPAC(this.interpretPAC(n,t)),this.currentChannel=r,!0}interpretPAC(e,t){let n,r={color:null,italics:!1,indent:null,underline:!1,row:e};return n=t>95?t-96:t-64,r.underline=(n&1)==1,n<=13?r.color=[`white`,`green`,`blue`,`cyan`,`red`,`yellow`,`magenta`,`white`][Math.floor(n/2)]:n<=15?(r.italics=!0,r.color=`white`):r.indent=Math.floor((n-16)/2)*4,r}parseChars(e,t){let n,r=null,i=null;if(e>=25?(n=2,i=e-8):(n=1,i=e),i>=17&&i<=19){let e;e=i===17?t+80:i===18?t+112:t+144,this.logger.log(2,()=>`Special char '`+Rp(e)+`' in channel `+n),r=[e]}else e>=32&&e<=127&&(r=t===0?[e]:[e,t]);return r&&this.logger.log(3,()=>`Char codes = `+qp(r).join(`,`)),r}parseBackgroundAttributes(e,t){if(!((e===16||e===24)&&t>=32&&t<=47||(e===23||e===31)&&t>=45&&t<=47))return!1;let n,r={};e===16||e===24?(n=Math.floor((t-32)/2),r.background=Gp[n],t%2==1&&(r.background+=`_semi`)):t===45?r.background=`transparent`:(r.foreground=`black`,t===47&&(r.underline=!0));let i=e<=23?1:2;return this.getChannel(i).setBkgData(r),!0}reset(){for(let e=0;e<Object.keys(this.channels).length;e++){let t=this.channels[e];t&&t.reset()}tm(null,null,this.cmdHistory)}cueSplitAtTime(e){for(let t=0;t<this.channels.length;t++){let n=this.channels[t];n&&n.cueSplitAtTime(e)}}};function tm(e,t,n){n.a=e,n.b=t}function nm(e,t,n){return n.a===e&&n.b===t}function rm(){return{a:null,b:null}}var im=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,n){(this.startTime===null||this.startTime>e)&&(this.startTime=e),this.endTime=t,this.screen=n,this.timelineController.createCaptionsTrack(this.trackName)}reset(){this.cueRanges=[],this.startTime=null}},am=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=sm(),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(L.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(L.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(L.MANIFEST_LOADING,this.onManifestLoading,this),e.on(L.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(L.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(L.FRAG_LOADING,this.onFragLoading,this),e.on(L.FRAG_LOADED,this.onFragLoaded,this),e.on(L.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.on(L.FRAG_DECRYPTED,this.onFragDecrypted,this),e.on(L.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(L.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.on(L.BUFFER_APPENDED,this.onBufferAppended,this),e.on(L.BUFFER_FLUSHING,this.onBufferFlushing,this)}destroy(){let{hls:e}=this;e.off(L.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(L.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(L.MANIFEST_LOADING,this.onManifestLoading,this),e.off(L.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(L.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(L.FRAG_LOADING,this.onFragLoading,this),e.off(L.FRAG_LOADED,this.onFragLoaded,this),e.off(L.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.off(L.FRAG_DECRYPTED,this.onFragDecrypted,this),e.off(L.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(L.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.off(L.BUFFER_APPENDED,this.onBufferAppended,this),e.off(L.BUFFER_FLUSHING,this.onBufferFlushing,this),this.hls=this.config=this.media=null,this.cea608Parser1=this.cea608Parser2=void 0}initCea608Parsers(){let e=new im(this,`textTrack1`),t=new im(this,`textTrack2`),n=new im(this,`textTrack3`),r=new im(this,`textTrack4`);this.cea608Parser1=new em(1,e,t),this.cea608Parser2=new em(3,n,r)}addCues(e,t,n,r,i){let a=!1;for(let e=i.length;e--;){let r=i[e],o=om(r[0],r[1],t,n);if(o>=0&&(r[0]=Math.min(r[0],t),r[1]=Math.max(r[1],n),a=!0,o/(n-t)>.5))return}if(a||i.push([t,n]),this.config.renderTextTracksNatively){let i=this.cueCache[e];if(i){let e=this.Cues.newCue(null,t,n,r);e.length&&i.push.apply(i,e)}else{let i=this.captionsTracks[e].track;this.Cues.newCue(i,t,n,r)}}else{let i=this.Cues.newCue(null,t,n,r),a=this.captionsProperties[e]?.media;this.hls.trigger(L.CUES_PARSED,{type:`captions`,cues:i,track:e,closedCaptions:a})}}onInitPtsFound(e,{id:t,timestampOffsets:n}){let{unparsedFrags:r}=this;t===z.MAIN&&(this.initPTS=n),r.length&&(this.unparsedFrags=[],r.forEach(e=>{this.initPTS[e.frag.cc]?this.onFragLoaded(L.FRAG_LOADED,e):this.hls.trigger(L.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:e.frag,part:null,error: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:n,cueCache:r,media:i}=this,{label:a,languageCode:o}=t[e];i&&(r[e]=[],n[e]=Mf(i,`captions`,a,o,`hidden`))}createNonNativeTrack(e){if(this.nonNativeCaptionsTracks[e])return;let t=this.captionsProperties[e];if(!t)return;let n={_id:e,label:t.label,kind:`captions`,default:t.media?!!t.media.default:!1,closedCaptions:t.media};this.nonNativeCaptionsTracks[e]=n,this.hls.trigger(L.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:[n]})}onMediaAttaching(e,t){this.media=t.media}onMediaDetaching(e,t){let n=!!t.transferMedia;if(this.media=null,!n){if(this.config.renderTextTracksNatively){let{captionsTracks:e,cueCache:t}=this;for(let n in e)e[n].remove(),delete t[n]}this.cueCache={},this.captionsTracks={},this.nonNativeCaptionsTracks={}}}onManifestLoading(){this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs=sm(),this.tracks=[],this.captionsTracks={},this.nonNativeCaptionsTracks={},this.unparsedFrags=[],this.initPTS=[],this.cea608Parser1&&this.cea608Parser2&&(this.cea608Parser1.reset(),this.cea608Parser2.reset())}onSubtitleTracksUpdated(e,t){let n=t.subtitleTracks||[];if(n.length&&!this.config.renderTextTracksNatively&&!Pl(this.tracks,n)){let e=n.map(e=>({label:e.name,kind:e.type.toLowerCase(),default:e.default,subtitleTrack:e}));this.hls.trigger(L.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:e})}this.tracks=n}onManifestLoaded(e,t){this.config.enableCEA708Captions&&t.captions&&t.captions.forEach(e=>{let t=/(?:CC|SERVICE)([1-4])/.exec(e.instreamId);if(!t)return;let n=`textTrack${t[1]}`,r=this.captionsProperties[n];r&&(r.label=e.name,e.lang&&(r.languageCode=e.lang),r.media=e)})}closedCaptionsForLevel(e){return this.hls.levels[e.level]?.attrs[`CLOSED-CAPTIONS`]}onFragLoading(e,t){if(this.enabled&&t.frag.type===z.MAIN){let{cea608Parser1:e,cea608Parser2:n,lastSn:r}=this,{cc:i,sn:a}=t.frag,o=t.part?.index??-1;e&&n&&(a!==r+1||a===r&&o!==this.lastPartIndex+1||i!==this.lastCc)&&(e.reset(),n.reset()),this.lastCc=i,this.lastSn=a,this.lastPartIndex=o}}onFragLoaded(e,t){let{frag:n,payload:r}=t;if(n.level<this.tracks.length&&n.type===z.SUBTITLE){var i;if(r.byteLength||(i=n.initSegment)!=null&&(i=i.data)!=null&&i.byteLength){let e=n.decryptdata,r=`stats`in t;if(e==null||!e.encrypted||r){let e=this.tracks[n.level],r=this.vttCCs;r[n.cc]||(r[n.cc]={start:n.start,prevCC:this.prevCC,new:!0},this.prevCC=n.cc),e?.textCodec===gf?this._parseIMSC1(t):this._parseVTTs(t)}}else{let e=`part`in t?t.part:null;this.hls.trigger(L.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:n,part:e,error:Error(`Empty subtitle payload`)})}}}_parseIMSC1(e){let{frag:t,payload:n}=e,r=`part`in e?e.part:null;if(!this.initPTS[t.cc]){this.unparsedFrags.push(e);return}let i=this.hls;bf(n,this.initPTS[t.cc],e=>{this._appendCues(e,t.level),i.trigger(L.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:t,part:r})},e=>{i.logger.log(`Cannot parse IMSC1 (sn: ${t.sn} @${t.start}): ${e}`),i.trigger(L.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:t,part:r,error:e})})}_parseVTTs(e){let{frag:t,payload:n}=e,r=`part`in e?e.part:null,{initPTS:i,unparsedFrags:a}=this,o=i.length-1;if(!i[t.cc]&&o===-1){a.push(e);return}let s=this.hls,c=t.initSegment?.data;hf(c?Tr(c,new Uint8Array(n)).buffer:n,this.initPTS[t.cc],this.vttCCs,t.cc,(r&&!c?r:t).start,e=>{this._appendCues(e,t.level),s.trigger(L.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:t,part:r})},n=>{let i=n.message.startsWith(`Missing initPTS`);if(s.logger.log(`${i?`Deferred parsing of`:`Cannot parse`} VTT cue (sn: ${t.sn} @${t.start}): ${n}`),i){a.push(e);return}this.config.enableIMSC1&&this._fallbackToIMSC1(e),s.trigger(L.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:t,part:r,error:n})})}_fallbackToIMSC1(e){let{frag:t,payload:n}=e,r=this.tracks[t.level];r.textCodec||bf(n,this.initPTS[t.cc],()=>{r.textCodec=gf,this._parseIMSC1(e)},()=>{r.textCodec=`wvtt`})}_appendCues(e,t){let n=this.hls;if(this.config.renderTextTracksNatively){let n=this.tracks[t].trackNode?.track;if(!n||n.mode===`disabled`)return;e.forEach(e=>Pf(n,e))}else{let r=this.tracks[t];if(!r)return;let i=r.default?`default`:`subtitles`+t;n.trigger(L.CUES_PARSED,{type:`subtitles`,cues:e,track:i,subtitleTrack:r})}}onFragDecrypted(e,t){let{frag:n}=t;n.type===z.SUBTITLE&&this.onFragLoaded(L.FRAG_LOADED,t)}onSubtitleTracksCleared(){this.tracks=[],this.captionsTracks={}}onFragParsingUserdata(e,t){if(!this.enabled||!this.config.enableCEA708Captions)return;let{frag:n,samples:r}=t;if(n.type!==z.MAIN||this.closedCaptionsForLevel(n)!==`NONE`)for(let e=0;e<r.length;e++){let t=r[e].bytes;if(t){this.cea608Parser1||this.initCea608Parsers();let n=this.extractCea608Data(t);this.cea608Parser1.addData(r[e].pts,n[0]),this.cea608Parser2.addData(r[e].pts,n[1])}}}onBufferAppended(e,t){if(this.config.renderTextTracksNatively){var n;let{type:e,timeRanges:r}=t;if(e===`video`&&(n=r[e])!=null&&n.length){let{captionsTracks:e,cueCache:t}=this;Object.keys(t).forEach(n=>{let r=e[n]?.track;if(r){let e=t[n];for(let t=0;t<e.length;t++)Pf(r,e[t])}delete t[n]})}}}onBufferFlushing(e,t){let{startOffset:n,endOffset:r,endOffsetSubtitles:i,type:a}=t,{media:o}=this;if(!(!o||o.currentTime<r)){if(!a||a===`video`){let{captionsTracks:e,cueCache:t}=this;Object.keys(e).forEach(t=>Ff(e[t].track,n,r)),Object.keys(t).forEach(e=>{let i=t[e];for(let e=i.length;e--;){let t=i[e];t.startTime>=n&&t.endTime<=r&&i.splice(e,1)}})}this.config.renderTextTracksNatively&&n===0&&i!==void 0&&this.tracks.forEach(e=>{let t=e.trackNode?.track;t&&Ff(t,n,i)})}}extractCea608Data(e){let t=[[],[]],n=e[0]&31,r=2;for(let i=0;i<n;i++){let n=e[r++],i=127&e[r++],a=127&e[r++];if((i!==0||a!==0)&&4&n){let e=3&n;(e===0||e===1)&&(t[e].push(i),t[e].push(a))}}return t}};function om(e,t,n,r){return Math.min(t,r)-Math.max(e,n)}function sm(){return{ccOffset:0,presentationOffset:0,0:{start:0,prevCC:-1,new:!0}}}var cm=/\s/,lm={newCue(e,t,n,r){let i=[],a,o,s,c,l,u=self.VTTCue||self.TextTrackCue;for(let f=0;f<r.rows.length;f++)if(a=r.rows[f],s=!0,c=0,l=``,!a.isEmpty()){var d;for(let e=0;e<a.chars.length;e++)cm.test(a.chars[e].uchar)&&s?c++:(l+=a.chars[e].uchar,s=!1);a.cueStartTime=t,t===n&&(n+=1e-4),c>=16?c--:c++;let r=lf(l.trim()),p=mf(t,n,r);e!=null&&(d=e.cues)!=null&&d.getCueById(p)||(o=new u(t,n,r),o.id=p,o.line=f+1,o.align=`left`,o.position=10+Math.min(80,Math.floor(c*8/32)*10),i.push(o))}return e&&i.length&&(i.sort((e,t)=>e.line===`auto`||t.line===`auto`?0:e.line>8&&t.line>8?t.line-e.line:e.line-t.line),i.forEach(t=>Pf(e,t))),i}},um=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 Ct}destroy(){this.callbacks=this.context=this.config=null,this.abortInternal(),this.stats=null}load(e,t,n){let r=this.stats;if(r.loading.start)throw Error(`Loader can only be used once.`);r.loading.start=self.performance.now(),this.context=e,this.config=t,this.callbacks=n,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(Wt(e,t,!0))this.retry(e);else{U.warn(`timeout while loading ${this.context?.url}`);let e=this.callbacks;e&&(this.abortInternal(),e.onTimeout(this.stats,this.context,this.getNetworkDetails()))}}retry(e){let{context:t,stats:n}=this;this.retryDelay=Ht(e,n.retry),n.retry++,U.warn(`${status?`HTTP Status `+status:`Timeout`} while loading ${t?.url}, retrying ${n.retry}/${e.maxNumRetry} in ${this.retryDelay}ms`),this.abortInternal(),this.resetInternalLoader(),self.clearTimeout(this.retryTimeout),this.retryTimeout=self.setTimeout(()=>this.loadInternal(),this.retryDelay)}};function dm(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch{}return!1}var fm=/(\d+)-(\d+)\/(\d+)/,pm=class extends um{constructor(e){super(),this.fetchSetup=void 0,this.request=null,this.response=null,this.controller=null,this.fetchSetup=e.fetchSetup||_m}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:n}=this;if(!e||!t)return;n.loading.first=0,n.loaded=0,n.aborted=!1,this.controller=new self.AbortController;let r=mm(t,this.controller.signal),i=t.responseType===`arraybuffer`,a=i?`byteLength`:`length`,{maxTimeToFirstByteMs:o,maxLoadTimeMs:s}=e.loadPolicy;this.request=this.fetchSetup(t,r),self.clearTimeout(this.requestTimeout),e.timeout=o&&P(o)?o:s,this.requestTimeout=self.setTimeout(()=>{this.loadtimeout()},e.timeout),(El(this.request)?this.request.then(self.fetch):self.fetch(this.request)).then(r=>{this.response=r;let a=Math.max(self.performance.now(),n.loading.start);if(self.clearTimeout(this.requestTimeout),e.timeout=s,this.requestTimeout=self.setTimeout(()=>{this.loadtimeout()},s-(a-n.loading.start)),!r.ok){let{status:e,statusText:t}=r;throw new vm(t||`fetch, bad network response`,e,r)}n.loading.first=a,n.total=gm(r.headers)||n.total;let o=this.callbacks?.onProgress;return o&&P(e.highWaterMark)?this.loadProgressively(r,n,t,e.highWaterMark,o):i?r.arrayBuffer():t.responseType===`json`?r.json():r.text()}).then(r=>{var i;let o=this.response;if(!o)throw Error(`loader destroyed`);self.clearTimeout(this.requestTimeout),n.loading.end=Math.max(self.performance.now(),n.loading.first);let s=r[a];s&&(n.loaded=n.total=s);let c={url:o.url,data:r,code:o.status},l=this.callbacks?.onProgress;l&&!P(e.highWaterMark)&&l(n,t,r,o),(i=this.callbacks)==null||i.onSuccess(c,n,t,o)}).catch(r=>{if(self.clearTimeout(this.requestTimeout),n.aborted)return;let i=r&&r.code||0,a=r?r.message:null,o=e.loadPolicy.errorRetry,s=n.retry;if(Wt(o,s,!1,{url:t.url,data:void 0,code:i}))this.retry(o);else{var c;U.error(`${i} while loading ${t.url}`),(c=this.callbacks)==null||c.onError({code:i,text:a},t,r?r.details:null,n)}})}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,n,r=0,i){let a=new As,o=e.body.getReader(),s=()=>o.read().then(o=>{if(o.done)return a.dataLength&&i(t,n,a.flush().buffer,e),Promise.resolve(new ArrayBuffer(0));let c=o.value,l=c.length;return t.loaded+=l,l<r||a.dataLength?(a.push(c),a.dataLength>=r&&i(t,n,a.flush().buffer,e)):i(t,n,c.buffer,e),s()}).catch(()=>Promise.reject());return s()}};function mm(e,t){let n={method:`GET`,mode:`cors`,credentials:`same-origin`,signal:t,headers:new self.Headers(V({},e.headers))};return e.rangeEnd&&n.headers.set(`Range`,`bytes=`+e.rangeStart+`-`+String(e.rangeEnd-1)),n}function hm(e){let t=fm.exec(e);if(t)return parseInt(t[2])-parseInt(t[1])+1}function gm(e){let t=e.get(`Content-Range`);if(t){let e=hm(t);if(P(e))return e}let n=e.get(`Content-Length`);if(n)return parseInt(n)}function _m(e,t){return new self.Request(e.url,t)}var vm=class extends Error{constructor(e,t,n){super(e),this.code=void 0,this.details=void 0,this.code=t,this.details=n}},ym=(e,t,n)=>Math.max(t,Math.min(e,n)),bm=/^age:\s*[\d.]+\s*$/im,xm=class extends um{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 n=this.loader=new self.XMLHttpRequest,r=this.stats;r.loading.first=0,r.loaded=0,r.aborted=!1;let i=this.xhrSetup;i?Promise.resolve().then(()=>{if(!(this.loader!==n||this.stats.aborted))return i.call(this,n,t.url,t)}).catch(e=>{if(!(this.loader!==n||this.stats.aborted))return n.open(`GET`,t.url,!0),i.call(this,n,t.url,t)}).then(()=>{this.loader!==n||this.stats.aborted||this.openAndSendXhr(n,t,e)}).catch(e=>{var i;(i=this.callbacks)==null||i.onError({code:n.status,text:e.message},t,n,r)}):this.openAndSendXhr(n,t,e)}openAndSendXhr(e,t,n){e.readyState||e.open(`GET`,t.url,!0);let r=t.headers,{maxTimeToFirstByteMs:i,maxLoadTimeMs:a}=n.loadPolicy;if(r)for(let t in r)e.setRequestHeader(t,r[t]);t.rangeEnd&&e.setRequestHeader(`Range`,`bytes=${t.rangeStart}-${t.rangeEnd-1}`),e.onreadystatechange=this.readystatechange.bind(this),e.onprogress=this.loadprogress.bind(this),e.responseType=t.responseType,self.clearTimeout(this.requestTimeout),n.timeout=i&&P(i)?i:a,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),n.timeout),e.send()}readystatechange(){let{context:e,loader:t,stats:n}=this;if(!e||!t)return;let r=t.readyState,i=this.config;if(!n.aborted&&r>=2&&(n.loading.first===0&&(n.loading.first=Math.max(self.performance.now(),n.loading.start),i.timeout!==i.loadPolicy.maxLoadTimeMs&&(self.clearTimeout(this.requestTimeout),i.timeout=i.loadPolicy.maxLoadTimeMs,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),i.loadPolicy.maxLoadTimeMs-(n.loading.first-n.loading.start)))),r===4)){self.clearTimeout(this.requestTimeout),t.onreadystatechange=null,t.onprogress=null;let r=t.status,s=t.responseType===`text`?t.responseText:null;if(r>=200&&r<300){let i=s??t.response;if(i!=null){var a;n.loading.end=Math.max(self.performance.now(),n.loading.first);let o=t.responseType===`arraybuffer`?i.byteLength:i.length;n.loaded=n.total=o,n.bwEstimate=n.total*8e3/(n.loading.end-n.loading.first);let s=this.callbacks?.onProgress;s&&s(n,e,i,t);let c={url:t.responseURL,data:i,code:r};e.rangeEnd&&o!==e.rangeEnd-e.rangeStart&&U.warn(`Payload length ${o} does not match requested Range: bytes=${e.rangeStart}-${e.rangeEnd-1}`),(a=this.callbacks)==null||a.onSuccess(c,n,e,t);return}}let c=i.loadPolicy.errorRetry,l=n.retry;if(Wt(c,l,!1,{url:e.url,data:void 0,code:r}))this.retry(c);else{var o;U.error(`${r} while loading ${e.url}`),(o=this.callbacks)==null||o.onError({code:r,text:t.statusText},e,t,n)}}}loadprogress(e){let t=this.stats;t.loaded=e.loaded,e.lengthComputable&&(t.total=e.total)}getCacheAge(){let e=null;if(this.loader&&bm.test(this.loader.getAllResponseHeaders())){let t=this.loader.getResponseHeader(`age`);e=t?parseFloat(t):null}return e}getResponseHeader(e){return this.loader&&RegExp(`^${e}:\\s*[\\d.]+\\s*$`,`im`).test(this.loader.getAllResponseHeaders())?this.loader.getResponseHeader(e):null}},Sm=H(H({autoStartLoad:!0,startPosition:-1,defaultAudioCodec:void 0,debug:!1,capLevelOnFPSDrop:!1,capLevelToPlayerSize:!1,ignoreDevicePixelRatio:!1,maxDevicePixelRatio:1/0,preferManagedMediaSource:!1,initialLiveManifestSize:1,maxBufferLength:30,backBufferLength:1/0,frontBufferFlushThreshold:1/0,loopBackBufferFlush:void 0,startOnSegmentBoundary:!1,nextAudioTrackBufferFlushForwardOffset:.25,maxBufferSize:6e7,maxFragLookUpTolerance:.25,maxBufferHole:.1,detectStallWithCurrentTimeMs:1250,highBufferWatchdogPeriod:2,nudgeOffset:.1,nudgeMaxRetry:3,nudgeOnVideoHole:!0,skipBufferHolePadding:.1,liveSyncMode:`edge`,liveSyncDurationCount:3,liveSyncOnStallIncrease:1,liveMaxLatencyDurationCount:1/0,liveMaxUnchangedPlaylistRefresh:1/0,liveSyncDuration:void 0,liveMaxLatencyDuration:void 0,maxLiveSyncPlaybackRate:1,liveDurationInfinity:!1,liveBackBufferLength:null,maxMaxBufferLength:600,enableWorker:!0,workerPath:null,enableSoftwareAES:!0,startLevel:void 0,startFragPrefetch:!1,fpsDroppedMonitoringPeriod:5e3,fpsDroppedMonitoringThreshold:.2,appendErrorMaxRetry:3,appendTimeout:1/0,ignorePlaylistParsingErrors:!1,loader:xm,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:Oo,requireKeySystemAccessOnStart:!1,reuseKeySessions:!1,testBandwidth:!0,progressive:!1,lowLatencyMode:!0,cmcd:void 0,enableDateRangeMetadataCues:!0,enableEmsgMetadataCues:!0,enableEmsgKLVMetadata:!1,enableID3MetadataCues:!0,emsgKLVSchemaUri:void 0,enableInterstitialPlayback:!0,interstitialAppendInPlace:!0,interstitialLiveLookAhead:10,iframeCacheLimit:2097152,useMediaCapabilities:!0,preserveManualLevelOnError:!1,errorPenaltyExpireMs:0,certLoadPolicy:{default:{maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:null,errorRetry:null}},keyLoadPolicy:{default:{maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:2e4,backoff:`linear`},errorRetry:{maxNumRetry:8,retryDelayMs:1e3,maxRetryDelayMs:2e4,backoff:`linear`}}},manifestLoadPolicy:{default:{maxTimeToFirstByteMs:1/0,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},playlistLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:2,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},fragLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:12e4,timeoutRetry:{maxNumRetry:4,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:6,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},steeringManifestLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},interstitialAssetListLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:3e4,timeoutRetry:{maxNumRetry:0,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:0,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},manifestLoadingTimeOut:1e4,manifestLoadingMaxRetry:1,manifestLoadingRetryDelay:1e3,manifestLoadingMaxRetryTimeout:64e3,levelLoadingTimeOut:1e4,levelLoadingMaxRetry:4,levelLoadingRetryDelay:1e3,levelLoadingMaxRetryTimeout:64e3,fragLoadingTimeOut:2e4,fragLoadingMaxRetry:6,fragLoadingRetryDelay:1e3,fragLoadingMaxRetryTimeout:64e3,streamController:rp,abrController:Qi,bufferController:wa,capLevelController:Ll,errorController:ua,fpsController:$d,id3TrackController:Xf,gapController:Vf,latencyController:Mp},Cm()),{},{subtitleStreamController:Fp,subtitleTrackController:Rf,timelineController:am,audioStreamController:Ml,audioTrackController:Il,emeController:qd,cmcdController:Bd,contentSteeringController:Hd,iframeController:dp,interstitialsController:jp});function Cm(){return{cueHandler:lm,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 wm(e,t,n){if((t.liveSyncDurationCount||t.liveMaxLatencyDurationCount)&&(t.liveSyncDuration||t.liveMaxLatencyDuration))throw Error(`Illegal hls.js config: don't mix up liveSyncDurationCount/liveMaxLatencyDurationCount and liveSyncDuration/liveMaxLatencyDuration`);if(t.liveMaxLatencyDurationCount!==void 0&&(t.liveSyncDurationCount===void 0||t.liveMaxLatencyDurationCount<=t.liveSyncDurationCount))throw Error(`Illegal hls.js config: "liveMaxLatencyDurationCount" must be greater than "liveSyncDurationCount"`);if(t.liveMaxLatencyDuration!==void 0&&(t.liveSyncDuration===void 0||t.liveMaxLatencyDuration<=t.liveSyncDuration))throw Error(`Illegal hls.js config: "liveMaxLatencyDuration" must be greater than "liveSyncDuration"`);if(t.liveMaxUnchangedPlaylistRefresh!==void 0){let e=t.liveMaxUnchangedPlaylistRefresh,r=ym(e,2,1/0);r!==e&&n.warn(`hls.js config: "liveMaxUnchangedPlaylistRefresh" clamped from ${e} to ${r}.`),t.liveMaxUnchangedPlaylistRefresh=r}let r=Tm(e),i=[`manifest`,`level`,`frag`],a=[`TimeOut`,`MaxRetry`,`RetryDelay`,`MaxRetryTimeout`];return i.forEach(e=>{let i=`${e===`level`?`playlist`:e}LoadPolicy`,o=t[i]===void 0,s=[];a.forEach(n=>{let a=`${e}Loading${n}`,c=t[a];if(c!==void 0&&o){s.push(a);let e=r[i].default;switch(t[i]={default:e},n){case`TimeOut`:e.maxLoadTimeMs=c,e.maxTimeToFirstByteMs=c;break;case`MaxRetry`:e.errorRetry.maxNumRetry=c,e.timeoutRetry.maxNumRetry=c;break;case`RetryDelay`:e.errorRetry.retryDelayMs=c,e.timeoutRetry.retryDelayMs=c;break;case`MaxRetryTimeout`:e.errorRetry.maxRetryDelayMs=c,e.timeoutRetry.maxRetryDelayMs=c}}}),s.length&&n.warn(`hls.js config: "${s.join(`", "`)}" setting(s) are deprecated, use "${i}": ${q(t[i])}`)}),H(H({},r),t)}function Tm(e){return e&&typeof e==`object`?Array.isArray(e)?e.map(Tm):Object.keys(e).reduce((t,n)=>(t[n]=Tm(e[n]),t),{}):e}function Em(e,t){let n=e.loader;n!==pm&&n!==xm?(t.log(`[config]: Custom loader detected, cannot enable progressive streaming`),e.progressive=!1):dm()&&(e.loader=pm,e.progressive=!0,e.enableSoftwareAES=!0,t.log(`[config]: Progressive streaming enabled, using FetchLoader`))}var Dm=class extends Nl{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(L.MANIFEST_LOADING,this.onManifestLoading,this),e.on(L.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(L.LEVEL_LOADED,this.onLevelLoaded,this),e.on(L.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(L.FRAG_BUFFERED,this.onFragBuffered,this),e.on(L.ERROR,this.onError,this)}_unregisterListeners(){let{hls:e}=this;e.off(L.MANIFEST_LOADING,this.onManifestLoading,this),e.off(L.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(L.LEVEL_LOADED,this.onLevelLoaded,this),e.off(L.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(L.FRAG_BUFFERED,this.onFragBuffered,this),e.off(L.ERROR,this.onError,this)}destroy(){this._unregisterListeners(),this.steering=null,this.resetLevels(),super.destroy()}stopLoad(){this._levels.forEach(e=>{e.loadError=0,e.fragmentError=0}),super.stopLoad()}resetLevels(){this._startLevel=void 0,this.manualLevelIndex=-1,this.currentLevelIndex=-1,this.currentLevel=null,this._levels=[],this._maxAutoLevel=-1,this._iframeVariants=[]}onManifestLoading(e,t){this.resetLevels()}onManifestLoaded(e,t){let n=this.hls.config.preferManagedMediaSource,r=[],i={},a={},o=!1,s=!1,c=!1,l=!1;t.levels.forEach(e=>{let t=e.attrs,u=Am(e,n),{audioCodec:d,videoCodec:f,imageCodec:p,width:m,height:h}=e;if(!u){this.log(`Some or all CODECS not supported "${t.CODECS}"`);return}o||=!!(m&&h),s||=!!f,c||=!!d,l||=!!p;let{CODECS:g,"FRAME-RATE":_,"HDCP-LEVEL":v,"PATHWAY-ID":y,RESOLUTION:b,"VIDEO-RANGE":x}=t,S=`${`${y||`.`}-`}${e.bitrate}-${b}-${_}-${g}-${x}-${v}`;if(!i[S]){let t=this.createLevel(e);i[S]=t,a[S]=1,r.push(t)}else if(i[S].uri!==e.url&&!e.attrs[`PATHWAY-ID`]){let t=a[S]+=1;e.attrs[`PATHWAY-ID`]=Array(t+1).join(`.`);let n=this.createLevel(e);i[S]=n,r.push(n)}else e.iframes||(i[S].addGroupId(`audio`,t.AUDIO),i[S].addGroupId(`text`,t.SUBTITLES))}),this.filterAndSortMediaOptions(r,t,o,s,c,l)}createLevel(e){let t=new Mi(e),n=e.supplemental;if(n!=null&&n.videoCodec&&!km(n.videoCodec,this.hls.config.preferManagedMediaSource)){let e=Error(`SUPPLEMENTAL-CODECS not supported "${n.videoCodec}"`);this.log(e.message),t.supportedResult=gi(e,[])}return t}filterAndSortMediaOptions(e,t,n,r,i,a){let o=[],s=[],c=e,l=t.stats?.parsing||{},u=this.hls.config.preferManagedMediaSource;if((n||r)&&i&&(c=c.filter(({videoCodec:e,videoRange:t,width:n,height:r})=>(!!e||!!(n&&r))&&Oi(t))),r&&a&&(c=c.filter(e=>!e.imageCodec)),c.length===0){Promise.resolve().then(()=>{if(this.hls){let e=`no level with compatible codecs found in manifest`,n=e;t.levels.length&&(n=`one or more CODECS in variant not supported: ${q(t.levels.map(e=>e.attrs.CODECS).filter((e,t,n)=>n.indexOf(e)===t))}`,this.warn(n),e+=` (${n})`);let r=Error(e);this.hls.trigger(L.ERROR,{type:F.MEDIA_ERROR,details:I.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:t.url,error:r,reason:n})}}),l.end=performance.now();return}t.audioTracks&&(o=t.audioTracks.filter(e=>!e.audioCodec||Om(e.audioCodec,u)),jm(o)),t.subtitles&&(s=t.subtitles,jm(s));let d=c.slice(0);c.sort((e,t)=>{if(e.attrs[`HDCP-LEVEL`]!==t.attrs[`HDCP-LEVEL`])return(e.attrs[`HDCP-LEVEL`]||``)>(t.attrs[`HDCP-LEVEL`]||``)?1:-1;if(n&&e.height!==t.height)return e.height-t.height;if(e.frameRate!==t.frameRate)return e.frameRate-t.frameRate;if(e.videoRange!==t.videoRange)return Di.indexOf(e.videoRange)-Di.indexOf(t.videoRange);if(e.videoCodec!==t.videoCodec){let n=ei(e.videoCodec),r=ei(t.videoCodec);if(n!==r)return r-n}if(e.uri===t.uri&&e.codecSet!==t.codecSet){let n=ti(e.codecSet),r=ti(t.codecSet);if(n!==r)return r-n}return e.averageBitrate===t.averageBitrate?0:e.averageBitrate-t.averageBitrate});let f=d[0];if(this.steering&&(c=this.steering.filterParsedLevels(c),c.length!==d.length)){for(let e=0;e<d.length;e++)if(d[e].pathwayId===c[0].pathwayId){f=d[e];break}}this._levels=c;for(let e=0;e<c.length;e++)if(c[e]===f){this._firstLevel=e;let t=f.bitrate,n=this.hls.bandwidthEstimate;if(this.log(`manifest loaded, ${c.length} level(s) found, first bitrate: ${t}`),this.hls.userConfig?.abrEwmaDefaultEstimate===void 0){let e=Math.min(t,this.hls.config.abrEwmaDefaultEstimateMax);e>n&&n===this.hls.abrEwmaDefaultEstimate&&(this.hls.bandwidthEstimate=e)}break}let p=t.iframeVariants.filter(e=>Am(e,u));this._iframeVariants=p;let m=i&&!r,h=this.hls.config,g=!!(h.audioStreamController&&h.audioTrackController),_={levels:c,audioTracks:o,subtitleTracks:s,iframeVariants:p,sessionData:t.sessionData,sessionKeys:t.sessionKeys,firstLevel:this._firstLevel,stats:t.stats,audio:i,video:r,altAudio:g&&!m&&o.some(e=>!!e.url)};l.end=performance.now(),this.hls.trigger(L.MANIFEST_PARSED,_)}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 n=Error(`invalid level idx`),r=e<0;if(this.hls.trigger(L.ERROR,{type:F.OTHER_ERROR,details:I.LEVEL_SWITCH_ERROR,level:e,fatal:r,error:n,reason:n.message}),r)return;e=Math.min(e,t.length-1)}let n=this.currentLevelIndex,r=this.currentLevel,i=r?r.attrs[`PATHWAY-ID`]:void 0,a=t[e],o=a.attrs[`PATHWAY-ID`];if(this.currentLevelIndex=e,this.currentLevel=a,n===e&&r&&i===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 ${n}${i?` with Pathway `+i:``}`);let s={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(L.LEVEL_SWITCHING,s);let c=a.details;if(!c||c.live){let e=this.switchParams(a.uri,r?.details,c);this.loadPlaylist(e)}}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?this.hls.firstAutoLevel:e}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(),n=e.filter(e=>t.indexOf(e)!==-1);if(e.length<1){this.warn(`pathwayPriority ${e} should contain at least one pathway from list: ${t}`);return}this.steering.pathwayPriority=n}}onError(e,t){!t.fatal&&t.context&&t.context.type===R.LEVEL&&t.context.level===this.level&&this.checkRetry(t)}onFragBuffered(e,{frag:t}){if(t.type===z.MAIN){let e=t.elementaryStreams;if(!Object.keys(e).some(t=>!!e[t]))return;let n=this._levels[t.level];n!=null&&n.loadError&&(this.log(`Resetting level error count of ${n.loadError} on frag buffered`),n.loadError=0)}}onLevelLoaded(e,t){var n;let{level:r,details:i}=t,a=t.levelInfo;if(!a){var o;this.warn(`Invalid level index ${r}`),(o=t.deliveryDirectives)!=null&&o.skip&&(i.deltaUpdateFailed=!0);return}if(a===this.currentLevel||t.withoutMultiVariant){a.fragmentError===0&&(a.loadError=0);let e=a.details;e===t.details&&e.advanced&&(e=void 0),this.playlistLoaded(r,t,e)}else(n=t.deliveryDirectives)!=null&&n.skip&&(i.deltaUpdateFailed=!0)}loadPlaylist(e){super.loadPlaylist(),this.shouldLoadPlaylist(this.currentLevel)&&this.scheduleLoading(this.currentLevel,e)}loadingPlaylist(e,t){super.loadingPlaylist(e,t);let n=this.getUrlWithDirectives(e.uri,t),r=this.currentLevelIndex,i=e.attrs[`PATHWAY-ID`],a=e.details,o=a?.age;this.log(`Loading level index ${r}${t?.msn===void 0?``:` at sn `+t.msn+` part `+t.part}${i?` Pathway `+i:``}${o&&a.live?` age `+o.toFixed(1)+(a.type&&` `+a.type||``):``} ${n}`),this.hls.trigger(L.LEVEL_LOADING,{url:n,level:r,levelInfo:e,pathwayId:e.attrs[`PATHWAY-ID`],id:0,deliveryDirectives:t||null})}get nextLoadLevel(){return this.manualLevelIndex===-1?this.hls.nextAutoLevel:this.manualLevelIndex}set nextLoadLevel(e){let t=this.currentLevelIndex;if(this.manualLevelIndex===-1&&e!==t&&e!==-1){let n=this.hls.config.abrSwitchInterval;if(n>0){let r=performance.now(),i=r-this.lastABRSwitchTime,a=n*1e3;if(this.lastABRSwitchTime>-1&&i<a){this.warn(`Preventing ABR level switch: ${t} -> ${e} (${Math.round(i)}ms < ${a}ms / ${n}s)`);return}this.lastABRSwitchTime=r,this.log(`Allowing ABR level switch: ${t} -> ${e} (${Math.round(i)}ms >= ${a}ms / ${n}s)`)}}this.level=e,this.manualLevelIndex===-1&&(this.hls.nextAutoLevel=e)}removeLevel(e){var t;if(this._levels.length===1)return;let n=this._levels.filter((t,n)=>n!==e||(this.steering&&this.steering.removeLevel(t),t===this.currentLevel&&(this.currentLevel=null,this.currentLevelIndex=-1,t.details&&t.details.fragments.forEach(e=>e.level=-1)),!1));_s(n),this._levels=n,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 r=n.length-1;this._firstLevel=Math.min(this._firstLevel,r),this._startLevel&&=Math.min(this._startLevel,r),this.hls.trigger(L.LEVELS_UPDATED,{levels:n})}onLevelsUpdated(e,{levels:t}){this._levels=t}checkMaxAutoUpdated(){let{autoLevelCapping:e,maxAutoLevel:t,maxHdcpLevel:n}=this.hls;this._maxAutoLevel!==t&&(this._maxAutoLevel=t,this.hls.trigger(L.MAX_AUTO_LEVEL_UPDATED,{autoLevelCapping:e,levels:this.levels,maxAutoLevel:t,minAutoLevel:this.hls.minAutoLevel,maxHdcpLevel:n}))}};function Om(e,t){return Zr(e,`audio`,t)}function km(e,t){return Zr(e,`video`,t)}function Am(e,t){let{audioCodec:n,videoCodec:r}=e;n&&(e.audioCodec=n=ai(n,t)||void 0),r&&=e.videoCodec=li(r);let{unknownCodecs:i}=e;return!(i?.length||n&&!Om(n,t)||r&&!km(r,t))}function jm(e){let t={};e.forEach(e=>{let n=e.groupId||``;e.id=t[n]=t[n]||0,t[n]++})}var Mm=class extends Xt{constructor(e,t){super(`key-loader`,t),this.config=void 0,this.keyLoaderInfo={},this.emeController=null,this.config=e}abort(e){for(let t in this.keyLoaderInfo){let n=this.keyLoaderInfo[t].loader;if(n){if(e&&e!==n.context?.frag.type)return;n.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,n){return this.emeController?this.emeController.loadClear(e,t,n):null}load(e,t){return!e.decryptdata&&e.encrypted&&this.emeController&&this.config.emeEnabled?this.emeController.selectKeySystemFormat(e).then(n=>this.loadInternal(e,t,n)):this.loadInternal(e,t)}loadInternal(e,t,n){n&&e.setKeyFormat(n);let r=e.decryptdata;if(!r){let t=Error(n?`Expected frag.decryptdata to be defined after setting format ${n}`:`Missing decryption data on fragment in onKeyLoading (emeEnabled with controller: ${this.emeController&&this.config.emeEnabled})`);return Promise.reject(Nm(e,I.KEY_LOAD_ERROR,t))}let i=e;switch(r.method){case`SAMPLE-AES`:case`SAMPLE-AES-CENC`:case`SAMPLE-AES-CTR`:return r.keyFormat===`identity`?this.loadKeyHTTP(i):t?t.then(()=>this.loadKeyEME(i)):this.loadKeyEME(i);case`AES-128`:case`AES-256`:case`AES-256-CTR`:return this.loadKeyHTTP(i);default:return Promise.reject(Nm(e,I.KEY_LOAD_ERROR,Error(`Key supplied with unsupported METHOD: "${r.method}"`)))}}loadKeyEME(e){if(this.emeController&&this.config.emeEnabled){var t;if(!e.decryptdata.keyId&&(t=e.initSegment)!=null&&t.data){let t=hr(e.initSegment.data);if(t.length){let n=t[0],r=e.decryptdata.uri;if(n.some(e=>e!==0))this.log(`Using keyId found in init segment ${Hn(n)} keyUri: ${r}`),Po.setKeyIdForUri(r,n);else{let e=Po.addKeyIdForUri(r);this.log(`Patching empty keyId with ${Hn(e)} keyUri: ${r}`),n=e}e.decryptdata.keyId=n}}return this.emeController.loadKey(e).then(()=>({frag:e,keyInfo:{decryptdata:e.decryptdata}}))}return Promise.reject(Nm(e,I.KEY_LOAD_ERROR,Error(`emeEnabled with controller: ${this.emeController&&this.config.emeEnabled})`)))}loadKeyHTTP(e){let t=e.decryptdata,n=t.uri;if(!n)return Promise.reject(Nm(e,I.KEY_LOAD_ERROR,Error(`Invalid key URI: "${n}"`)));let r=this.keyLoaderInfo[n];if(r){if(r.decryptdata.key)return t.key=r.decryptdata.key,r.keyLoadPromise=null,Promise.resolve({frag:e,keyInfo:r});if(r.keyLoadPromise)return r.keyLoadPromise.then(n=>(t.key=r.decryptdata.key,H(H({},n),{},{frag:e})))}this.log(`Loading${t.keyId?` keyId: `+Hn(t.keyId):``} URI: ${t.uri} from ${e.type} ${e.level}`);let i=this.config,a=i.loader,o=new a(i);e.keyLoader=o;let s=this.keyLoaderInfo[n]={decryptdata:t,keyLoadPromise:null,loader:o};return s.keyLoadPromise=new Promise((t,r)=>{let a={type:R.KEY,keyInfo:s,frag:e,responseType:`arraybuffer`,url:n},c=i.keyLoadPolicy.default,l={loadPolicy:c,timeout:c.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0};o.load(a,l,{onSuccess:(e,n,i,a)=>{let{frag:o,keyInfo:s,url:c}=i;if(!o.decryptdata||s!==this.keyLoaderInfo[c])return this.resetLoader(i),r(Nm(o,I.KEY_LOAD_ERROR,Error(`after key load, decryptdata unset or changed`),a));s.decryptdata.key=o.decryptdata.key=new Uint8Array(e.data),o.keyLoader=s.loader=s.keyLoadPromise=null,t({frag:o,keyInfo:s})},onError:(t,i,a,o)=>{this.resetLoader(i),r(Nm(e,I.KEY_LOAD_ERROR,Error(`HTTP Error ${t.code} loading key ${t.text}`),a,H({url:n,data:void 0},t)))},onTimeout:(t,n,i)=>{this.resetLoader(n),r(Nm(e,I.KEY_LOAD_TIMEOUT,Error(`key loading timed out`),i))},onAbort:(t,n,i)=>{this.resetLoader(n),r(Nm(e,I.INTERNAL_ABORTED,Error(`key loading aborted`),i))}})})}resetLoader(e){let{frag:t,keyInfo:n,url:r}=e,i=n.loader;t.keyLoader===i&&(t.keyLoader=n.loader=n.keyLoadPromise=null),delete this.keyLoaderInfo[r],i&&i.destroy()}};function Nm(e,t=I.KEY_LOAD_ERROR,n,r,i){return new Xa({type:F.NETWORK_ERROR,details:t,fatal:!1,frag:e,response:i,error:n,networkDetails:r||null})}function Pm(e){let{type:t}=e;switch(t){case R.AUDIO_TRACK:return z.AUDIO;case R.SUBTITLE_TRACK:return z.SUBTITLE;default:return z.MAIN}}function Fm(e,t){let n=e.url;return(n===void 0||n.indexOf(`data:`)===0)&&(n=t.url),n}var Im=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(L.MANIFEST_LOADING,this.onManifestLoading,this),e.on(L.LEVEL_LOADING,this.onLevelLoading,this),e.on(L.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.on(L.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),e.on(L.LEVELS_UPDATED,this.onLevelsUpdated,this)}unregisterListeners(){let{hls:e}=this;e.off(L.MANIFEST_LOADING,this.onManifestLoading,this),e.off(L.LEVEL_LOADING,this.onLevelLoading,this),e.off(L.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.off(L.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),e.off(L.LEVELS_UPDATED,this.onLevelsUpdated,this)}createInternalLoader(e){let t=this.hls.config,n=t.pLoader,r=t.loader,i=new(n||r)(t);return this.loaders[e.type]=i,i}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:n}=t;this.variableList=null,this.load({id:null,level:0,responseType:`text`,type:R.MANIFEST,url:n,deliveryDirectives:null,levelOrTrack:null})}onLevelLoading(e,t){let{id:n,level:r,pathwayId:i,url:a,deliveryDirectives:o,levelInfo:s}=t;this.load({id:n,level:r,pathwayId:i,responseType:`text`,type:R.LEVEL,url:a,deliveryDirectives:o,levelOrTrack:s})}onAudioTrackLoading(e,t){let{id:n,groupId:r,url:i,deliveryDirectives:a,track:o}=t;this.load({id:n,groupId:r,level:null,responseType:`text`,type:R.AUDIO_TRACK,url:i,deliveryDirectives:a,levelOrTrack:o})}onSubtitleTrackLoading(e,t){let{id:n,groupId:r,url:i,deliveryDirectives:a,track:o}=t;this.load({id:n,groupId:r,level:null,responseType:`text`,type:R.SUBTITLE_TRACK,url:i,deliveryDirectives:a,levelOrTrack:o})}onLevelsUpdated(e,t){let n=this.loaders[R.LEVEL];if(n){let e=n.context;e&&!t.levels.some(t=>t===e.levelOrTrack)&&(n.abort(),delete this.loaders[R.LEVEL])}}load(e){let t=this.hls.config,n=this.getInternalLoader(e);if(n){let t=this.hls.logger,r=n.context;if(r?.levelOrTrack===e.levelOrTrack&&(r.url===e.url||r.deliveryDirectives&&!e.deliveryDirectives)){r.url===e.url?t.log(`[playlist-loader]: ignore ${e.url} ongoing request`):t.log(`[playlist-loader]: ignore ${e.url} in favor of ${r.url}`);return}t.log(`[playlist-loader]: aborting previous loader for type: ${e.type}`),n.abort()}let r;if(r=e.type===R.MANIFEST?t.manifestLoadPolicy.default:V({},t.playlistLoadPolicy.default,{timeoutRetry:null,errorRetry:null}),n=this.createInternalLoader(e),P(e.deliveryDirectives?.part)){let t;if(e.type===R.LEVEL&&e.level!==null?t=this.hls.levels[e.level].details:e.type===R.AUDIO_TRACK&&e.id!==null?t=this.hls.audioTracks[e.id].details:e.type===R.SUBTITLE_TRACK&&e.id!==null&&(t=this.hls.subtitleTracks[e.id].details),t){let e=t.partTarget,n=t.targetduration;if(e&&n){let t=Math.max(e*3,n*.8)*1e3;r=V({},r,{maxTimeToFirstByteMs:Math.min(t,r.maxTimeToFirstByteMs),maxLoadTimeMs:Math.min(t,r.maxTimeToFirstByteMs)})}}}let i=r.errorRetry||r.timeoutRetry||{},a={loadPolicy:r,timeout:r.maxLoadTimeMs,maxRetry:i.maxNumRetry||0,retryDelay:i.retryDelayMs||0,maxRetryDelay:i.maxRetryDelayMs||0};n.load(e,a,{onSuccess:(e,t,n,r)=>{let i=this.getInternalLoader(n);this.resetInternalLoader(n.type);let a=e.data;t.parsing.start=performance.now(),Uo.isMediaPlaylist(a)||n.type!==R.MANIFEST?this.handleTrackOrLevelPlaylist(e,t,n,r||null,i):this.handleMasterPlaylist(e,t,n,r)},onError:(e,t,n,r)=>{this.handleNetworkError(t,n,!1,e,r)},onTimeout:(e,t,n)=>{this.handleNetworkError(t,n,!0,void 0,e)}})}checkAutostartLoad(){if(!this.hls)return;let{config:{autoStartLoad:e,startPosition:t},forceStartLoad:n}=this.hls;(e||n)&&(this.hls.logger.log(`${e?`auto`:`force`} startLoad with configured startPosition ${t}`),this.hls.startLoad(t))}handleMasterPlaylist(e,t,n,r){let i=this.hls,a=e.data,o=Fm(e,n),s=Uo.parseMasterPlaylist(a,o);if(s.playlistParsingError){t.parsing.end=performance.now(),this.handleManifestParsingError(e,n,s.playlistParsingError,r,t);return}let{contentSteering:c,levels:l,iframeVariants:u,sessionData:d,sessionKeys:f,startTimeOffset:p,variableList:m}=s;this.variableList=m,l.forEach(e=>{let{unknownCodecs:t}=e;if(t){let{preferManagedMediaSource:n}=this.hls.config,{audioCodec:r,videoCodec:i}=e;for(let a=t.length;a--;){let o=t[a];Zr(o,`audio`,n)?(e.audioCodec=r=r?`${r},${o}`:o,Yr.audio[r.substring(0,4)]=2,t.splice(a,1)):Zr(o,`video`,n)&&(e.videoCodec=i=i?`${i},${o}`:o,Yr.video[i.substring(0,4)]=2,t.splice(a,1))}}});let{AUDIO:h=[],SUBTITLES:g,"CLOSED-CAPTIONS":_}=Uo.parseMasterPlaylistMedia(a,o,s);h.length&&!h.some(e=>!e.url)&&l[0].audioCodec&&!l[0].attrs.AUDIO&&(this.hls.logger.log(`[playlist-loader]: audio codec signaled in quality level, but no embedded audio track signaled, create one`),h.unshift({type:`main`,name:`main`,groupId:`main`,default:!1,autoselect:!1,forced:!1,id:-1,attrs:new so({}),bitrate:0,url:``})),i.trigger(L.MANIFEST_LOADED,{levels:l,audioTracks:h,subtitles:g,iframeVariants:u,captions:_,contentSteering:c,url:o,stats:t,networkDetails:r,sessionData:d,sessionKeys:f,startTimeOffset:p,variableList:m})}handleTrackOrLevelPlaylist(e,t,n,r,i){let a=this.hls,{id:o,level:s,type:c}=n,l=Fm(e,n),u=P(s)?s:P(o)?o:0,d=Pm(n),f=Uo.parseLevelPlaylist(e.data,l,u,d,0,this.variableList);if(c===R.MANIFEST){let e={attrs:new so({}),bitrate:0,details:f,name:``,url:l};f.requestScheduled=t.loading.start+ps(f,0),a.trigger(L.MANIFEST_LOADED,{levels:[e],audioTracks:[],iframeVariants:[],url:l,stats:t,networkDetails:r,sessionData:null,sessionKeys:null,contentSteering:null,startTimeOffset:null,variableList:null})}t.parsing.end=performance.now(),n.levelDetails=f,this.handlePlaylistLoaded(f,e,t,n,r,i)}handleManifestParsingError(e,t,n,r,i){this.hls.trigger(L.ERROR,{type:F.NETWORK_ERROR,details:I.MANIFEST_PARSING_ERROR,fatal:t.type===R.MANIFEST,url:e.url,err:n,error:n,reason:n.message,response:e,context:t,networkDetails:r,stats:i})}handleNetworkError(e,t,n=!1,r,i){let a=`A network ${n?`timeout`:`error`+(r?` (status `+r.code+`)`:``)} occurred while loading ${e.type}`;e.type===R.LEVEL?a+=`: ${e.level} id: ${e.id}`:(e.type===R.AUDIO_TRACK||e.type===R.SUBTITLE_TRACK)&&(a+=` id: ${e.id} group-id: "${e.groupId}"`);let o=Error(a);this.hls.logger.warn(`[playlist-loader]: ${a}`);let s=I.UNKNOWN,c=!1,l=this.getInternalLoader(e);switch(e.type){case R.MANIFEST:s=n?I.MANIFEST_LOAD_TIMEOUT:I.MANIFEST_LOAD_ERROR,c=!0;break;case R.LEVEL:s=n?I.LEVEL_LOAD_TIMEOUT:I.LEVEL_LOAD_ERROR,c=!1;break;case R.AUDIO_TRACK:s=n?I.AUDIO_TRACK_LOAD_TIMEOUT:I.AUDIO_TRACK_LOAD_ERROR,c=!1;break;case R.SUBTITLE_TRACK:s=n?I.SUBTITLE_TRACK_LOAD_TIMEOUT:I.SUBTITLE_LOAD_ERROR,c=!1}l&&this.resetInternalLoader(e.type);let u={type:F.NETWORK_ERROR,details:s,fatal:c,url:e.url,loader:l,context:e,error:o,networkDetails:t,stats:i};if(r){let n=e.url;t&&`url`in t&&(n=t.url),u.response=H({url:n,data:void 0},r)}this.hls.trigger(L.ERROR,u)}handlePlaylistLoaded(e,t,n,r,i,a){let o=this.hls,{type:s,level:c,levelOrTrack:l,id:u,groupId:d,deliveryDirectives:f}=r,p=Fm(t,r),m=Pm(r),h=typeof r.level==`number`&&m===z.MAIN?c:void 0;l&&`iframes`in l&&l.iframes&&!e.iframesOnly&&(e.playlistParsingError=Error(`EXT-X-I-FRAME-STREAM-INF media playlist MUST contain an EXT-X-I-FRAMES-ONLY tag`),e.iframesOnly=!0);let g=e.playlistParsingError;if(g){if(this.hls.logger.warn(`${g} ${e.url}`),!o.config.ignorePlaylistParsingErrors){o.trigger(L.ERROR,{type:F.NETWORK_ERROR,details:I.LEVEL_PARSING_ERROR,fatal:!1,url:p,error:g,reason:g.message,response:t,context:r,level:h,parent:m,networkDetails:i,stats:n});return}e.playlistParsingError=null}if(!e.fragments.length){let a=e.playlistParsingError=Error(`No Segments found in Playlist`);o.trigger(L.ERROR,{type:F.NETWORK_ERROR,details:I.LEVEL_EMPTY_ERROR,fatal:!1,url:p,error:a,reason:a.message,response:t,context:r,level:h,parent:m,networkDetails:i,stats:n});return}switch(e.live&&a&&(a.getCacheAge&&(e.ageHeader=a.getCacheAge()||0),(!a.getCacheAge||isNaN(e.ageHeader))&&(e.ageHeader=0)),s){case R.MANIFEST:case R.LEVEL:if(h){if(!l)h=0;else if(l!==o.levels[h]){let e=o.levels.indexOf(l);e>-1&&(h=e)}}o.trigger(L.LEVEL_LOADED,{details:e,levelInfo:l||o.levels[0],level:h||0,id:u||0,stats:n,networkDetails:i,deliveryDirectives:f,withoutMultiVariant:s===R.MANIFEST,context:r});break;case R.AUDIO_TRACK:o.trigger(L.AUDIO_TRACK_LOADED,{details:e,track:l,id:u||0,groupId:d||``,stats:n,networkDetails:i,deliveryDirectives:f,context:r});break;case R.SUBTITLE_TRACK:o.trigger(L.SUBTITLE_TRACK_LOADED,{details:e,track:l,id:u||0,groupId:d||``,stats:n,networkDetails:i,deliveryDirectives:f,context:r})}}},$=class e{static get version(){return Is}static isMSESupported(){return Qf()}static isSupported(){return $f()}static getMediaSource(){return an()}static get Events(){return L}static get MetadataSchema(){return ec}static get ErrorTypes(){return F}static get ErrorDetails(){return I}static get DefaultConfig(){return e.defaultConfig?e.defaultConfig:Sm}static set DefaultConfig(t){e.defaultConfig=t}constructor(t={}){this.config=void 0,this.userConfig=void 0,this.logger=void 0,this._url=null,this.streamController=void 0,this.coreComponents=void 0,this.networkControllers=void 0,this._emitter=new Fs,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 n=this.logger=rn(t.debug||!1,`Hls instance`,t.loggerId||t.assetPlayerId),r=this.config=wm(e.DefaultConfig,t,n);this.userConfig=t,r.progressive&&Em(r,n);let{streamController:i,abrController:a,bufferController:o,capLevelController:s,errorController:c,fpsController:l,id3TrackController:u,iframeController:d,gapController:f}=r,p=new c(this),m=this.abrController=new a(this),h=new Ma(this),g=r.interstitialsController,_=g?this.interstitialsController=new g(this,e):null,v=o?this.bufferController=new o(this,h):null,y=s?this.capLevelController=new s(this):null,b=l?new l(this):null,x=r.cmcdController,S=x?this.cmcdController=new x(this):null,C=new Im(this),w=r.contentSteeringController,T=w?new w(this):null,E=this.levelController=new Dm(this,T),D=u?new u(this):void 0,O=new Mm(this.config,this.logger),k=this.streamController=new i(this,h,O),A=this.gapController=f?new f(this,h):void 0;y&&y.setStreamController(k);let j=[C,E,k];_&&j.splice(1,0,_),T&&j.splice(1,0,T),this.networkControllers=j;let M=[m];v&&M.push(v),A&&M.push(A),y&&M.push(y),b&&(b.setStreamController(k),M.push(b)),D&&M.push(D),M.push(h),this.audioTrackController=this.createController(r.audioTrackController,j);let N=r.audioStreamController;N&&j.push(this.audioStreamController=new N(this,h,O)),this.subtitleTrackController=this.createController(r.subtitleTrackController,j);let ee=r.subtitleStreamController;ee&&j.push(this.subtititleStreamController=new ee(this,h,O)),this.createController(r.timelineController,M),O.emeController=this.emeController=this.createController(r.emeController,M),S&&M.push(S),this.latencyController=this.createController(r.latencyController,M),this.coreComponents=M,this.iframeController=d?new d(this,e):void 0,j.push(p);let te=p.onErrorOut;typeof te==`function`&&this.on(L.ERROR,te,p),this.on(L.MANIFEST_LOADED,C.onManifestLoaded,C)}createController(e,t){if(e){let n=new e(this);return t&&t.push(n),n}return null}on(e,t,n=this){this._emitter.on(e,t,n)}once(e,t,n=this){this._emitter.once(e,t,n)}removeAllListeners(e){this._emitter.removeAllListeners(e)}off(e,t,n=this,r){this._emitter.off(e,t,n,r)}listeners(e){return this._emitter.listeners(e)}emit(e,t,n){return this._emitter.emit(e,t,n)}trigger(e,t){if(this.config.debug)return this.emit(e,e,t);try{return this.emit(e,e,t)}catch(t){if(this.logger.error(`An internal error happened while handling event `+e+`. Error message: "`+t.message+`". Here is a stacktrace:`,t),!this.triggeringException){this.triggeringException=!0;let n=e===L.ERROR;this.trigger(L.ERROR,{type:F.OTHER_ERROR,details:I.INTERNAL_EXCEPTION,fatal:n,event:e,error:t}),this.triggeringException=!1}}return!1}listenerCount(e){return this._emitter.listenerCount(e)}destroy(){this.logger.log(`destroy`),this.trigger(L.DESTROYING,void 0),this.detachMedia(),this.removeAllListeners(),this._autoLevelCapping=-1,this._url=null,this.networkControllers.forEach(e=>e.destroy()),this.networkControllers.length=0,this.coreComponents.forEach(e=>e.destroy()),this.coreComponents.length=0,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 t=Error(`attachMedia failed: invalid argument (${e})`);this.trigger(L.ERROR,{type:F.OTHER_ERROR,details:I.ATTACH_MEDIA_ERROR,fatal:!0,error:t});return}this.logger.log(`attachMedia`),this._media&&(this.logger.warn(`media must be detached before attaching`),this.detachMedia());let t=`media`in e,n=t?e.media:e,r=t?e:{media:n};this._media=n,this.trigger(L.MEDIA_ATTACHING,r)}detachMedia(){this.logger.log(`detachMedia`);let e={};this.trigger(L.MEDIA_DETACHING,e),this._media=null,this.trigger(L.MEDIA_DETACHED,e)}transferMedia(){this._media=null;let e=this.bufferController?.transferMedia()||null,t={transferMedia:e};return this.trigger(L.MEDIA_DETACHING,t),this.trigger(L.MEDIA_DETACHED,t),e}loadSource(e){var t;this.stopLoad();let n=this.media,r=this._url,i=this._url=St.buildAbsoluteURL(self.location.href,e,{alwaysNormalize:!0});this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.logger.log(`loadSource:${i}`),n&&r&&(r!==i||(t=this.bufferController)!=null&&t.hasSourceTypes())&&(this.detachMedia(),this.attachMedia(n)),this.trigger(L.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 n=0;n<this.networkControllers.length&&(this.networkControllers[n].startLoad(e,t),this.started&&this.networkControllers);n++);}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!==Q.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={[z.MAIN]:this.streamController.inFlightFrag};return this.audioStreamController&&(e[z.AUDIO]=this.audioStreamController.inFlightFrag),this.subtititleStreamController&&(e[z.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,n=e?.currentTime;this.detachMedia(),e&&(this.attachMedia(e),t&&(n?this.startLoad(n):this.config.autoStartLoad||this.startLoad()))}removeLevel(e){this.levelController.removeLevel(e)}get sessionId(){let e=this._sessionId;return e||=this._sessionId=vn(),e}get levels(){return this.levelController.levels||[]}get latestLevelDetails(){return this.streamController.getLevelDetails()||null}get loadLevelObj(){return this.levelController.loadLevelObj}get currentLevel(){return this.streamController.currentLevel}set currentLevel(e){this.logger.log(`set currentLevel:${e}`),this.levelController.manualLevel=e,this.streamController.immediateLevelSwitch()}get nextLevel(){return this.streamController.nextLevel}set nextLevel(e){this.logger.log(`set nextLevel:${e}`),this.levelController.manualLevel=e,this.streamController.nextLevelSwitch()}get loadLevel(){return this.levelController.level}set loadLevel(e){this.logger.log(`set loadLevel:${e}`),this.levelController.manualLevel=e}get nextLoadLevel(){return this.levelController.nextLoadLevel}set nextLoadLevel(e){this.levelController.nextLoadLevel=e}get firstLevel(){return Math.max(this.levelController.firstLevel,this.minAutoLevel)}set firstLevel(e){this.logger.log(`set firstLevel:${e}`),this.levelController.firstLevel=e}get startLevel(){let e=this.levelController.startLevel;return 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,n=!!e;t&&n!==this.config.capLevelToPlayerSize&&(n?t.startCapping():(t.stopCapping(),this.autoLevelCapping=-1,this.streamController.nextLevelSwitch()),this.config.capLevelToPlayerSize=n)}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){Ei(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 n=e.length;for(let r=0;r<n;r++)if(e[r].maxBitrate>=t)return r;return 0}get maxAutoLevel(){let{levels:e,autoLevelCapping:t,maxHdcpLevel:n}=this,r;if(r=t===-1&&e!=null&&e.length?e.length-1:t,n)for(let t=r;t--;){let r=e[t].attrs[`HDCP-LEVEL`];if(r&&r<=n)return t}return r}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(){return this.audioStreamController?.getFwdBufferInfo()||null}get maxBufferLength(){return this.streamController.maxBufferLength}setAudioOption(e){return this.audioTrackController?.setAudioOption(e)||null}setSubtitleOption(e){return this.subtitleTrackController?.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(){return this.audioStreamController?.nextAudioTrack??-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(){return this.latencyController?.liveSyncPosition??null}get latency(){return this.latencyController?.latency||0}get maxLatency(){return this.latencyController?.maxLatency||0}get targetLatency(){return this.latencyController?.targetLatency||null}set targetLatency(e){this.latencyController&&(this.latencyController.targetLatency=e)}get drift(){return this.latencyController?.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(){return this.levelController.iframeVariants||[]}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){return vi(e,zi(t),navigator.mediaCapabilities)}};$.defaultConfig=void 0;var Lm={droppedFrames:0};function Rm(e){try{return new URL(e).host}catch{return``}}var zm=/\.(m3u8|ts|m4s|mp4|cmfv|cmfa)(\?|$)/i;function Bm(e){if(typeof performance>`u`||typeof performance.getEntriesByType!=`function`)return``;let t=``,n=-1,r=performance.getEntriesByType(`resource`);for(let i of r)if(!(i.startTime<e)&&(i.initiatorType===`video`||i.initiatorType===`audio`||zm.test(i.name))&&i.startTime>=n){let e=Rm(i.name);e&&(t=e,n=i.startTime)}return t}function Vm(e){let t=e.getVideoPlaybackQuality?.();return{dropped:t?.droppedVideoFrames??0,totalFrames:t?.totalVideoFrames??0}}var Hm=class{constructor(e){i(this,`video`,void 0),i(this,`baseFrames`,0),i(this,`baseDropped`,0),i(this,`lastFrames`,0),i(this,`lastDropped`,0),this.video=e}read(){let e=Vm(this.video);return e.totalFrames<this.lastFrames&&(this.baseFrames+=this.lastFrames),e.dropped<this.lastDropped&&(this.baseDropped+=this.lastDropped),this.lastFrames=e.totalFrames,this.lastDropped=e.dropped,{dropped:this.baseDropped+e.dropped,totalFrames:this.baseFrames+e.totalFrames}}attach(){let e=()=>void this.read();return this.video.addEventListener(`timeupdate`,e),this.video.addEventListener(`seeking`,e),()=>{this.video.removeEventListener(`timeupdate`,e),this.video.removeEventListener(`seeking`,e)}}};function Um(e,t){let n=[[`playing`,()=>t(`playing`)],[`waiting`,()=>t(`buffering`)],[`stalled`,()=>t(`buffering`)],[`pause`,()=>{e.ended||t(`paused`)}],[`ended`,()=>t(`ended`)]];for(let[t,r]of n)e.addEventListener(t,r);return()=>{for(let[t,r]of n)e.removeEventListener(t,r)}}var Wm=2e3,Gm=3,Km=500,qm=6e3,Jm=.25,Ym=250,Xm=.05,Zm=4,Qm=12e3,$m=.25,eh=1e3;function th(e){try{let t=new TextDecoder(`utf-8`).decode(new Uint8Array(e));return/^skd:\/\/[0-9a-fA-F-]{36}:([0-9a-fA-F]{32})$/.exec(t)?.[1]}catch{return}}function nh(e){return!!(e??(typeof document<`u`?document.createElement(`video`):void 0))?.canPlayType(`application/vnd.apple.mpegurl`)}function rh(){if(typeof window>`u`)return!1;let e=`WebKitMediaKeys`in window||typeof HTMLMediaElement<`u`&&`webkitSetMediaKeys`in HTMLMediaElement.prototype,t=typeof navigator<`u`&&/Apple/i.test(navigator.vendor??``);return e||t}function ih(){if(typeof navigator>`u`||!rh())return!1;let e=navigator.userAgent??``;return/iPhone|iPad|iPod/.test(e)?!0:/Macintosh/.test(e)&&typeof navigator.maxTouchPoints==`number`&&navigator.maxTouchPoints>1}var ah=class{constructor(e){i(this,`name`,`native`),i(this,`deps`,void 0),i(this,`onLoaded`,void 0),i(this,`onError`,void 0),i(this,`onEncrypted`,void 0),i(this,`fairplayLicenseUrl`,void 0),i(this,`keySession`,null),i(this,`fairplayArmed`,!1),i(this,`onVisibility`,null),i(this,`onPageShow`,null),i(this,`hiddenSince`,null),i(this,`refocusTimer`,null),i(this,`edgeTimer`,null),i(this,`onEdgeReset`,null),i(this,`lastBufferedEnd`,null),i(this,`bufferedAdvancedAt`,null),i(this,`lastSeekableEnd`,null),i(this,`edgeStampedAt`,null),i(this,`lastTickAt`,null),i(this,`endedEmitted`,!1),i(this,`fairplayKeyIV`,void 0),i(this,`loadStarted`,void 0),i(this,`preloadTouched`,!1),i(this,`savedPreload`,null),i(this,`cdnHost`,``),i(this,`builtAt`,void 0),i(this,`frameCounter`,void 0),i(this,`detachFrames`,null),this.deps=e,this.frameCounter=new Hm(e.video),this.loadStarted=e.deferLoad!==!0,this.builtAt=typeof performance<`u`?performance.now():0}async load(){this.detachFrames??=this.frameCounter.attach();let{video:e,descriptor:t,emit:n}=this.deps;if(this.endedEmitted=!1,this.watchRefocus(),this.watchBufferedEnd(),this.loadStarted||(this.preloadTouched=!0,this.savedPreload=e.getAttribute(`preload`),e.preload=`none`),t.drmEnabled){if(!t.drm?.fairplay){n({type:`error`,error:new a(`DRM_CLIENT`,0,`native HLS engine cannot satisfy this DRM (Widevine requires the hls.js engine); use engine "auto"/"hls" on a Widevine-capable browser`),fatal:!0});return}this.armFairPlay()}let r=!this.loadStarted;this.onLoaded=r?void 0:()=>n({type:`ready`}),this.onError=()=>n({type:`error`,error:new a(`INTERNAL`,0,`native HLS playback error`),fatal:!0}),this.onLoaded&&e.addEventListener(`loadedmetadata`,this.onLoaded,{once:!0}),e.addEventListener(`error`,this.onError),e.src=ch(t.manifestUrl,t.analytics?.sid),e.load()}startLoad(){this.loadStarted||(this.loadStarted=!0,this.restorePreload())}restorePreload(){if(!this.preloadTouched)return;this.preloadTouched=!1;let{video:e}=this.deps;this.savedPreload===null?e.removeAttribute(`preload`):e.setAttribute(`preload`,this.savedPreload)}armFairPlay(){let{video:e,descriptor:t,credential:n,deviceId:r,userId:i,emit:o}=this.deps,l=t.drm?.fairplay;if(!l)return;this.fairplayLicenseUrl=l.licenseUrl;let u=(e,t,n,r)=>o({type:`error`,error:new a(c(t,r),t,e,r?{serverCode:r}:void 0),fatal:n}),d=async e=>{try{return await e.text()}catch{return``}};this.onEncrypted=a=>{let o=a;o.initData&&!this.fairplayArmed&&(this.fairplayArmed=!0,this.fairplayKeyIV=th(o.initData),(async()=>{try{let a=await(await navigator.requestMediaKeySystemAccess(`com.apple.fps`,[{initDataTypes:[o.initDataType],videoCapabilities:[{contentType:`application/vnd.apple.mpegurl`,robustness:``}],distinctiveIdentifier:`not-allowed`,persistentState:`not-allowed`,sessionTypes:[`temporary`]}])).createMediaKeys(),c=await fetch(l.certificateUrl,{headers:{"x-api-key":n.apiKey}});if(!c.ok){this.fairplayArmed=!1,u(`FairPlay certificate request failed: ${c.status}`,c.status,!0);return}await a.setServerCertificate(await c.arrayBuffer()),await e.setMediaKeys(a);let f=a.createSession();this.keySession=f,f.addEventListener(`message`,e=>{(async()=>{try{let a=await fetch(this.fairplayLicenseUrl??l.licenseUrl,{method:`POST`,body:e.message,headers:{"x-api-key":n.apiKey,"X-Match-Urn":t.matchUrn,"X-Device-Id":r,...i?{"X-User-Id":i}:{},...this.fairplayKeyIV?{"X-Key-Iv":this.fairplayKeyIV}:{}}});if(!a.ok){let e=a.status===403?s(await d(a)):void 0;u(`FairPlay license request failed: ${a.status}`,a.status,!0,e);return}await f.update(new Uint8Array(await a.arrayBuffer()))}catch(e){u(`FairPlay license request failed: ${String(e)}`,0,!0)}})()}),await f.generateRequest(o.initDataType,o.initData)}catch(e){this.fairplayArmed=!1,u(`FairPlay key session failed: ${String(e)}`,0,!0)}})())},e.addEventListener(`encrypted`,this.onEncrypted)}setLicenseUrls(e){e.fairplay&&(this.fairplayLicenseUrl=e.fairplay)}getQualityLevels(){return[]}getCurrentQuality(){return-1}setQuality(e){}setMaxBitrate(e){}getAudioTracks(){let e=this.deps.video.audioTracks;return e?Array.from({length:e.length},(t,n)=>{let r=e[n];return{id:n,name:r.label||r.language||`Audio ${n+1}`,lang:r.language||void 0,default:r.enabled}}):[]}setAudioTrack(e){let t=this.deps.video.audioTracks;if(t)for(let n=0;n<t.length;n+=1)t[n].enabled=n===e}getTextTracks(){let e=this.deps.video.textTracks;return Array.from({length:e.length},(t,n)=>{let r=e[n];return{id:n,name:r.label||r.language||`Text ${n+1}`,lang:r.language||void 0}})}setTextTrack(e){let t=this.deps.video.textTracks;for(let n=0;n<t.length;n+=1)t[n].mode=n===e?`showing`:`disabled`}seekToLive(){let e=this.deps.video,t=this.liveEnd();t==null||t<=e.currentTime||(e.currentTime=t)}getStats(){let e=this.deps.video,t=this.frameCounter.read(),n={droppedFrames:t.dropped,decodedFrames:t.totalFrames};if(this.cdnHost||=Bm(this.builtAt),this.cdnHost&&(n.cdnHost=this.cdnHost),this.deps.descriptor.drmEnabled&&(n.keySystem=`fairplay`),e.duration===1/0){n.isLive=!0;let t=this.liveEdgeEstimate(),r=t==null?NaN:t-e.currentTime;Number.isFinite(r)&&(n.atLiveEdge=r<=Zm,!e.paused&&r>=0&&(n.latencySeconds=r))}else Number.isFinite(e.duration)&&e.duration>0&&(n.isLive=!1);return n}stop(){this.unwatchBufferedEnd();try{this.deps.video.pause()}catch{}}watchRefocus(){this.deps.snapToLiveOnRefocus===!1||typeof document>`u`||this.onVisibility||(this.onVisibility=()=>{let e=oh();if(document.visibilityState===`hidden`){this.hiddenSince=e,this.cancelRefocus();return}let t=this.hiddenSince;this.hiddenSince=null,t!=null&&e-t>=Wm&&this.armRefocus()},this.onPageShow=e=>{e.persisted&&this.armRefocus()},document.addEventListener(`visibilitychange`,this.onVisibility),typeof window<`u`&&window.addEventListener(`pageshow`,this.onPageShow))}armRefocus(){if(this.cancelRefocus(),Number.isFinite(this.deps.video.duration))return;let e=this.liveEnd(),t=oh,n=t(),r=0,i=()=>{if(this.refocusTimer=null,Number.isFinite(this.deps.video.duration))return;r+=Km;let a=this.liveEnd(),o=a!=null&&(e==null||a>=e+Jm),s=Math.max(r,t()-n)>=qm;if(o||s&&a!=null){this.snapToLive();return}this.refocusTimer=setTimeout(i,Km)};this.refocusTimer=setTimeout(i,Km)}cancelRefocus(){this.refocusTimer!=null&&clearTimeout(this.refocusTimer),this.refocusTimer=null}watchBufferedEnd(){if(this.edgeTimer!=null)return;let{video:e}=this.deps;this.onEdgeReset=e=>{this.lastBufferedEnd=null,this.bufferedAdvancedAt=null,e.type===`emptied`&&this.resetEndStale()},e.addEventListener(`seeking`,this.onEdgeReset),e.addEventListener(`emptied`,this.onEdgeReset),this.edgeTimer=setInterval(()=>{if(e.duration!==1/0)return;this.checkEndStale();let t=sh(e,e.currentTime);t!=null&&((this.lastBufferedEnd==null||Math.abs(t-this.lastBufferedEnd)>=Xm)&&(this.bufferedAdvancedAt=oh()),this.lastBufferedEnd=t)},Ym)}checkEndStale(){if(this.endedEmitted)return;let e=oh(),t=this.lastTickAt==null?0:e-this.lastTickAt;this.lastTickAt=e;let n=this.liveEnd();if(n==null)return;let r=this.lastSeekableEnd==null||Math.abs(n-this.lastSeekableEnd)>=$m;this.lastSeekableEnd=n;let i=this.deps.video,a=typeof document<`u`&&document.visibilityState===`hidden`;if(r||t>eh||a||i.paused){this.edgeStampedAt=e;return}e-(this.edgeStampedAt??e)>Qm&&(this.endedEmitted=!0,this.deps.emit({type:`ended`,reason:`stalled`}))}resetEndStale(){this.lastSeekableEnd=null,this.edgeStampedAt=null,this.lastTickAt=null}unwatchBufferedEnd(){this.edgeTimer!=null&&clearInterval(this.edgeTimer),this.edgeTimer=null,this.onEdgeReset&&=(this.deps.video.removeEventListener(`seeking`,this.onEdgeReset),this.deps.video.removeEventListener(`emptied`,this.onEdgeReset),null),this.resetEndStale(),this.lastBufferedEnd=null,this.bufferedAdvancedAt=null}liveEdgeEstimate(){let e=this.deps.video;if(e.duration!==1/0)return null;let t=this.liveEnd(),n=sh(e,e.currentTime)??this.lastBufferedEnd;if(n!=null){let e=this.bufferedAdvancedAt,r=n+(e==null?0:Math.max(0,(oh()-e)/1e3));(t==null||r>t)&&(t=r)}return t!=null&&Number.isFinite(t)?t:null}liveEnd(){let e=this.deps.video;if(e.duration!==1/0||e.seekable.length===0)return null;let t=e.seekable.end(e.seekable.length-1);return Number.isFinite(t)?t:null}snapToLive(){let e=this.deps.video,t=this.liveEnd();if(t==null)return;let n=e.seekable.start(e.seekable.length-1),r=Math.min(e.currentTime,t),i=Math.max(n,t-Gm,r);try{e.currentTime=i}catch{}}destroy(){this.detachFrames?.(),this.detachFrames=null,this.cancelRefocus(),this.unwatchBufferedEnd(),this.onVisibility&&typeof document<`u`&&(document.removeEventListener(`visibilitychange`,this.onVisibility),this.onVisibility=null),this.onPageShow&&typeof window<`u`&&(window.removeEventListener(`pageshow`,this.onPageShow),this.onPageShow=null);let{video:e}=this.deps;this.onLoaded&&e.removeEventListener(`loadedmetadata`,this.onLoaded),this.onError&&e.removeEventListener(`error`,this.onError),this.onEncrypted&&e.removeEventListener(`encrypted`,this.onEncrypted),this.keySession?.close().catch(()=>{}),this.keySession=null,this.fairplayArmed=!1,this.fairplayKeyIV=void 0;try{e.pause()}catch{}e.removeAttribute(`src`),this.restorePreload();try{e.load()}catch{}}};function oh(){return typeof performance<`u`?performance.now():Date.now()}function sh(e,t){let n=e.buffered;if(!n||!Number.isFinite(t))return null;for(let e=0;e<n.length;e+=1)if(n.start(e)<=t+.1&&n.end(e)>t){let t=n.end(e);return Number.isFinite(t)?t:null}return null}function ch(e,t){return t?`${e}${e.includes(`?`)?`&`:`?`}CMCD=${encodeURIComponent(`sid="${t}"`)}`:e}function lh(e,t=Date.now()){if(!e)return!1;let n;try{n=new URL(e).searchParams.get(`exp`)}catch{return!1}return!n||!/^\d+$/.test(n)?!1:Number(n)*1e3<=t}var uh=4096;function dh(e){if(!e||typeof e!=`object`)return;let{response:t}=e;if(typeof t==`string`)return t;let n;if(Object.prototype.toString.call(t)===`[object ArrayBuffer]`?n=new Uint8Array(t):ArrayBuffer.isView(t)&&(n=new Uint8Array(t.buffer,t.byteOffset,t.byteLength)),!(!n||n.byteLength===0||n.byteLength>uh))try{return new TextDecoder().decode(n)}catch{return}}var fh=15e3,ph=5e3,mh=6,hh=4e3,gh=2;function _h(e){try{let t=new URL(e);return t.searchParams.delete(`CMCD`),t.toString()}catch{return e}}var vh=class{constructor(e={}){i(this,`cmcd`,void 0),i(this,`entries`,new Map),i(this,`keyed`,new Set),i(this,`perTrack`,new Map),i(this,`hints`,new Map),i(this,`stats`,{started:0,served:0,missed:0,failed:0,expired:0,hintStarted:0,hintServed:0,hintFailed:0,hintExpired:0,hintDropped:0}),this.cmcd=e}keyUsable(e){this.keyed.add(e)}isActive(e){return!this.keyed.has(e)}prefetch(e,t,n){if(!this.isActive(t))return;let r=_h(e);if(this.entries.has(r))return;let i=this.perTrack.get(t)??0;i>=mh||(this.perTrack.set(t,i+1),this.start(r,this.withCmcd(e,t,n),!1,fh),this.stats.started+=1)}prefetchHint(e,t){let n=_h(e);if(this.entries.has(n))return;let r=this.hints.get(t)??[];for(;r.length>=gh;){let e=r.shift();e!==void 0&&this.drop(e)&&(this.stats.hintDropped+=1)}r.push(n),this.hints.set(t,r),this.start(n,this.withCmcd(e,t,`media`),!0,hh),this.stats.hintStarted+=1}dropHints(e){for(let t of this.hints.get(e)??[])this.drop(t)&&(this.stats.hintDropped+=1);this.hints.delete(e)}drop(e){let t=this.entries.get(e);return t?(this.entries.delete(e),t.abort.abort(),!0):!1}start(e,t,n,r){let i=new AbortController,a={started:performance.now(),first:0,end:0,hint:n,headers:Promise.resolve(),bytes:Promise.resolve(null),abort:i},o=()=>{};a.headers=new Promise(e=>o=e),a.bytes=fetch(t,{credentials:`omit`,mode:`cors`,signal:i.signal}).then(async e=>{if(a.first=performance.now(),o(),!e.ok)return null;let t=await e.arrayBuffer();return a.end=performance.now(),t}).catch(()=>null).finally(o),this.entries.set(e,a),setTimeout(()=>{this.entries.get(e)===a&&(this.entries.delete(e),i.abort(),n?this.stats.hintExpired+=1:this.stats.expired+=1)},r)}take(e){let t=_h(e),n=this.entries.get(t);return n&&this.entries.delete(t),n}destroy(){for(let e of this.entries.values())e.abort.abort();this.entries.clear(),this.hints.clear()}withCmcd(e,t,n){let{sessionId:r,contentId:i}=this.cmcd;if(!r&&!i)return e;let a=[];i&&a.push(`cid="${i}"`),a.push(`ot=${n===`init`?`i`:t===`audio`?`a`:`v`}`),a.push(`sf=h`),r&&a.push(`sid="${r}"`),a.push(`st=ll`);try{let t=new URL(e);return t.searchParams.set(`CMCD`,a.join(`,`)),t.toString()}catch{return e}}};function yh(e){let t=$.DefaultConfig?.loader;if(typeof t!=`function`)return;class n extends t{constructor(...e){super(...e),i(this,`served`,!1),i(this,`cancelled`,!1),i(this,`entry`,void 0),i(this,`stats`,bh())}load(t,n,r){let i=t.rangeEnd?void 0:e.take(t.url);if(!i){super.load(t,n,r);return}this.served=!0,this.entry=i;let a=performance.now(),o=()=>{i.hint?e.stats.hintFailed+=1:e.stats.failed+=1},s=()=>{!this.cancelled&&this.served&&(i.abort.abort(),o(),this.served=!1,this.entry=void 0,super.load(t,n,r))},c=n?.loadPolicy,l=c?.maxTimeToFirstByteMs||ph,u=setTimeout(s,l);i.headers.then(()=>{clearTimeout(u);let e=c?.maxLoadTimeMs;e&&(u=setTimeout(s,Math.max(0,e-(performance.now()-a))))}),i.bytes.then(s=>{if(clearTimeout(u),this.cancelled||!this.served)return;if(!s){o(),this.served=!1,super.load(t,n,r);return}let c=this.stats;if(i.hint){e.stats.hintServed+=1;let t=performance.now(),n=Math.max(0,(i.end||t)-(i.first||t)),r=Math.max(0,(i.first||t)-a);c.loading.end=t,c.loading.first=t-n,c.loading.start=c.loading.first-r}else e.stats.served+=1,c.loading.start=a,c.loading.first=Math.max(a,i.first||a),c.loading.end=performance.now();c.loaded=c.total=s.byteLength,this.entry=void 0,r.onSuccess({url:t.url,data:s},c,t,null)})}abort(){if(this.served){this.cancelled=!0,this.stats.aborted=!0,this.entry?.abort.abort(),this.entry=void 0;return}super.abort()}}return n}function bh(){return{aborted:!1,loaded:0,retry:0,total:0,chunkCount:0,bwEstimate:0,loading:{start:0,first:0,end:0},parsing:{start:0,end:0},buffering:{start:0,first:0,end:0}}}function xh(e){return e===`audio`?`audio`:`main`}function Sh(e,t){let n=[];t.initSegment?.url&&!t.initSegment.data&&n.push({url:t.initSegment.url,kind:`init`});let r=((t.type===`audio`?e.audioTracks?.[e.audioTrack]?.details:typeof t.level==`number`?e.levels?.[t.level]?.details:void 0)?.partList??[]).filter(e=>e.fragment.sn===t.sn);if(r.length)for(let e of r)e.url&&n.push({url:e.url,kind:`media`});else t.url&&n.push({url:t.url,kind:`media`});return n}function Ch(e){let t=e,n=t?.preloadHint;if(!n||!t?.url||n.TYPE!==`PART`||n[`BYTERANGE-START`]!==void 0||n[`BYTERANGE-LENGTH`]!==void 0)return null;let r=n.URI;if(typeof r!=`string`||!r)return null;try{return new URL(r,t.url).toString()}catch{return null}}function wh(e,t){return e.length===0?0:e[Math.min(e.length,Math.max(1,Math.ceil(t/100*e.length)))-1]??0}function Th(){return $.isSupported()}var Eh=3,Dh=1e6,Oh=20,kh=1e4,Ah=3,jh=5,Mh=3,Nh=1e4,Ph=3e4,Fh=12e3,Ih=3e3,Lh=.02,Rh=6e3,zh=.5,Bh=3,Vh=.5,Hh=1.1,Uh=.25,Wh=5e3,Gh=4e3,Kh=2,qh=5,Jh=2,Yh=2,Xh=4,Zh=4,Qh=2e3,$h=3e4,eg=1,tg=2;function ng(e,t,n){if(n<=0||t<0||t>=e.length)return t;let r=(t,n)=>e[t].width===e[n].width&&e[t].height===e[n].height,i=t=>{for(;t+1<e.length&&r(t+1,t);)t++;return t},a=i(t);for(let t=0;t<n&&a+1<e.length;t++)a=i(a+1);return a}var rg=.2,ig=30,ag=2,og=2,sg=2,cg=9,lg=.5,ug=64,dg=1e4,fg=8,pg=.6,mg=.4,hg=.4,gg=2,_g=6e4,vg=.5,yg=3.5,bg=300;function xg(e){return(e?.part??e?.frag)?.stats}function Sg(){if(typeof navigator>`u`)return 0;try{let e=navigator.connection?.rtt;return typeof e==`number`&&Number.isFinite(e)&&e>0?e:0}catch{return 0}}function Cg(e){if(e.liveSyncDurationCount!=null||e.liveMaxLatencyDurationCount!=null){delete e.liveSyncDuration,delete e.liveMaxLatencyDuration;return}e.liveSyncDuration??=sg;let t=Math.max(12,e.liveSyncDuration+cg);(e.liveMaxLatencyDuration==null||e.liveMaxLatencyDuration<=e.liveSyncDuration)&&(e.liveMaxLatencyDuration=t),wg(e,e.liveSyncDuration)}function wg(e,t){let n=(e,t,n)=>Math.min(n,Math.max(t,e));e.maxStarvationDelay??=n(t/2,.5,4),e.maxLoadingDelay??=n(t,1,4),e.abrEwmaFastLive??=n(t/2,1,3)}var Tg=class{constructor(e){i(this,`name`,`hls`),i(this,`hls`,null),i(this,`deps`,void 0),i(this,`licenseUrl`,void 0),i(this,`detectedLowLatency`,!1),i(this,`bytesLoaded`,0),i(this,`prefetch`,null),i(this,`reportedFirstPlaylist`,!1),i(this,`reportedFirstBytes`,!1),i(this,`reportedDrmReady`,!1),i(this,`playlistBytesLoaded`,0),i(this,`renditionSwitches`,0),i(this,`licenseTimeMs`,0),i(this,`licenseRequested`,!1),i(this,`upshifts`,0),i(this,`downshifts`,0),i(this,`lastLevelIndex`,-1),i(this,`requestCount`,0),i(this,`requestErrors`,0),i(this,`requestTimesMs`,[]),i(this,`cdnHost`,``),i(this,`ladderHeights`,void 0),i(this,`ladderTopBitrateKbps`,0),i(this,`mediaRecoveries`,0),i(this,`networkRecoveries`,0),i(this,`licenseRecoveries`,0),i(this,`recoveryResetTimer`,null),i(this,`networkRetryTimer`,null),i(this,`licenseRetryTimer`,null),i(this,`onVisibility`,null),i(this,`onSeeking`,null),i(this,`onPause`,null),i(this,`onPlay`,null),i(this,`pauseSuspendTimer`,null),i(this,`loadSuspended`,!1),i(this,`stopped`,!1),i(this,`sawLive`,!1),i(this,`lastEndSN`,-1),i(this,`lastAdvanceMs`,0),i(this,`endWatchdog`,null),i(this,`endedEmitted`,!1),i(this,`lastFragLoadingMs`,0),i(this,`starvedTicks`,0),i(this,`starvationKicks`,0),i(this,`kickPending`,!1),i(this,`kickTicks`,0),i(this,`starvationRebuilds`,0),i(this,`kickKind`,null),i(this,`starvedFrames`,0),i(this,`deadTicks`,0),i(this,`mainFragsSinceTick`,0),i(this,`bwFragsLoaded`,0),i(this,`bwSavedAt`,0),i(this,`recentMainFrags`,[]),i(this,`chaseSuspended`,!1),i(this,`savedLiveMaxLatency`,void 0),i(this,`savedMaxSyncRate`,void 0),i(this,`chaseLatency`,-1),i(this,`catchUpRate`,1),i(this,`catchUpEngaged`,!1),i(this,`onTimeUpdate`,null),i(this,`chaseTicks`,0),i(this,`liveRetargets`,0),i(this,`holdBackEnabled`,void 0),i(this,`holdBackSamples`,[]),i(this,`holdBackBase`,-1),i(this,`holdBackStepCount`,0),i(this,`holdBackApplied`,0),i(this,`holdBackSlowTicks`,0),i(this,`holdBackFastSince`,0),i(this,`holdBackSteps`,0),i(this,`holdBackPriorChecked`,!1),i(this,`capObserver`,null),i(this,`capTimer`,null),i(this,`sizeCapLevel`,null),i(this,`bitrateCapLevel`,-1),i(this,`pushedCapLevel`,-1),i(this,`pushedCapReason`,null),i(this,`fpsCapBitrate`,null),i(this,`fpsCapFailedHeight`,null),i(this,`fpsCapManaged`,!0),i(this,`fpsLastFrames`,-1),i(this,`fpsLastDropped`,-1),i(this,`fpsBadTicks`,0),i(this,`fpsGraceTicks`,0),i(this,`fpsDownCaps`,0),i(this,`sizeCapManaged`,!0),i(this,`dprMedia`,null),i(this,`onDprChange`,null),i(this,`loadStarted`,void 0),i(this,`frameCounter`,void 0),i(this,`detachFrames`,null),this.deps=e,this.holdBackEnabled=e.adaptiveHoldBack!==!1,this.frameCounter=new Hm(e.video),this.licenseUrl=e.descriptor.drm?.widevine?.licenseUrl,this.loadStarted=e.deferLoad!==!0}async load(){this.detachFrames??=this.frameCounter.attach();let{descriptor:e,snapToLiveOnRefocus:t,video:n,emit:r}=this.deps,i=nh(n)&&rh(),o=!!e.drm?.widevine?.licenseUrl&&!i;if(e.drmEnabled&&!o){r({type:`error`,error:new a(`DRM_CLIENT`,0,e.drm?.fairplay?.licenseUrl&&i?`FairPlay cannot be played on the hls.js engine (WebKit binds keys via the media sinf box); use engine "auto" or "native"`:`DRM is required but none of the stream’s key systems is usable on this platform (WebKit takes FairPlay only; other browsers take Widevine only)`),fatal:!0});return}e.drmEnabled&&o&&!this.deps.hlsConfig?.requestMediaKeySystemAccessFunc&&(Xe(n),rt()),this.startHls(),t!==!1&&typeof document<`u`&&(this.onVisibility=()=>{let e=this.hls;if(document.visibilityState!==`visible`||!e)return;let t=e.liveSyncPosition;if(typeof t!=`number`)return;let r=typeof e.targetLatency==`number`&&e.targetLatency>0?e.targetLatency:3;t-n.currentTime>Math.max(r*3,8)&&(n.currentTime=t)},document.addEventListener(`visibilitychange`,this.onVisibility)),this.onSeeking=()=>{this.clampOverSeek(),this.loadSuspended&&(this.resumeLoading(),this.schedulePauseSuspend())},n.addEventListener(`seeking`,this.onSeeking),this.onTimeUpdate=()=>this.updateCatchUpBand(),n.addEventListener(`timeupdate`,this.onTimeUpdate),this.onPause=()=>this.schedulePauseSuspend(),this.onPlay=()=>this.resumeLoading(),n.addEventListener(`pause`,this.onPause),n.addEventListener(`play`,this.onPlay),this.sizeCapManaged&&typeof ResizeObserver<`u`&&(this.capObserver=new ResizeObserver(()=>this.onMediaResize()),this.capObserver.observe(n),this.watchDprChanges())}schedulePauseSuspend(){this.pauseSuspendTimer||this.loadSuspended||this.stopped||!this.loadStarted||(this.pauseSuspendTimer=setTimeout(()=>{this.pauseSuspendTimer=null;let{video:e}=this.deps;if(e.paused&&!e.ended&&!this.stopped&&this.hls){try{this.hls.stopLoad()}catch{return}this.loadSuspended=!0}},Wh))}resumeLoading(){if(this.pauseSuspendTimer&&=(clearTimeout(this.pauseSuspendTimer),null),this.resetChaseWindow(),this.resetFrameDropWindow(),this.loadSuspended&&(this.loadSuspended=!1,!this.stopped&&this.hls)){this.lastAdvanceMs=Date.now(),this.lastFragLoadingMs=0,this.resetStarvationWindow(),this.resetChaseWindow(),this.clearKick();try{this.hls.startLoad(-1)}catch{}}}startLoad(){this.loadStarted||(this.loadStarted=!0,this.deps.video.paused&&this.schedulePauseSuspend(),this.hls?.startLoad(-1))}watchDprChanges(){if(typeof matchMedia!=`function`)return;this.unwatchDprChanges();let e=typeof self<`u`&&self.devicePixelRatio||1,t=matchMedia(`(resolution: ${e}dppx)`);if(typeof t.addEventListener!=`function`)return;let n=()=>{this.onMediaResize(),this.watchDprChanges()};t.addEventListener(`change`,n),this.dprMedia=t,this.onDprChange=n}unwatchDprChanges(){this.dprMedia&&this.onDprChange&&this.dprMedia.removeEventListener(`change`,this.onDprChange),this.dprMedia=null,this.onDprChange=null}clampOverSeek(){let e=this.hls;if(!e||this.chaseSuspended||(e.levels[e.currentLevel]??e.levels[e.loadLevel])?.details?.live!==!0)return;let t=e.liveSyncPosition;if(typeof t!=`number`||!Number.isFinite(t))return;let{video:n}=this.deps;n.currentTime<=t+lg||(n.currentTime=t)}reanchorPartTimeline(e,t){let{frag:n,part:r}=t;if(!r||r.index!==0||n.type!==`main`||typeof n.sn!=`number`)return;let i=e.levels[n.level]?.details;if(!i?.live)return;let a=r.elementaryStreams.video??r.elementaryStreams.audiovideo??r.elementaryStreams.audio;if(!a)return;let o=n.sn,s=i.fragments.find(e=>e&&e.sn===o)??(i.fragmentHint?.sn===o?i.fragmentHint:void 0);if(!s)return;let c=a.startPTS-s.start;if(!(!Number.isFinite(c)||Math.abs(c)<Lh)){for(let e of i.fragments)e&&e.setStart(e.start+c);i.fragmentHint?.setStart(i.fragmentHint.start+c),this.deps.debug===!0&&console.info(`havik-player: LL-HLS timeline re-anchored by ${c>=0?`+`:``}${c.toFixed(3)}s at sn ${n.sn} (level ${n.level})`)}}startHls(){let{video:e,descriptor:t,credential:n,deviceId:r,userId:i,lowLatency:a,debug:o,hlsConfig:s,emit:c}=this.deps;this.clearKick(),this.resetStarvationWindow(),this.resetChaseWindow(),this.resetFrameDropWindow(),this.lastFragLoadingMs=0,this.lastEndSN=-1,this.lastAdvanceMs=0;let l=t.drmEnabled&&!!(t.drm?.widevine?.licenseUrl||t.drm?.fairplay?.licenseUrl),u=nh(this.deps.video)&&rh(),d={debug:o===!0,enableWorker:!a,lowLatencyMode:a,backBufferLength:90,liveDurationInfinity:!0,maxBufferHole:.5,maxLiveSyncPlaybackRate:u?1:1.1,abrEwmaDefaultEstimate:this.startEstimate(),capLevelToPlayerSize:!1,...this.loadStarted?{}:{autoStartLoad:!1},...l?{emeEnabled:!0,drmSystems:{...this.licenseUrl?{"com.widevine.alpha":{licenseUrl:this.licenseUrl}}:{}},drmSystemOptions:{videoRobustness:Ye.video,audioRobustness:Ye.audio,videoEncryptionScheme:Ye.scheme,audioEncryptionScheme:Ye.scheme},...We()?{requestMediaKeySystemAccessFunc:Je(e)}:{},licenseXhrSetup:(e,a)=>{let o=performance.now(),s=()=>{e.open(`POST`,this.licenseUrl??a,!0),e.setRequestHeader(`x-api-key`,n.apiKey),e.setRequestHeader(`X-Match-Urn`,t.matchUrn),e.setRequestHeader(`X-Device-Id`,r),i&&e.setRequestHeader(`X-User-Id`,i),this.licenseRequested=!0,e.addEventListener(`loadend`,()=>{this.licenseTimeMs===0&&(this.licenseTimeMs=Math.max(1,Math.round(performance.now()-o)))})},{freshLicenseUrl:c}=this.deps;if(!c||!lh(this.licenseUrl)){s();return}let l=this.hls,u,d=new Promise(e=>{u=setTimeout(()=>e(void 0),Nh)});return Promise.race([c().catch(()=>void 0),d]).finally(()=>clearTimeout(u)).then(e=>{if(!this.hls||this.hls!==l)throw Error(`havik-player: engine torn down during refresh`);e&&(this.licenseUrl=e),s()})}}:{},...t.analytics?.sid?{cmcd:{sessionId:t.analytics.sid,contentId:t.matchUrn,useHeaders:!1}}:{},...s};this.prefetch?.destroy(),this.prefetch=null;let f=!1,p=!1,m=l&&this.deps.mediaDuringKey!==!1,h=this.deps.preloadHints===!0;if((m||h)&&!d.fLoader){let e=new vh({sessionId:t.analytics?.sid,contentId:t.matchUrn}),n=yh(e);n&&(this.prefetch=e,f=m,p=h,d.fLoader=n)}Cg(d),this.catchUpRate=typeof d.maxLiveSyncPlaybackRate==`number`?d.maxLiveSyncPlaybackRate:1,this.catchUpEngaged=!1,this.catchUpRate>1&&(d.maxLiveSyncPlaybackRate=1),this.sizeCapManaged=d.capLevelToPlayerSize!==!0,this.fpsCapManaged=!(s&&`capLevelOnFPSDrop`in s),this.loadStarted=d.autoStartLoad!==!1;let g=new $(d);if(this.hls=g,this.armHoldBack(g,d),g.on($.Events.FRAG_PARSED,(e,t)=>this.reanchorPartTimeline(g,t)),g.on($.Events.MANIFEST_PARSED,()=>{this.mediaRecoveries=0,this.networkRecoveries=0,l&&!this.deps.hlsConfig?.requestMediaKeySystemAccessFunc&&this.dropLevelsWidevineCannotPlay(g),this.measureLadder(g),this.applySizeCap(),this.loadSuspended=!1,e.paused&&this.schedulePauseSuspend(),c({type:`ready`})}),g.on($.Events.FRAG_BUFFERED,(e,t)=>{t?.frag?.type===`main`&&(this.kickKind!==`dead`&&this.clearKick(),(this.mediaRecoveries>0||this.networkRecoveries>0||this.licenseRecoveries>0||this.starvationKicks>0||this.starvationRebuilds>0)&&!this.recoveryResetTimer&&(this.recoveryResetTimer=setTimeout(()=>{this.mediaRecoveries=0,this.networkRecoveries=0,this.licenseRecoveries=0,this.starvationKicks=0,this.starvationRebuilds=0,this.recoveryResetTimer=null},Ph)))}),g.on($.Events.FRAG_LOADING,(e,t)=>{t?.frag?.type===`main`&&(this.lastFragLoadingMs=Date.now())}),g.on($.Events.FRAG_LOADED,(e,t)=>{t?.frag?.type===`main`&&(this.mainFragsSinceTick+=1,this.bwFragsLoaded+=1,this.maybeRememberBandwidth(!1));let n=t?.frag,r=xg(t),i=r?.loaded;typeof i==`number`&&(this.bytesLoaded+=i),!this.reportedFirstBytes&&typeof i==`number`&&i>0&&(this.reportedFirstBytes=!0,c({type:`firstBytes`}));let a=r?.loading;a&&a.end>0&&a.start>0&&(this.requestCount+=1,this.requestTimesMs.push(Math.max(0,Math.round(a.end-a.start))),this.requestTimesMs.length>ug&&this.requestTimesMs.shift()),this.sampleHoldBack(t);let o=n?.url;if(o){let e=Rm(o);e&&(this.cdnHost=e)}}),g.on($.Events.LEVEL_LOADED,(e,t)=>{let n=t?.stats?.loaded;if(typeof n==`number`&&(this.playlistBytesLoaded+=n),this.reportedFirstPlaylist||(this.reportedFirstPlaylist=!0,c({type:`firstPlaylist`})),this.detectedLowLatency)return;let r=t.details;(r?.partList?.length||(r?.partTarget??0)>0)&&(this.detectedLowLatency=!0,c({type:`lowLatencyDetected`,value:!0}))}),g.on($.Events.LEVEL_LOADED,(e,t)=>this.trackEnd(t)),this.prefetch&&p){let e=this.prefetch,t=this.deps.video,n=(n,r)=>{if(t.paused)return;let i=n;if(!i?.live||!i.partList?.length||typeof i.edge!=`number`)return;let a=t.buffered,o=a.length?a.end(a.length-1):0;if(i.edge-o>Eh*(i.partTarget||.5))return;let s=Ch(n);s&&e.prefetchHint(s,r)};g.on($.Events.LEVEL_LOADED,(e,t)=>{t.level===g.loadLevel&&n(t.details,`main`)}),g.on($.Events.AUDIO_TRACK_LOADED,(e,t)=>{t?.id===g.audioTrack&&n(t?.details,`audio`)}),g.on($.Events.LEVEL_SWITCHING,()=>e.dropHints(`main`)),g.on($.Events.AUDIO_TRACK_SWITCHING,()=>e.dropHints(`audio`))}if(this.prefetch&&f){let e=this.prefetch;g.on($.Events.KEY_LOADING,(t,n)=>{let r=n?.frag,i=xh(r?.type);if(r&&e.isActive(i))for(let t of Sh(g,r))e.prefetch(t.url,i,t.kind)}),g.on($.Events.KEY_LOADED,(t,n)=>e.keyUsable(xh(n?.frag?.type)))}g.on($.Events.KEY_LOADED,()=>{l&&!this.reportedDrmReady&&(this.reportedDrmReady=!0,c({type:`drmReady`}))}),this.endWatchdog&&clearInterval(this.endWatchdog),this.endWatchdog=setInterval(()=>{this.checkEndStale(),this.checkStarvation(),this.updateCatchUpBand(),this.checkFutileChase(),this.adaptHoldBack(),this.checkFrameDrops()},Ih),g.on($.Events.LEVEL_SWITCHED,(e,t)=>{this.renditionSwitches+=1;let n=this.lastLevelIndex>=0?g.levels[this.lastLevelIndex]:void 0,r=g.levels[t.level];n&&r&&r.bitrate!==n.bitrate&&(r.bitrate>n.bitrate?this.upshifts+=1:this.downshifts+=1),this.lastLevelIndex=t.level,this.armFrameDropGrace(),c({type:`qualitychange`,index:t.level})}),g.on($.Events.AUDIO_TRACK_SWITCHED,(e,t)=>c({type:`audiotrackchange`,id:t.id})),g.on($.Events.SUBTITLE_TRACK_SWITCH,(e,t)=>c({type:`texttrackchange`,id:t.id})),g.on($.Events.ERROR,(e,t)=>this.onError(t)),g.loadSource(t.manifestUrl),g.attachMedia(e)}getQualityLevels(){return this.hls?this.hls.levels.map((e,t)=>({index:t,width:e.width||void 0,height:e.height||void 0,bitrate:e.bitrate,codecs:e.videoCodec||e.codecSet||void 0})):[]}getCurrentQuality(){return this.hls?this.hls.autoLevelEnabled?-1:this.hls.currentLevel:-1}setQuality(e){this.hls&&(this.hls.currentLevel=e)}setMaxBitrate(e){let t=this.hls;if(t){if(e==null)this.bitrateCapLevel=-1;else{let n=-1;t.levels.forEach((t,r)=>{t.bitrate<=e&&(n=r)}),this.bitrateCapLevel=n}this.pushCap()}}computeSizeCapTarget(){let e=this.hls;if(!e||e.levels.length===0)return null;let{video:t}=this.deps,n=t.getBoundingClientRect(),r=n.width,i=n.height;if(!r&&!i&&(r=t.width||0,i=t.height||0),!(r>0)||!(i>0))return null;let a=e.config??{},o=typeof self<`u`&&self.devicePixelRatio>0?self.devicePixelRatio:1,s=a.ignoreDevicePixelRatio?1:o;s=Math.min(s,a.maxDevicePixelRatio??1/0);let c=Ll.getMaxLevelByMediaSize(e.levels,r*s,i*s),l=this.deps.sizeCapHeadroom;if(l==null&&o>=tg)return c;let u=l??eg,d=Number.isNaN(u)?eg:u===1/0?e.levels.length:Math.max(0,Math.floor(u));return ng(e.levels,c,d)}onMediaResize(){if(!this.sizeCapManaged)return;let e=this.computeSizeCapTarget();if(e==null)return;if(this.sizeCapLevel==null){this.applySizeCap();return}if(e===this.sizeCapLevel){this.capTimer&&=(clearTimeout(this.capTimer),null);return}this.capTimer&&clearTimeout(this.capTimer);let t=e>this.sizeCapLevel?Qh:$h;this.capTimer=setTimeout(()=>{this.capTimer=null,this.computeSizeCapTarget()===e?this.applySizeCap():this.onMediaResize()},t)}measureLadder(e){let t=e.levels.map(e=>e.height).filter(e=>!!e);this.ladderHeights=t.length?[...new Set(t)].sort((e,t)=>e-t):void 0,this.ladderTopBitrateKbps=e.levels.length?Math.round(Math.max(...e.levels.map(e=>e.bitrate))/1e3):0}dropLevelsWidevineCannotPlay(e){this.removeLevelsWhere(e,e=>it(e)!==!0);let t=new Set(e.levels.map(e=>e.videoCodec).filter(e=>!!e&&Ze(e)!==`avc`&&!!Ze(e)));for(let n of t)nt(n).then(t=>{t||this.hls!==e||this.removeLevelsWhere(e,e=>e===n)&&(this.measureLadder(e),this.applySizeCap())})}removeLevelsWhere(e,t){let n=e.levels??[],r=[],i=new Set;if(n.forEach((e,n)=>{let a=e.videoCodec;a&&Ze(a)&&t(a)&&(r.push(n),i.add(a))}),!r.length)return!1;let a=[...i].join(`, `);if(!n.some((e,t)=>r.includes(t)?!1:!Ze(e.videoCodec)||it(e.videoCodec)===!0))return console.warn(`havik-player: every rendition is ${a}, which Widevine may not play on this browser; keeping them`),!1;for(let t=r.length-1;t>=0;--t)e.removeLevel(r[t]);return console.info(`havik-player: skipped ${r.length} rendition(s) Widevine cannot play on this browser (${a})`),!0}applySizeCap(){if(!this.sizeCapManaged)return;this.capTimer&&=(clearTimeout(this.capTimer),null);let e=this.computeSizeCapTarget();e!=null&&(this.sizeCapLevel=e,this.pushCap())}pushCap(){let e=this.hls;if(!e)return;let t=[[`size`,this.sizeCapLevel??-1],[`bitrate`,this.bitrateCapLevel],[`fps`,this.fpsCapLevel(e)]],n=-1,r=null;for(let[e,i]of t)i>=0&&(n<0||i<n)&&(n=i,r=e);e.autoLevelCapping=n,this.pushedCapLevel=n,this.pushedCapReason=r}getAudioTracks(){return this.hls?this.hls.audioTracks.map(e=>({id:e.id,name:e.name,lang:e.lang||void 0,default:!!e.default})):[]}setAudioTrack(e){this.hls&&(this.hls.audioTrack=e)}getTextTracks(){return this.hls?this.hls.subtitleTracks.map(e=>({id:e.id,name:e.name,lang:e.lang||void 0})):[]}setTextTrack(e){let t=this.hls;t&&(e<0?(t.subtitleTrack=-1,t.subtitleDisplay=!1):(t.subtitleTrack=e,t.subtitleDisplay=!0))}seekToLive(){let e=this.hls;e&&typeof e.liveSyncPosition==`number`&&(this.deps.video.currentTime=e.liveSyncPosition)}setLicenseUrls(e){e.widevine&&(this.licenseUrl=e.widevine)}getStats(){let e=this.hls,t=this.frameCounter.read(),n={droppedFrames:t.dropped,decodedFrames:t.totalFrames,lowLatency:this.detectedLowLatency,bytesLoaded:this.bytesLoaded,playlistBytesLoaded:this.playlistBytesLoaded,renditionSwitches:this.renditionSwitches,liveRetargets:this.liveRetargets,holdBackSteps:this.holdBackSteps,fpsDownCaps:this.fpsDownCaps,licenseTimeMs:this.licenseTimeMs,upshifts:this.upshifts,downshifts:this.downshifts,requestCount:this.requestCount,requestErrors:this.requestErrors,requestTimesMs:[...this.requestTimesMs],ladderHeights:this.ladderHeights,ladderTopBitrateKbps:this.ladderTopBitrateKbps||void 0};if(this.cdnHost&&(n.cdnHost=this.cdnHost),this.licenseRequested&&(n.keySystem=`widevine`,n.drmSecurityLevel=`L3`),e){n.qualityPinned=!e.autoLevelEnabled,typeof e.latency==`number`&&(n.latencySeconds=e.latency),typeof e.targetLatency==`number`&&e.targetLatency>0&&(n.targetLatencySeconds=e.targetLatency),typeof e.bandwidthEstimate==`number`&&(n.bandwidthKbps=Math.round(e.bandwidthEstimate/1e3));let t=e.currentLevel>=0?e.levels[e.currentLevel]:void 0;t&&(n.levelHeight=t.height);let r=e.autoLevelCapping,i=r>=0?e.levels[r]:void 0;if(i&&i.height>0){n.maxLevelHeight=i.height;let t=e.config??{};t.capLevelToPlayerSize!==!0&&t.capLevelOnFPSDrop!==!0&&r===this.pushedCapLevel&&this.pushedCapReason&&(n.capReason=this.pushedCapReason)}t?.videoCodec&&(n.videoCodec=t.videoCodec),t?.audioCodec&&(n.audioCodec=t.audioCodec),t&&typeof t.bitrate==`number`&&(n.renditionBitrateKbps=Math.round(t.bitrate/1e3)),typeof t?.details?.live==`boolean`&&(n.isLive=t.details.live,typeof e.liveSyncPosition==`number`&&(n.atLiveEdge=this.deps.video.currentTime>=e.liveSyncPosition-1.5))}return n}trackEnd(e){let t=e.details;if(t){if(t.live===!0){let e=!this.sawLive;this.sawLive=!0,e&&this.applyHoldBackPrior();let n=t.endSN??-1;n!==this.lastEndSN&&(this.lastEndSN=n,this.lastAdvanceMs=Date.now(),this.chaseSuspended&&this.resumeChasing());return}this.sawLive&&this.emitEnded(`endlist`)}}checkEndStale(){if(this.endedEmitted||!this.sawLive||this.lastAdvanceMs===0)return;if(typeof document<`u`&&document.hidden){this.lastAdvanceMs=Date.now();return}if(this.loadSuspended){this.lastAdvanceMs=Date.now();return}let e=Date.now()-this.lastAdvanceMs;!this.chaseSuspended&&e>Rh&&this.suspendChasing(),e>Fh&&this.emitEnded(`stalled`)}resetStarvationWindow(){this.starvedTicks=0,this.deadTicks=0,this.mainFragsSinceTick=0,this.recentMainFrags=[]}clearKick(){this.kickPending=!1,this.kickTicks=0,this.kickKind=null}checkStarvation(){let e=this.hls,{video:t}=this.deps;if(!e||this.endedEmitted||!this.sawLive||this.chaseSuspended)return;if(typeof document<`u`&&document.hidden||this.loadSuspended){this.resetStarvationWindow();return}let n=Date.now(),r=this.lastAdvanceMs!==0&&n-this.lastAdvanceMs<Rh,i=this.lastFragLoadingMs!==0&&n-this.lastFragLoadingMs>Gh,a=t.readyState<HTMLMediaElement.HAVE_FUTURE_DATA&&!t.paused,{totalFrames:o,dropped:s}=Vm(t),c=o-s,l=c!==this.starvedFrames;if(this.starvedFrames=c,!a||l){(t.readyState>=HTMLMediaElement.HAVE_FUTURE_DATA||l)&&this.clearKick(),this.resetStarvationWindow();return}if(!r){this.resetStarvationWindow();return}if(this.kickPending&&(this.kickKind===`dead`||i)&&(this.kickTicks+=1),this.starvedTicks=i?this.starvedTicks+1:0,this.deadTicks+=1,this.recentMainFrags.push(this.mainFragsSinceTick),this.mainFragsSinceTick=0,this.recentMainFrags.length>Xh&&this.recentMainFrags.shift(),this.clearRecoveryReset(),this.kickPending&&this.kickTicks>=Jh&&(this.clearKick(),this.starvationRebuilds<Yh)){this.starvationRebuilds+=1,this.resetStarvationWindow(),this.clearRecoveryReset(),console.warn(`havik-player: restarting the load did not resume video (the wedge is in hls.js state that only a rebuild clears) — rebuilding the player`),this.rebuildInstance(`starvation rebuild`);return}let u=i&&this.starvedTicks>=Kh,d=!i&&this.deadTicks>=Xh&&this.recentMainFrags.reduce((e,t)=>e+t,0)>=Zh;if((u||d)&&(this.resetStarvationWindow(),!(this.starvationKicks>=qh))){this.starvationKicks+=1,this.kickPending=!0,this.kickTicks=0,this.kickKind=d?`dead`:`quiet`,this.clearRecoveryReset(),console.warn(d?`havik-player: video starved while hls.js keeps loading media it never plays (dead pipeline at the live edge) — restarting the load`:`havik-player: video starved while the live playlist advances (wedged hls.js fragment pipeline) — restarting the load`);try{e.stopLoad(),e.startLoad(-1)}catch(e){console.warn(`havik-player: starvation kick failed`,e)}}}updateCatchUpBand(){let e=this.hls;if(!e||this.catchUpRate<=1||this.chaseSuspended||this.loadSuspended)return;let t=e.latency,n=e.targetLatency;if(typeof t!=`number`||typeof n!=`number`||!Number.isFinite(t))return;let r=t-n;!this.catchUpEngaged&&r>zh?this.catchUpEngaged=!0:this.catchUpEngaged&&r<=zh&&this.deps.video.playbackRate===1&&(this.catchUpEngaged=!1);let i=this.catchUpEngaged?this.catchUpRate:1;e.config.maxLiveSyncPlaybackRate!==i&&(e.config.maxLiveSyncPlaybackRate=i)}fpsCapLevel(e){if(this.fpsCapBitrate==null)return-1;let t=this.fpsCapFailedHeight,n=-1;return e.levels.forEach((e,r)=>{let i=t==null||!(e.height>0)||e.height<t;e.bitrate<=this.fpsCapBitrate&&i&&(n=r)}),n<0?0:n}armFrameDropGrace(){this.fpsGraceTicks>0||(this.fpsGraceTicks=og,this.fpsBadTicks=0)}resetFrameDropWindow(){this.fpsLastFrames=-1,this.fpsLastDropped=-1,this.fpsBadTicks=0}checkFrameDrops(){let e=this.hls,{video:t}=this.deps;if(!e||!this.fpsCapManaged||this.loadSuspended||t.paused||!e.autoLevelEnabled||typeof document<`u`&&document.hidden){this.resetFrameDropWindow();return}let{totalFrames:n,dropped:r}=Vm(t),i=this.fpsLastFrames<0,a=n-this.fpsLastFrames,o=r-this.fpsLastDropped;if(this.fpsLastFrames=n,this.fpsLastDropped=r,i||a<ig||o<0){this.fpsBadTicks=0;return}if(this.fpsGraceTicks>0){--this.fpsGraceTicks,this.fpsBadTicks=0;return}if(o<=rg*a){this.fpsBadTicks=0;return}if(this.fpsBadTicks+=1,this.fpsBadTicks<ag)return;this.fpsBadTicks=0;let s=e.levels,c=s[e.currentLevel];if(!c)return;let l=s.filter(e=>e.height>0&&e.height<c.height),u=(l.length?l:s.filter(e=>e.bitrate<c.bitrate)).map(e=>e.bitrate).sort((e,t)=>t-e)[0];u!=null&&(this.fpsCapBitrate!=null&&u>=this.fpsCapBitrate||(this.fpsCapBitrate=u,l.length&&(this.fpsCapFailedHeight=c.height),this.fpsDownCaps+=1,console.warn(`havik-player: dropping ${Math.round(100*o/a)}% of frames at ${c.height}p — capping quality below it`),this.pushCap()))}resetChaseWindow(){this.chaseLatency=-1,this.chaseTicks=0}checkFutileChase(){let e=this.hls,{video:t}=this.deps;if(!e||this.endedEmitted||!this.sawLive||this.chaseSuspended||this.loadSuspended||typeof document<`u`&&document.hidden){this.resetChaseWindow();return}let n=e.latency,r=t.playbackRate,i=e.config.maxLiveSyncPlaybackRate;if(!(!t.paused&&typeof i==`number`&&i>1&&r>=Math.min(Hh,i)&&r<=i&&typeof n==`number`&&Number.isFinite(n))){this.resetChaseWindow();return}if(this.chaseLatency<0||this.chaseLatency-n>=Vh){this.chaseLatency=n,this.chaseTicks=0;return}if(this.chaseTicks+=1,this.chaseTicks<Bh)return;this.resetChaseWindow();let a=typeof e.config.liveMaxLatencyDuration==`number`?e.config.liveMaxLatencyDuration:e.maxLatency;if(!(a>1))return;let o=e.targetLatency;if(typeof o!=`number`||!(o>0))return;let s=Math.min(n,a-1);s<o+Uh||(console.warn(`havik-player: catch-up at ${r}x not gaining on the live edge (latency ${n.toFixed(1)}s); holding at ${s.toFixed(1)}s`),this.liveRetargets+=1,e.targetLatency=s,this.deps.emit({type:`livetargetchange`,change:{targetSeconds:s,previousSeconds:o,reason:`futile-chase`}}))}armHoldBack(e,t){this.holdBackEnabled&&(this.holdBackSlowTicks=0,this.holdBackFastSince=0,this.holdBackSamples=[],this.holdBackBase<0&&typeof t.liveSyncDuration==`number`&&(this.holdBackBase=t.liveSyncDuration),this.holdBackApplied>0&&(e.targetLatency=this.holdBackApplied))}applyHoldBackPrior(){let e=this.hls;if(!this.holdBackEnabled||this.holdBackPriorChecked||!e||(this.holdBackPriorChecked=!0,this.holdBackApplied>0||this.holdBackStepCount>0))return;let t=e.targetLatency;if(this.holdBackBase<0&&typeof t==`number`&&t>0&&(this.holdBackBase=t),this.holdBackBase<0)return;let n=Sg();if(!(n>=bg))return;let r=typeof t==`number`&&t>0?t:this.holdBackBase,i=Math.min(this.holdBackCeiling(e),this.holdBackBase+vg);i>r&&(this.holdBackStepCount=1,this.moveHoldBack(e,r,i,`connection-rtt`,`connection rtt ${n} ms`))}holdBackCeiling(e){let t=this.deps.adaptiveHoldBackCeiling,n=typeof t==`number`&&Number.isFinite(t)?t:yg,r=typeof e.config.liveMaxLatencyDuration==`number`?e.config.liveMaxLatencyDuration:e.maxLatency;return r>1?Math.min(n,r-1):n}sampleHoldBack(e){if(!this.holdBackEnabled||typeof document<`u`&&document.hidden)return;let t=e.frag?.type;if(t!==`main`&&t!==`audio`)return;let n=e.part?e.part.duration:this.detectedLowLatency?0:e.frag?.duration;if(typeof n!=`number`||!(n>0))return;let r=xg(e)?.loading;if(!r||!(r.start>0)||!(r.end>0))return;let i=r.first>r.start?r.first:r.end,a=Math.max(0,i-r.start)/(n*1e3);this.holdBackSamples.push({t:Date.now(),ratio:a}),this.holdBackSamples.length>256&&this.holdBackSamples.shift()}adaptHoldBack(){if(!this.holdBackEnabled)return;let e=this.hls;if(!e||this.endedEmitted||!this.sawLive||this.chaseSuspended||this.loadSuspended||typeof document<`u`&&document.hidden){this.holdBackSlowTicks=0,this.holdBackFastSince=0,this.holdBackSamples=[];return}let t=Date.now(),n=t-dg,r=this.holdBackSamples,i=0;for(;i<r.length&&r[i].t<n;)i+=1;i>0&&r.splice(0,i);let a=e.targetLatency;if(typeof a!=`number`||!(a>0))return;this.holdBackBase<0&&(this.holdBackBase=a);let o=this.holdBackBase,s=this.holdBackCeiling(e);if(r.length<fg){this.holdBackSlowTicks=0;return}let c=r.map(e=>e.ratio).sort((e,t)=>e-t),l=wh(c,95),u=wh(c,50),d=Math.round(l*1e3);if(l>=pg&&u>=mg){if(this.holdBackFastSince=0,this.holdBackSlowTicks+=1,this.holdBackSlowTicks<gg)return;this.holdBackSlowTicks=0;let t=Math.ceil((s-o)/vg),n=Math.ceil((a-o)/vg-1e-9);if(n>this.holdBackStepCount&&(this.holdBackStepCount=n),this.holdBackStepCount>=t)return;this.holdBackStepCount+=1;let r=Math.min(s,o+this.holdBackStepCount*vg);if(r<=a)return;this.moveHoldBack(e,a,r,`slow-fetches`,`part fetches slow (first byte p50 ${Math.round(u*1e3)} / p95 ${d} ms per 1 s of media)`);return}if(this.holdBackSlowTicks=0,l>=hg){this.holdBackFastSince=0;return}if(this.holdBackFastSince===0){this.holdBackFastSince=t;return}if(t-this.holdBackFastSince<_g||(this.holdBackFastSince=t,this.holdBackStepCount===0||a!==this.holdBackApplied))return;--this.holdBackStepCount;let f=Math.max(o,o+this.holdBackStepCount*vg);f>=a||this.moveHoldBack(e,a,f,`fast-fetches`,`part fetches fast again (p95 first byte ${d} ms per 1 s of media)`)}moveHoldBack(e,t,n,r,i){console.info(`havik-player: ${i}; live target ${t.toFixed(1)}s → ${n.toFixed(1)}s`),this.holdBackApplied=n,this.holdBackSteps+=1,e.targetLatency=n,this.deps.emit({type:`livetargetchange`,change:{targetSeconds:n,previousSeconds:t,reason:r}})}suspendChasing(){let e=this.hls;if(!e)return;this.chaseSuspended=!0,this.savedLiveMaxLatency=e.config.liveMaxLatencyDuration,this.savedMaxSyncRate=e.config.maxLiveSyncPlaybackRate,e.config.liveMaxLatencyDuration=2**53-1,e.config.maxLiveSyncPlaybackRate=1;let{video:t}=this.deps,n=this.savedMaxSyncRate;t.playbackRate>1&&typeof n==`number`&&t.playbackRate<=n&&(t.playbackRate=1)}resumeChasing(){this.chaseSuspended=!1;let e=this.hls;e&&(e.config.liveMaxLatencyDuration=this.savedLiveMaxLatency,e.config.maxLiveSyncPlaybackRate=this.savedMaxSyncRate)}emitEnded(e){this.endedEmitted||(this.endedEmitted=!0,this.endWatchdog&&=(clearInterval(this.endWatchdog),null),this.deps.emit({type:`ended`,reason:e}))}stop(){this.endWatchdog&&=(clearInterval(this.endWatchdog),null),this.clearKick(),this.stopped=!0,this.loadSuspended=!1,this.pauseSuspendTimer&&=(clearTimeout(this.pauseSuspendTimer),null);try{this.hls?.stopLoad()}catch{}try{this.deps.video.pause()}catch{}}startEstimate(){return this.deps.rememberBandwidth===!1?Dh:ze()??Dh}maybeRememberBandwidth(e){if(this.deps.rememberBandwidth===!1||this.bwFragsLoaded<Oh)return;let t=Date.now();if(!e&&t-this.bwSavedAt<kh)return;let n=this.hls?.bandwidthEstimate;typeof n!=`number`||!Number.isFinite(n)||n<=0||(this.bwSavedAt=t,Be(n))}destroy(){if(this.maybeRememberBandwidth(!0),this.detachFrames?.(),this.detachFrames=null,this.prefetch?.destroy(),this.prefetch=null,this.clearRecoveryReset(),this.capTimer&&=(clearTimeout(this.capTimer),null),this.capObserver&&=(this.capObserver.disconnect(),null),this.unwatchDprChanges(),this.endWatchdog&&=(clearInterval(this.endWatchdog),null),this.onVisibility&&typeof document<`u`&&(document.removeEventListener(`visibilitychange`,this.onVisibility),this.onVisibility=null),this.onSeeking&&=(this.deps.video.removeEventListener(`seeking`,this.onSeeking),null),this.onTimeUpdate&&=(this.deps.video.removeEventListener(`timeupdate`,this.onTimeUpdate),null),this.onPause&&=(this.deps.video.removeEventListener(`pause`,this.onPause),null),this.onPlay&&=(this.deps.video.removeEventListener(`play`,this.onPlay),null),this.pauseSuspendTimer&&=(clearTimeout(this.pauseSuspendTimer),null),this.networkRetryTimer&&=(clearTimeout(this.networkRetryTimer),null),this.licenseRetryTimer&&=(clearTimeout(this.licenseRetryTimer),null),this.hls){try{this.hls.destroy()}catch(e){console.warn(`havik-player: hls.js destroy() threw during teardown`,e)}this.hls=null}}clearRecoveryReset(){this.recoveryResetTimer&&=(clearTimeout(this.recoveryResetTimer),null)}scheduleLicenseRetry(e){if(e.details!==$.ErrorDetails.KEY_SYSTEM_LICENSE_REQUEST_FAILED&&e.details!==$.ErrorDetails.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED)return!1;let t=e.response?.code??0;if(!(t===0||t===408||t===429||t>=500)||this.licenseRecoveries>=Mh)return!1;this.licenseRecoveries+=1;let n=Math.min(8e3,500*2**(this.licenseRecoveries-1));return this.licenseRetryTimer=setTimeout(()=>{this.licenseRetryTimer=null,this.rebuildInstance(`license retry`)},n),!0}rebuildInstance(e){if(this.hls){try{this.hls.destroy()}catch(t){console.warn(`havik-player: hls.js destroy() threw during ${e}`,t)}this.hls=null,this.startHls(),this.armFrameDropGrace()}}onError(e){if(e.type===$.ErrorTypes.NETWORK_ERROR&&String(e.details??``).startsWith(`frag`)&&(this.requestErrors+=1),!e.fatal)return;let t=this.hls;if(t){if(this.clearRecoveryReset(),e.type===$.ErrorTypes.KEY_SYSTEM_ERROR){if(this.scheduleLicenseRetry(e))return;this.deps.emit({type:`error`,error:this.toError(e,`DRM`),fatal:!0,detail:e.details});return}if(e.type===$.ErrorTypes.NETWORK_ERROR){if(this.networkRecoveries<jh){this.networkRecoveries+=1;let e=Math.min(8e3,1e3*2**(this.networkRecoveries-1));this.networkRetryTimer=setTimeout(()=>{this.networkRetryTimer=null,this.hls&&this.hls.startLoad()},e);return}this.deps.emit({type:`error`,error:this.toError(e,`NETWORK`),fatal:!0,detail:e.details});return}if(e.type===$.ErrorTypes.MEDIA_ERROR){if(this.mediaRecoveries<Ah){this.mediaRecoveries+=1,t.recoverMediaError();return}this.deps.emit({type:`error`,error:this.toError(e),fatal:!0,detail:e.details});return}this.deps.emit({type:`error`,error:this.toError(e),fatal:!0,detail:e.details})}}toError(e,t=`PLAYBACK`){let n=e.response?.code??0,r=e.details??e.type,i=e.reason??e.error?.message??``,o=t===`DRM`&&n===403&&e.details===$.ErrorDetails.KEY_SYSTEM_LICENSE_REQUEST_FAILED?s(dh(e.networkDetails)):void 0;return new a(t===`DRM`?c(n,o):n===401?`UNAUTHORIZED`:n===403?`FORBIDDEN`:`INTERNAL`,n,`${t} error: ${r}${i?` (${i})`:``}`,o?{serverCode:o}:void 0)}},Eg=15e3,Dg=6e5,Og=3e5,kg=100,Ag=1,jg=1e3,Mg=3e4,Ng=1e3,Pg={inline:`PRESENTATION_INLINE`,fullscreen:`PRESENTATION_FULLSCREEN`,pip:`PRESENTATION_PIP`},Fg={widevine:`KEY_SYSTEM_WIDEVINE`,fairplay:`KEY_SYSTEM_FAIRPLAY`,none:`KEY_SYSTEM_NONE`},Ig=new Set([`INVALID_URN`,`NOT_FOUND`,`GEO_DENIED`,`GONE`,`TOO_EARLY`,`UNAVAILABLE`,`UNAUTHORIZED`,`FORBIDDEN`,`RATE_LIMITED`,`TIMEOUT`]),Lg={idle:`PLAYER_STATE_IDLE`,waiting:`PLAYER_STATE_WAITING`,loading:`PLAYER_STATE_LOADING`,playing:`PLAYER_STATE_PLAYING`,buffering:`PLAYER_STATE_BUFFERING`,paused:`PLAYER_STATE_PAUSED`,ended:`PLAYER_STATE_ENDED`,error:`PLAYER_STATE_ERROR`};function Rg(e){try{let t=new URL(e),[n,...r]=t.hostname.split(`.`);return!n||r.length===0||n!==`feed`&&!n.startsWith(`feed-`)?void 0:(t.hostname=[n.replace(/^feed/,`beacons`),...r].join(`.`),t.pathname=``,t.search=``,t.origin)}catch{return}}var zg=(e,t)=>e.replace(/\/$/,``).toLowerCase()===t.replace(/\/$/,``).toLowerCase(),Bg=new Set,Vg=new Set,Hg=new Set,Ug=e=>`this page's Content-Security-Policy blocks QoE beacons. Add ${e} to connect-src; until then none are sent.`;function Wg(e){if(e.disposition!==`enforce`||e.effectiveDirective!==`connect-src`)return;let t;try{let n=new URL(e.blockedURI);t=n.origin+n.pathname}catch{return}if(Bg.has(t)&&!Vg.has(t)){Vg.add(t),b(Ug(new URL(t).origin));for(let e of Hg)e.noteCspBlocked()}}function Gg(e,t){return b(t,e),{disabledReason:t}}function Kg(e,t,n){if(n)return t&&!zg(t,n)&&b(`analytics.endpoint "${t}" ignored; the server named "${n}".`),{endpoint:n};if(t)return{endpoint:t};if(t!==void 0)return Gg(`empty-endpoint`,`analytics is disabled: no QoE beacons will be sent. analytics.endpoint was supplied but empty. Pass a real beacons origin, analytics: { endpoint: 'https://beacons[-dev].<domain>' }, or omit the option to derive it from baseUrl (or analytics: false to opt out).`);let r=Rg(e);if(r)return{endpoint:r};let i;try{i=new URL(e).hostname||e}catch{i=e}return Gg(i,`analytics is disabled: no QoE beacons will be sent. The beacons endpoint cannot be derived from the baseUrl host "${i}" — the convention is feed[-dev].<domain> → beacons[-dev].<domain>. Pass an explicit endpoint, analytics: { endpoint: 'https://beacons[-dev].<domain>' }, to createPlayer (or analytics: false to opt out deliberately).`)}var qg=class{constructor(e){i(this,`opts`,void 0),i(this,`url`,void 0),i(this,`cspKey`,void 0),i(this,`now`,void 0),i(this,`seq`,0),i(this,`pending`,[]),i(this,`timer`,null),i(this,`endedFlag`,!1),i(this,`lastBytes`,0),i(this,`lastPlaylistBytes`,0),i(this,`lastDropped`,0),i(this,`lastSwitches`,0),i(this,`playingSinceMs`,null),i(this,`hiddenSinceMs`,null),i(this,`playingTotalMs`,0),i(this,`hiddenTotalMs`,0),i(this,`lastHbPlayingMs`,0),i(this,`lastHbHiddenMs`,0),i(this,`lastHbRebufferMs`,0),i(this,`lastHbRebufferCount`,0),i(this,`lastHbActiveMs`,0),i(this,`rebufferCount`,0),i(this,`rebufferTotalMs`,0),i(this,`bufferingSinceMs`,null),i(this,`isBuffering`,!1),i(this,`errorCount`,0),i(this,`seekCount`,0),i(this,`pauseCount`,0),i(this,`isPlaying`,!1),i(this,`isHidden`,!1),i(this,`isMuted`,!1),i(this,`activeSinceMs`,null),i(this,`activeTotalMs`,0),i(this,`mutedSinceMs`,null),i(this,`mutedTotalMs`,0),i(this,`lastHbMutedMs`,0),i(this,`volumeChanges`,0),i(this,`muteChanges`,0),i(this,`presentation`,`inline`),i(this,`presentationSinceMs`,void 0),i(this,`fullscreenTotalMs`,0),i(this,`pipTotalMs`,0),i(this,`waitingSinceMs`,null),i(this,`waitingTotalMs`,0),i(this,`firstAudioMs`,0),i(this,`timeToFirstStallMs`,0),i(this,`lastStallMs`,0),i(this,`lastErrorMs`,0),i(this,`lastSeekMs`,-1),i(this,`stallIsSeekInduced`,!1),i(this,`lastErrorStage`,null),i(this,`sawFirstBytes`,!1),i(this,`mediaInfoSignature`,``),i(this,`lastUpshifts`,0),i(this,`lastDownshifts`,0),i(this,`lastDecoded`,0),i(this,`lastRequestCount`,0),i(this,`lastRequestErrors`,0),i(this,`pendingStart`,null),i(this,`firstFlushTimer`,null),i(this,`idleTimer`,null),i(this,`lastTickMs`,0),i(this,`bornMs`,void 0),i(this,`startupAnchorMs`,void 0),i(this,`startupTimeMs`,0),i(this,`manifestLoadMs`,0),i(this,`firstFragLoadMs`,0),i(this,`firstPlaylistMs`,0),i(this,`drmSetupMs`,0),i(this,`onPagehide`,()=>this.end(`END_REASON_PAGEHIDE`)),i(this,`cspBlockedNoted`,!1),i(this,`onFreeze`,()=>{this.endedFlag||this.flush(!0)}),i(this,`onResume`,()=>this.checkSuspension(this.now())),i(this,`onVisibility`,()=>{typeof document>`u`||(document.visibilityState===`hidden`?(this.hiddenSinceMs===null&&(this.hiddenSinceMs=this.now()),this.isHidden=!0):(this.hiddenSinceMs!==null&&(this.hiddenTotalMs+=this.now()-this.hiddenSinceMs,this.hiddenSinceMs=null),this.isHidden=!1),this.syncActive(),this.syncBuffering())}),this.opts={...e,heartbeatMs:e.heartbeatMs??Eg,idleMs:e.idleMs??Dg},this.url=`${e.endpoint.replace(/\/$/,``)}/v1/beacons`;try{let e=new URL(this.url);this.cspKey=e.origin+e.pathname}catch{this.cspKey=void 0}this.now=e.now??(()=>Date.now()),this.bornMs=this.now(),this.presentationSinceMs=this.bornMs,this.startupAnchorMs=this.bornMs}start(){if(this.endedFlag)return;let e={player:this.opts.player,sdkVersion:this.opts.sdkVersion,...this.opts.environment};this.pendingStart=e,this.enqueue({sessionStart:e}),this.firstFlushTimer=setTimeout(()=>this.flush(),jg),this.lastTickMs=this.now(),this.timer=setInterval(()=>this.heartbeat(),this.opts.heartbeatMs),typeof window<`u`&&window.addEventListener(`pagehide`,this.onPagehide),typeof document<`u`&&(document.addEventListener(`visibilitychange`,this.onVisibility),document.addEventListener(`freeze`,this.onFreeze),document.addEventListener(`resume`,this.onResume),this.cspKey&&Bg.add(this.cspKey),document.addEventListener(`securitypolicyviolation`,Wg),Hg.add(this),this.noteCspBlocked(),this.onVisibility())}checkSuspension(e){if(this.endedFlag||!this.opts.idleMs)return!1;let t=Math.max(this.opts.idleMs,Og);return this.lastTickMs>0&&e-this.lastTickMs>=t?(this.endIdle(this.lastTickMs),!0):(this.lastTickMs=e,!1)}syncIdle(e){e===`paused`&&this.opts.idleMs?this.idleTimer===null&&(this.idleTimer=setTimeout(()=>{this.idleTimer=null,this.endIdle()},this.opts.idleMs)):this.idleTimer!==null&&(clearTimeout(this.idleTimer),this.idleTimer=null)}endIdle(e){this.endedFlag||(this.end(`END_REASON_IDLE`,e),this.opts.onIdle?.())}noteStateChange(e,t,n,r){if(this.endedFlag||e===t)return;let i=this.now();if(t===`playing`?(this.playingSinceMs===null&&(this.playingSinceMs=i),this.startupTimeMs===0&&(this.startupTimeMs=Math.max(Ag,i-this.startupAnchorMs)),this.firstAudioMs===0&&!this.isMuted&&(this.firstAudioMs=Math.max(Ag,i-this.startupAnchorMs)),this.isMuted&&this.mutedSinceMs===null&&(this.mutedSinceMs=i)):this.playingSinceMs!==null&&(this.playingTotalMs+=i-this.playingSinceMs,this.playingSinceMs=null,this.mutedSinceMs!==null&&(this.mutedTotalMs+=i-this.mutedSinceMs,this.mutedSinceMs=null)),this.isPlaying=t===`playing`,this.syncActive(),t===`waiting`?this.waitingSinceMs=i:this.waitingSinceMs!==null&&(this.waitingTotalMs+=i-this.waitingSinceMs,this.waitingSinceMs=null),t===`buffering`&&e===`playing`){this.stallIsSeekInduced=this.seekInduced(i);let e=!this.isHidden&&!this.stallIsSeekInduced;e&&(this.rebufferCount+=1),this.isBuffering=!0,this.lastStallMs=i,e&&this.timeToFirstStallMs===0&&(this.timeToFirstStallMs=Math.max(Ag,Math.round(this.playingTotalMs)))}else e===`buffering`&&(this.isBuffering=!1,this.stallIsSeekInduced=!1);this.syncBuffering(),t===`paused`&&(this.pauseCount+=1),this.syncIdle(t);let a={fromState:Lg[e]??`PLAYER_STATE_UNSPECIFIED`,toState:Lg[t]??`PLAYER_STATE_UNSPECIFIED`,presentation:Pg[this.presentation]},o=this.causeOf(e,t,i);o&&(a.cause=o),n>0&&(a.positionMs=Math.round(n)),r&&(a.renditionHeight=r),this.enqueue({stateChange:a})}seekInduced(e){return this.lastSeekMs>=0&&e-this.lastSeekMs<Ng}causeOf(e,t,n){if(t===`error`)return`TRANSITION_CAUSE_ERROR`;if(t===`buffering`)return this.seekInduced(n)?`TRANSITION_CAUSE_SEEK`:`TRANSITION_CAUSE_NETWORK_STALL`;if(t===`paused`||t===`playing`&&e===`paused`)return`TRANSITION_CAUSE_USER`}syncActive(e=this.now()){let t=this.isPlaying&&!this.isHidden&&!this.isMuted;t&&this.activeSinceMs===null?this.activeSinceMs=e:!t&&this.activeSinceMs!==null&&(this.activeTotalMs+=e-this.activeSinceMs,this.activeSinceMs=null)}syncBuffering(){let e=this.isBuffering&&!this.isHidden&&!this.stallIsSeekInduced;e&&this.bufferingSinceMs===null?this.bufferingSinceMs=this.now():!e&&this.bufferingSinceMs!==null&&(this.rebufferTotalMs+=this.now()-this.bufferingSinceMs,this.bufferingSinceMs=null)}closePresentation(e=this.now()){let t=e-this.presentationSinceMs;this.presentation===`fullscreen`?this.fullscreenTotalMs+=t:this.presentation===`pip`&&(this.pipTotalMs+=t),this.presentationSinceMs=e}noteAutoplay(e){this.pendingStart&&(this.pendingStart.autoplay=e)}noteEnvironment(e){this.pendingStart&&Object.assign(this.pendingStart,e)}seedVolume(e,t){this.endedFlag||(this.isMuted=e||t===0,this.isMuted&&this.isPlaying&&this.mutedSinceMs===null&&(this.mutedSinceMs=this.now()),this.syncActive())}noteVolume(e,t){if(this.endedFlag)return;let n=e||t===0;if(n===this.isMuted){this.volumeChanges+=1;return}this.muteChanges+=1;let r=this.now();n?this.isPlaying&&this.mutedSinceMs===null&&(this.mutedSinceMs=r):(this.mutedSinceMs!==null&&(this.mutedTotalMs+=r-this.mutedSinceMs,this.mutedSinceMs=null),this.firstAudioMs===0&&this.isPlaying&&(this.firstAudioMs=Math.max(Ag,r-this.startupAnchorMs))),this.isMuted=n,this.syncActive()}notePresentation(e){this.endedFlag||e===this.presentation||(this.closePresentation(),this.presentation=e)}notePlayIntent(){this.endedFlag||this.startupTimeMs>0||(this.startupAnchorMs=this.now(),this.manifestLoadMs>0&&(this.manifestLoadMs=Ag),this.firstPlaylistMs>0&&(this.firstPlaylistMs=Ag),this.firstFragLoadMs>0&&(this.firstFragLoadMs=Ag),this.drmSetupMs>0&&(this.drmSetupMs=Ag))}noteReady(){this.manifestLoadMs===0&&(this.manifestLoadMs=Math.max(Ag,this.now()-this.startupAnchorMs))}noteFirstPlaylist(){this.firstPlaylistMs===0&&(this.firstPlaylistMs=Math.max(Ag,this.now()-this.startupAnchorMs))}noteDrmReady(){this.drmSetupMs===0&&(this.drmSetupMs=Math.max(Ag,this.now()-this.startupAnchorMs))}noteFirstBytes(){this.sawFirstBytes=!0,this.firstFragLoadMs===0&&(this.firstFragLoadMs=Math.max(Ag,this.now()-this.startupAnchorMs))}noteSeek(){this.endedFlag||(this.seekCount+=1,this.lastSeekMs=this.now())}noteError(e,t,n,r,i,a){if(this.endedFlag)return;this.errorCount+=1,this.lastErrorMs=this.now();let o={code:e};t&&(o.detail=t),n&&(o.fatal=!0),r>0&&(o.httpStatus=r),i>0&&(o.positionMs=Math.round(i));let s=this.stageOf(e,t,a);o.stage=s,this.lastErrorStage=s;let c=this.safeSample()?.cdnHost;c&&(o.cdnHost=c),this.enqueue({error:o}),this.flush()}stageOf(e,t,n){let r=n??``;if(r!==``)return/^fragLoad/i.test(r)?this.sawFirstBytes?`ERROR_STAGE_SEGMENT`:`ERROR_STAGE_FIRST_SEGMENT`:/^(manifest|level|audioTrack|subtitleTrack)/i.test(r)?`ERROR_STAGE_MANIFEST`:/key|licen[cs]e/i.test(r)?`ERROR_STAGE_DRM`:/parsing|append|buffer|remux|decrypt|media/i.test(r)?`ERROR_STAGE_DECODE`:`ERROR_STAGE_OTHER`;if(e===`DRM_CLIENT`||e===`DRM_DEVICE_REVOKED`)return`ERROR_STAGE_DRM`;if(Ig.has(e))return`ERROR_STAGE_RESOLVE`;let i=t??``;return/frag|segment/i.test(i)?this.sawFirstBytes?`ERROR_STAGE_SEGMENT`:`ERROR_STAGE_FIRST_SEGMENT`:/manifest|level|playlist/i.test(i)?`ERROR_STAGE_MANIFEST`:/key|licen[cs]e/i.test(i)?`ERROR_STAGE_DRM`:/buffer|decode|media|append/i.test(i)?`ERROR_STAGE_DECODE`:`ERROR_STAGE_OTHER`}noteEnded(){this.end(`END_REASON_ENDED`)}noteDestroyed(){this.end(`END_REASON_STOPPED`)}noteFatal(){this.end(`END_REASON_FATAL_ERROR`)}heartbeat(){if(this.endedFlag)return;let e=this.now();if(this.checkSuspension(e)||this.cspBlocked())return;let t=this.opts.sample(),n=this.playingTotalMs;this.playingSinceMs!==null&&(n+=e-this.playingSinceMs);let r=this.hiddenTotalMs;this.hiddenSinceMs!==null&&(r+=e-this.hiddenSinceMs);let i=this.rebufferTotalMs;this.bufferingSinceMs!==null&&(i+=e-this.bufferingSinceMs);let a=this.activeTotalMs;this.activeSinceMs!==null&&(a+=e-this.activeSinceMs);let o={},s=t.bytesLoaded??0;s>this.lastBytes&&(o.bytesDownloadedDelta=s-this.lastBytes),this.lastBytes=s;let c=t.playlistBytesLoaded??0;c>this.lastPlaylistBytes&&(o.playlistBytesDelta=c-this.lastPlaylistBytes),this.lastPlaylistBytes=c;let l=t.droppedFrames??0;l>this.lastDropped&&(o.droppedFramesDelta=l-this.lastDropped),this.lastDropped=l;let u=t.renditionSwitches??0;u>this.lastSwitches&&(o.renditionSwitchesDelta=u-this.lastSwitches),this.lastSwitches=u,n>this.lastHbPlayingMs&&(o.playingMsDelta=Math.round(n-this.lastHbPlayingMs)),this.lastHbPlayingMs=n,r>this.lastHbHiddenMs&&(o.hiddenMsDelta=Math.round(r-this.lastHbHiddenMs)),this.lastHbHiddenMs=r,i>this.lastHbRebufferMs&&(o.rebufferMsDelta=Math.round(i-this.lastHbRebufferMs)),this.lastHbRebufferMs=i,this.rebufferCount>this.lastHbRebufferCount&&(o.rebufferCountDelta=this.rebufferCount-this.lastHbRebufferCount),this.lastHbRebufferCount=this.rebufferCount,a>this.lastHbActiveMs&&(o.activeMsDelta=Math.round(a-this.lastHbActiveMs)),this.lastHbActiveMs=a,typeof t.latencySeconds==`number`&&(o.latencyMs=Math.round(t.latencySeconds*1e3)),typeof t.targetLatencySeconds==`number`&&(o.targetLatencyMs=Math.round(t.targetLatencySeconds*1e3)),typeof t.bandwidthKbps==`number`&&(o.bandwidthEstKbps=t.bandwidthKbps),typeof t.levelHeight==`number`&&(o.renditionHeight=t.levelHeight),typeof t.renditionBitrateKbps==`number`&&(o.renditionBitrateKbps=t.renditionBitrateKbps),t.atLiveEdge===!0&&(o.atLiveEdge=!0),typeof t.bufferedMs==`number`&&t.bufferedMs>0&&(o.bufferedMs=Math.round(t.bufferedMs)),o.playerState=Lg[t.state]??`PLAYER_STATE_UNSPECIFIED`;let d=this.mutedTotalMs;this.mutedSinceMs!==null&&(d+=e-this.mutedSinceMs),d>this.lastHbMutedMs&&(o.mutedMsDelta=Math.round(d-this.lastHbMutedMs)),this.lastHbMutedMs=d;let f=t.upshifts??0;f>this.lastUpshifts&&(o.upshiftsDelta=f-this.lastUpshifts),this.lastUpshifts=f;let p=t.downshifts??0;p>this.lastDownshifts&&(o.downshiftsDelta=p-this.lastDownshifts),this.lastDownshifts=p;let m=t.decodedFrames??0;m>this.lastDecoded&&(o.decodedFramesDelta=m-this.lastDecoded),this.lastDecoded=m;let h=t.requestErrors??0;h>this.lastRequestErrors&&(o.requestErrorsDelta=h-this.lastRequestErrors),this.lastRequestErrors=h;let g=t.requestCount??0,_=g-this.lastRequestCount;if(this.lastRequestCount=g,_>0){o.requestCountDelta=_;let e=t.requestTimesMs??[],n=e.slice(Math.max(0,e.length-_)).sort((e,t)=>e-t);n.length>0&&(o.requestTimeP50Ms=wh(n,50),o.requestTimeP95Ms=wh(n,95))}typeof t.latencySeconds==`number`&&typeof t.targetLatencySeconds==`number`&&(o.driftMs=Math.round((t.latencySeconds-t.targetLatencySeconds)*1e3)),typeof t.playbackRate==`number`&&t.playbackRate>0&&(o.playbackRate=t.playbackRate),t.qualityPinned===!0&&(o.qualityPinned=!0),t.cdnHost&&(o.cdnHost=t.cdnHost),this.maybeEmitMediaInfo(t),this.enqueue({heartbeat:o}),this.flush(),s>0&&this.noteFirstBytes()}maybeEmitMediaInfo(e){if(!(e.videoCodec??e.keySystem??e.ladderHeights))return;let t={};e.videoCodec&&(t.videoCodec=e.videoCodec),e.audioCodec&&(t.audioCodec=e.audioCodec),e.keySystem&&(t.keySystem=Fg[e.keySystem]),e.drmSecurityLevel&&(t.drmSecurityLevel=e.drmSecurityLevel),e.ladderHeights?.length&&(t.ladderHeights=e.ladderHeights),e.ladderTopBitrateKbps&&(t.ladderTopBitrateKbps=e.ladderTopBitrateKbps),e.lowLatency&&(t.lowLatency=!0);let n=JSON.stringify(t);n!==this.mediaInfoSignature&&(this.mediaInfoSignature=n,this.enqueue({mediaInfo:t}))}end(e,t){if(this.endedFlag)return;this.endedFlag=!0,Hg.delete(this);let n=t??this.now();this.playingSinceMs!==null&&(this.playingTotalMs+=n-this.playingSinceMs,this.playingSinceMs=null),this.hiddenSinceMs!==null&&(this.hiddenTotalMs+=n-this.hiddenSinceMs,this.hiddenSinceMs=null),this.bufferingSinceMs!==null&&(this.rebufferTotalMs+=n-this.bufferingSinceMs,this.bufferingSinceMs=null),this.mutedSinceMs!==null&&(this.mutedTotalMs+=n-this.mutedSinceMs,this.mutedSinceMs=null),this.waitingSinceMs!==null&&(this.waitingTotalMs+=n-this.waitingSinceMs,this.waitingSinceMs=null),this.isPlaying=!1,this.syncActive(n),this.closePresentation(n),this.firstFlushTimer&&=(clearTimeout(this.firstFlushTimer),null),this.timer&&=(clearInterval(this.timer),null),this.idleTimer&&=(clearTimeout(this.idleTimer),null),typeof window<`u`&&window.removeEventListener(`pagehide`,this.onPagehide),typeof document<`u`&&(document.removeEventListener(`visibilitychange`,this.onVisibility),document.removeEventListener(`freeze`,this.onFreeze),document.removeEventListener(`resume`,this.onResume));let r=this.safeSample();r&&this.maybeEmitMediaInfo(r);let i={reason:e},a=r?.bytesLoaded??this.lastBytes;a>0&&(i.bytesDownloadedTotal=a),this.playingTotalMs>0&&(i.watchTimeMs=Math.round(this.playingTotalMs)),this.rebufferCount>0&&(i.rebufferCount=this.rebufferCount),this.rebufferTotalMs>0&&(i.rebufferTimeMs=Math.round(this.rebufferTotalMs)),this.startupTimeMs>0&&(i.startupTimeMs=Math.round(this.startupTimeMs)),this.manifestLoadMs>0&&(i.manifestLoadMs=Math.round(this.manifestLoadMs)),this.firstPlaylistMs>0&&(i.firstPlaylistMs=Math.round(this.firstPlaylistMs)),this.firstFragLoadMs>0&&(i.firstFragLoadMs=Math.round(this.firstFragLoadMs)),this.drmSetupMs>0&&(i.drmSetupMs=Math.round(this.drmSetupMs));let o=r?.licenseTimeMs??0;o>0&&(i.licenseTimeMs=Math.round(o));let s=r?.droppedFrames??this.lastDropped;s>0&&(i.droppedFramesTotal=s),this.errorCount>0&&(i.errorCount=this.errorCount),this.hiddenTotalMs>0&&(i.hiddenTimeMs=Math.round(this.hiddenTotalMs)),this.seekCount>0&&(i.seekCount=this.seekCount),this.pauseCount>0&&(i.pauseCount=this.pauseCount),this.firstAudioMs>0&&(i.firstAudioMs=Math.round(this.firstAudioMs)),this.waitingTotalMs>0&&(i.waitingForLiveMs=Math.round(this.waitingTotalMs)),this.timeToFirstStallMs>0&&(i.timeToFirstStallMs=Math.round(this.timeToFirstStallMs));let c=r?.positionMs??0;c>0&&(i.exitPositionMs=Math.round(c)),this.activeTotalMs>0&&(i.activeWatchTimeMs=Math.round(this.activeTotalMs)),this.mutedTotalMs>0&&(i.mutedTimeMs=Math.round(this.mutedTotalMs));let l=e!==`END_REASON_ENDED`;l&&this.lastStallMs>0&&n-this.lastStallMs<=Mg&&(i.abandonAfterStallMs=Math.max(Ag,Math.round(n-this.lastStallMs))),l&&this.lastErrorMs>0&&n-this.lastErrorMs<=Mg&&(i.abandonAfterErrorMs=Math.max(Ag,Math.round(n-this.lastErrorMs))),this.fullscreenTotalMs>0&&(i.fullscreenTimeMs=Math.round(this.fullscreenTotalMs)),this.pipTotalMs>0&&(i.pipTimeMs=Math.round(this.pipTotalMs)),this.volumeChanges>0&&(i.volumeChanges=this.volumeChanges),this.muteChanges>0&&(i.muteChanges=this.muteChanges);let u=r?.decodedFrames??this.lastDecoded;u>0&&(i.decodedFramesTotal=u),e===`END_REASON_STOPPED`&&this.startupTimeMs===0&&this.lastErrorStage===null&&(e=`END_REASON_ABORTED`,i.reason=e),this.startupTimeMs===0&&e!==`END_REASON_ABORTED`&&(i.failedStage=this.lastErrorStage??(this.manifestLoadMs===0?`ERROR_STAGE_MANIFEST`:this.firstFragLoadMs===0?`ERROR_STAGE_FIRST_SEGMENT`:`ERROR_STAGE_OTHER`)),this.pending.push(this.wrap({sessionEnd:i})),this.flush(e===`END_REASON_PAGEHIDE`)}safeSample(){try{return this.opts.sample()}catch{return null}}wrap(e){return this.seq+=1,{sid:this.opts.sid,clientTime:new Date(this.now()).toISOString(),seq:this.seq,...e}}noteCspBlocked(){this.cspBlockedNoted||this.endedFlag||!this.cspBlocked()||(this.cspBlockedNoted=!0,this.opts.onBlocked?.(Ug(new URL(this.url).origin)))}cspBlocked(){return!!this.cspKey&&Vg.has(this.cspKey)}enqueue(e){if(!this.cspBlocked())for(this.pending.push(this.wrap(e));this.pending.length>kg;){let e=this.pending.findIndex(e=>e.heartbeat||e.stateChange);this.pending.splice(e>=0?e:0,1)}}flush(e=!1){if(this.firstFlushTimer&&=(clearTimeout(this.firstFlushTimer),null),this.pendingStart=null,this.pending.length===0)return;if(this.cspBlocked()){this.pending=[];return}let t=JSON.stringify({beacons:this.pending});if(this.pending=[],e){let e=this.opts.sendBeacon??(typeof navigator<`u`&&navigator.sendBeacon?navigator.sendBeacon.bind(navigator):void 0);if(e&&e(this.url,t))return}let n=this.opts.fetchFn??(typeof fetch<`u`?fetch:void 0);n&&n(this.url,{method:`POST`,headers:{"content-type":`application/json`},body:t,keepalive:!0}).catch(()=>{})}};function Jg(){if(typeof window>`u`)return{integration:`INTEGRATION_KIND_SDK`};let e;try{e=window.top!==window.self}catch{e=!0}let t=window.location?.origin;if(!e)return{host:t&&t!==`null`?t:void 0,integration:`INTEGRATION_KIND_SDK`};let n;try{let e=window.location.ancestorOrigins;e&&e.length>0&&(n=e[e.length-1]??void 0),!n&&typeof document<`u`&&document.referrer&&(n=new URL(document.referrer).origin)}catch{n=void 0}return n===`null`&&(n=void 0),{host:n,integration:`INTEGRATION_KIND_IFRAME`}}function Yg(){if(typeof navigator>`u`)return`DEVICE_CLASS_OTHER`;let e=navigator.userAgentData,t=e?.platform??``;if(/tv|tizen|webos/i.test(t))return`DEVICE_CLASS_TV`;let n=typeof screen<`u`?Math.min(screen.width,screen.height):0;return e?.mobile??(typeof navigator.maxTouchPoints==`number`&&navigator.maxTouchPoints>1&&n>0&&n<900)?n>=600?`DEVICE_CLASS_TABLET`:`DEVICE_CLASS_PHONE`:e||n>=900||/mac|win|linux|chrome os/i.test(t)?`DEVICE_CLASS_DESKTOP`:`DEVICE_CLASS_OTHER`}function Xg(){let e=typeof navigator<`u`?navigator.connection:void 0;if(!e)return{connectionType:`CONNECTION_TYPE_UNKNOWN`};let t={wifi:`CONNECTION_TYPE_WIFI`,cellular:`CONNECTION_TYPE_CELLULAR`,ethernet:`CONNECTION_TYPE_ETHERNET`},n={"slow-2g":`RADIO_ACCESS_ESTIMATED_SLOW_2G`,"2g":`RADIO_ACCESS_ESTIMATED_2G`,"3g":`RADIO_ACCESS_ESTIMATED_3G`,"4g":`RADIO_ACCESS_ESTIMATED_4G`},r=(e,t)=>Object.prototype.hasOwnProperty.call(e,t)?e[t]:void 0,i={connectionType:e.type?r(t,e.type)??`CONNECTION_TYPE_OTHER`:`CONNECTION_TYPE_UNKNOWN`};if(e.effectiveType){let t=r(n,e.effectiveType);t&&(i.radioAccess=t)}return typeof e.downlink==`number`&&e.downlink>0&&(i.downlinkKbps=Math.round(e.downlink*1e3)),typeof e.rtt==`number`&&e.rtt>0&&(i.rttMs=Math.round(e.rtt)),e.saveData&&(i.saveData=!0),i}function Zg(e){let t=Jg(),n={deviceClass:Yg(),integration:t.integration,...Xg()};t.host&&(n.host=t.host),typeof screen<`u`&&screen.width>0&&(n.screenWidth=screen.width,n.screenHeight=screen.height),typeof window<`u`&&window.devicePixelRatio>0&&(n.devicePixelRatio=Math.round(window.devicePixelRatio*100)/100);let r=e.getBoundingClientRect?.();return r&&r.width>0&&(n.viewportWidth=Math.round(r.width),n.viewportHeight=Math.round(r.height)),n}async function Qg(){let e=typeof navigator<`u`?navigator.userAgentData:void 0;if(!e?.getHighEntropyValues)return{};try{let t=await e.getHighEntropyValues([`model`,`platformVersion`]),n={};return t.model&&(n.deviceModel=t.model),t.platformVersion&&(n.osVersion=t.platformVersion),n}catch{return{}}}var $g=`2.24.0`,e_={accent:`#E1B600`,accentText:`#1B1C23`,background:`#0e0f13`,surface:`#1B1C23`,surfaceMuted:`#2a2c36`,text:`#ffffff`,textMuted:`#9aa0ad`,border:`rgba(255, 255, 255, 0.1)`,radius:`8px`,fontFamily:`ui-sans-serif, system-ui, -apple-system, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif`},t_={accent:`--havik-accent`,accentText:`--havik-accent-text`,background:`--havik-bg`,surface:`--havik-surface`,surfaceMuted:`--havik-surface-muted`,text:`--havik-text`,textMuted:`--havik-text-muted`,border:`--havik-border`,radius:`--havik-radius`,fontFamily:`--havik-font`};function n_(e,t){let n={...e_,...t};for(let t of Object.keys(t_))e.style.setProperty(t_[t],n[t]);n.logoUrl&&e.style.setProperty(`--havik-logo`,`url("${n.logoUrl}")`)}var r_=`havik-player-styles`,i_=`
|
|
47
47
|
.havik-player{position:relative;display:block;width:100%;background:var(--havik-bg,#0e0f13);
|
|
48
48
|
color:var(--havik-text,#fff);font-family:var(--havik-font,system-ui,sans-serif);
|
|
49
49
|
overflow:hidden;line-height:1.4;-webkit-tap-highlight-color:transparent}
|
|
@@ -171,5 +171,5 @@ Schedule: ${a.map(e=>Ep(e))} pos: ${this.timelinePos}`),s.length&&this.log(`Remo
|
|
|
171
171
|
.havik-menu__item:hover{background:var(--havik-surface-muted,#2a2c36)}
|
|
172
172
|
.havik-menu__item[aria-checked="true"]{color:var(--havik-accent,#E1B600);font-weight:600}
|
|
173
173
|
.havik-menu__item[aria-checked="true"]::after{content:'✓'}
|
|
174
|
-
`,t_=new WeakMap;function n_(e=document,t){let n=e.querySelector(`style#${$g}`);if(n&&(!t||t_.get(n)===t))return;let r=e.createElement(`style`);r.id=$g,t&&(r.nonce=t,r.setAttribute(`nonce`,t)),r.textContent=e_,t_.set(r,t),n?n.replaceWith(r):e.head.appendChild(r)}var r_={play:`<path d="M8 5v14l11-7z"/>`,pause:`<path d="M6 5h4v14H6zM14 5h4v14h-4z"/>`,volumeHigh:`<path d="M3 10v4h4l5 5V5L7 10H3zm13.5 2a4.5 4.5 0 0 0-2.5-4v8a4.5 4.5 0 0 0 2.5-4zm-2.5-9v2.06A7 7 0 0 1 14 19v2a9 9 0 0 0 0-18z"/>`,volumeMute:`<path d="M3 10v4h4l5 5V5L7 10H3zm16.5 2 2.5-2.5-1.4-1.4L18 10.6 15.4 8 14 9.4l2.6 2.6L14 14.6l1.4 1.4 2.6-2.6 2.6 2.6 1.4-1.4z"/>`,cc:`<path d="M19 4H5a2 2 0 0 0-2 2v12a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2V6a2 2 0 0 0-2-2zM10 11H8.5v-.5h-2v3h2V13H10v1a1 1 0 0 1-1 1H6a1 1 0 0 1-1-1v-4a1 1 0 0 1 1-1h3a1 1 0 0 1 1 1v1zm7 0h-1.5v-.5h-2v3h2V13H17v1a1 1 0 0 1-1 1h-3a1 1 0 0 1-1-1v-4a1 1 0 0 1 1-1h3a1 1 0 0 1 1 1v1z"/>`,settings:`<path d="M19.14 12.94c.04-.3.06-.61.06-.94 0-.32-.02-.64-.07-.94l2.03-1.58c.18-.14.23-.41.12-.61l-1.92-3.32c-.12-.22-.37-.29-.59-.22l-2.39.96c-.5-.38-1.03-.7-1.62-.94l-.36-2.54c-.04-.24-.24-.41-.48-.41h-3.84c-.24 0-.43.17-.47.41l-.36 2.54c-.59.24-1.13.57-1.62.94l-2.39-.96c-.22-.08-.47 0-.59.22L2.74 8.87c-.12.21-.08.47.12.61l2.03 1.58c-.05.3-.09.63-.09.94s.02.64.07.94l-2.03 1.58c-.18.14-.23.41-.12.61l1.92 3.32c.12.22.37.29.59.22l2.39-.96c.5.38 1.03.7 1.62.94l.36 2.54c.05.24.24.41.48.41h3.84c.24 0 .44-.17.47-.41l.36-2.54c.59-.24 1.13-.56 1.62-.94l2.39.96c.22.08.47 0 .59-.22l1.92-3.32c.11-.2.06-.47-.12-.61l-2.01-1.58zM12 15.6c-1.98 0-3.6-1.62-3.6-3.6s1.62-3.6 3.6-3.6 3.6 1.62 3.6 3.6-1.62 3.6-3.6 3.6z"/>`,pip:`<path d="M19 7h-8v6h8V7zm4 12V5a2 2 0 0 0-2-2H3a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h18a2 2 0 0 0 2-2zm-2 .02H3V4.98h18v14.04z"/>`,fullscreen:`<path d="M7 14H5v5h5v-2H7v-3zm-2-4h2V7h3V5H5v5zm12 7h-3v2h5v-5h-2v3zM14 5v2h3v3h2V5h-5z"/>`,fullscreenExit:`<path d="M5 16h3v3h2v-5H5v2zm3-8H5v2h5V5H8v3zm6 11h2v-3h3v-2h-5v5zm2-11V5h-2v5h5V8h-3z"/>`,liveDot:`<circle cx="12" cy="12" r="6"/>`,retry:`<path d="M17.65 6.35A8 8 0 1 0 19.73 13h-2.08A6 6 0 1 1 12 6c1.66 0 3.14.69 4.22 1.78L13 11h7V4l-2.35 2.35z"/>`};function i_(e){return`<svg viewBox="0 0 24 24" aria-hidden="true" focusable="false" fill="currentColor">${r_[e]}</svg>`}var a_=3e3,o_=250,s_=new Set([`GONE`,`NOT_FOUND`,`GEO_DENIED`,`INVALID_URN`,`UNAUTHORIZED`,`DRM_DEVICE_REVOKED`]);function c_(e){let t=`This match isn't available in your country`;return e?`${t} (${e})`:t}var l_=`This device can't play protected video`;function u_(e){return new d_(e)}var d_=class{constructor(e){i(this,`root`,void 0),i(this,`video`,void 0),i(this,`player`,void 0),i(this,`doc`,void 0),i(this,`autoHideMs`,void 0),i(this,`overlay`,void 0),i(this,`center`,void 0),i(this,`spinner`,void 0),i(this,`bar`,void 0),i(this,`gradient`,void 0),i(this,`seek`,void 0),i(this,`seekBuffered`,void 0),i(this,`seekPlayed`,void 0),i(this,`seekThumb`,void 0),i(this,`playBtn`,void 0),i(this,`muteBtn`,void 0),i(this,`volSlider`,void 0),i(this,`live`,void 0),i(this,`liveGo`,void 0),i(this,`time`,void 0),i(this,`ccBtn`,void 0),i(this,`audioBtn`,void 0),i(this,`qualityBtn`,void 0),i(this,`pipBtn`,void 0),i(this,`fsBtn`,void 0),i(this,`menu`,void 0),i(this,`statusBox`,null),i(this,`statusKind`,null),i(this,`statusMsg`,null),i(this,`hasPlayed`,!1),i(this,`fsSupported`,!0),i(this,`lastError`,null),i(this,`logoUrl`,void 0),i(this,`statusOverlays`,void 0),i(this,`streamEnded`,void 0),i(this,`endedMessage`,void 0),i(this,`interruptedMessage`,void 0),i(this,`errorMessage`,void 0),i(this,`hideTimer`,void 0),i(this,`tapTimer`,void 0),i(this,`surfacePointerType`,``),i(this,`surfaceWasHidden`,!1),i(this,`pointerClosedMenu`,!1),i(this,`openMenu`,null),i(this,`scrubbing`,!1),i(this,`offFns`,[]),this.root=e.root,this.video=e.video,this.player=e.player,this.doc=e.root.ownerDocument??document,this.autoHideMs=e.autoHideMs??a_,this.logoUrl=e.logoUrl,this.statusOverlays=e.statusOverlays!==!1,this.streamEnded=e.streamEnded??(()=>!1),this.endedMessage=e.endedMessage??`This stream has ended`,this.interruptedMessage=e.interruptedMessage??`Reconnecting — please stand by`,this.errorMessage=e.errorMessage,n_(this.doc,e.cspNonce),this.root.classList.add(`havik-player`),this.root.hasAttribute(`tabindex`)||(this.root.tabIndex=0),this.root.setAttribute(`role`,`region`),this.root.setAttribute(`aria-label`,`Video player`);let t=(e,t,n)=>{let r=this.doc.createElement(e);if(r.className=t,n)for(let[e,t]of Object.entries(n))r.setAttribute(e,t);return r},n=(e,n,r)=>{let i=t(`button`,e,{type:`button`,"aria-label":r,title:r});return i.innerHTML=i_(n),i};this.overlay=t(`div`,`havik-overlay`),this.center=t(`button`,`havik-center`,{type:`button`,"aria-label":`Play`}),this.center.innerHTML=i_(`play`),this.spinner=t(`div`,`havik-spinner`),this.spinner.style.display=`none`,this.overlay.append(this.center,this.spinner),this.gradient=t(`div`,`havik-gradient`),this.bar=t(`div`,`havik-bar`),this.seek=t(`div`,`havik-seek`,{role:`slider`,"aria-label":`Seek`,"aria-valuemin":`0`,"aria-valuemax":`100`,tabindex:`0`});let r=t(`div`,`havik-seek__track`);this.seekBuffered=t(`div`,`havik-seek__buffered`),this.seekPlayed=t(`div`,`havik-seek__played`),this.seekThumb=t(`div`,`havik-seek__thumb`),r.append(this.seekBuffered,this.seekPlayed,this.seekThumb),this.seek.append(r);let a=t(`div`,`havik-controls`);this.playBtn=n(`havik-btn`,`play`,`Play`),this.muteBtn=n(`havik-btn`,`volumeHigh`,`Mute`),this.volSlider=t(`input`,`havik-vol__slider`,{type:`range`,min:`0`,max:`1`,step:`0.05`,"aria-label":`Volume`});let o=t(`div`,`havik-vol`);o.append(this.muteBtn,this.volSlider),this.live=t(`div`,`havik-live`),this.live.innerHTML=i_(`liveDot`);let s=this.doc.createElement(`span`);s.textContent=`LIVE`,this.liveGo=t(`button`,`havik-live__go`,{type:`button`}),this.liveGo.textContent=`Go live`,this.live.append(s,this.liveGo),this.time=t(`div`,`havik-time`),this.time.textContent=`0:00`,this.time.style.display=`none`;let c=t(`div`,`havik-spacer`);if(this.ccBtn=n(`havik-btn`,`cc`,`Subtitles`),this.audioBtn=n(`havik-btn`,`settings`,`Audio track`),this.qualityBtn=n(`havik-btn`,`settings`,`Quality`),this.pipBtn=n(`havik-btn`,`pip`,`Picture in picture`),this.fsBtn=n(`havik-btn`,`fullscreen`,`Fullscreen`),this.ccBtn.style.display=`none`,this.audioBtn.style.display=`none`,this.qualityBtn.style.display=`none`,this.pipSupported()||(this.pipBtn.style.display=`none`),this.syncFullscreenSupport(),a.append(this.playBtn,o,this.live,this.time,c,this.ccBtn,this.audioBtn,this.qualityBtn,this.pipBtn,this.fsBtn),this.bar.append(this.seek,a),this.menu=t(`div`,`havik-menu`,{role:`menu`}),this.menu.hidden=!0,this.root.append(this.gradient,this.overlay,this.bar,this.menu),e.logoUrl){let n=t(`div`,`havik-watermark`);n.style.backgroundImage=`url("${e.logoUrl}")`,this.root.append(n)}this.wire(),this.syncPlayPause(),this.syncVolume(),this.scheduleHide()}on(e,t,n,r){e.addEventListener(t,n,r),this.offFns.push(()=>e.removeEventListener(t,n,r))}wire(){let e=this.video;this.on(this.playBtn,`click`,()=>this.togglePlay()),this.on(this.center,`click`,()=>this.togglePlay()),this.on(this.overlay,`pointerdown`,e=>{this.surfacePointerType=e.pointerType??``,this.surfaceWasHidden=this.root.classList.contains(`havik-hide`)}),this.on(this.overlay,`click`,e=>{e.target===this.overlay&&this.onSurfaceClick()}),this.on(this.muteBtn,`click`,()=>this.player.setMuted(!e.muted)),this.on(this.volSlider,`input`,()=>{let t=Number(this.volSlider.value);this.setVolumeFill(t),this.player.setVolume(t),t>0&&e.muted&&this.player.setMuted(!1)}),this.on(this.liveGo,`click`,()=>this.player.seekToLive()),this.on(this.pipBtn,`click`,()=>void this.togglePip()),this.on(this.fsBtn,`click`,()=>void this.toggleFullscreen()),this.on(this.ccBtn,`click`,()=>this.toggleMenu(`cc`)),this.on(this.audioBtn,`click`,()=>this.toggleMenu(`audio`)),this.on(this.qualityBtn,`click`,()=>this.toggleMenu(`quality`)),this.on(this.seek,`pointerdown`,e=>this.onSeekDown(e)),this.on(this.seek,`keydown`,e=>this.onSeekKey(e)),this.on(e,`play`,()=>this.syncPlayPause()),this.on(e,`pause`,()=>this.syncPlayPause()),this.on(e,`volumechange`,()=>this.syncVolume()),this.on(e,`timeupdate`,()=>this.syncProgress()),this.on(e,`progress`,()=>this.syncProgress()),this.on(e,`durationchange`,()=>this.syncProgress()),this.on(e,`loadedmetadata`,()=>this.syncFullscreenSupport()),this.offFns.push(this.player.on(`statechange`,()=>this.syncState())),this.offFns.push(this.player.on(`ended`,()=>this.syncState())),this.offFns.push(this.player.on(`ready`,()=>this.refreshTracks())),this.offFns.push(this.player.on(`qualitychange`,()=>this.onTracksChanged())),this.offFns.push(this.player.on(`audiotrackchange`,()=>this.onTracksChanged())),this.offFns.push(this.player.on(`texttrackchange`,()=>this.onTracksChanged())),this.offFns.push(this.player.on(`pipchange`,e=>this.syncPip(e))),this.offFns.push(this.player.on(`stats`,()=>this.syncLive())),this.offFns.push(this.player.on(`error`,e=>{this.lastError=e,this.statusKind=null,this.syncState()}));let t=e=>e.pointerType!==`touch`;this.on(this.root,`pointermove`,e=>{t(e)&&this.poke()}),this.on(this.root,`pointerleave`,e=>{t(e)&&this.scheduleHide(0)}),this.on(this.root,`focusin`,()=>this.poke()),this.on(this.root,`keydown`,e=>this.onKey(e)),this.on(this.doc,`pointerdown`,e=>this.onDocPointer(e),{capture:!0}),this.on(this.doc,`fullscreenchange`,()=>this.syncFullscreen()),this.on(this.doc,`webkitfullscreenchange`,()=>this.syncFullscreen()),this.on(e,`webkitbeginfullscreen`,()=>this.syncFullscreen()),this.on(e,`webkitendfullscreen`,()=>this.syncFullscreen()),this.syncState()}togglePlay(){this.video.paused||this.video.ended?this.player.play():this.player.pause()}onSurfaceClick(){let e=this.surfacePointerType===`touch`;if(this.surfacePointerType=``,!e){this.tapTimer&&clearTimeout(this.tapTimer),this.tapTimer=void 0,this.togglePlay();return}if(this.pointerClosedMenu){this.tapTimer&&clearTimeout(this.tapTimer),this.tapTimer=void 0,this.poke();return}if(this.tapTimer){clearTimeout(this.tapTimer),this.tapTimer=void 0,this.togglePlay();return}let t=this.surfaceWasHidden;this.tapTimer=setTimeout(()=>{this.tapTimer=void 0,this.toggleBar(t)},o_)}toggleBar(e){e?this.poke():this.hideIfIdle()}syncPlayPause(){let e=!this.video.paused&&!this.video.ended;this.setIcon(this.playBtn,e?`pause`:`play`),this.playBtn.setAttribute(`aria-label`,e?`Pause`:`Play`),this.setIcon(this.center,e?`pause`:`play`),this.center.classList.toggle(`havik-gone`,e||!!this.statusBox),e?this.scheduleHide():this.show()}syncState(){let e=this.player.state;(e===`playing`||e===`buffering`)&&(this.hasPlayed=!0),this.syncStatus(e);let t=e===`loading`||e===`buffering`;this.spinner.style.display=t&&!this.statusBox?``:`none`,(t||this.statusBox)&&this.center.classList.add(`havik-gone`),this.syncLive()}syncStatus(e){let t=null;this.statusOverlays&&(e===`ended`?t=`ended`:e===`error`?t=`error`:e===`waiting`?t=`waiting`:!this.hasPlayed&&(e===`idle`||e===`paused`)&&(t=`preplay`)),this.renderStatus(t)}statusMessageFor(e){return e===`ended`?this.player.endedReason===`interrupted`?this.interruptedMessage:this.endedMessage:e===`waiting`?this.hasPlayed?`Reconnecting — please stand by`:`Starting soon…`:e===`error`?this.errorMessage===void 0?this.lastError?.code===`GEO_DENIED`?c_(this.lastError.country):this.lastError?.code===`DRM_DEVICE_REVOKED`?l_:this.lastError?.message??`Playback unavailable`:this.errorMessage:null}renderStatus(e){let t=this.statusMessageFor(e);if(e===this.statusKind&&t===this.statusMsg||(this.statusKind=e,this.statusMsg=t,this.statusBox?.remove(),this.statusBox=null,this.root.classList.toggle(`havik-has-status`,!!e),!e))return;let n=this.doc.createElement(`div`);if(n.className=`havik-status havik-status--${e}`,this.logoUrl){let e=this.doc.createElement(`div`);e.className=`havik-status__logo`,n.append(e)}if(e===`preplay`){let e=this.doc.createElement(`button`);e.type=`button`,e.className=`havik-status__btn havik-status__btn--play`,e.setAttribute(`aria-label`,`Play`),e.innerHTML=i_(`play`),e.addEventListener(`click`,()=>void this.player.play()),n.append(e)}else{let r=this.doc.createElement(`div`);if(r.className=`havik-status__msg`,r.textContent=t??``,n.append(r),e===`error`&&this.lastError&&!s_.has(this.lastError.code)){let e=this.doc.createElement(`button`);e.type=`button`,e.className=`havik-status__btn`,e.innerHTML=`${i_(`retry`)}<span>Retry</span>`,e.addEventListener(`click`,()=>void this.player.retry()),n.append(e)}}this.root.append(n),this.statusBox=n,this.show()}syncVolume(){let e=this.video,t=e.muted||e.volume===0;this.setIcon(this.muteBtn,t?`volumeMute`:`volumeHigh`),this.muteBtn.setAttribute(`aria-label`,t?`Unmute`:`Mute`);let n=t?0:e.volume;this.volSlider.value=String(n),this.setVolumeFill(n)}setVolumeFill(e){this.volSlider.style.setProperty(`--havik-vol`,String(Math.min(1,Math.max(0,e))))}seekableRange(){let e=this.video,t,n;if(e.seekable&&e.seekable.length>0)t=e.seekable.start(0),n=e.seekable.end(e.seekable.length-1);else if(Number.isFinite(e.duration)&&e.duration>0)t=0,n=e.duration;else return null;let r=this.player.getStats();return r.isLive!==!1&&r.targetLatencySeconds&&r.targetLatencySeconds>0&&(n=Math.max(t,n-r.targetLatencySeconds)),n>t?{start:t,end:n}:null}syncProgress(){if(this.scrubbing)return;let e=this.seekableRange();if(!e){this.seekPlayed.style.width=`100%`;return}let t=e.end-e.start,n=Math.min(1,Math.max(0,(this.video.currentTime-e.start)/t));this.seekPlayed.style.width=`${(n*100).toFixed(2)}%`,this.seekThumb.style.left=`${(n*100).toFixed(2)}%`,this.seek.setAttribute(`aria-valuenow`,String(Math.round(n*100)));let r=this.video.buffered;if(r&&r.length>0){let n=r.end(r.length-1),i=Math.min(1,Math.max(0,(n-e.start)/t));this.seekBuffered.style.width=`${(i*100).toFixed(2)}%`}!this.player.getStats().isLive&&Number.isFinite(this.video.duration)&&(this.time.textContent=`${f_(this.video.currentTime)} / ${f_(this.video.duration)}`)}syncLive(){let e=this.player.getStats(),t=e.isLive!==!1,n=this.player.state===`ended`,r=!t&&!this.streamEnded();this.live.style.display=t&&!n?``:`none`,this.time.style.display=r?``:`none`,this.seek.style.display=r?``:`none`,this.live.classList.toggle(`is-live`,e.atLiveEdge!==!1&&t)}onSeekDown(e){let t=this.seekableRange();if(!t)return;e.preventDefault(),this.scrubbing=!0;let n=e=>this.seekToPointer(e,t),r=()=>{this.scrubbing=!1,this.doc.removeEventListener(`pointermove`,n),this.doc.removeEventListener(`pointerup`,r)};this.doc.addEventListener(`pointermove`,n),this.doc.addEventListener(`pointerup`,r),this.seekToPointer(e,t)}seekToPointer(e,t){let n=this.seek.getBoundingClientRect(),r=n.width>0?Math.min(1,Math.max(0,(e.clientX-n.left)/n.width)):0;this.seekPlayed.style.width=`${(r*100).toFixed(2)}%`,this.seekThumb.style.left=`${(r*100).toFixed(2)}%`,this.video.currentTime=t.start+r*(t.end-t.start)}onSeekKey(e){e.key===`ArrowLeft`?(this.nudge(-5),e.preventDefault()):e.key===`ArrowRight`&&(this.nudge(5),e.preventDefault())}nudge(e){let t=this.seekableRange();t&&(this.video.currentTime=Math.min(t.end,Math.max(t.start,this.video.currentTime+e)))}toggleMenu(e){if(this.openMenu===e){this.closeMenu();return}this.openMenu=e,this.renderMenu(e),this.menu.hidden=!1,this.show()}closeMenu(){this.openMenu=null,this.menu.hidden=!0,this.menu.replaceChildren()}renderMenu(e){e===`quality`?this.renderQualityMenu():e===`audio`?this.renderAudioMenu():this.renderCcMenu()}menuItem(e,t,n){let r=this.doc.createElement(`button`);r.type=`button`,r.className=`havik-menu__item`,r.setAttribute(`role`,`menuitemradio`),r.setAttribute(`aria-checked`,t?`true`:`false`);let i=this.doc.createElement(`span`);return i.textContent=e,r.append(i),r.addEventListener(`click`,()=>{n(),this.closeMenu()}),r}renderQualityMenu(){let e=this.player.getQualityLevels(),t=this.player.getCurrentQuality(),n=this.doc.createElement(`div`);n.className=`havik-menu__title`,n.textContent=`Quality`,this.menu.replaceChildren(n,this.menuItem(`Auto`,t===-1,()=>this.player.setQuality(`auto`)));for(let n of e)this.menu.append(this.menuItem(p_(n),t===n.index,()=>this.player.setQuality(n.index)))}renderAudioMenu(){let e=this.player.getAudioTracks(),t=this.doc.createElement(`div`);t.className=`havik-menu__title`,t.textContent=`Audio`,this.menu.replaceChildren(t);for(let t of e)this.menu.append(this.menuItem(m_(t),t.default,()=>this.player.setAudioTrack(t.id)))}renderCcMenu(){let e=this.player.getTextTracks(),t=this.doc.createElement(`div`);t.className=`havik-menu__title`,t.textContent=`Subtitles`,this.menu.replaceChildren(t,this.menuItem(`Off`,!1,()=>this.player.setTextTrack(-1)));for(let t of e)this.menu.append(this.menuItem(h_(t),!1,()=>this.player.setTextTrack(t.id)))}onTracksChanged(){this.openMenu&&this.renderMenu(this.openMenu)}refreshTracks(){let e=this.player.getQualityLevels(),t=this.player.getAudioTracks(),n=this.player.getTextTracks();this.qualityBtn.style.display=e.length>1?``:`none`,this.audioBtn.style.display=t.length>1?``:`none`,this.ccBtn.style.display=n.length>0?``:`none`,this.onTracksChanged()}pipSupported(){return`pictureInPictureEnabled`in this.doc&&typeof this.video.requestPictureInPicture==`function`}async togglePip(){this.doc.pictureInPictureElement===this.video?await this.player.exitPictureInPicture():await this.player.enterPictureInPicture()}syncPip(e){this.pipBtn.setAttribute(`aria-pressed`,e?`true`:`false`)}async toggleFullscreen(){try{le(this.video,this.root)?await fe(this.video,this.root):await de(this.video,this.root)}catch{}}syncFullscreenSupport(){this.fsSupported=ue(this.video,this.root),this.fsBtn.style.display=this.fsSupported?``:`none`}syncFullscreen(){let e=le(this.video,this.root);this.setIcon(this.fsBtn,e?`fullscreenExit`:`fullscreen`),this.fsBtn.setAttribute(`aria-label`,e?`Exit fullscreen`:`Fullscreen`)}poke(){this.show(),this.scheduleHide()}show(){this.root.classList.remove(`havik-hide`)}scheduleHide(e=this.autoHideMs){this.hideTimer&&clearTimeout(this.hideTimer),this.hideTimer=setTimeout(()=>this.hideIfIdle(),e)}hideIfIdle(){!this.video.paused&&!this.video.ended&&!this.openMenu&&!this.statusBox&&this.root.classList.add(`havik-hide`)}onDocPointer(e){this.pointerClosedMenu=!1,this.openMenu&&!this.menu.contains(e.target)&&([this.qualityBtn,this.audioBtn,this.ccBtn].some(t=>t.contains(e.target))||(this.closeMenu(),this.pointerClosedMenu=!0))}onKey(e){let t=e.target;if(!(t&&t!==this.root&&t!==this.seek&&t.tagName===`INPUT`)){switch(e.key){case` `:case`k`:this.togglePlay();break;case`m`:this.player.setMuted(!this.video.muted);break;case`f`:if(!this.fsSupported)return;this.toggleFullscreen();break;case`c`:this.ccBtn.style.display!==`none`&&this.toggleMenu(`cc`);break;case`l`:this.player.seekToLive();break;case`ArrowUp`:this.player.setVolume(Math.min(1,this.video.volume+.1));break;case`ArrowDown`:this.player.setVolume(Math.max(0,this.video.volume-.1));break;case`ArrowLeft`:this.nudge(-5);break;case`ArrowRight`:this.nudge(5);break;default:return}this.poke(),e.preventDefault()}}setIcon(e,t){e.innerHTML=i_(t)}destroy(){this.hideTimer&&clearTimeout(this.hideTimer),this.tapTimer&&clearTimeout(this.tapTimer);for(let e of this.offFns)try{e()}catch{}this.offFns.length=0,this.closeMenu(),this.statusBox?.remove();for(let e of[this.overlay,this.gradient,this.bar,this.menu])e.remove();this.root.classList.remove(`havik-player`,`havik-hide`,`havik-has-status`)}};function f_(e){(!Number.isFinite(e)||e<0)&&(e=0);let t=Math.floor(e%60),n=Math.floor(e/60%60),r=Math.floor(e/3600),i=r>0?String(n).padStart(2,`0`):String(n),a=String(t).padStart(2,`0`);return r>0?`${r}:${i}:${a}`:`${i}:${a}`}function p_(e){return e.height?`${e.height}p`:`${Math.round(e.bitrate/1e3)} kbps`}function m_(e){return e.name||e.lang||`Track ${e.id}`}function h_(e){return e.name||e.lang||`Track ${e.id}`}var g_=6e3,__=45e3,v_=2e3,y_=3,b_=5e3,x_=2e3,S_=48e4,C_=`keySystemLicenseRequestFailed`;function w_(e){if(e.env!==void 0&&e.baseUrl!==void 0)throw new a(`INTERNAL`,0,`createPlayer: pass env OR baseUrl, not both (got env=${JSON.stringify(e.env)} and baseUrl=${JSON.stringify(e.baseUrl)})`);if(e.env!==void 0)return ht(e.env);if(!e.baseUrl)throw new a(`INTERNAL`,0,`createPlayer: env or baseUrl is required (env: 'integration' | 'production')`);return e.baseUrl}async function T_(e){if(!e.video||typeof e.video.play!=`function`)throw new a(`INTERNAL`,0,`createPlayer: opts.video must be an HTMLVideoElement`);let t=w_(e);if(!e.matchUrn)throw new a(`INVALID_URN`,0,`createPlayer: matchUrn is required`);if(!e.credential)throw new a(`INTERNAL`,0,`createPlayer: credential is required`);let n=new E_({...e,baseUrl:t});return await n.start(),n}var E_=class{constructor(e){i(this,`opts`,void 0),i(this,`abort`,new AbortController),i(this,`listeners`,{}),i(this,`engine`,null),i(this,`controlBar`,null),i(this,`container`,null),i(this,`detachMedia`,void 0),i(this,`detachPip`,void 0),i(this,`detachEndedPlayGuard`,void 0),i(this,`statsTimer`,void 0),i(this,`refreshTimer`,void 0),i(this,`refreshInFlight`,void 0),i(this,`onRefocus`,void 0),i(this,`onReturnVisible`,null),i(this,`onReturnPageShow`,null),i(this,`hiddenAtMs`,null),i(this,`staleLicenseReloaded`,!1),i(this,`_state`,`idle`),i(this,`_descriptor`,null),i(this,`destroyed`,!1),i(this,`loadGen`,0),i(this,`liveStateSub`,null),i(this,`endedHandled`,!1),i(this,`_endedReason`,null),i(this,`rejoinTimer`,null),i(this,`armingSub`,null),i(this,`armSseTimer`,null),i(this,`armFallbackCtrl`,null),i(this,`_lastError`,null),i(this,`analyticsSession`,null),i(this,`detachMediaListeners`,void 0),i(this,`playRequested`,!1),i(this,`idleClosed`,!1),i(this,`pendingStartLoad`,!1),this.opts=e}get state(){return this._state}get descriptor(){return this._descriptor}get endedReason(){return this._endedReason}async start(){this.opts.muted&&(this.opts.video.muted=!0),this.opts.poster&&(this.opts.video.poster=this.opts.poster),this.mountControls(),this.attachPipListeners(),this.attachEndedPlayGuard(),this.setState(`loading`);let e=++this.loadGen,t=this.resolveOptions();try{let n=await ee(t);if(await this.onResolved(n,e),e===this.loadGen&&this._state===`error`&&this._lastError){let e=this._lastError;throw this.destroy(),e}}catch(t){if(this.opts.waitForLive&&t instanceof a&&u(t.code)){this.setState(`waiting`),this.beginArming(e,t.liveStartsAtMs);return}throw t}}resolveOptions(){return{baseUrl:this.opts.baseUrl,matchUrn:this.opts.matchUrn,credential:this.opts.credential,signal:this.abort.signal,apiHeaders:this.opts.apiHeaders}}beginArming(e,t,n=!1){let r=this.opts.liveStateEvents===!1?void 0:this.opts.eventsBaseUrl??we(this.opts.baseUrl);r?this.armWithSse(e,r,t,n):this.beginArmingByPolling(e)}beginArmingByPolling(e){te({...this.resolveOptions(),signal:this.abort.signal,waitForLive:this.buildWaitConfig(e)}).then(t=>{if(!(this.destroyed||this.abort.signal.aborted||e!==this.loadGen))return this.onResolved(t,e)}).catch(t=>{this.destroyed||this.abort.signal.aborted||e!==this.loadGen||this.fail(t instanceof a?t:new a(`INTERNAL`,0,String(t)))})}armWithSse(e,t,n,r=!1){let i=!1,o=!1,s=new AbortController;this.armFallbackCtrl=s,this.setState(`waiting`);let c=this.opts.waitForLive,l=c&&c!==!0?c.kickoffAt:void 0,d=typeof l==`number`?l:typeof l==`string`?Date.parse(l):NaN,f=n??(Number.isFinite(d)?d:void 0);setTimeout(()=>{i||this.destroyed||e!==this.loadGen||this.emit(`waiting`,{phase:r?`unavailable`:`tooEarly`,retryInMs:__,attempt:1,elapsedMs:0,...!r&&f!==void 0&&f>Date.now()?{ttkMs:f-Date.now()}:{}})},0);let p=()=>this.destroyed||this.abort.signal.aborted||e!==this.loadGen,m=async t=>{if(!(i||p())){i=!0,this.closeArming(),s.abort();try{await this.onResolved(t,e)}catch(e){if(p())return;this.fail(e instanceof a?e:new a(`INTERNAL`,0,String(e)))}}},h=()=>{i||o||p()||(o=!0,te({...this.resolveOptions(),signal:s.signal,waitForLive:this.buildWaitConfig(e)}).then(e=>m(e)).catch(e=>{i||p()||s.signal.aborted||(i=!0,this.closeArming(),this.fail(e instanceof a?e:new a(`INTERNAL`,0,String(e))))}))},g=()=>{i||p()||ee(this.resolveOptions()).then(e=>m(e)).catch(e=>{if(!(i||p())){if(e instanceof a&&u(e.code)){h();return}i=!0,this.closeArming(),s.abort(),this.fail(e instanceof a?e:new a(`INTERNAL`,0,String(e)))}})},_=e=>{this.armSseTimer&&clearTimeout(this.armSseTimer),this.armSseTimer=setTimeout(()=>{!i&&!p()&&h()},e)};_(g_),this.armingSub=Ce({eventsBaseUrl:t,matchUrn:this.opts.matchUrn,credential:this.opts.credential,onAlive:()=>_(__),onState:e=>{i||p()||(e.state===`live`||e.state===`gone`)&&setTimeout(g,Math.random()*v_)},onError:()=>h()})}closeArming(){this.armSseTimer&&=(clearTimeout(this.armSseTimer),null),this.armFallbackCtrl?.abort(),this.armFallbackCtrl=null,this.armingSub?.close(),this.armingSub=null}buildWaitConfig(e){let t=this.opts.waitForLive&&this.opts.waitForLive!==!0?this.opts.waitForLive:{};return{...t,onState:n=>{this.destroyed||e!==this.loadGen||(this.setState(`waiting`),this.emit(`waiting`,n),t.onState?.(n))}}}async onResolved(e,t){if(this.destroyed||t!==this.loadGen)return;this._descriptor=e,this.endedHandled=!1,this._endedReason=null;let n=await d(this.opts.credential);if(this.destroyed||t!==this.loadGen)return;this.setState(`loading`);let r=this.opts.autoplay===!1&&!this.playRequested,i=this.createEngine(e,n,r),a=Um(this.opts.video,e=>{this._state!==`ended`&&this._state!==`error`&&this.setState(e)});if(await i.load(),this.destroyed||t!==this.loadGen){a(),i.destroy();return}if(this._state===`error`){a(),i.destroy();return}this.engine=i,this.detachMedia=a,this.opts.maxBitrate!=null&&i.setMaxBitrate(this.opts.maxBitrate),this.startStats(),this.scheduleLicenseRefresh(),this.startLiveState(t),this.watchReturn(),this.startAnalytics(e,i,t),r&&(this.pendingStartLoad=!0,this.setState(`paused`),i.name===`native`&&setTimeout(()=>{this.destroyed||t!==this.loadGen||this.engine!==i||(this.analyticsSession?.noteReady(),this.emit(`ready`))},0))}onAnalyticsIdle(e){this.destroyed||this.engine!==e||(this.idleClosed=!0,this.pendingStartLoad=!1,e.stop())}startAnalytics(e,t,n){if(this.analyticsSession?.noteDestroyed(),this.analyticsSession=null,this.detachMediaListeners?.(),this.opts.analytics===!1)return;let r=e.analytics?.sid;if(!r)return;let i=typeof this.opts.analytics==`object`?this.opts.analytics.endpoint:void 0,{endpoint:o,disabledReason:s}=Hg(this.opts.baseUrl,i,e.analytics?.endpoint);if(!o){s&&setTimeout(()=>{this.destroyed||n!==this.loadGen||this.emit(`warning`,new a(`INTERNAL`,0,s))},0);return}let c=this.opts.video,l=new Ug({endpoint:o,sid:r,player:t.name===`native`?`PLAYER_SAFARI_NATIVE`:`PLAYER_HLSJS`,sdkVersion:Yg,environment:qg(c),idleMs:typeof this.opts.analytics==`object`?this.opts.analytics.idleMs:void 0,onIdle:()=>this.onAnalyticsIdle(t),onBlocked:e=>setTimeout(()=>{this.destroyed||n!==this.loadGen||this.emit(`warning`,new a(`INTERNAL`,0,e))},0),sample:()=>{let e=this.engine?.getStats()??Lm,t=c.buffered.length?Math.max(0,c.buffered.end(c.buffered.length-1)-c.currentTime):0;return{...e,bufferedMs:Math.round(t*1e3),state:this._state,positionMs:Math.round(c.currentTime*1e3),playbackRate:c.playbackRate}}});this.analyticsSession=l;let u=()=>l.noteSeek(),d=()=>l.noteVolume(c.muted,c.volume);c.addEventListener(`seeking`,u),c.addEventListener(`volumechange`,d),this.detachMediaListeners=()=>{c.removeEventListener(`seeking`,u),c.removeEventListener(`volumechange`,d)},l.start(),l.seedVolume(c.muted,c.volume),l.notePresentation(this.currentPresentation()),Jg().then(e=>l.noteEnvironment(e)),this.opts.autoplay===!1&&l.noteAutoplay(`AUTOPLAY_RESULT_NOT_ATTEMPTED`)}currentPresentation(){let e=this.opts.video;if(typeof document<`u`&&document.pictureInPictureElement===e)return`pip`;let t=typeof document<`u`?document.fullscreenElement:null;return e.webkitDisplayingFullscreen===!0||t&&(t===e||t.contains(e))?`fullscreen`:`inline`}createEngine(e,t,n=!1){let r={...this.opts.hlsConfig};this.opts.startLevel!=null&&(r.startLevel=this.opts.startLevel),this.opts.liveLatencyTarget!=null&&(r.liveSyncDuration=this.opts.liveLatencyTarget);let i={video:this.opts.video,descriptor:e,credential:t,deviceId:De(),userId:this.opts.userId,lowLatency:this.opts.lowLatency===void 0||this.opts.lowLatency===`auto`||this.opts.lowLatency,snapToLiveOnRefocus:this.opts.snapToLiveOnRefocus,rememberBandwidth:this.opts.rememberBandwidth,sizeCapHeadroom:this.opts.sizeCapHeadroom,adaptiveHoldBack:this.opts.adaptiveHoldBack,adaptiveHoldBackCeiling:this.opts.adaptiveHoldBackCeiling,mediaDuringKey:this.opts.mediaDuringKey,debug:this.opts.debug,deferLoad:n,hlsConfig:r,emit:e=>this.onEngineEvent(e),freshLicenseUrl:()=>this.refreshLicense()},o=this.opts.engine??`auto`;if(o===`native`)return new ah(i);if(o===`hls`)return new xg(i);if(e.drmEnabled&&e.drm?.fairplay?.licenseUrl&&e.drm.fairplay.certificateUrl&&nh(this.opts.video)&&rh()||!e.drmEnabled&&ih()&&nh(this.opts.video))return new ah(i);if(Sh())return new xg(i);if(nh(this.opts.video))return new ah(i);throw new a(`INTERNAL`,0,`no supported HLS playback engine in this browser`)}onEngineEvent(e){if(!this.destroyed)switch(e.type){case`firstPlaylist`:this.analyticsSession?.noteFirstPlaylist();break;case`firstBytes`:this.analyticsSession?.noteFirstBytes();break;case`drmReady`:this.analyticsSession?.noteDrmReady(),this.staleLicenseReloaded=!1;break;case`ready`:this.analyticsSession?.noteReady(),this.emit(`ready`),(this.opts.autoplay!==!1||this.playRequested)&&this.play();break;case`lowLatencyDetected`:this._descriptor&&(this._descriptor.isLowLatency=e.value);break;case`livetargetchange`:this.emit(`latencytargetchange`,e.change);break;case`qualitychange`:this.emit(`qualitychange`,e.index);break;case`audiotrackchange`:this.emit(`audiotrackchange`,e.id);break;case`texttrackchange`:this.emit(`texttrackchange`,e.id);break;case`ended`:this.onStreamEnded();break;case`error`:{let t=e.fatal&&this.isStaleLicenseDenial(e);if(this.analyticsSession?.noteError(e.error.code,e.error.message,e.fatal&&!t,e.error.httpStatus??0,Math.round(this.opts.video.currentTime*1e3),e.detail),t){this.staleLicenseReloaded=!0;let t=this.loadGen;this.emit(`warning`,e.error),Promise.resolve().then(()=>{if(!(this.destroyed||t!==this.loadGen)&&this._state!==`error`&&this._state!==`ended`)return this.reload().catch(()=>void 0)})}else e.fatal?this.fail(e.error):this.emit(`warning`,e.error);break}}}startLiveState(e){if(this.opts.liveStateEvents===!1)return;let t=this.opts.eventsBaseUrl??we(this.opts.baseUrl);if(!t)return;this.closeLiveState();let n=0,r=!1;this.liveStateSub=Ce({eventsBaseUrl:t,matchUrn:this.opts.matchUrn,credential:this.opts.credential,onState:t=>{this.destroyed||e!==this.loadGen||(t.state===`gone`?this.onStreamEnded(!0,t.reason??`match_ended`):t.state===`ended`?this.onStreamEnded(!1,t.reason):t.state===`live`&&this.endedHandled&&this.scheduleRejoin(e))},onAlive:()=>{n=0,r=!1},onError:i=>{if(!(this.destroyed||e!==this.loadGen||r)&&!this.endedHandled){if(i instanceof xe&&(i.terminal||i.status===404)){r=!0,this.emit(`warning`,new a(o(i.status),i.status,`live-state events answered HTTP ${i.status} for ${this.opts.matchUrn}: the match is `+(i.terminal?`gone, so the subscription stopped`:`not in the catalog (ended and dropped, or not listed yet), so it retries every 5 min`)+` — end-of-stream detection falls back to the HLS staleness watchdog.`));return}n+=1,n>=y_&&(r=!0,this.emit(`warning`,new a(`NETWORK`,0,`live-state events unreachable at ${t} after ${n} attempts — end-of-stream detection degraded to the HLS staleness watchdog. Check the events host, the api-key's allowed origins, and CSP connect-src.`)))}}})}closeLiveState(){this.liveStateSub?.close(),this.liveStateSub=null}watchReturn(){this.onReturnVisible||typeof document>`u`||this.opts.liveStateEvents!==!1&&(document.visibilityState===`hidden`&&(this.hiddenAtMs=Date.now()),this.onReturnVisible=()=>{if(document.visibilityState===`hidden`){this.hiddenAtMs??=Date.now();return}let e=this.hiddenAtMs;this.hiddenAtMs=null,e!=null&&Date.now()-e>=b_&&this.resyncLiveState()},this.onReturnPageShow=e=>{e.persisted&&this.resyncLiveState()},document.addEventListener(`visibilitychange`,this.onReturnVisible),typeof window<`u`&&window.addEventListener(`pageshow`,this.onReturnPageShow))}unwatchReturn(){this.onReturnVisible&&typeof document<`u`&&document.removeEventListener(`visibilitychange`,this.onReturnVisible),this.onReturnPageShow&&typeof window<`u`&&window.removeEventListener(`pageshow`,this.onReturnPageShow),this.onReturnVisible=null,this.onReturnPageShow=null,this.hiddenAtMs=null}resyncLiveState(){!this.destroyed&&this.liveStateSub&&this.startLiveState(this.loadGen)}onStreamEnded(e=!1,t){if(!this.destroyed){if((e||!this.rejoinEnabled())&&(this.cancelRejoin(),this.closeLiveState()),this.endedHandled){t===`match_ended`&&this._endedReason!==`match_ended`&&(this._endedReason=t,this.emit(`ended`,t),this.leavePipOnEnd());return}this.endedHandled=!0,this._endedReason=t??null,this.stopRefresh(),this.pendingStartLoad=!1,this.engine?.stop(),this.setState(`ended`),this.leavePipOnEnd()}}leavePipOnEnd(){this._endedReason===`interrupted`&&this.rejoinEnabled()||this.exitPictureInPicture().catch(()=>{})}get streamEnded(){return this._state===`ended`&&this.endedHandled}rejoinEnabled(){return this.opts.rejoinOnLive!==!1&&this.opts.liveStateEvents!==!1}scheduleRejoin(e){this.rejoinEnabled()&&!this.rejoinTimer&&(this.rejoinTimer=setTimeout(()=>{this.rejoinTimer=null,!(this.destroyed||e!==this.loadGen||this._state!==`ended`)&&this.rejoin()},Math.random()*v_))}cancelRejoin(){this.rejoinTimer&&=(clearTimeout(this.rejoinTimer),null)}rejoin(){let e=++this.loadGen;this.teardownPlayback(),this.setState(`waiting`),this.beginArming(e,void 0,!0)}teardownPlayback(){this.stopStats(),this.stopRefresh(),this.cancelRejoin(),this.closeArming(),this.closeLiveState(),this.detachMedia?.(),this.engine?.destroy(),this.engine=null,this.pendingStartLoad=!1,this.idleClosed=!1}mountControls(){let e=this.opts.controls??`custom`,t=this.opts.video;if(e===`native`){t.controls=!0;return}if(e===`none`){t.controls=!1;return}t.controls=!1;let n=(t.ownerDocument??document).createElement(`div`),r=t.parentNode;r&&r.insertBefore(n,t),n.appendChild(t),Qg(n,this.opts.theme),this.container=n,this.controlBar=u_({root:n,video:t,player:this,logoUrl:this.opts.theme?.logoUrl,statusOverlays:this.opts.statusOverlays,endedMessage:this.opts.endedMessage,streamEnded:()=>this.streamEnded,interruptedMessage:this.opts.interruptedMessage,errorMessage:this.opts.errorMessage,cspNonce:this.opts.cspNonce})}unmountControls(){this.controlBar?.destroy(),this.controlBar=null;let e=this.container;e&&(e.parentNode?(e.parentNode.insertBefore(this.opts.video,e),e.remove()):this.opts.video.parentNode===e&&e.removeChild(this.opts.video)),this.container=null}attachPipListeners(){let e=this.opts.video,t=()=>this.analyticsSession?.notePresentation(this.currentPresentation()),n=()=>{t(),this.emit(`pipchange`,!0)},r=()=>{t(),this.emit(`pipchange`,!1)};e.addEventListener(`enterpictureinpicture`,n),e.addEventListener(`leavepictureinpicture`,r);let i=typeof document<`u`?document:void 0;i?.addEventListener(`fullscreenchange`,t),i?.addEventListener(`webkitfullscreenchange`,t),this.detachPip=()=>{e.removeEventListener(`enterpictureinpicture`,n),e.removeEventListener(`leavepictureinpicture`,r),i?.removeEventListener(`fullscreenchange`,t),i?.removeEventListener(`webkitfullscreenchange`,t)}}attachEndedPlayGuard(){let e=this.opts.video,t=()=>{this.streamEnded&&e.pause()};e.addEventListener(`play`,t),this.detachEndedPlayGuard=()=>e.removeEventListener(`play`,t)}startStats(){this.stopStats();let e=Math.max(500,this.opts.statsIntervalMs??x_);this.statsTimer=setInterval(()=>{if(!this.engine)return;let e=this.engine.getStats();(e.bytesLoaded??0)>0&&this.analyticsSession?.noteFirstBytes(),this.emit(`stats`,e)},e)}stopStats(){this.statsTimer&&clearInterval(this.statsTimer),this.statsTimer=void 0}isStaleLicenseDenial(e){return this.staleLicenseReloaded||this.opts.hlsConfig?.licenseXhrSetup||this._state===`ended`||this._state===`error`||e.detail!==C_||e.error.httpStatus!==403||e.error.code!==`FORBIDDEN`||e.error.serverCode===`license_refused`?!1:lh(this._descriptor?.drm?.widevine?.licenseUrl)}scheduleLicenseRefresh(){if(this.stopRefresh(),!this._descriptor?.drmEnabled)return;typeof document<`u`&&this.engine?.name===`hls`&&(this.onRefocus=()=>{document.visibilityState!==`visible`||this.destroyed||lh(this._descriptor?.drm?.widevine?.licenseUrl)&&this.refreshLicense()},document.addEventListener(`visibilitychange`,this.onRefocus));let e=this.opts.licenseRefreshMs??S_;e&&(this.refreshTimer=setInterval(()=>void this.refreshLicense(),e))}stopRefresh(){this.refreshTimer&&clearInterval(this.refreshTimer),this.refreshTimer=void 0,this.onRefocus&&typeof document<`u`&&(document.removeEventListener(`visibilitychange`,this.onRefocus),this.onRefocus=void 0)}refreshLicense(){let e=this.engine;if(this.destroyed||!e)return Promise.resolve(void 0);if(this.refreshInFlight?.engine===e)return this.refreshInFlight.promise;let t=(async()=>{try{let t=await ee(this.resolveOptions());if(this.destroyed||this.engine!==e)return;let n=t.drm?.widevine?.licenseUrl,r=t.drm?.fairplay?.licenseUrl;return(n||r)&&(e.setLicenseUrls({widevine:n,fairplay:r}),this._descriptor=t),n}catch(e){e instanceof a&&!u(e.code)&&(this.stopRefresh(),this.destroyed||this.emit(`warning`,e));return}finally{this.refreshInFlight?.promise===t&&(this.refreshInFlight=void 0)}})();return this.refreshInFlight={engine:e,promise:t},t}async play(){if(this.destroyed)return;let e=!this.playRequested;if(this.playRequested=!0,this.idleClosed&&this._state!==`ended`&&this._state!==`error`){this.idleClosed=!1,await this.reload();return}if(this.streamEnded)return;let t=this.pendingStartLoad&&this._state!==`ended`&&this._state!==`error`;this.opts.autoplay===!1&&this.analyticsSession?.notePlayIntent(),t&&(this.pendingStartLoad=!1,this.setState(`loading`),this.engine?.startLoad());try{await this.opts.video.play(),e&&this.analyticsSession?.noteAutoplay(this.opts.video.muted?`AUTOPLAY_RESULT_ALLOWED_MUTED`:`AUTOPLAY_RESULT_ALLOWED`)}catch(n){n instanceof DOMException&&n.name===`NotAllowedError`&&(this.analyticsSession?.noteAutoplay(`AUTOPLAY_RESULT_BLOCKED`),e&&(this.playRequested=!1),t&&!this.destroyed&&this._state===`loading`&&this.setState(`paused`),this.emit(`autoplayblocked`))}}pause(){this.destroyed||this.opts.video.pause()}setMuted(e){this.destroyed||(this.opts.video.muted=e)}setVolume(e){this.destroyed||(this.opts.video.volume=Math.min(1,Math.max(0,e)))}getStats(){return this.engine?.getStats()??Lm}getQualityLevels(){return this.engine?.getQualityLevels()??[]}getCurrentQuality(){return this.engine?.getCurrentQuality()??-1}setQuality(e){this.destroyed||this.engine?.setQuality(e===`auto`?-1:e)}setMaxBitrate(e){this.destroyed||this.engine?.setMaxBitrate(e)}getAudioTracks(){return this.engine?.getAudioTracks()??[]}setAudioTrack(e){this.destroyed||this.engine?.setAudioTrack(e)}getTextTracks(){return this.engine?.getTextTracks()??[]}setTextTrack(e){this.destroyed||this.engine?.setTextTrack(e)}seekToLive(){this.destroyed||this.engine?.seekToLive()}async enterPictureInPicture(){if(this.destroyed)return;let e=this.opts.video;typeof e.requestPictureInPicture==`function`&&await e.requestPictureInPicture()}async exitPictureInPicture(){let e=document;e.pictureInPictureElement===this.opts.video&&typeof e.exitPictureInPicture==`function`&&await e.exitPictureInPicture()}async enterFullscreen(){return!this.destroyed&&de(this.opts.video,this.container??void 0)}async exitFullscreen(){await fe(this.opts.video,this.container??void 0)}fullscreenSupported(){return!this.destroyed&&ue(this.opts.video,this.container??void 0)}retry(){return this.reload()}async reload(){if(this.destroyed)return;let e=++this.loadGen;this.teardownPlayback();try{let t=await te({...this.resolveOptions(),waitForLive:this.opts.waitForLive?this.buildWaitConfig(e):void 0});if(await this.onResolved(t,e),e===this.loadGen&&this._state===`error`&&this._lastError)throw this._lastError}catch(t){if(this.destroyed||this.abort.signal.aborted||e!==this.loadGen)return;throw t!==this._lastError&&this.fail(t instanceof a?t:new a(`INTERNAL`,0,String(t))),t}}on(e,t){let n=this.listeners[e]??=new Set;return n.add(t),()=>n.delete(t)}destroy(){this.destroyed||(this.destroyed=!0,this.loadGen+=1,this.abort.abort(),this.stopStats(),this.stopRefresh(),this.unmountControls(),this.cancelRejoin(),this.closeArming(),this.closeLiveState(),this.unwatchReturn(),this.detachMedia?.(),this.detachPip?.(),this.detachEndedPlayGuard?.(),this.analyticsSession?.noteDestroyed(),this.analyticsSession=null,this.detachMediaListeners?.(),this.engine?.destroy(),this.engine=null,this.setState(`idle`),this.clearListeners())}clearListeners(){for(let e of Object.keys(this.listeners))this.listeners[e]?.clear()}fail(e){this._lastError=e,this.setState(`error`),this.analyticsSession?.noteFatal(),this.emit(`error`,e)}setState(e){if(e===this._state)return;let t=this._state;if(this._state=e,this.analyticsSession){let n=this.opts.video;this.analyticsSession.noteStateChange(t,e,Math.round(n.currentTime*1e3),this.engine?.getStats().levelHeight),e===`ended`&&this.analyticsSession.noteEnded()}switch(this.emit(`statechange`,e),e){case`playing`:this.emit(`playing`);break;case`buffering`:this.emit(`buffering`);break;case`paused`:this.emit(`paused`);break;case`ended`:this.emit(`ended`,this._endedReason??void 0)}}emit(e,t){this.listeners[e]?.forEach(e=>{try{e(t)}catch{}})}};function D_(e){return!!e&&typeof e==`object`&&typeof e.type==`string`&&e.type.startsWith(`oddin:`)}function O_(e){if(!e.container||typeof e.container.appendChild!=`function`)throw Error(`mountEmbed: opts.container must be a DOM element`);if(!e.src)throw Error(`mountEmbed: opts.src is required`);if(!e.baseUrl||!e.matchUrn)throw Error(`mountEmbed: opts.baseUrl and opts.matchUrn are required`);let t=new URL(e.src,location.href),n=e.allowedFrameOrigin??t.origin;t.searchParams.set(`baseUrl`,e.baseUrl),t.searchParams.set(`matchUrn`,e.matchUrn),t.searchParams.set(`parentOrigin`,location.origin),e.muted!=null&&t.searchParams.set(`muted`,String(e.muted)),e.apiKey&&(t.searchParams.set(`apiKey`,e.apiKey),console.warn(`havik-player: passing apiKey to mountEmbed places it in the iframe URL — DEV/DEMO only. In production inject it server-side into window.HAVIK_EMBED_CONFIG on the embed page.`));let r=document.createElement(`iframe`);r.src=t.toString(),r.allow=`autoplay; encrypted-media; fullscreen`,r.setAttribute(`allowfullscreen`,``),r.referrerPolicy=`no-referrer`,r.setAttribute(`sandbox`,e.sandbox??`allow-scripts allow-same-origin allow-presentation`),r.style.cssText=`border:0;width:100%;height:100%;display:block`,e.container.appendChild(r);let i=new Set,a=t=>{if(t.source!==r.contentWindow||t.origin!==n||!D_(t.data))return;let a=t.data;a.type===`oddin:ready`&&a.protocol!==1&&console.warn(`havik-player: embed protocol v${a.protocol} != host v1. Pin the embed page version to the SDK version to avoid skew.`),e.onEvent?.(a),i.forEach(e=>e(a))};window.addEventListener(`message`,a);let o=e=>r.contentWindow?.postMessage(e,n);return{iframe:r,play:()=>o({type:`oddin:play`}),pause:()=>o({type:`oddin:pause`}),setMuted:e=>o({type:`oddin:setMuted`,muted:e}),setVolume:e=>o({type:`oddin:setVolume`,volume:e}),setQuality:e=>o({type:`oddin:setQuality`,index:e}),setMaxBitrate:e=>o({type:`oddin:setMaxBitrate`,bitrate:e}),setAudioTrack:e=>o({type:`oddin:setAudioTrack`,id:e}),setTextTrack:e=>o({type:`oddin:setTextTrack`,id:e}),seekToLive:()=>o({type:`oddin:seekToLive`}),enterPip:()=>o({type:`oddin:enterPip`}),exitPip:()=>o({type:`oddin:exitPip`}),retry:()=>o({type:`oddin:retry`}),load:e=>o({type:`oddin:load`,matchUrn:e}),on:e=>(i.add(e),()=>i.delete(e)),destroy:()=>{o({type:`oddin:destroy`}),window.removeEventListener(`message`,a),r.remove()}}}var k_=/^[A-Za-z0-9:_.-]{1,128}$/;function A_(e){if(typeof e==`boolean`)return e;if(typeof e==`object`&&e){let t=e.endpoint;return typeof t==`string`?{endpoint:t}:{}}}function j_(){let e=window.HAVIK_EMBED_CONFIG;if(e)return{baseUrl:e.baseUrl??``,matchUrn:e.matchUrn??``,apiKey:e.apiKey??``,parentOrigin:e.parentOrigin,autoplay:e.autoplay??!0,muted:e.muted??!0,waitForLive:e.waitForLive??!0,analytics:A_(e.analytics)};let t=new URLSearchParams(location.search);return{baseUrl:t.get(`baseUrl`)??``,matchUrn:t.get(`matchUrn`)??``,apiKey:t.get(`apiKey`)??``,parentOrigin:t.get(`parentOrigin`)??void 0,autoplay:!0,muted:t.get(`muted`)!==`false`,waitForLive:!0}}async function M_(){let e=j_();P_();let t=document.createElement(`video`);t.setAttribute(`playsinline`,``),t.muted=e.muted??!0,t.style.cssText=`width:100%;height:100%;object-fit:contain;background:#000;aspect-ratio:auto`,document.body.appendChild(t);let n=e.parentOrigin&&e.parentOrigin!==`null`?e.parentOrigin:null;n||console.warn(`havik-player: embed has no parentOrigin — the postMessage bridge is disabled (no events posted, no commands accepted). mountEmbed sets parentOrigin automatically.`);let r=e=>{if(n)try{window.parent?.postMessage(e,n)}catch{}};if(!e.baseUrl||!e.matchUrn||!e.apiKey){r({type:`oddin:error`,code:`INTERNAL`,message:`embed missing baseUrl/matchUrn/apiKey`});return}let i=null,o=e=>{e.on(`statechange`,e=>r({type:`oddin:state`,state:e})),e.on(`ready`,()=>r({type:`oddin:tracks`,quality:e.getQualityLevels(),audio:e.getAudioTracks(),text:e.getTextTracks()})),e.on(`waiting`,e=>r({type:`oddin:waiting`,retryInMs:e.retryInMs,attempt:e.attempt,phase:e.phase})),e.on(`qualitychange`,e=>r({type:`oddin:qualitychange`,index:e})),e.on(`audiotrackchange`,e=>r({type:`oddin:audiotrackchange`,id:e})),e.on(`texttrackchange`,e=>r({type:`oddin:texttrackchange`,id:e})),e.on(`stats`,e=>r({type:`oddin:stats`,droppedFrames:e.droppedFrames,latencySeconds:e.latencySeconds,bandwidthKbps:e.bandwidthKbps,levelHeight:e.levelHeight,lowLatency:e.lowLatency,isLive:e.isLive,atLiveEdge:e.atLiveEdge})),e.on(`error`,e=>r({type:`oddin:error`,code:e.code,message:e.message,...e.country===void 0?{}:{country:e.country}})),e.on(`autoplayblocked`,()=>{r({type:`oddin:autoplayblocked`}),N_(t,e)})},s=async n=>{i?.destroy(),i=null;try{let r=await T_({video:t,baseUrl:e.baseUrl,matchUrn:n,credential:{apiKey:e.apiKey},autoplay:e.autoplay,muted:e.muted,waitForLive:e.waitForLive,analytics:e.analytics});i=r;let a=t.parentElement;a?.classList.contains(`havik-player`)&&(a.style.cssText=`position:absolute;inset:0;width:100%;height:100%;aspect-ratio:auto`),o(r)}catch(e){let t=e instanceof a?e.code:`INTERNAL`,n=e instanceof Error?e.message:String(e),i=e instanceof a?e.country:void 0;r({type:`oddin:error`,code:t,message:n,...i===void 0?{}:{country:i}})}},c=()=>{window.removeEventListener(`message`,u),window.removeEventListener(`pagehide`,c),i?.destroy(),i=null},l=e=>{switch(e.type){case`oddin:play`:i?.play();break;case`oddin:pause`:i?.pause();break;case`oddin:setMuted`:typeof e.muted==`boolean`&&i?.setMuted(e.muted);break;case`oddin:setVolume`:typeof e.volume==`number`&&Number.isFinite(e.volume)&&i?.setVolume(e.volume);break;case`oddin:setQuality`:typeof e.index==`number`&&i?.setQuality(e.index);break;case`oddin:setMaxBitrate`:(e.bitrate===null||typeof e.bitrate==`number`&&Number.isFinite(e.bitrate))&&i?.setMaxBitrate(e.bitrate);break;case`oddin:setAudioTrack`:typeof e.id==`number`&&i?.setAudioTrack(e.id);break;case`oddin:setTextTrack`:typeof e.id==`number`&&i?.setTextTrack(e.id);break;case`oddin:seekToLive`:i?.seekToLive();break;case`oddin:enterPip`:i?.enterPictureInPicture();break;case`oddin:exitPip`:i?.exitPictureInPicture();break;case`oddin:retry`:i?.retry();break;case`oddin:load`:typeof e.matchUrn==`string`&&k_.test(e.matchUrn)&&s(e.matchUrn);break;case`oddin:destroy`:c()}},u=e=>{n&&e.origin===n&&D_(e.data)&&l(e.data)};n&&window.addEventListener(`message`,u),window.addEventListener(`pagehide`,c,{once:!0}),await s(e.matchUrn),r({type:`oddin:ready`,protocol:1})}function N_(e,t){if(document.getElementById(`havik-tap`))return;let n=document.createElement(`button`);n.id=`havik-tap`,n.textContent=`▶ Tap to play`,n.style.cssText=`position:fixed;inset:0;width:100%;height:100%;border:0;background:rgba(0,0,0,.55);color:#fff;font:600 18px system-ui,sans-serif;cursor:pointer;z-index:9`,n.addEventListener(`click`,()=>{n.remove(),t.play()}),document.body.appendChild(n)}function P_(){let e=document.createElement(`style`);e.textContent=`html,body{margin:0;height:100%;background:#000;overflow:hidden}body{display:flex}`,document.head.appendChild(e)}return e.LiveStateHttpError=xe,e.ODDIN_THEME=Xg,e.PlaybackError=a,e.applyTheme=Qg,e.baseUrlForEnv=ht,e.bootEmbed=M_,e.clearDeviceId=Oe,e.clearRememberedBandwidth=Ve,e.createPlayer=T_,e.deriveEventsBaseUrl=we,e.detectDrmSupport=dt,e.enterVideoFullscreen=de,e.exitVideoFullscreen=fe,e.fetchCatalog=pe,e.fetchTournament=he,e.flattenMatches=_e,e.fullscreenSupported=ue,e.getDeviceId=De,e.isLowLatencyManifest=pt,e.isOddinMessage=D_,e.licenseRequestHeaders=Ae,e.mountEmbed=O_,e.pollToLive=N,e.resolveStream=te,e.subscribeLiveState=Ce,e.videoFullscreenActive=le,e.watchStatus=ye,e})({});
|
|
174
|
+
`,a_=new WeakMap;function o_(e=document,t){let n=e.querySelector(`style#${r_}`);if(n&&(!t||a_.get(n)===t))return;let r=e.createElement(`style`);r.id=r_,t&&(r.nonce=t,r.setAttribute(`nonce`,t)),r.textContent=i_,a_.set(r,t),n?n.replaceWith(r):e.head.appendChild(r)}var s_={play:`<path d="M8 5v14l11-7z"/>`,pause:`<path d="M6 5h4v14H6zM14 5h4v14h-4z"/>`,volumeHigh:`<path d="M3 10v4h4l5 5V5L7 10H3zm13.5 2a4.5 4.5 0 0 0-2.5-4v8a4.5 4.5 0 0 0 2.5-4zm-2.5-9v2.06A7 7 0 0 1 14 19v2a9 9 0 0 0 0-18z"/>`,volumeMute:`<path d="M3 10v4h4l5 5V5L7 10H3zm16.5 2 2.5-2.5-1.4-1.4L18 10.6 15.4 8 14 9.4l2.6 2.6L14 14.6l1.4 1.4 2.6-2.6 2.6 2.6 1.4-1.4z"/>`,cc:`<path d="M19 4H5a2 2 0 0 0-2 2v12a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2V6a2 2 0 0 0-2-2zM10 11H8.5v-.5h-2v3h2V13H10v1a1 1 0 0 1-1 1H6a1 1 0 0 1-1-1v-4a1 1 0 0 1 1-1h3a1 1 0 0 1 1 1v1zm7 0h-1.5v-.5h-2v3h2V13H17v1a1 1 0 0 1-1 1h-3a1 1 0 0 1-1-1v-4a1 1 0 0 1 1-1h3a1 1 0 0 1 1 1v1z"/>`,settings:`<path d="M19.14 12.94c.04-.3.06-.61.06-.94 0-.32-.02-.64-.07-.94l2.03-1.58c.18-.14.23-.41.12-.61l-1.92-3.32c-.12-.22-.37-.29-.59-.22l-2.39.96c-.5-.38-1.03-.7-1.62-.94l-.36-2.54c-.04-.24-.24-.41-.48-.41h-3.84c-.24 0-.43.17-.47.41l-.36 2.54c-.59.24-1.13.57-1.62.94l-2.39-.96c-.22-.08-.47 0-.59.22L2.74 8.87c-.12.21-.08.47.12.61l2.03 1.58c-.05.3-.09.63-.09.94s.02.64.07.94l-2.03 1.58c-.18.14-.23.41-.12.61l1.92 3.32c.12.22.37.29.59.22l2.39-.96c.5.38 1.03.7 1.62.94l.36 2.54c.05.24.24.41.48.41h3.84c.24 0 .44-.17.47-.41l.36-2.54c.59-.24 1.13-.56 1.62-.94l2.39.96c.22.08.47 0 .59-.22l1.92-3.32c.11-.2.06-.47-.12-.61l-2.01-1.58zM12 15.6c-1.98 0-3.6-1.62-3.6-3.6s1.62-3.6 3.6-3.6 3.6 1.62 3.6 3.6-1.62 3.6-3.6 3.6z"/>`,pip:`<path d="M19 7h-8v6h8V7zm4 12V5a2 2 0 0 0-2-2H3a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h18a2 2 0 0 0 2-2zm-2 .02H3V4.98h18v14.04z"/>`,fullscreen:`<path d="M7 14H5v5h5v-2H7v-3zm-2-4h2V7h3V5H5v5zm12 7h-3v2h5v-5h-2v3zM14 5v2h3v3h2V5h-5z"/>`,fullscreenExit:`<path d="M5 16h3v3h2v-5H5v2zm3-8H5v2h5V5H8v3zm6 11h2v-3h3v-2h-5v5zm2-11V5h-2v5h5V8h-3z"/>`,liveDot:`<circle cx="12" cy="12" r="6"/>`,retry:`<path d="M17.65 6.35A8 8 0 1 0 19.73 13h-2.08A6 6 0 1 1 12 6c1.66 0 3.14.69 4.22 1.78L13 11h7V4l-2.35 2.35z"/>`};function c_(e){return`<svg viewBox="0 0 24 24" aria-hidden="true" focusable="false" fill="currentColor">${s_[e]}</svg>`}var l_=3e3,u_=250,d_=new Set([`GONE`,`NOT_FOUND`,`GEO_DENIED`,`INVALID_URN`,`UNAUTHORIZED`,`DRM_DEVICE_REVOKED`]);function f_(e){let t=`This match isn't available in your country`;return e?`${t} (${e})`:t}var p_=`This device can't play protected video`;function m_(e){return new h_(e)}var h_=class{constructor(e){i(this,`root`,void 0),i(this,`video`,void 0),i(this,`player`,void 0),i(this,`doc`,void 0),i(this,`autoHideMs`,void 0),i(this,`overlay`,void 0),i(this,`center`,void 0),i(this,`spinner`,void 0),i(this,`bar`,void 0),i(this,`gradient`,void 0),i(this,`seek`,void 0),i(this,`seekBuffered`,void 0),i(this,`seekPlayed`,void 0),i(this,`seekThumb`,void 0),i(this,`playBtn`,void 0),i(this,`muteBtn`,void 0),i(this,`volSlider`,void 0),i(this,`live`,void 0),i(this,`liveGo`,void 0),i(this,`time`,void 0),i(this,`ccBtn`,void 0),i(this,`audioBtn`,void 0),i(this,`qualityBtn`,void 0),i(this,`pipBtn`,void 0),i(this,`fsBtn`,void 0),i(this,`menu`,void 0),i(this,`statusBox`,null),i(this,`statusKind`,null),i(this,`statusMsg`,null),i(this,`hasPlayed`,!1),i(this,`fsSupported`,!0),i(this,`lastError`,null),i(this,`logoUrl`,void 0),i(this,`statusOverlays`,void 0),i(this,`streamEnded`,void 0),i(this,`endedMessage`,void 0),i(this,`interruptedMessage`,void 0),i(this,`errorMessage`,void 0),i(this,`hideTimer`,void 0),i(this,`tapTimer`,void 0),i(this,`surfacePointerType`,``),i(this,`surfaceWasHidden`,!1),i(this,`pointerClosedMenu`,!1),i(this,`openMenu`,null),i(this,`scrubbing`,!1),i(this,`offFns`,[]),this.root=e.root,this.video=e.video,this.player=e.player,this.doc=e.root.ownerDocument??document,this.autoHideMs=e.autoHideMs??l_,this.logoUrl=e.logoUrl,this.statusOverlays=e.statusOverlays!==!1,this.streamEnded=e.streamEnded??(()=>!1),this.endedMessage=e.endedMessage??`This stream has ended`,this.interruptedMessage=e.interruptedMessage??`Reconnecting — please stand by`,this.errorMessage=e.errorMessage,o_(this.doc,e.cspNonce),this.root.classList.add(`havik-player`),this.root.hasAttribute(`tabindex`)||(this.root.tabIndex=0),this.root.setAttribute(`role`,`region`),this.root.setAttribute(`aria-label`,`Video player`);let t=(e,t,n)=>{let r=this.doc.createElement(e);if(r.className=t,n)for(let[e,t]of Object.entries(n))r.setAttribute(e,t);return r},n=(e,n,r)=>{let i=t(`button`,e,{type:`button`,"aria-label":r,title:r});return i.innerHTML=c_(n),i};this.overlay=t(`div`,`havik-overlay`),this.center=t(`button`,`havik-center`,{type:`button`,"aria-label":`Play`}),this.center.innerHTML=c_(`play`),this.spinner=t(`div`,`havik-spinner`),this.spinner.style.display=`none`,this.overlay.append(this.center,this.spinner),this.gradient=t(`div`,`havik-gradient`),this.bar=t(`div`,`havik-bar`),this.seek=t(`div`,`havik-seek`,{role:`slider`,"aria-label":`Seek`,"aria-valuemin":`0`,"aria-valuemax":`100`,tabindex:`0`});let r=t(`div`,`havik-seek__track`);this.seekBuffered=t(`div`,`havik-seek__buffered`),this.seekPlayed=t(`div`,`havik-seek__played`),this.seekThumb=t(`div`,`havik-seek__thumb`),r.append(this.seekBuffered,this.seekPlayed,this.seekThumb),this.seek.append(r);let a=t(`div`,`havik-controls`);this.playBtn=n(`havik-btn`,`play`,`Play`),this.muteBtn=n(`havik-btn`,`volumeHigh`,`Mute`),this.volSlider=t(`input`,`havik-vol__slider`,{type:`range`,min:`0`,max:`1`,step:`0.05`,"aria-label":`Volume`});let o=t(`div`,`havik-vol`);o.append(this.muteBtn,this.volSlider),this.live=t(`div`,`havik-live`),this.live.innerHTML=c_(`liveDot`);let s=this.doc.createElement(`span`);s.textContent=`LIVE`,this.liveGo=t(`button`,`havik-live__go`,{type:`button`}),this.liveGo.textContent=`Go live`,this.live.append(s,this.liveGo),this.time=t(`div`,`havik-time`),this.time.textContent=`0:00`,this.time.style.display=`none`;let c=t(`div`,`havik-spacer`);if(this.ccBtn=n(`havik-btn`,`cc`,`Subtitles`),this.audioBtn=n(`havik-btn`,`settings`,`Audio track`),this.qualityBtn=n(`havik-btn`,`settings`,`Quality`),this.pipBtn=n(`havik-btn`,`pip`,`Picture in picture`),this.fsBtn=n(`havik-btn`,`fullscreen`,`Fullscreen`),this.ccBtn.style.display=`none`,this.audioBtn.style.display=`none`,this.qualityBtn.style.display=`none`,this.pipSupported()||(this.pipBtn.style.display=`none`),this.syncFullscreenSupport(),a.append(this.playBtn,o,this.live,this.time,c,this.ccBtn,this.audioBtn,this.qualityBtn,this.pipBtn,this.fsBtn),this.bar.append(this.seek,a),this.menu=t(`div`,`havik-menu`,{role:`menu`}),this.menu.hidden=!0,this.root.append(this.gradient,this.overlay,this.bar,this.menu),e.logoUrl){let n=t(`div`,`havik-watermark`);n.style.backgroundImage=`url("${e.logoUrl}")`,this.root.append(n)}this.wire(),this.syncPlayPause(),this.syncVolume(),this.scheduleHide()}on(e,t,n,r){e.addEventListener(t,n,r),this.offFns.push(()=>e.removeEventListener(t,n,r))}wire(){let e=this.video;this.on(this.playBtn,`click`,()=>this.togglePlay()),this.on(this.center,`click`,()=>this.togglePlay()),this.on(this.overlay,`pointerdown`,e=>{this.surfacePointerType=e.pointerType??``,this.surfaceWasHidden=this.root.classList.contains(`havik-hide`)}),this.on(this.overlay,`click`,e=>{e.target===this.overlay&&this.onSurfaceClick()}),this.on(this.muteBtn,`click`,()=>this.player.setMuted(!e.muted)),this.on(this.volSlider,`input`,()=>{let t=Number(this.volSlider.value);this.setVolumeFill(t),this.player.setVolume(t),t>0&&e.muted&&this.player.setMuted(!1)}),this.on(this.liveGo,`click`,()=>this.player.seekToLive()),this.on(this.pipBtn,`click`,()=>void this.togglePip()),this.on(this.fsBtn,`click`,()=>void this.toggleFullscreen()),this.on(this.ccBtn,`click`,()=>this.toggleMenu(`cc`)),this.on(this.audioBtn,`click`,()=>this.toggleMenu(`audio`)),this.on(this.qualityBtn,`click`,()=>this.toggleMenu(`quality`)),this.on(this.seek,`pointerdown`,e=>this.onSeekDown(e)),this.on(this.seek,`keydown`,e=>this.onSeekKey(e)),this.on(e,`play`,()=>this.syncPlayPause()),this.on(e,`pause`,()=>this.syncPlayPause()),this.on(e,`volumechange`,()=>this.syncVolume()),this.on(e,`timeupdate`,()=>this.syncProgress()),this.on(e,`progress`,()=>this.syncProgress()),this.on(e,`durationchange`,()=>this.syncProgress()),this.on(e,`loadedmetadata`,()=>this.syncFullscreenSupport()),this.offFns.push(this.player.on(`statechange`,()=>this.syncState())),this.offFns.push(this.player.on(`ended`,()=>this.syncState())),this.offFns.push(this.player.on(`ready`,()=>this.refreshTracks())),this.offFns.push(this.player.on(`qualitychange`,()=>this.onTracksChanged())),this.offFns.push(this.player.on(`audiotrackchange`,()=>this.onTracksChanged())),this.offFns.push(this.player.on(`texttrackchange`,()=>this.onTracksChanged())),this.offFns.push(this.player.on(`pipchange`,e=>this.syncPip(e))),this.offFns.push(this.player.on(`stats`,()=>this.syncLive())),this.offFns.push(this.player.on(`error`,e=>{this.lastError=e,this.statusKind=null,this.syncState()}));let t=e=>e.pointerType!==`touch`;this.on(this.root,`pointermove`,e=>{t(e)&&this.poke()}),this.on(this.root,`pointerleave`,e=>{t(e)&&this.scheduleHide(0)}),this.on(this.root,`focusin`,()=>this.poke()),this.on(this.root,`keydown`,e=>this.onKey(e)),this.on(this.doc,`pointerdown`,e=>this.onDocPointer(e),{capture:!0}),this.on(this.doc,`fullscreenchange`,()=>this.syncFullscreen()),this.on(this.doc,`webkitfullscreenchange`,()=>this.syncFullscreen()),this.on(e,`webkitbeginfullscreen`,()=>this.syncFullscreen()),this.on(e,`webkitendfullscreen`,()=>this.syncFullscreen()),this.syncState()}togglePlay(){this.video.paused||this.video.ended?this.player.play():this.player.pause()}onSurfaceClick(){let e=this.surfacePointerType===`touch`;if(this.surfacePointerType=``,!e){this.tapTimer&&clearTimeout(this.tapTimer),this.tapTimer=void 0,this.togglePlay();return}if(this.pointerClosedMenu){this.tapTimer&&clearTimeout(this.tapTimer),this.tapTimer=void 0,this.poke();return}if(this.tapTimer){clearTimeout(this.tapTimer),this.tapTimer=void 0,this.togglePlay();return}let t=this.surfaceWasHidden;this.tapTimer=setTimeout(()=>{this.tapTimer=void 0,this.toggleBar(t)},u_)}toggleBar(e){e?this.poke():this.hideIfIdle()}syncPlayPause(){let e=!this.video.paused&&!this.video.ended;this.setIcon(this.playBtn,e?`pause`:`play`),this.playBtn.setAttribute(`aria-label`,e?`Pause`:`Play`),this.setIcon(this.center,e?`pause`:`play`),this.center.classList.toggle(`havik-gone`,e||!!this.statusBox),e?this.scheduleHide():this.show()}syncState(){let e=this.player.state;(e===`playing`||e===`buffering`)&&(this.hasPlayed=!0),this.syncStatus(e);let t=e===`loading`||e===`buffering`;this.spinner.style.display=t&&!this.statusBox?``:`none`,(t||this.statusBox)&&this.center.classList.add(`havik-gone`),this.syncLive()}syncStatus(e){let t=null;this.statusOverlays&&(e===`ended`?t=`ended`:e===`error`?t=`error`:e===`waiting`?t=`waiting`:!this.hasPlayed&&(e===`idle`||e===`paused`)&&(t=`preplay`)),this.renderStatus(t)}statusMessageFor(e){return e===`ended`?this.player.endedReason===`interrupted`?this.interruptedMessage:this.endedMessage:e===`waiting`?this.hasPlayed?`Reconnecting — please stand by`:`Starting soon…`:e===`error`?this.errorMessage===void 0?this.lastError?.code===`GEO_DENIED`?f_(this.lastError.country):this.lastError?.code===`DRM_DEVICE_REVOKED`?p_:this.lastError?.message??`Playback unavailable`:this.errorMessage:null}renderStatus(e){let t=this.statusMessageFor(e);if(e===this.statusKind&&t===this.statusMsg||(this.statusKind=e,this.statusMsg=t,this.statusBox?.remove(),this.statusBox=null,this.root.classList.toggle(`havik-has-status`,!!e),!e))return;let n=this.doc.createElement(`div`);if(n.className=`havik-status havik-status--${e}`,this.logoUrl){let e=this.doc.createElement(`div`);e.className=`havik-status__logo`,n.append(e)}if(e===`preplay`){let e=this.doc.createElement(`button`);e.type=`button`,e.className=`havik-status__btn havik-status__btn--play`,e.setAttribute(`aria-label`,`Play`),e.innerHTML=c_(`play`),e.addEventListener(`click`,()=>void this.player.play()),n.append(e)}else{let r=this.doc.createElement(`div`);if(r.className=`havik-status__msg`,r.textContent=t??``,n.append(r),e===`error`&&this.lastError&&!d_.has(this.lastError.code)){let e=this.doc.createElement(`button`);e.type=`button`,e.className=`havik-status__btn`,e.innerHTML=`${c_(`retry`)}<span>Retry</span>`,e.addEventListener(`click`,()=>void this.player.retry()),n.append(e)}}this.root.append(n),this.statusBox=n,this.show()}syncVolume(){let e=this.video,t=e.muted||e.volume===0;this.setIcon(this.muteBtn,t?`volumeMute`:`volumeHigh`),this.muteBtn.setAttribute(`aria-label`,t?`Unmute`:`Mute`);let n=t?0:e.volume;this.volSlider.value=String(n),this.setVolumeFill(n)}setVolumeFill(e){this.volSlider.style.setProperty(`--havik-vol`,String(Math.min(1,Math.max(0,e))))}seekableRange(){let e=this.video,t,n;if(e.seekable&&e.seekable.length>0)t=e.seekable.start(0),n=e.seekable.end(e.seekable.length-1);else if(Number.isFinite(e.duration)&&e.duration>0)t=0,n=e.duration;else return null;let r=this.player.getStats();return r.isLive!==!1&&r.targetLatencySeconds&&r.targetLatencySeconds>0&&(n=Math.max(t,n-r.targetLatencySeconds)),n>t?{start:t,end:n}:null}syncProgress(){if(this.scrubbing)return;let e=this.seekableRange();if(!e){this.seekPlayed.style.width=`100%`;return}let t=e.end-e.start,n=Math.min(1,Math.max(0,(this.video.currentTime-e.start)/t));this.seekPlayed.style.width=`${(n*100).toFixed(2)}%`,this.seekThumb.style.left=`${(n*100).toFixed(2)}%`,this.seek.setAttribute(`aria-valuenow`,String(Math.round(n*100)));let r=this.video.buffered;if(r&&r.length>0){let n=r.end(r.length-1),i=Math.min(1,Math.max(0,(n-e.start)/t));this.seekBuffered.style.width=`${(i*100).toFixed(2)}%`}!this.player.getStats().isLive&&Number.isFinite(this.video.duration)&&(this.time.textContent=`${g_(this.video.currentTime)} / ${g_(this.video.duration)}`)}syncLive(){let e=this.player.getStats(),t=e.isLive!==!1,n=this.player.state===`ended`,r=!t&&!this.streamEnded();this.live.style.display=t&&!n?``:`none`,this.time.style.display=r?``:`none`,this.seek.style.display=r?``:`none`,this.live.classList.toggle(`is-live`,e.atLiveEdge!==!1&&t)}onSeekDown(e){let t=this.seekableRange();if(!t)return;e.preventDefault(),this.scrubbing=!0;let n=e=>this.seekToPointer(e,t),r=()=>{this.scrubbing=!1,this.doc.removeEventListener(`pointermove`,n),this.doc.removeEventListener(`pointerup`,r)};this.doc.addEventListener(`pointermove`,n),this.doc.addEventListener(`pointerup`,r),this.seekToPointer(e,t)}seekToPointer(e,t){let n=this.seek.getBoundingClientRect(),r=n.width>0?Math.min(1,Math.max(0,(e.clientX-n.left)/n.width)):0;this.seekPlayed.style.width=`${(r*100).toFixed(2)}%`,this.seekThumb.style.left=`${(r*100).toFixed(2)}%`,this.video.currentTime=t.start+r*(t.end-t.start)}onSeekKey(e){e.key===`ArrowLeft`?(this.nudge(-5),e.preventDefault()):e.key===`ArrowRight`&&(this.nudge(5),e.preventDefault())}nudge(e){let t=this.seekableRange();t&&(this.video.currentTime=Math.min(t.end,Math.max(t.start,this.video.currentTime+e)))}toggleMenu(e){if(this.openMenu===e){this.closeMenu();return}this.openMenu=e,this.renderMenu(e),this.menu.hidden=!1,this.show()}closeMenu(){this.openMenu=null,this.menu.hidden=!0,this.menu.replaceChildren()}renderMenu(e){e===`quality`?this.renderQualityMenu():e===`audio`?this.renderAudioMenu():this.renderCcMenu()}menuItem(e,t,n){let r=this.doc.createElement(`button`);r.type=`button`,r.className=`havik-menu__item`,r.setAttribute(`role`,`menuitemradio`),r.setAttribute(`aria-checked`,t?`true`:`false`);let i=this.doc.createElement(`span`);return i.textContent=e,r.append(i),r.addEventListener(`click`,()=>{n(),this.closeMenu()}),r}renderQualityMenu(){let e=this.player.getQualityLevels(),t=this.player.getCurrentQuality(),n=this.doc.createElement(`div`);n.className=`havik-menu__title`,n.textContent=`Quality`,this.menu.replaceChildren(n,this.menuItem(`Auto`,t===-1,()=>this.player.setQuality(`auto`)));for(let n of e)this.menu.append(this.menuItem(__(n),t===n.index,()=>this.player.setQuality(n.index)))}renderAudioMenu(){let e=this.player.getAudioTracks(),t=this.doc.createElement(`div`);t.className=`havik-menu__title`,t.textContent=`Audio`,this.menu.replaceChildren(t);for(let t of e)this.menu.append(this.menuItem(v_(t),t.default,()=>this.player.setAudioTrack(t.id)))}renderCcMenu(){let e=this.player.getTextTracks(),t=this.doc.createElement(`div`);t.className=`havik-menu__title`,t.textContent=`Subtitles`,this.menu.replaceChildren(t,this.menuItem(`Off`,!1,()=>this.player.setTextTrack(-1)));for(let t of e)this.menu.append(this.menuItem(y_(t),!1,()=>this.player.setTextTrack(t.id)))}onTracksChanged(){this.openMenu&&this.renderMenu(this.openMenu)}refreshTracks(){let e=this.player.getQualityLevels(),t=this.player.getAudioTracks(),n=this.player.getTextTracks();this.qualityBtn.style.display=e.length>1?``:`none`,this.audioBtn.style.display=t.length>1?``:`none`,this.ccBtn.style.display=n.length>0?``:`none`,this.onTracksChanged()}pipSupported(){return`pictureInPictureEnabled`in this.doc&&typeof this.video.requestPictureInPicture==`function`}async togglePip(){this.doc.pictureInPictureElement===this.video?await this.player.exitPictureInPicture():await this.player.enterPictureInPicture()}syncPip(e){this.pipBtn.setAttribute(`aria-pressed`,e?`true`:`false`)}async toggleFullscreen(){try{le(this.video,this.root)?await fe(this.video,this.root):await de(this.video,this.root)}catch{}}syncFullscreenSupport(){this.fsSupported=ue(this.video,this.root),this.fsBtn.style.display=this.fsSupported?``:`none`}syncFullscreen(){let e=le(this.video,this.root);this.setIcon(this.fsBtn,e?`fullscreenExit`:`fullscreen`),this.fsBtn.setAttribute(`aria-label`,e?`Exit fullscreen`:`Fullscreen`)}poke(){this.show(),this.scheduleHide()}show(){this.root.classList.remove(`havik-hide`)}scheduleHide(e=this.autoHideMs){this.hideTimer&&clearTimeout(this.hideTimer),this.hideTimer=setTimeout(()=>this.hideIfIdle(),e)}hideIfIdle(){!this.video.paused&&!this.video.ended&&!this.openMenu&&!this.statusBox&&this.root.classList.add(`havik-hide`)}onDocPointer(e){this.pointerClosedMenu=!1,this.openMenu&&!this.menu.contains(e.target)&&([this.qualityBtn,this.audioBtn,this.ccBtn].some(t=>t.contains(e.target))||(this.closeMenu(),this.pointerClosedMenu=!0))}onKey(e){let t=e.target;if(!(t&&t!==this.root&&t!==this.seek&&t.tagName===`INPUT`)){switch(e.key){case` `:case`k`:this.togglePlay();break;case`m`:this.player.setMuted(!this.video.muted);break;case`f`:if(!this.fsSupported)return;this.toggleFullscreen();break;case`c`:this.ccBtn.style.display!==`none`&&this.toggleMenu(`cc`);break;case`l`:this.player.seekToLive();break;case`ArrowUp`:this.player.setVolume(Math.min(1,this.video.volume+.1));break;case`ArrowDown`:this.player.setVolume(Math.max(0,this.video.volume-.1));break;case`ArrowLeft`:this.nudge(-5);break;case`ArrowRight`:this.nudge(5);break;default:return}this.poke(),e.preventDefault()}}setIcon(e,t){e.innerHTML=c_(t)}destroy(){this.hideTimer&&clearTimeout(this.hideTimer),this.tapTimer&&clearTimeout(this.tapTimer);for(let e of this.offFns)try{e()}catch{}this.offFns.length=0,this.closeMenu(),this.statusBox?.remove();for(let e of[this.overlay,this.gradient,this.bar,this.menu])e.remove();this.root.classList.remove(`havik-player`,`havik-hide`,`havik-has-status`)}};function g_(e){(!Number.isFinite(e)||e<0)&&(e=0);let t=Math.floor(e%60),n=Math.floor(e/60%60),r=Math.floor(e/3600),i=r>0?String(n).padStart(2,`0`):String(n),a=String(t).padStart(2,`0`);return r>0?`${r}:${i}:${a}`:`${i}:${a}`}function __(e){return e.height?`${e.height}p`:`${Math.round(e.bitrate/1e3)} kbps`}function v_(e){return e.name||e.lang||`Track ${e.id}`}function y_(e){return e.name||e.lang||`Track ${e.id}`}var b_=6e3,x_=45e3,S_=2e3,C_=3,w_=5e3,T_=2e3,E_=48e4,D_=`keySystemLicenseRequestFailed`;function O_(e){if(e.env!==void 0&&e.baseUrl!==void 0)throw new a(`INTERNAL`,0,`createPlayer: pass env OR baseUrl, not both (got env=${JSON.stringify(e.env)} and baseUrl=${JSON.stringify(e.baseUrl)})`);if(e.env!==void 0)return ht(e.env);if(!e.baseUrl)throw new a(`INTERNAL`,0,`createPlayer: env or baseUrl is required (env: 'integration' | 'production')`);return e.baseUrl}async function k_(e){if(!e.video||typeof e.video.play!=`function`)throw new a(`INTERNAL`,0,`createPlayer: opts.video must be an HTMLVideoElement`);let t=O_(e);if(!e.matchUrn)throw new a(`INVALID_URN`,0,`createPlayer: matchUrn is required`);if(!e.credential)throw new a(`INTERNAL`,0,`createPlayer: credential is required`);let n=new A_({...e,baseUrl:t});return await n.start(),n}var A_=class{constructor(e){i(this,`opts`,void 0),i(this,`abort`,new AbortController),i(this,`listeners`,{}),i(this,`engine`,null),i(this,`controlBar`,null),i(this,`container`,null),i(this,`detachMedia`,void 0),i(this,`detachPip`,void 0),i(this,`detachEndedPlayGuard`,void 0),i(this,`statsTimer`,void 0),i(this,`refreshTimer`,void 0),i(this,`refreshInFlight`,void 0),i(this,`onRefocus`,void 0),i(this,`onReturnVisible`,null),i(this,`onReturnPageShow`,null),i(this,`hiddenAtMs`,null),i(this,`staleLicenseReloaded`,!1),i(this,`_state`,`idle`),i(this,`_descriptor`,null),i(this,`destroyed`,!1),i(this,`loadGen`,0),i(this,`liveStateSub`,null),i(this,`endedHandled`,!1),i(this,`_endedReason`,null),i(this,`rejoinTimer`,null),i(this,`armingSub`,null),i(this,`armSseTimer`,null),i(this,`armFallbackCtrl`,null),i(this,`_lastError`,null),i(this,`analyticsSession`,null),i(this,`detachMediaListeners`,void 0),i(this,`playRequested`,!1),i(this,`idleClosed`,!1),i(this,`pendingStartLoad`,!1),this.opts=e}get state(){return this._state}get descriptor(){return this._descriptor}get endedReason(){return this._endedReason}async start(){this.opts.muted&&(this.opts.video.muted=!0),this.opts.poster&&(this.opts.video.poster=this.opts.poster),this.mountControls(),this.attachPipListeners(),this.attachEndedPlayGuard(),this.setState(`loading`);let e=++this.loadGen,t=this.resolveOptions();try{let n=await ee(t);if(await this.onResolved(n,e),e===this.loadGen&&this._state===`error`&&this._lastError){let e=this._lastError;throw this.destroy(),e}}catch(t){if(this.opts.waitForLive&&t instanceof a&&u(t.code)){this.setState(`waiting`),this.beginArming(e,t.liveStartsAtMs);return}throw t}}resolveOptions(){return{baseUrl:this.opts.baseUrl,matchUrn:this.opts.matchUrn,credential:this.opts.credential,signal:this.abort.signal,apiHeaders:this.opts.apiHeaders}}beginArming(e,t,n=!1){let r=this.opts.liveStateEvents===!1?void 0:this.opts.eventsBaseUrl??we(this.opts.baseUrl);r?this.armWithSse(e,r,t,n):this.beginArmingByPolling(e)}beginArmingByPolling(e){te({...this.resolveOptions(),signal:this.abort.signal,waitForLive:this.buildWaitConfig(e)}).then(t=>{if(!(this.destroyed||this.abort.signal.aborted||e!==this.loadGen))return this.onResolved(t,e)}).catch(t=>{this.destroyed||this.abort.signal.aborted||e!==this.loadGen||this.fail(t instanceof a?t:new a(`INTERNAL`,0,String(t)))})}armWithSse(e,t,n,r=!1){let i=!1,o=!1,s=new AbortController;this.armFallbackCtrl=s,this.setState(`waiting`);let c=this.opts.waitForLive,l=c&&c!==!0?c.kickoffAt:void 0,d=typeof l==`number`?l:typeof l==`string`?Date.parse(l):NaN,f=n??(Number.isFinite(d)?d:void 0);setTimeout(()=>{i||this.destroyed||e!==this.loadGen||this.emit(`waiting`,{phase:r?`unavailable`:`tooEarly`,retryInMs:x_,attempt:1,elapsedMs:0,...!r&&f!==void 0&&f>Date.now()?{ttkMs:f-Date.now()}:{}})},0);let p=()=>this.destroyed||this.abort.signal.aborted||e!==this.loadGen,m=async t=>{if(!(i||p())){i=!0,this.closeArming(),s.abort();try{await this.onResolved(t,e)}catch(e){if(p())return;this.fail(e instanceof a?e:new a(`INTERNAL`,0,String(e)))}}},h=()=>{i||o||p()||(o=!0,te({...this.resolveOptions(),signal:s.signal,waitForLive:this.buildWaitConfig(e)}).then(e=>m(e)).catch(e=>{i||p()||s.signal.aborted||(i=!0,this.closeArming(),this.fail(e instanceof a?e:new a(`INTERNAL`,0,String(e))))}))},g=()=>{i||p()||ee(this.resolveOptions()).then(e=>m(e)).catch(e=>{if(!(i||p())){if(e instanceof a&&u(e.code)){h();return}i=!0,this.closeArming(),s.abort(),this.fail(e instanceof a?e:new a(`INTERNAL`,0,String(e)))}})},_=e=>{this.armSseTimer&&clearTimeout(this.armSseTimer),this.armSseTimer=setTimeout(()=>{!i&&!p()&&h()},e)};_(b_),this.armingSub=Ce({eventsBaseUrl:t,matchUrn:this.opts.matchUrn,credential:this.opts.credential,onAlive:()=>_(x_),onState:e=>{i||p()||(e.state===`live`||e.state===`gone`)&&setTimeout(g,Math.random()*S_)},onError:()=>h()})}closeArming(){this.armSseTimer&&=(clearTimeout(this.armSseTimer),null),this.armFallbackCtrl?.abort(),this.armFallbackCtrl=null,this.armingSub?.close(),this.armingSub=null}buildWaitConfig(e){let t=this.opts.waitForLive&&this.opts.waitForLive!==!0?this.opts.waitForLive:{};return{...t,onState:n=>{this.destroyed||e!==this.loadGen||(this.setState(`waiting`),this.emit(`waiting`,n),t.onState?.(n))}}}async onResolved(e,t){if(this.destroyed||t!==this.loadGen)return;this._descriptor=e,this.endedHandled=!1,this._endedReason=null;let n=await d(this.opts.credential);if(this.destroyed||t!==this.loadGen)return;this.setState(`loading`);let r=this.opts.autoplay===!1&&!this.playRequested,i=this.createEngine(e,n,r),a=Um(this.opts.video,e=>{this._state!==`ended`&&this._state!==`error`&&this.setState(e)});if(await i.load(),this.destroyed||t!==this.loadGen){a(),i.destroy();return}if(this._state===`error`){a(),i.destroy();return}this.engine=i,this.detachMedia=a,this.opts.maxBitrate!=null&&i.setMaxBitrate(this.opts.maxBitrate),this.startStats(),this.scheduleLicenseRefresh(),this.startLiveState(t),this.watchReturn(),this.startAnalytics(e,i,t),r&&(this.pendingStartLoad=!0,this.setState(`paused`),i.name===`native`&&setTimeout(()=>{this.destroyed||t!==this.loadGen||this.engine!==i||(this.analyticsSession?.noteReady(),this.emit(`ready`))},0))}onAnalyticsIdle(e){this.destroyed||this.engine!==e||(this.idleClosed=!0,this.pendingStartLoad=!1,e.stop())}startAnalytics(e,t,n){if(this.analyticsSession?.noteDestroyed(),this.analyticsSession=null,this.detachMediaListeners?.(),this.opts.analytics===!1)return;let r=e.analytics?.sid;if(!r)return;let i=typeof this.opts.analytics==`object`?this.opts.analytics.endpoint:void 0,{endpoint:o,disabledReason:s}=Kg(this.opts.baseUrl,i,e.analytics?.endpoint);if(!o){s&&setTimeout(()=>{this.destroyed||n!==this.loadGen||this.emit(`warning`,new a(`INTERNAL`,0,s))},0);return}let c=this.opts.video,l=new qg({endpoint:o,sid:r,player:t.name===`native`?`PLAYER_SAFARI_NATIVE`:`PLAYER_HLSJS`,sdkVersion:$g,environment:Zg(c),idleMs:typeof this.opts.analytics==`object`?this.opts.analytics.idleMs:void 0,onIdle:()=>this.onAnalyticsIdle(t),onBlocked:e=>setTimeout(()=>{this.destroyed||n!==this.loadGen||this.emit(`warning`,new a(`INTERNAL`,0,e))},0),sample:()=>{let e=this.engine?.getStats()??Lm,t=c.buffered.length?Math.max(0,c.buffered.end(c.buffered.length-1)-c.currentTime):0;return{...e,bufferedMs:Math.round(t*1e3),state:this._state,positionMs:Math.round(c.currentTime*1e3),playbackRate:c.playbackRate}}});this.analyticsSession=l;let u=()=>l.noteSeek(),d=()=>l.noteVolume(c.muted,c.volume);c.addEventListener(`seeking`,u),c.addEventListener(`volumechange`,d),this.detachMediaListeners=()=>{c.removeEventListener(`seeking`,u),c.removeEventListener(`volumechange`,d)},l.start(),l.seedVolume(c.muted,c.volume),l.notePresentation(this.currentPresentation()),Qg().then(e=>l.noteEnvironment(e)),this.opts.autoplay===!1&&l.noteAutoplay(`AUTOPLAY_RESULT_NOT_ATTEMPTED`)}currentPresentation(){let e=this.opts.video;if(typeof document<`u`&&document.pictureInPictureElement===e)return`pip`;let t=typeof document<`u`?document.fullscreenElement:null;return e.webkitDisplayingFullscreen===!0||t&&(t===e||t.contains(e))?`fullscreen`:`inline`}createEngine(e,t,n=!1){let r={...this.opts.hlsConfig};this.opts.startLevel!=null&&(r.startLevel=this.opts.startLevel),this.opts.liveLatencyTarget!=null&&(r.liveSyncDuration=this.opts.liveLatencyTarget);let i={video:this.opts.video,descriptor:e,credential:t,deviceId:De(),userId:this.opts.userId,lowLatency:this.opts.lowLatency===void 0||this.opts.lowLatency===`auto`||this.opts.lowLatency,snapToLiveOnRefocus:this.opts.snapToLiveOnRefocus,rememberBandwidth:this.opts.rememberBandwidth,sizeCapHeadroom:this.opts.sizeCapHeadroom,adaptiveHoldBack:this.opts.adaptiveHoldBack,adaptiveHoldBackCeiling:this.opts.adaptiveHoldBackCeiling,mediaDuringKey:this.opts.mediaDuringKey,preloadHints:this.opts.preloadHints,debug:this.opts.debug,deferLoad:n,hlsConfig:r,emit:e=>this.onEngineEvent(e),freshLicenseUrl:()=>this.refreshLicense()},o=this.opts.engine??`auto`;if(o===`native`)return new ah(i);if(o===`hls`)return new Tg(i);if(e.drmEnabled&&e.drm?.fairplay?.licenseUrl&&e.drm.fairplay.certificateUrl&&nh(this.opts.video)&&rh()||!e.drmEnabled&&ih()&&nh(this.opts.video))return new ah(i);if(Th())return new Tg(i);if(nh(this.opts.video))return new ah(i);throw new a(`INTERNAL`,0,`no supported HLS playback engine in this browser`)}onEngineEvent(e){if(!this.destroyed)switch(e.type){case`firstPlaylist`:this.analyticsSession?.noteFirstPlaylist();break;case`firstBytes`:this.analyticsSession?.noteFirstBytes();break;case`drmReady`:this.analyticsSession?.noteDrmReady(),this.staleLicenseReloaded=!1;break;case`ready`:this.analyticsSession?.noteReady(),this.emit(`ready`),(this.opts.autoplay!==!1||this.playRequested)&&this.play();break;case`lowLatencyDetected`:this._descriptor&&(this._descriptor.isLowLatency=e.value);break;case`livetargetchange`:this.emit(`latencytargetchange`,e.change);break;case`qualitychange`:this.emit(`qualitychange`,e.index);break;case`audiotrackchange`:this.emit(`audiotrackchange`,e.id);break;case`texttrackchange`:this.emit(`texttrackchange`,e.id);break;case`ended`:this.onStreamEnded();break;case`error`:{let t=e.fatal&&this.isStaleLicenseDenial(e);if(this.analyticsSession?.noteError(e.error.code,e.error.message,e.fatal&&!t,e.error.httpStatus??0,Math.round(this.opts.video.currentTime*1e3),e.detail),t){this.staleLicenseReloaded=!0;let t=this.loadGen;this.emit(`warning`,e.error),Promise.resolve().then(()=>{if(!(this.destroyed||t!==this.loadGen)&&this._state!==`error`&&this._state!==`ended`)return this.reload().catch(()=>void 0)})}else e.fatal?this.fail(e.error):this.emit(`warning`,e.error);break}}}startLiveState(e){if(this.opts.liveStateEvents===!1)return;let t=this.opts.eventsBaseUrl??we(this.opts.baseUrl);if(!t)return;this.closeLiveState();let n=0,r=!1;this.liveStateSub=Ce({eventsBaseUrl:t,matchUrn:this.opts.matchUrn,credential:this.opts.credential,onState:t=>{this.destroyed||e!==this.loadGen||(t.state===`gone`?this.onStreamEnded(!0,t.reason??`match_ended`):t.state===`ended`?this.onStreamEnded(!1,t.reason):t.state===`live`&&this.endedHandled&&this.scheduleRejoin(e))},onAlive:()=>{n=0,r=!1},onError:i=>{if(!(this.destroyed||e!==this.loadGen||r)&&!this.endedHandled){if(i instanceof xe&&(i.terminal||i.status===404)){r=!0,this.emit(`warning`,new a(o(i.status),i.status,`live-state events answered HTTP ${i.status} for ${this.opts.matchUrn}: the match is `+(i.terminal?`gone, so the subscription stopped`:`not in the catalog (ended and dropped, or not listed yet), so it retries every 5 min`)+` — end-of-stream detection falls back to the HLS staleness watchdog.`));return}n+=1,n>=C_&&(r=!0,this.emit(`warning`,new a(`NETWORK`,0,`live-state events unreachable at ${t} after ${n} attempts — end-of-stream detection degraded to the HLS staleness watchdog. Check the events host, the api-key's allowed origins, and CSP connect-src.`)))}}})}closeLiveState(){this.liveStateSub?.close(),this.liveStateSub=null}watchReturn(){this.onReturnVisible||typeof document>`u`||this.opts.liveStateEvents!==!1&&(document.visibilityState===`hidden`&&(this.hiddenAtMs=Date.now()),this.onReturnVisible=()=>{if(document.visibilityState===`hidden`){this.hiddenAtMs??=Date.now();return}let e=this.hiddenAtMs;this.hiddenAtMs=null,e!=null&&Date.now()-e>=w_&&this.resyncLiveState()},this.onReturnPageShow=e=>{e.persisted&&this.resyncLiveState()},document.addEventListener(`visibilitychange`,this.onReturnVisible),typeof window<`u`&&window.addEventListener(`pageshow`,this.onReturnPageShow))}unwatchReturn(){this.onReturnVisible&&typeof document<`u`&&document.removeEventListener(`visibilitychange`,this.onReturnVisible),this.onReturnPageShow&&typeof window<`u`&&window.removeEventListener(`pageshow`,this.onReturnPageShow),this.onReturnVisible=null,this.onReturnPageShow=null,this.hiddenAtMs=null}resyncLiveState(){!this.destroyed&&this.liveStateSub&&this.startLiveState(this.loadGen)}onStreamEnded(e=!1,t){if(!this.destroyed){if((e||!this.rejoinEnabled())&&(this.cancelRejoin(),this.closeLiveState()),this.endedHandled){t===`match_ended`&&this._endedReason!==`match_ended`&&(this._endedReason=t,this.emit(`ended`,t),this.leavePipOnEnd());return}this.endedHandled=!0,this._endedReason=t??null,this.stopRefresh(),this.pendingStartLoad=!1,this.engine?.stop(),this.setState(`ended`),this.leavePipOnEnd()}}leavePipOnEnd(){this._endedReason===`interrupted`&&this.rejoinEnabled()||this.exitPictureInPicture().catch(()=>{})}get streamEnded(){return this._state===`ended`&&this.endedHandled}rejoinEnabled(){return this.opts.rejoinOnLive!==!1&&this.opts.liveStateEvents!==!1}scheduleRejoin(e){this.rejoinEnabled()&&!this.rejoinTimer&&(this.rejoinTimer=setTimeout(()=>{this.rejoinTimer=null,!(this.destroyed||e!==this.loadGen||this._state!==`ended`)&&this.rejoin()},Math.random()*S_))}cancelRejoin(){this.rejoinTimer&&=(clearTimeout(this.rejoinTimer),null)}rejoin(){let e=++this.loadGen;this.teardownPlayback(),this.setState(`waiting`),this.beginArming(e,void 0,!0)}teardownPlayback(){this.stopStats(),this.stopRefresh(),this.cancelRejoin(),this.closeArming(),this.closeLiveState(),this.detachMedia?.(),this.engine?.destroy(),this.engine=null,this.pendingStartLoad=!1,this.idleClosed=!1}mountControls(){let e=this.opts.controls??`custom`,t=this.opts.video;if(e===`native`){t.controls=!0;return}if(e===`none`){t.controls=!1;return}t.controls=!1;let n=(t.ownerDocument??document).createElement(`div`),r=t.parentNode;r&&r.insertBefore(n,t),n.appendChild(t),n_(n,this.opts.theme),this.container=n,this.controlBar=m_({root:n,video:t,player:this,logoUrl:this.opts.theme?.logoUrl,statusOverlays:this.opts.statusOverlays,endedMessage:this.opts.endedMessage,streamEnded:()=>this.streamEnded,interruptedMessage:this.opts.interruptedMessage,errorMessage:this.opts.errorMessage,cspNonce:this.opts.cspNonce})}unmountControls(){this.controlBar?.destroy(),this.controlBar=null;let e=this.container;e&&(e.parentNode?(e.parentNode.insertBefore(this.opts.video,e),e.remove()):this.opts.video.parentNode===e&&e.removeChild(this.opts.video)),this.container=null}attachPipListeners(){let e=this.opts.video,t=()=>this.analyticsSession?.notePresentation(this.currentPresentation()),n=()=>{t(),this.emit(`pipchange`,!0)},r=()=>{t(),this.emit(`pipchange`,!1)};e.addEventListener(`enterpictureinpicture`,n),e.addEventListener(`leavepictureinpicture`,r);let i=typeof document<`u`?document:void 0;i?.addEventListener(`fullscreenchange`,t),i?.addEventListener(`webkitfullscreenchange`,t),this.detachPip=()=>{e.removeEventListener(`enterpictureinpicture`,n),e.removeEventListener(`leavepictureinpicture`,r),i?.removeEventListener(`fullscreenchange`,t),i?.removeEventListener(`webkitfullscreenchange`,t)}}attachEndedPlayGuard(){let e=this.opts.video,t=()=>{this.streamEnded&&e.pause()};e.addEventListener(`play`,t),this.detachEndedPlayGuard=()=>e.removeEventListener(`play`,t)}startStats(){this.stopStats();let e=Math.max(500,this.opts.statsIntervalMs??T_);this.statsTimer=setInterval(()=>{if(!this.engine)return;let e=this.engine.getStats();(e.bytesLoaded??0)>0&&this.analyticsSession?.noteFirstBytes(),this.emit(`stats`,e)},e)}stopStats(){this.statsTimer&&clearInterval(this.statsTimer),this.statsTimer=void 0}isStaleLicenseDenial(e){return this.staleLicenseReloaded||this.opts.hlsConfig?.licenseXhrSetup||this._state===`ended`||this._state===`error`||e.detail!==D_||e.error.httpStatus!==403||e.error.code!==`FORBIDDEN`||e.error.serverCode===`license_refused`?!1:lh(this._descriptor?.drm?.widevine?.licenseUrl)}scheduleLicenseRefresh(){if(this.stopRefresh(),!this._descriptor?.drmEnabled)return;typeof document<`u`&&this.engine?.name===`hls`&&(this.onRefocus=()=>{document.visibilityState!==`visible`||this.destroyed||lh(this._descriptor?.drm?.widevine?.licenseUrl)&&this.refreshLicense()},document.addEventListener(`visibilitychange`,this.onRefocus));let e=this.opts.licenseRefreshMs??E_;e&&(this.refreshTimer=setInterval(()=>void this.refreshLicense(),e))}stopRefresh(){this.refreshTimer&&clearInterval(this.refreshTimer),this.refreshTimer=void 0,this.onRefocus&&typeof document<`u`&&(document.removeEventListener(`visibilitychange`,this.onRefocus),this.onRefocus=void 0)}refreshLicense(){let e=this.engine;if(this.destroyed||!e)return Promise.resolve(void 0);if(this.refreshInFlight?.engine===e)return this.refreshInFlight.promise;let t=(async()=>{try{let t=await ee(this.resolveOptions());if(this.destroyed||this.engine!==e)return;let n=t.drm?.widevine?.licenseUrl,r=t.drm?.fairplay?.licenseUrl;return(n||r)&&(e.setLicenseUrls({widevine:n,fairplay:r}),this._descriptor=t),n}catch(e){e instanceof a&&!u(e.code)&&(this.stopRefresh(),this.destroyed||this.emit(`warning`,e));return}finally{this.refreshInFlight?.promise===t&&(this.refreshInFlight=void 0)}})();return this.refreshInFlight={engine:e,promise:t},t}async play(){if(this.destroyed)return;let e=!this.playRequested;if(this.playRequested=!0,this.idleClosed&&this._state!==`ended`&&this._state!==`error`){this.idleClosed=!1,await this.reload();return}if(this.streamEnded)return;let t=this.pendingStartLoad&&this._state!==`ended`&&this._state!==`error`;this.opts.autoplay===!1&&this.analyticsSession?.notePlayIntent(),t&&(this.pendingStartLoad=!1,this.setState(`loading`),this.engine?.startLoad());try{await this.opts.video.play(),e&&this.analyticsSession?.noteAutoplay(this.opts.video.muted?`AUTOPLAY_RESULT_ALLOWED_MUTED`:`AUTOPLAY_RESULT_ALLOWED`)}catch(n){n instanceof DOMException&&n.name===`NotAllowedError`&&(this.analyticsSession?.noteAutoplay(`AUTOPLAY_RESULT_BLOCKED`),e&&(this.playRequested=!1),t&&!this.destroyed&&this._state===`loading`&&this.setState(`paused`),this.emit(`autoplayblocked`))}}pause(){this.destroyed||this.opts.video.pause()}setMuted(e){this.destroyed||(this.opts.video.muted=e)}setVolume(e){this.destroyed||(this.opts.video.volume=Math.min(1,Math.max(0,e)))}getStats(){return this.engine?.getStats()??Lm}getQualityLevels(){return this.engine?.getQualityLevels()??[]}getCurrentQuality(){return this.engine?.getCurrentQuality()??-1}setQuality(e){this.destroyed||this.engine?.setQuality(e===`auto`?-1:e)}setMaxBitrate(e){this.destroyed||this.engine?.setMaxBitrate(e)}getAudioTracks(){return this.engine?.getAudioTracks()??[]}setAudioTrack(e){this.destroyed||this.engine?.setAudioTrack(e)}getTextTracks(){return this.engine?.getTextTracks()??[]}setTextTrack(e){this.destroyed||this.engine?.setTextTrack(e)}seekToLive(){this.destroyed||this.engine?.seekToLive()}async enterPictureInPicture(){if(this.destroyed)return;let e=this.opts.video;typeof e.requestPictureInPicture==`function`&&await e.requestPictureInPicture()}async exitPictureInPicture(){let e=document;e.pictureInPictureElement===this.opts.video&&typeof e.exitPictureInPicture==`function`&&await e.exitPictureInPicture()}async enterFullscreen(){return!this.destroyed&&de(this.opts.video,this.container??void 0)}async exitFullscreen(){await fe(this.opts.video,this.container??void 0)}fullscreenSupported(){return!this.destroyed&&ue(this.opts.video,this.container??void 0)}retry(){return this.reload()}async reload(){if(this.destroyed)return;let e=++this.loadGen;this.teardownPlayback();try{let t=await te({...this.resolveOptions(),waitForLive:this.opts.waitForLive?this.buildWaitConfig(e):void 0});if(await this.onResolved(t,e),e===this.loadGen&&this._state===`error`&&this._lastError)throw this._lastError}catch(t){if(this.destroyed||this.abort.signal.aborted||e!==this.loadGen)return;throw t!==this._lastError&&this.fail(t instanceof a?t:new a(`INTERNAL`,0,String(t))),t}}on(e,t){let n=this.listeners[e]??=new Set;return n.add(t),()=>n.delete(t)}destroy(){this.destroyed||(this.destroyed=!0,this.loadGen+=1,this.abort.abort(),this.stopStats(),this.stopRefresh(),this.unmountControls(),this.cancelRejoin(),this.closeArming(),this.closeLiveState(),this.unwatchReturn(),this.detachMedia?.(),this.detachPip?.(),this.detachEndedPlayGuard?.(),this.analyticsSession?.noteDestroyed(),this.analyticsSession=null,this.detachMediaListeners?.(),this.engine?.destroy(),this.engine=null,this.setState(`idle`),this.clearListeners())}clearListeners(){for(let e of Object.keys(this.listeners))this.listeners[e]?.clear()}fail(e){this._lastError=e,this.setState(`error`),this.analyticsSession?.noteFatal(),this.emit(`error`,e)}setState(e){if(e===this._state)return;let t=this._state;if(this._state=e,this.analyticsSession){let n=this.opts.video;this.analyticsSession.noteStateChange(t,e,Math.round(n.currentTime*1e3),this.engine?.getStats().levelHeight),e===`ended`&&this.analyticsSession.noteEnded()}switch(this.emit(`statechange`,e),e){case`playing`:this.emit(`playing`);break;case`buffering`:this.emit(`buffering`);break;case`paused`:this.emit(`paused`);break;case`ended`:this.emit(`ended`,this._endedReason??void 0)}}emit(e,t){this.listeners[e]?.forEach(e=>{try{e(t)}catch{}})}};function j_(e){return!!e&&typeof e==`object`&&typeof e.type==`string`&&e.type.startsWith(`oddin:`)}function M_(e){if(!e.container||typeof e.container.appendChild!=`function`)throw Error(`mountEmbed: opts.container must be a DOM element`);if(!e.src)throw Error(`mountEmbed: opts.src is required`);if(!e.baseUrl||!e.matchUrn)throw Error(`mountEmbed: opts.baseUrl and opts.matchUrn are required`);let t=new URL(e.src,location.href),n=e.allowedFrameOrigin??t.origin;t.searchParams.set(`baseUrl`,e.baseUrl),t.searchParams.set(`matchUrn`,e.matchUrn),t.searchParams.set(`parentOrigin`,location.origin),e.muted!=null&&t.searchParams.set(`muted`,String(e.muted)),e.apiKey&&(t.searchParams.set(`apiKey`,e.apiKey),console.warn(`havik-player: passing apiKey to mountEmbed places it in the iframe URL — DEV/DEMO only. In production inject it server-side into window.HAVIK_EMBED_CONFIG on the embed page.`));let r=document.createElement(`iframe`);r.src=t.toString(),r.allow=`autoplay; encrypted-media; fullscreen`,r.setAttribute(`allowfullscreen`,``),r.referrerPolicy=`no-referrer`,r.setAttribute(`sandbox`,e.sandbox??`allow-scripts allow-same-origin allow-presentation`),r.style.cssText=`border:0;width:100%;height:100%;display:block`,e.container.appendChild(r);let i=new Set,a=t=>{if(t.source!==r.contentWindow||t.origin!==n||!j_(t.data))return;let a=t.data;a.type===`oddin:ready`&&a.protocol!==1&&console.warn(`havik-player: embed protocol v${a.protocol} != host v1. Pin the embed page version to the SDK version to avoid skew.`),e.onEvent?.(a),i.forEach(e=>e(a))};window.addEventListener(`message`,a);let o=e=>r.contentWindow?.postMessage(e,n);return{iframe:r,play:()=>o({type:`oddin:play`}),pause:()=>o({type:`oddin:pause`}),setMuted:e=>o({type:`oddin:setMuted`,muted:e}),setVolume:e=>o({type:`oddin:setVolume`,volume:e}),setQuality:e=>o({type:`oddin:setQuality`,index:e}),setMaxBitrate:e=>o({type:`oddin:setMaxBitrate`,bitrate:e}),setAudioTrack:e=>o({type:`oddin:setAudioTrack`,id:e}),setTextTrack:e=>o({type:`oddin:setTextTrack`,id:e}),seekToLive:()=>o({type:`oddin:seekToLive`}),enterPip:()=>o({type:`oddin:enterPip`}),exitPip:()=>o({type:`oddin:exitPip`}),retry:()=>o({type:`oddin:retry`}),load:e=>o({type:`oddin:load`,matchUrn:e}),on:e=>(i.add(e),()=>i.delete(e)),destroy:()=>{o({type:`oddin:destroy`}),window.removeEventListener(`message`,a),r.remove()}}}var N_=/^[A-Za-z0-9:_.-]{1,128}$/;function P_(e){if(typeof e==`boolean`)return e;if(typeof e==`object`&&e){let t=e.endpoint;return typeof t==`string`?{endpoint:t}:{}}}function F_(){let e=window.HAVIK_EMBED_CONFIG;if(e)return{baseUrl:e.baseUrl??``,matchUrn:e.matchUrn??``,apiKey:e.apiKey??``,parentOrigin:e.parentOrigin,autoplay:e.autoplay??!0,muted:e.muted??!0,waitForLive:e.waitForLive??!0,analytics:P_(e.analytics)};let t=new URLSearchParams(location.search);return{baseUrl:t.get(`baseUrl`)??``,matchUrn:t.get(`matchUrn`)??``,apiKey:t.get(`apiKey`)??``,parentOrigin:t.get(`parentOrigin`)??void 0,autoplay:!0,muted:t.get(`muted`)!==`false`,waitForLive:!0}}async function I_(){let e=F_();R_();let t=document.createElement(`video`);t.setAttribute(`playsinline`,``),t.muted=e.muted??!0,t.style.cssText=`width:100%;height:100%;object-fit:contain;background:#000;aspect-ratio:auto`,document.body.appendChild(t);let n=e.parentOrigin&&e.parentOrigin!==`null`?e.parentOrigin:null;n||console.warn(`havik-player: embed has no parentOrigin — the postMessage bridge is disabled (no events posted, no commands accepted). mountEmbed sets parentOrigin automatically.`);let r=e=>{if(n)try{window.parent?.postMessage(e,n)}catch{}};if(!e.baseUrl||!e.matchUrn||!e.apiKey){r({type:`oddin:error`,code:`INTERNAL`,message:`embed missing baseUrl/matchUrn/apiKey`});return}let i=null,o=e=>{e.on(`statechange`,e=>r({type:`oddin:state`,state:e})),e.on(`ready`,()=>r({type:`oddin:tracks`,quality:e.getQualityLevels(),audio:e.getAudioTracks(),text:e.getTextTracks()})),e.on(`waiting`,e=>r({type:`oddin:waiting`,retryInMs:e.retryInMs,attempt:e.attempt,phase:e.phase})),e.on(`qualitychange`,e=>r({type:`oddin:qualitychange`,index:e})),e.on(`audiotrackchange`,e=>r({type:`oddin:audiotrackchange`,id:e})),e.on(`texttrackchange`,e=>r({type:`oddin:texttrackchange`,id:e})),e.on(`stats`,e=>r({type:`oddin:stats`,droppedFrames:e.droppedFrames,latencySeconds:e.latencySeconds,bandwidthKbps:e.bandwidthKbps,levelHeight:e.levelHeight,lowLatency:e.lowLatency,isLive:e.isLive,atLiveEdge:e.atLiveEdge})),e.on(`error`,e=>r({type:`oddin:error`,code:e.code,message:e.message,...e.country===void 0?{}:{country:e.country}})),e.on(`autoplayblocked`,()=>{r({type:`oddin:autoplayblocked`}),L_(t,e)})},s=async n=>{i?.destroy(),i=null;try{let r=await k_({video:t,baseUrl:e.baseUrl,matchUrn:n,credential:{apiKey:e.apiKey},autoplay:e.autoplay,muted:e.muted,waitForLive:e.waitForLive,analytics:e.analytics});i=r;let a=t.parentElement;a?.classList.contains(`havik-player`)&&(a.style.cssText=`position:absolute;inset:0;width:100%;height:100%;aspect-ratio:auto`),o(r)}catch(e){let t=e instanceof a?e.code:`INTERNAL`,n=e instanceof Error?e.message:String(e),i=e instanceof a?e.country:void 0;r({type:`oddin:error`,code:t,message:n,...i===void 0?{}:{country:i}})}},c=()=>{window.removeEventListener(`message`,u),window.removeEventListener(`pagehide`,c),i?.destroy(),i=null},l=e=>{switch(e.type){case`oddin:play`:i?.play();break;case`oddin:pause`:i?.pause();break;case`oddin:setMuted`:typeof e.muted==`boolean`&&i?.setMuted(e.muted);break;case`oddin:setVolume`:typeof e.volume==`number`&&Number.isFinite(e.volume)&&i?.setVolume(e.volume);break;case`oddin:setQuality`:typeof e.index==`number`&&i?.setQuality(e.index);break;case`oddin:setMaxBitrate`:(e.bitrate===null||typeof e.bitrate==`number`&&Number.isFinite(e.bitrate))&&i?.setMaxBitrate(e.bitrate);break;case`oddin:setAudioTrack`:typeof e.id==`number`&&i?.setAudioTrack(e.id);break;case`oddin:setTextTrack`:typeof e.id==`number`&&i?.setTextTrack(e.id);break;case`oddin:seekToLive`:i?.seekToLive();break;case`oddin:enterPip`:i?.enterPictureInPicture();break;case`oddin:exitPip`:i?.exitPictureInPicture();break;case`oddin:retry`:i?.retry();break;case`oddin:load`:typeof e.matchUrn==`string`&&N_.test(e.matchUrn)&&s(e.matchUrn);break;case`oddin:destroy`:c()}},u=e=>{n&&e.origin===n&&j_(e.data)&&l(e.data)};n&&window.addEventListener(`message`,u),window.addEventListener(`pagehide`,c,{once:!0}),await s(e.matchUrn),r({type:`oddin:ready`,protocol:1})}function L_(e,t){if(document.getElementById(`havik-tap`))return;let n=document.createElement(`button`);n.id=`havik-tap`,n.textContent=`▶ Tap to play`,n.style.cssText=`position:fixed;inset:0;width:100%;height:100%;border:0;background:rgba(0,0,0,.55);color:#fff;font:600 18px system-ui,sans-serif;cursor:pointer;z-index:9`,n.addEventListener(`click`,()=>{n.remove(),t.play()}),document.body.appendChild(n)}function R_(){let e=document.createElement(`style`);e.textContent=`html,body{margin:0;height:100%;background:#000;overflow:hidden}body{display:flex}`,document.head.appendChild(e)}return e.LiveStateHttpError=xe,e.ODDIN_THEME=e_,e.PlaybackError=a,e.applyTheme=n_,e.baseUrlForEnv=ht,e.bootEmbed=I_,e.clearDeviceId=Oe,e.clearRememberedBandwidth=Ve,e.createPlayer=k_,e.deriveEventsBaseUrl=we,e.detectDrmSupport=dt,e.enterVideoFullscreen=de,e.exitVideoFullscreen=fe,e.fetchCatalog=pe,e.fetchTournament=he,e.flattenMatches=_e,e.fullscreenSupported=ue,e.getDeviceId=De,e.isLowLatencyManifest=pt,e.isOddinMessage=j_,e.licenseRequestHeaders=Ae,e.mountEmbed=M_,e.pollToLive=N,e.resolveStream=te,e.subscribeLiveState=Ce,e.videoFullscreenActive=le,e.watchStatus=ye,e})({});
|
|
175
175
|
//# sourceMappingURL=havik-player.global.js.map
|