@oddin-gg/havik-player 2.22.0 → 2.23.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 +2 -2
- package/dist/havik-player.global.js.map +1 -1
- package/dist/index.cjs +2 -2
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +61 -1
- package/dist/index.d.ts +61 -1
- package/dist/index.js +376 -249
- package/dist/index.js.map +1 -1
- package/docs/API.md +99 -54
- package/embed/index.html +1 -1
- package/examples/vanilla.html +1 -1
- package/package.json +1 -1
|
@@ -41,7 +41,7 @@ transfer tracks: ${q(r,(e,t)=>e===`initSegment`?void 0:t)}}`),!an(r,n)){t.mediaS
|
|
|
41
41
|
`)}),s.flush()}var df=`stpp.ttml.im1t`,ff=/^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/,pf=/^(\d*(?:\.\d*)?)(h|m|s|ms|f|t)$/,mf={left:`start`,center:`center`,right:`end`,start:`start`,end:`end`};function hf(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=>Dn(e)),o=Fc(t.baseTime,1,t.timescale);try{a.forEach(e=>n(gf(e,o)))}catch(e){r(e)}}function gf(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,frameRateMultiplier:0,tickRate:1},i=Object.keys(r).reduce((e,t)=>(e[t]=n.getAttribute(`ttp:${t}`)||r[t],e),{});!n.getAttribute(`ttp:tickRate`)&&n.getAttribute(`ttp:frameRate`)&&(i.tickRate=Number(i.frameRate)*Number(i.subFrameRate));let a=n.getAttribute(`xml:space`)!==`preserve`,o=vf(_f(n,`styling`,`style`)),s=vf(_f(n,`layout`,`region`)),c=_f(n,`body`,`[begin]`);return[].map.call(c,e=>{let n=yf(e,a);if(!n||!e.hasAttribute(`begin`))return null;let r=Cf(e.getAttribute(`begin`),i),c=Cf(e.getAttribute(`dur`),i),l=Cf(e.getAttribute(`end`),i);if(r===null)throw Sf(e);if(l===null){if(c===null)throw Sf(e);l=r+c}let u=new Yd(r-t,l-t,n);u.id=lf(u.startTime,u.endTime,u.text);let d=s[e.getAttribute(`region`)],f=o[e.getAttribute(`style`)],p=bf(d,f,o),{textAlign:m}=p;if(m){let e=mf[m];e&&(u.lineAlign=e),u.align=m}return V(u,p),u}).filter(e=>e!==null)}function _f(e,t,n){let r=e.getElementsByTagName(t)[0];return r?[].slice.call(r.querySelectorAll(n)):[]}function vf(e){return e.reduce((e,t)=>{let n=t.getAttribute(`xml:id`);return n&&(e[n]=t),e},{})}function yf(e,t){return[].slice.call(e.childNodes).reduce((e,n,r)=>{var i;return n.nodeName===`br`&&r?e+`
|
|
42
42
|
`:(i=n.childNodes)!=null&&i.length?yf(n,t):t?e+n.textContent.trim().replace(/\s+/g,` `):e+n.textContent},``)}function bf(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=xf(t,r,a)||xf(e,r,a)||xf(i,r,a);return o&&(n[a]=o),n},{})}function xf(e,t,n){return e&&e.hasAttributeNS(t,n)?e.getAttributeNS(t,n):null}function Sf(e){return Error(`Could not parse ttml timestamp ${e}`)}function Cf(e,t){if(!e)return null;let n=Zd(e);return n===null&&(ff.test(e)?n=wf(e,t):pf.test(e)&&(n=Tf(e,t))),n}function wf(e,t){let n=ff.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 Tf(e,t){let n=pf.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 Ef(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 Df(e){return e.forced&&Gr()?`forced`:e.characteristics&&/transcribes-spoken-dialog/gi.test(e.characteristics)&&/describes-music-and-sound/gi.test(e.characteristics)?`captions`:`subtitles`}function Of(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 kf(e,t,n,r){let i=e.mode;if(i===`disabled`&&(e.mode=`hidden`),e.cues&&e.cues.length>0){let i=jf(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 Af(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 jf(e,t,n){let r=[],i=Af(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 Mf=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||=Ef(this.media,Df(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===df?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=Bi(t,e);if(n>-1)i=e[n];else{let e=Bi(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||Vi(i,e)))return r}if(e){for(let n=0;n<t.length;n++){let r=t[n];if(gl(e.attrs,r.attrs,[`LANGUAGE`,`ASSOC-LANGUAGE`,`CHARACTERISTICS`]))return n}for(let n=0;n<t.length;n++){let r=t[n];if(gl(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&&Ji(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&&Vi(e,n))return n;let r=Bi(e,this.tracksInGroup);if(r>-1){let e=this.tracksInGroup[r];return this.setSubtitleTrack(r,!0),e}if(n)return null;{let n=Bi(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)}},Nf=2,Pf=100,Ff=class extends ja{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(Pf),this.mediaSource=t.mediaSource;let n=this.media=t.media;X(n,`playing`,this.onMediaPlaying),X(n,`waiting`,this.onMediaWaiting),X(n,`ended`,this.onMediaEnded)}onMediaDetaching(e,t){this.clearInterval();let{media:n}=this;n&&(Z(n,`playing`,this.onMediaPlaying),Z(n,`waiting`,this.onMediaWaiting),Z(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&&zf(c,e,l,this.hls);let u=c.nextStart||0;if(i&&l&&this.hls){let t=If(this.hls.inFlightFragments,e),n=c.len>Nf,r=!u||t||u-e>Nf&&!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:Nf,i=Rf(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=Rf(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=Rf(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);zf(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)||If(r.inFlightFragments,s))return 0;let n=!1,i=e.end;for(;i<s;){let e=Rf(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 If(e,t){let n=Lf(e.main);if(n&&n.start<=t)return n;let r=Lf(e.audio);return r&&r.start<=t?r:null}function Lf(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 Rf(e,t){return t.getAppendedFrag(e,z.MAIN)||t.getPartialFragment(e)}function zf(e,t,n,r){let i=r.latestLevelDetails,a=Rf(t,n);if(ds(r.config)&&!e.nextStart&&i&&a&&r.interstitialsManager){let n=`type`in a?a:a.fragment,o=ia(i,n.sn);o?.level===n.level&&us(o,r.interstitialsManager.playerQueue,t)&&(e.nextStart=o.start)}}var Bf=.25;function Vf(){if(!(typeof self>`u`))return self.VTTCue||self.TextTrackCue}function Hf(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 Uf=(()=>{let e=Vf();try{e&&new e(0,1/0,``)}catch{return Number.MAX_VALUE}return 1/0})(),Wf=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 Ef(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=Vf();if(a)for(let e=0;e<i.length;e++){let t=i[e].type;if(t===Is.emsg&&!n||!r)continue;let o=In(i[e].data),s=i[e].pts,c=s+i[e].duration;c>Uf&&(c=Uf),c-s<=0&&(c=s+Bf);for(let e=0;e<o.length;e++){let n=o[e];if(!Ln(n)){this.updateId3CueEnds(s,t);let e=Hf(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===Uf&&(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===Is.audioId3&&s:r===`video`?e=>e.type===Is.emsg&&o:e=>e.type===Is.audioId3&&s||e.type===Is.emsg&&o,kf(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=Vf();if(n&&r&&!a){let{fragmentStart:t,fragmentEnd:r}=e,i=this.assetCue;i?(i.startTime=t,i.endTime=r):o&&(i=this.assetCue=Hf(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=Uf,{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(!Wa(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];Ga(c)&&(e=Vn(e));let i=Hf(o,r,f,{key:c,data:e},Is.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 Gf(){return self.SourceBuffer||self.WebKitSourceBuffer}function Kf(){if(!nn())return!1;let e=Gf();return!e||e.prototype&&typeof e.prototype.appendBuffer==`function`&&typeof e.prototype.remove==`function`}function qf(){if(!Kf())return!1;let e=nn();return typeof e?.isTypeSupported==`function`&&([`avc1.42E01E,mp4a.40.2`,`av01.0.01M.08`,`vp09.00.50.08`].some(t=>e.isTypeSupported(Zr(t,`video`)))||[`mp4a.40.2`,`fLaC`].some(t=>e.isTypeSupported(Zr(t,`audio`))))}function Jf(){var e;let t=Gf();return typeof(t==null||(e=t.prototype)==null?void 0:e.changeType)==`function`}var Yf={DISABLED:0,SWITCHING:1,SWITCHED:2},Xf=100,Zf=class extends ls{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=Yf.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(Xf),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(){var e;super.onTickEnd(),(e=this.media)!=null&&e.readyState&&this.media.seeking===!1&&(this.lastCurrentTime=this.media.currentTime),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)){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&&Ct(f)&&this.fragmentTracker.getState(f)!==da.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===da.NOT_LOADED||r===da.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!==Yf.DISABLED&&(this.getLevelDetails()?.fragmentStart||0)>this.lastCurrentTime&&super.flushMainBuffer(0,1/0,`audio`)}getBufferOutput(){return this.mediaBuffer&&this.altAudio===Yf.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===Yf.SWITCHED&&!this.audioOnly?`video`:null}onMediaAttached(e,t){super.onMediaAttached(e,t);let n=t.media;X(n,`playing`,this.onMediaPlaying),X(n,`seeked`,this.onMediaSeeked)}onMediaDetaching(e,t){let{media:n}=this;n&&(Z(n,`playing`,this.onMediaPlaying),Z(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=Yf.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&&!Jf(),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 dl(this.hls,z.MAIN,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)),f=n?n.index:-1,p=f!==-1,{decryptRange:m,byteRange:h}=Da(t,n,this.iframesOnly),g=new Ma(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!==Yf.DISABLED;if(qi(t.url,n))this.altAudio=Yf.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=Yf.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=qi(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?Yf.SWITCHED:Yf.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(Ct(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._hasEnoughToStart=!0,this.seekToStartPos()),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.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)>Nf&&(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(`${Ct(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=ai(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&&!Ur()&&(r=`mp4a.40.5`)}r&&r.indexOf(`mp4a.40.5`)!==-1&&Kr()&&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?$i(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}},Qf=class extends Zf{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&&Ct(t)&&this.cacheSet(t,new Uint8Array(r.slice(0))),super._handleFragmentLoadProgress(e)}loadFragment(e,t,n){let r=this.fragmentTracker.getState(e);if((r===da.NOT_LOADED||r===da.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 xt;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?cs(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)}},$f=class extends Qf{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&&!wt(t,this.fragPlaying))return this.fragPlaying=t,!0}return!1}getMainFwdBufferInfo(){return{len:0,start:this.playhead,end:this.playhead,bufferedIndex:-1}}},ep=10,tp=`Image I-Frame player does not accept HTMLMediaElements`,np={seekOnAppend:!0},rp,ip,ap=class extends Jt{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,rp||=op(t),ip||=sp(rp),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)>ep&&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(rp,this.hls?.iframeVariants,e)}createImageIFramePlayer(e){let t=this.hls?.iframeVariants.filter(e=>e.imageCodec);return this.createInstance(ip,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],_=Yi(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 op(e){return class extends e{constructor(e,t,n,r){e.streamController||=Qf,super(e),this._url=t,this.streamController.setInitPts(n),this.streamController.initDetails=r}loadSource(){}loadMediaAt(e,t=np){if(e<0)return;let n=H(H({},np),t);this.loadingEnabled||this.startLoad(e),this.streamController.loadMediaAt(e,n)}}}function sp(e){return class extends e{constructor(e,t,n,r){e.cmcdController=void 0,e.emeController=void 0,e.streamController||=$f,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(tp)}detachMedia(){}recoverMediaError(){}transferMedia(){return null}loadMediaAt(e){if(e<0)return null;this.loadingEnabled||this.startLoad(e),this.streamController.loadMediaAt(e)}}}var cp=.025,lp=function(e){return e[e.Point=0]=`Point`,e[e.Range=1]=`Range`,e}({});function up(e,t,n){return`${e.identifier}-${n+1}-${of(t)}`}var dp=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 pp(t,e)?fp(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-fp(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 pp(t,e)?fp(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)<cp))}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`?lp.Range:lp.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 gp(this)}};function fp(e,t){return e-t.start<t.duration/2&&!(Math.abs(e-(t.start+t.duration))<cp)?t.start:t.start+t.duration}function pp(e,t){return t>e.start-cp&&t<e.start+e.duration+cp}function mp(e,t,n){let r=new self.URL(e,n);return r.protocol!==`data:`&&Si(r,`_HLS_primary_id`,t),r}function hp(e,t){for(;(n=e.assetList[++t])!=null&&n.error;)var n;return t}function gp(e){return`["${e.identifier}" ${e.cue.pre?`<pre>`:e.cue.post?`<post>`:``}${e.timelineStart.toFixed(2)}-${e.resumeTime.toFixed(2)}]`}function _p(e){let t=e.timelineStart,n=e.duration||0;return`["${e.identifier}" ${t.toFixed(2)}-${(t+n).toFixed(2)}]`}var vp=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=mp(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: ${_p(this.assetItem)} ${this.hls?.sessionId} ${this.appendInPlace?`append-in-place`:``}`}},yp=.033,bp=class extends Jt{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 dp(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===lp.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>yp){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>yp?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=$i(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<yp&&(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)>cp?(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=$i(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)<cp+s||Math.abs(o.end-n)<cp+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 xp(e){return`[${e.event?`"`+e.event.identifier+`"`:`primary`}: ${e.start.toFixed(2)}-${e.end.toFixed(2)}]`}var Sp=class{constructor(e){this.hls=void 0,this.hls=e}destroy(){this.hls=null}loadAssetList(e,t){let n=e.assetListUrl,r;try{r=mp(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:`&&Si(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 Cp(e){var t;e==null||(t=e.play())==null||t.catch(()=>{})}function wp(e,t){return`[${e}] Advancing timeline position to ${t}`}var Tp=class extends Jt{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}
|
|
43
43
|
Schedule: ${a.map(e=>xp(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),this.waitingItem=this.updateItem(this.waitingItem);let d=this.bufferingItem;if(d&&(u=this.updateItem(d,this.bufferedPos),this.itemsMatch(d,u)?this.bufferingItem=u:d.event&&(this.bufferingItem=this.playingItem,this.clearInterstitial(d.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)>cp&&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),d&&u!==l&&this.trimInPlace(u,d),this.checkBuffer()}},this.hls=e,this.HlsPlayerClass=t,this.assetListLoader=new Sp(e),this.schedule=new bp(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){Z(e,`play`,this.onPlay),Z(e,`pause`,this.onPause),Z(e,`seeking`,this.onSeeking),Z(e,`timeupdate`,this.onTimeupdate)}onMediaAttaching(e,t){let n=this.media=t.media;X(n,`seeking`,this.onSeeking),X(n,`timeupdate`,this.onTimeupdate),X(n,`play`,this.onPlay),X(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!==lp.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(wp(`checkStart (preroll)`,r));let n=e.findEventIndex(t[0].identifier);this.setSchedulePosition(n)}else if(r>=0||!this.primaryLive){this.log(wp(`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(wp(`checkStart (playing item)`,i.start));let t=e.findItemIndex(i);this.setSchedulePosition(t)}}advanceAssetBuffering(e,t){let n=e.event,r=hp(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=hp(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(wp(`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&&xp(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} ${_p(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} ${xp(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=$i(null,e,c);i&&(t=Math.min(Math.max(n[r].start,fp(t,i)),n[r].end))}}if(this.log(wp(`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=hp(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 ${xp(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&&Cp(l.media)}else o?(this.resumePrimary(o,e,r),this.shouldPlay&&Cp(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 ${xp(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(wp(`resumePrimary`,i)),this.timelinePos=i),this.attachPrimary(i,e)),!n)return;let a=this.schedule?.items;a&&(this.log(`INTERSTITIALS_PRIMARY_RESUMED ${xp(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(wp(`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?xp(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?xp(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=zi(t);this.playerQueue.forEach(({hls:e})=>e&&(e.setAudioOption(t)||e.setAudioOption(n)))}onSubtitleTrackSwitch(e,t){let n=zi(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 ${xp(e)} (was ${xp(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 ${xp(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:up(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=Yi(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:of(t.uri)})),this.getAssetPlayer(l)&&this.warn(`Duplicate date range identifier ${e} and asset ${l}`);let f=new vp(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 ${_p(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&&xp(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} ${_p(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&&!an(s,e.tracks)){let t=Error(`Asset ${_p(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&&_p(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:ua(!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: ${xp(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||!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}}}},Ep=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=ds(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}},Dp=500,Op=class extends ls{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(Dp),this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,this.tick()}onManifestLoading(){super.onManifestLoading(),this.mainDetails=null}onMediaDetaching(e,t){this.tracksBuffered=[],super.onMediaDetaching(e,t)}onLevelLoaded(e,t){this.mainDetails=t.details}onSubtitleFragProcessed(e,t){let{frag:n,part:r,success:i}=t;if(!i)return;let a=this.tracksBuffered[this.currentTrackId];if(!a)return;let o,s=(r||n).start;for(let e=0;e<a.length;e++)if(s>=a[e].start&&s<=a[e].end){o=a[e];break}let c=s+(r||n).duration;if(o?o.end=c:(o={start:s,end:c},a.push(o)),!r||c>=n.end){let e=this.fragmentTracker.fragBuffered(n);r&&e&&(e.range.subs={time:[{startPTS:n.start,endPTS:c}],partial:!0}),Ct(n)&&!this.fragContextChanged(n)&&(this.fragPrevious=n),this.fragBufferedComplete(n,r),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&&hl(this.levels,t)){this.levels=t.map(e=>new Ai(e));return}this.tracksBuffered=[],this.levels=t.map(e=>{let t=new Ai(e);return this.tracksBuffered[t.id]=[],t}),this.fragmentTracker.removeFragmentsInRange(0,1/0,z.SUBTITLE),this.fragPrevious=null,this.mediaBuffer=null}onSubtitleTrackSwitch(e,t){var n;if(this.currentTrackId=t.id,!((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(Dp)}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||(as(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&&Za(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,Qa(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,{end:s,len:c}=J.bufferedInfo(this.tracksBuffered[this.currentTrackId]||[],o,a.maxBufferHole);if(c>Math.max(this.hls.maxBufferLength+i.levelTargetDuration,this.hls.mainForwardBufferInfo?.len||0)||c&&!this.buffering)return;let l=this.getNextFragment(s,i);if(!l)return;if(Ct(l)){var e;let t=l.sn-i.startSN,n=i.fragments[t-1];l.cc===n?.cc&&!((e=i.partList)!=null&&e.length)&&this.fragmentTracker.getState(n)===da.NOT_LOADED&&(l=n)}this.loadFragment(l,r,s)}}loadFragment(e,t,n){let r=this.fragmentTracker.getState(e);(r===da.NOT_LOADED||r===da.PARTIAL)&&super.loadFragment(e,t,n)}get mediaBufferTimeRanges(){return new kp(this.tracksBuffered[this.currentTrackId]||[])}},kp=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)}}}},Ap={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},jp=e=>String.fromCharCode(Ap[e]||e),Mp=15,Np=42,Pp={17:1,18:3,21:5,22:7,23:9,16:11,19:12,20:14},Fp={17:2,18:4,21:6,22:8,23:10,19:13,20:15},Ip={25:1,26:3,29:5,30:7,31:9,24:11,27:12,28:14},Lp={25:2,26:4,29:6,30:8,31:10,27:13,28:15},Rp=[`white`,`green`,`blue`,`cyan`,`red`,`yellow`,`magenta`,`black`,`transparent`],zp=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}`)}}},Bp=function(e){let t=[];for(let n=0;n<e.length;n++)t.push(e[n].toString(16));return t},Vp=Object.freeze({foreground:`white`,underline:!1,italics:!1,background:`black`,flash:!1}),Hp=class{constructor(){this.styles=Vp}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=Vp}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}},Up=class{constructor(){this.uchar=` `,this.penState=new Hp}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}},Wp=class{constructor(e){this.chars=[],this.pos=0,this.currPenState=new Hp,this.cueStartTime=null,this.logger=void 0;for(let e=0;e<Np;e++)this.chars.push(new Up);this.logger=e}equals(e){let t=this.chars,n=e.chars;for(let e=0;e<Np;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<Np;t++)this.chars[t].copy(e.chars[t])}isEmpty(){let e=this.chars;for(let t=0;t<Np;t++){let n=e[t];if(n.uchar!==` `)return!1;let r=n.penState.styles;if(r!==Vp&&(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>=Np&&(this.logger.log(3,`Too large cursor position `+this.pos),this.pos=41)}moveCursor(e){let t=Math.min(this.pos+e,Np);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=jp(e);if(this.pos>=Np){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<Np;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<Np;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)}},Gp=class{constructor(e){this.rows=[],this.currRow=14,this.nrRollUpRows=null,this.lastOutputScreen=null,this.logger=void 0;for(let t=0;t<Mp;t++)this.rows.push(new Wp(e));this.logger=e}reset(){for(let e=0;e<Mp;e++)this.rows[e].clear();this.currRow=14}equals(e){let t=!0;for(let n=0;n<Mp;n++)if(!this.rows[n].equals(e.rows[n])){t=!1;break}return t}copy(e){for(let t=0;t<Mp;t++){let n=this.rows[t].chars,r=e.rows[t].chars;for(let e=0;e<Np;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<Mp;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<Mp;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<Mp;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(`
|
|
44
|
-
`)),n}getTextAndFormat(){return this.rows}},Kp=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 Gp(n),this.nonDisplayedMemory=new Gp(n),this.lastOutputScreen=new Gp(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))}},qp=class{constructor(e,t,n){this.channels=[null,null,null],this.currentChannel=0,this.cmdHistory=Xp(),this.logger=void 0,this.field=void 0,this.outputFilters=void 0,this.logger=new zp,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 Kp(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,()=>`[`+Bp([t[e],t[e+1]])+`] -> (`+Bp([n,r])+`)`);let o=this.cmdHistory;if(n>=16&&n<=31){if(Yp(n,r,o)){Jp(null,null,o),this.logger.log(3,()=>`Repeated command (`+Bp([n,r])+`) is dropped`);continue}Jp(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 Jp(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 `+Bp([n,r])+` orig: `+Bp([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 (`+Bp([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?Pp[e]:Ip[e]:r===1?Fp[e]:Lp[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 '`+jp(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 = `+Bp(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=Rp[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()}Jp(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 Jp(e,t,n){n.a=e,n.b=t}function Yp(e,t,n){return n.a===e&&n.b===t}function Xp(){return{a:null,b:null}}var Zp=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}},Qp=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.unparsedVttFrags=[],this.captionsTracks={},this.cueCache={},this.nonNativeCaptionsTracks={},this.cea608Parser1=void 0,this.cea608Parser2=void 0,this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs=em(),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 Zp(this,`textTrack1`),t=new Zp(this,`textTrack2`),n=new Zp(this,`textTrack3`),r=new Zp(this,`textTrack4`);this.cea608Parser1=new qp(1,e,t),this.cea608Parser2=new qp(3,n,r)}addCues(e,t,n,r,i){let a=!1;for(let e=i.length;e--;){let r=i[e],o=$p(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{unparsedVttFrags:r}=this;t===z.MAIN&&(this.initPTS=n),r.length&&(this.unparsedVttFrags=[],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]=Ef(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=em(),this.tracks=[],this.captionsTracks={},this.nonNativeCaptionsTracks={},this.unparsedVttFrags=[],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&&!hl(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===df?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,i=this.hls;hf(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,unparsedVttFrags:a}=this,o=i.length-1;if(!i[t.cc]&&o===-1){a.push(e);return}let s=this.hls,c=t.initSegment?.data;uf(c?Cr(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||hf(n,this.initPTS[t.cc],()=>{r.textCodec=df,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=>Of(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++)Of(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=>kf(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&&kf(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 $p(e,t,n,r){return Math.min(t,r)-Math.max(e,n)}function em(){return{ccOffset:0,presentationOffset:0,0:{start:0,prevCC:-1,new:!0}}}var tm=/\s/,nm={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++)tm.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=rf(l.trim()),p=lf(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=>Of(e,t))),i}},rm=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 xt}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(Ht(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=Bt(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 im(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch{}return!1}var am=/(\d+)-(\d+)\/(\d+)/,om=class extends rm{constructor(e){super(),this.fetchSetup=void 0,this.request=null,this.response=null,this.controller=null,this.fetchSetup=e.fetchSetup||um}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=sm(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),(sl(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 dm(t||`fetch, bad network response`,e,r)}n.loading.first=a,n.total=lm(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(Ht(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 fs,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 sm(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 cm(e){let t=am.exec(e);if(t)return parseInt(t[2])-parseInt(t[1])+1}function lm(e){let t=e.get(`Content-Range`);if(t){let e=cm(t);if(P(e))return e}let n=e.get(`Content-Length`);if(n)return parseInt(n)}function um(e,t){return new self.Request(e.url,t)}var dm=class extends Error{constructor(e,t,n){super(e),this.code=void 0,this.details=void 0,this.code=t,this.details=n}},fm=(e,t,n)=>Math.max(t,Math.min(e,n)),pm=/^age:\s*[\d.]+\s*$/im,mm=class extends rm{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(Ht(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&&pm.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}},hm=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:mm,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:lo,requireKeySystemAccessOnStart:!1,testBandwidth:!0,progressive:!1,lowLatencyMode:!0,cmcd:void 0,enableDateRangeMetadataCues:!0,enableEmsgMetadataCues:!0,enableEmsgKLVMetadata:!1,enableID3MetadataCues:!0,emsgKLVSchemaUri:void 0,enableInterstitialPlayback:!0,interstitialAppendInPlace:!0,interstitialLiveLookAhead:10,iframeCacheLimit:2097152,useMediaCapabilities:!0,preserveManualLevelOnError:!1,errorPenaltyExpireMs:0,certLoadPolicy:{default:{maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:null,errorRetry:null}},keyLoadPolicy:{default:{maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:2e4,backoff:`linear`},errorRetry:{maxNumRetry:8,retryDelayMs:1e3,maxRetryDelayMs:2e4,backoff:`linear`}}},manifestLoadPolicy:{default:{maxTimeToFirstByteMs:1/0,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},playlistLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:2,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},fragLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:12e4,timeoutRetry:{maxNumRetry:4,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:6,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},steeringManifestLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},interstitialAssetListLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:3e4,timeoutRetry:{maxNumRetry:0,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:0,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},manifestLoadingTimeOut:1e4,manifestLoadingMaxRetry:1,manifestLoadingRetryDelay:1e3,manifestLoadingMaxRetryTimeout:64e3,levelLoadingTimeOut:1e4,levelLoadingMaxRetry:4,levelLoadingRetryDelay:1e3,levelLoadingMaxRetryTimeout:64e3,fragLoadingTimeOut:2e4,fragLoadingMaxRetry:6,fragLoadingRetryDelay:1e3,fragLoadingMaxRetryTimeout:64e3,streamController:Zf,abrController:Xi,bufferController:wl,capLevelController:Ml,errorController:sa,fpsController:Jd,id3TrackController:Wf,gapController:Ff,latencyController:Ep},gm()),{},{subtitleStreamController:Op,subtitleTrackController:Mf,timelineController:Qp,audioStreamController:pl,audioTrackController:_l,emeController:Hd,cmcdController:Fd,contentSteeringController:Ld,iframeController:ap,interstitialsController:Tp});function gm(){return{cueHandler:nm,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 _m(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=fm(e,2,1/0);r!==e&&n.warn(`hls.js config: "liveMaxUnchangedPlaylistRefresh" clamped from ${e} to ${r}.`),t.liveMaxUnchangedPlaylistRefresh=r}let r=vm(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 vm(e){return e&&typeof e==`object`?Array.isArray(e)?e.map(vm):Object.keys(e).reduce((t,n)=>(t[n]=vm(e[n]),t),{}):e}function ym(e,t){let n=e.loader;n!==om&&n!==mm?(t.log(`[config]: Custom loader detected, cannot enable progressive streaming`),e.progressive=!1):im()&&(e.loader=om,e.progressive=!0,e.enableSoftwareAES=!0,t.log(`[config]: Progressive streaming enabled, using FetchLoader`))}var bm=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=Cm(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 Ai(e),n=e.supplemental;if(n!=null&&n.videoCodec&&!Sm(n.videoCodec,this.hls.config.preferManagedMediaSource)){let e=Error(`SUPPLEMENTAL-CODECS not supported "${n.videoCodec}"`);this.log(e.message),t.supportedResult=mi(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))&&Ei(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||xm(e.audioCodec,u)),wm(o)),t.subtitles&&(s=t.subtitles,wm(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 Ti.indexOf(e.videoRange)-Ti.indexOf(t.videoRange);if(e.videoCodec!==t.videoCodec){let n=Qr(e.videoCodec),r=Qr(t.videoCodec);if(n!==r)return r-n}if(e.uri===t.uri&&e.codecSet!==t.codecSet){let n=$r(e.codecSet),r=$r(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=>Cm(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));Qo(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 xm(e,t){return Yr(e,`audio`,t)}function Sm(e,t){return Yr(e,`video`,t)}function Cm(e,t){let{audioCodec:n,videoCodec:r}=e;n&&(e.audioCodec=n=ri(n,t)||void 0),r&&=e.videoCodec=si(r);let{unknownCodecs:i}=e;return!(i?.length||n&&!xm(n,t)||r&&!Sm(r,t))}function wm(e){let t={};e.forEach(e=>{let n=e.groupId||``;e.id=t[n]=t[n]||0,t[n]++})}var Tm=class extends Jt{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(Em(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(Em(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=pr(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 ${Bn(n)} keyUri: ${r}`),go.setKeyIdForUri(r,n);else{let e=go.addKeyIdForUri(r);this.log(`Patching empty keyId with ${Bn(e)} keyUri: ${r}`),n=e}e.decryptdata.keyId=n}}return this.emeController.loadKey(e).then(()=>({frag:e,keyInfo:{decryptdata:e.decryptdata}}))}return Promise.reject(Em(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(Em(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: `+Bn(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 r(Em(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(Em(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(Em(e,I.KEY_LOAD_TIMEOUT,Error(`key loading timed out`),i))},onAbort:(t,n,i)=>{this.resetLoader(n),r(Em(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 Em(e,t=I.KEY_LOAD_ERROR,n,r,i){return new Aa({type:F.NETWORK_ERROR,details:t,fatal:!1,frag:e,response:i,error:n,networkDetails:r||null})}function Dm(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 Om(e,t){let n=e.url;return(n===void 0||n.indexOf(`data:`)===0)&&(n=t.url),n}var km=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(),To.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=Om(e,n),s=To.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];Yr(o,`audio`,n)?(e.audioCodec=r=r?`${r},${o}`:o,qr.audio[r.substring(0,4)]=2,t.splice(a,1)):Yr(o,`video`,n)&&(e.videoCodec=i=i?`${i},${o}`:o,qr.video[i.substring(0,4)]=2,t.splice(a,1))}}});let{AUDIO:h=[],SUBTITLES:g,"CLOSED-CAPTIONS":_}=To.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 Ha({}),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=Om(e,n),u=P(s)?s:P(o)?o:0,d=Dm(n),f=To.parseLevelPlaylist(e.data,l,u,d,0,this.variableList);if(c===R.MANIFEST){let e={attrs:new Ha({}),bitrate:0,details:f,name:``,url:l};f.requestScheduled=t.loading.start+Jo(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=Om(t,r),m=Dm(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 vs}static isMSESupported(){return Kf()}static isSupported(){return qf()}static getMediaSource(){return nn()}static get Events(){return L}static get MetadataSchema(){return Is}static get ErrorTypes(){return F}static get ErrorDetails(){return I}static get DefaultConfig(){return e.defaultConfig?e.defaultConfig:hm}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 _s,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=tn(t.debug||!1,`Hls instance`,t.loggerId||t.assetPlayerId),r=this.config=_m(e.DefaultConfig,t,n);this.userConfig=t,r.progressive&&ym(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 fa(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 km(this),w=r.contentSteeringController,T=w?new w(this):null,E=this.levelController=new bm(this,T),D=u?new u(this):void 0,O=new Tm(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=bt.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=gn(),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){wi(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 gi(e,Li(t),navigator.mediaCapabilities)}};$.defaultConfig=void 0;var Am={droppedFrames:0};function jm(e){try{return new URL(e).host}catch{return``}}var Mm=/\.(m3u8|ts|m4s|mp4|cmfv|cmfa)(\?|$)/i;function Nm(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`||Mm.test(i.name))&&i.startTime>=n){let e=jm(i.name);e&&(t=e,n=i.startTime)}return t}function Pm(e){let t=e.getVideoPlaybackQuality?.();return{dropped:t?.droppedVideoFrames??0,totalFrames:t?.totalVideoFrames??0}}var Fm=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=Pm(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 Im(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 Lm=2e3,Rm=3,zm=500,Bm=6e3,Vm=.25,Hm=250,Um=.05,Wm=4,Gm=12e3,Km=.25,qm=1e3;function Jm(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 Ym(e){return!!(e??(typeof document<`u`?document.createElement(`video`):void 0))?.canPlayType(`application/vnd.apple.mpegurl`)}function Xm(){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 Zm(){if(typeof navigator>`u`||!Xm())return!1;let e=navigator.userAgent??``;return/iPhone|iPad|iPod/.test(e)?!0:/Macintosh/.test(e)&&typeof navigator.maxTouchPoints==`number`&&navigator.maxTouchPoints>1}var Qm=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 Fm(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=th(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=Jm(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||=Nm(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<=Wm,!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=$m();if(document.visibilityState===`hidden`){this.hiddenSince=e,this.cancelRefocus();return}let t=this.hiddenSince;this.hiddenSince=null,t!=null&&e-t>=Lm&&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=$m,n=t(),r=0,i=()=>{if(this.refocusTimer=null,Number.isFinite(this.deps.video.duration))return;r+=zm;let a=this.liveEnd(),o=a!=null&&(e==null||a>=e+Vm),s=Math.max(r,t()-n)>=Bm;if(o||s&&a!=null){this.snapToLive();return}this.refocusTimer=setTimeout(i,zm)};this.refocusTimer=setTimeout(i,zm)}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=eh(e,e.currentTime);t!=null&&((this.lastBufferedEnd==null||Math.abs(t-this.lastBufferedEnd)>=Um)&&(this.bufferedAdvancedAt=$m()),this.lastBufferedEnd=t)},Hm)}checkEndStale(){if(this.endedEmitted)return;let e=$m(),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)>=Km;this.lastSeekableEnd=n;let i=this.deps.video,a=typeof document<`u`&&document.visibilityState===`hidden`;if(r||t>qm||a||i.paused){this.edgeStampedAt=e;return}e-(this.edgeStampedAt??e)>Gm&&(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=eh(e,e.currentTime)??this.lastBufferedEnd;if(n!=null){let e=this.bufferedAdvancedAt,r=n+(e==null?0:Math.max(0,($m()-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-Rm,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 $m(){return typeof performance<`u`?performance.now():Date.now()}function eh(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 th(e,t){return t?`${e}${e.includes(`?`)?`&`:`?`}CMCD=${encodeURIComponent(`sid="${t}"`)}`:e}function nh(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 rh=4096;function ih(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>rh))try{return new TextDecoder().decode(n)}catch{return}}var ah=15e3,oh=5e3,sh=6;function ch(e){try{let t=new URL(e);return t.searchParams.delete(`CMCD`),t.toString()}catch{return e}}var lh=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=ch(e);if(this.entries.has(r))return;let i=this.perTrack.get(t)??0;if(i>=sh)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)},ah)}take(e){let t=ch(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 uh(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,`stats`,dh())}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||oh,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 dh(){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 fh(e){return e===`audio`?`audio`:`main`}function ph(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 mh(){return $.isSupported()}var hh=1e6,gh=20,_h=1e4,vh=3,yh=5,bh=3,xh=1e4,Sh=3e4,Ch=12e3,wh=3e3,Th=.02,Eh=6e3,Dh=.5,Oh=3,kh=.5,Ah=1.1,jh=.25,Mh=5e3,Nh=4e3,Ph=2,Fh=5,Ih=2,Lh=2,Rh=4,zh=4,Bh=2e3,Vh=3e4,Hh=1,Uh=2;function Wh(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 Gh=.2,Kh=30,qh=2,Jh=2,Yh=9,Xh=.5,Zh=64;function Qh(e){if(e.liveSyncDurationCount!=null||e.liveMaxLatencyDurationCount!=null){delete e.liveSyncDuration,delete e.liveMaxLatencyDuration;return}e.liveSyncDuration??=Jh;let t=Math.max(12,e.liveSyncDuration+Yh);(e.liveMaxLatencyDuration==null||e.liveMaxLatencyDuration<=e.liveSyncDuration)&&(e.liveMaxLatencyDuration=t),$h(e,e.liveSyncDuration)}function $h(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 eg=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,`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,`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.frameCounter=new Fm(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=Ym(n)&&Xm(),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&&(Je(n),tt()),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}},Mh))}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+Xh||(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)<Th)){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=Ym(this.deps.video)&&Xm(),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:qe.video,audioRobustness:qe.audio,videoEncryptionScheme:qe.scheme,audioEncryptionScheme:qe.scheme},...He()?{requestMediaKeySystemAccessFunc:Ke(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||!nh(this.licenseUrl)){s();return}let l=this.hls,u,d=new Promise(e=>{u=setTimeout(()=>e(void 0),xh)});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 lh({sessionId:t.analytics?.sid,contentId:t.matchUrn}),n=uh(e);n&&(this.prefetch=e,d.fLoader=n)}Qh(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 $(d);if(this.hls=f,f.on($.Events.FRAG_PARSED,(e,t)=>this.reanchorPartTimeline(f,t)),f.on($.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($.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},Sh)))}),f.on($.Events.FRAG_LOADING,(e,t)=>{t?.frag?.type===`main`&&(this.lastFragLoadingMs=Date.now())}),f.on($.Events.FRAG_LOADED,(e,t)=>{t?.frag?.type===`main`&&(this.mainFragsSinceTick+=1,this.bwFragsLoaded+=1,this.maybeRememberBandwidth(!1));let n=t?.frag?.stats,r=n?.loaded;typeof r==`number`&&(this.bytesLoaded+=r),!this.reportedFirstBytes&&typeof r==`number`&&r>0&&(this.reportedFirstBytes=!0,c({type:`firstBytes`}));let i=n?.loading;i&&i.end>0&&i.start>0&&(this.requestCount+=1,this.requestTimesMs.push(Math.max(0,Math.round(i.end-i.start))),this.requestTimesMs.length>Zh&&this.requestTimesMs.shift());let a=t?.frag?.url;if(a){let e=jm(a);e&&(this.cdnHost=e)}}),f.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}))}),f.on($.Events.LEVEL_LOADED,(e,t)=>this.trackEnd(t)),this.prefetch){let e=this.prefetch;f.on($.Events.KEY_LOADING,(t,n)=>{let r=n?.frag,i=fh(r?.type);if(r&&e.isActive(i))for(let t of ph(f,r))e.prefetch(t.url,i,t.kind)}),f.on($.Events.KEY_LOADED,(t,n)=>e.keyUsable(fh(n?.frag?.type)))}f.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.checkFrameDrops()},wh),f.on($.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,c({type:`qualitychange`,index:t.level})}),f.on($.Events.AUDIO_TRACK_SWITCHED,(e,t)=>c({type:`audiotrackchange`,id:t.id})),f.on($.Events.SUBTITLE_TRACK_SWITCH,(e,t)=>c({type:`texttrackchange`,id:t.id})),f.on($.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=Ml.getMaxLevelByMediaSize(e.levels,r*s,i*s),l=this.deps.sizeCapHeadroom;if(l==null&&o>=Uh)return c;let u=l??Hh,d=Number.isNaN(u)?Hh:u===1/0?e.levels.length:Math.max(0,Math.floor(u));return Wh(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?Bh:Vh;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=>nt(e)!==!0);let t=new Set(e.levels.map(e=>e.videoCodec).filter(e=>!!e&&Ye(e)!==`avc`&&!!Ye(e)));for(let n of t)et(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&&Ye(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:!Ye(e.videoCodec)||nt(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,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){this.sawLive=!0;let e=t.endSN??-1;e!==this.lastEndSN&&(this.lastEndSN=e,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>Eh&&this.suspendChasing(),e>Ch&&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<Eh,i=this.lastFragLoadingMs!==0&&n-this.lastFragLoadingMs>Nh,a=t.readyState<HTMLMediaElement.HAVE_FUTURE_DATA&&!t.paused,{totalFrames:o,dropped:s}=Pm(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>Rh&&this.recentMainFrags.shift(),this.clearRecoveryReset(),this.kickPending&&this.kickTicks>=Ih&&(this.clearKick(),this.starvationRebuilds<Lh)){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>=Ph,d=!i&&this.deadTicks>=Rh&&this.recentMainFrags.reduce((e,t)=>e+t,0)>=zh;if((u||d)&&(this.resetStarvationWindow(),!(this.starvationKicks>=Fh))){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>Dh?this.catchUpEngaged=!0:this.catchUpEngaged&&r<=Dh&&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}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}=Pm(t),i=this.fpsLastFrames<0,a=n-this.fpsLastFrames,o=r-this.fpsLastDropped;if(this.fpsLastFrames=n,this.fpsLastDropped=r,i||a<Kh||o<0){this.fpsBadTicks=0;return}if(o<=Gh*a){this.fpsBadTicks=0;return}if(this.fpsBadTicks+=1,this.fpsBadTicks<qh)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(Ah,i)&&r<=i&&typeof n==`number`&&Number.isFinite(n))){this.resetChaseWindow();return}if(this.chaseLatency<0||this.chaseLatency-n>=kh){this.chaseLatency=n,this.chaseTicks=0;return}if(this.chaseTicks+=1,this.chaseTicks<Oh)return;this.resetChaseWindow();let a=typeof e.config.liveMaxLatencyDuration==`number`?e.config.liveMaxLatencyDuration:e.maxLatency;if(!(a>1))return;let o=typeof e.targetLatency==`number`?e.targetLatency:0,s=Math.min(n,a-1);s<o+jh||(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)}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?hh:Le()??hh}maybeRememberBandwidth(e){if(this.deps.rememberBandwidth===!1||this.bwFragsLoaded<gh)return;let t=Date.now();if(!e&&t-this.bwSavedAt<_h)return;let n=this.hls?.bandwidthEstimate;typeof n!=`number`||!Number.isFinite(n)||n<=0||(this.bwSavedAt=t,Re(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>=bh)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()}}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<yh){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<vh){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(ih(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)}},tg=15e3,ng=6e5,rg=3e5,ig=100,ag=1,og=1e3,sg=3e4,cg=1e3,lg={inline:`PRESENTATION_INLINE`,fullscreen:`PRESENTATION_FULLSCREEN`,pip:`PRESENTATION_PIP`},ug={widevine:`KEY_SYSTEM_WIDEVINE`,fairplay:`KEY_SYSTEM_FAIRPLAY`,none:`KEY_SYSTEM_NONE`};function dg(e,t){return e.length===0?0:e[Math.min(e.length,Math.max(1,Math.ceil(t/100*e.length)))-1]??0}var fg=new Set([`INVALID_URN`,`NOT_FOUND`,`GEO_DENIED`,`GONE`,`TOO_EARLY`,`UNAVAILABLE`,`UNAUTHORIZED`,`FORBIDDEN`,`RATE_LIMITED`,`TIMEOUT`]),pg={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 mg(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 hg=(e,t)=>e.replace(/\/$/,``).toLowerCase()===t.replace(/\/$/,``).toLowerCase(),gg=new Set,_g=new Set,vg=new Set,yg=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(gg.has(t)&&!_g.has(t)){_g.add(t),b(yg(new URL(t).origin));for(let e of vg)e.noteCspBlocked()}}function xg(e,t){return b(t,e),{disabledReason:t}}function Sg(e,t,n){if(n)return t&&!hg(t,n)&&b(`analytics.endpoint "${t}" ignored; the server named "${n}".`),{endpoint:n};if(t)return{endpoint:t};if(t!==void 0)return xg(`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=mg(e);if(r)return{endpoint:r};let i;try{i=new URL(e).hostname||e}catch{i=e}return xg(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 Cg=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??tg,idleMs:e.idleMs??ng},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(),og),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&&gg.add(this.cspKey),document.addEventListener(`securitypolicyviolation`,bg),vg.add(this),this.noteCspBlocked(),this.onVisibility())}checkSuspension(e){if(this.endedFlag||!this.opts.idleMs)return!1;let t=Math.max(this.opts.idleMs,rg);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:pg[e]??`PLAYER_STATE_UNSPECIFIED`,toState:pg[t]??`PLAYER_STATE_UNSPECIFIED`,presentation:lg[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<cg}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(fg.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=pg[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=dg(n,50),o.requestTimeP95Ms=dg(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=ug[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,vg.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<=sg&&(i.abandonAfterStallMs=Math.max(ag,Math.round(n-this.lastStallMs))),l&&this.lastErrorMs>0&&n-this.lastErrorMs<=sg&&(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?.(yg(new URL(this.url).origin)))}cspBlocked(){return!!this.cspKey&&_g.has(this.cspKey)}enqueue(e){if(!this.cspBlocked())for(this.pending.push(this.wrap(e));this.pending.length>ig;){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 Tg(){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 Eg(){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 Dg(e){let t=wg(),n={deviceClass:Tg(),integration:t.integration,...Eg()};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 Og(){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 kg=`2.22.0`,Ag={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`},jg={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 Mg(e,t){let n={...Ag,...t};for(let t of Object.keys(jg))e.style.setProperty(jg[t],n[t]);n.logoUrl&&e.style.setProperty(`--havik-logo`,`url("${n.logoUrl}")`)}var Ng=`havik-player-styles`,Pg=`
|
|
44
|
+
`)),n}getTextAndFormat(){return this.rows}},Kp=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 Gp(n),this.nonDisplayedMemory=new Gp(n),this.lastOutputScreen=new Gp(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))}},qp=class{constructor(e,t,n){this.channels=[null,null,null],this.currentChannel=0,this.cmdHistory=Xp(),this.logger=void 0,this.field=void 0,this.outputFilters=void 0,this.logger=new zp,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 Kp(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,()=>`[`+Bp([t[e],t[e+1]])+`] -> (`+Bp([n,r])+`)`);let o=this.cmdHistory;if(n>=16&&n<=31){if(Yp(n,r,o)){Jp(null,null,o),this.logger.log(3,()=>`Repeated command (`+Bp([n,r])+`) is dropped`);continue}Jp(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 Jp(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 `+Bp([n,r])+` orig: `+Bp([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 (`+Bp([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?Pp[e]:Ip[e]:r===1?Fp[e]:Lp[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 '`+jp(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 = `+Bp(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=Rp[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()}Jp(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 Jp(e,t,n){n.a=e,n.b=t}function Yp(e,t,n){return n.a===e&&n.b===t}function Xp(){return{a:null,b:null}}var Zp=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}},Qp=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.unparsedVttFrags=[],this.captionsTracks={},this.cueCache={},this.nonNativeCaptionsTracks={},this.cea608Parser1=void 0,this.cea608Parser2=void 0,this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs=em(),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 Zp(this,`textTrack1`),t=new Zp(this,`textTrack2`),n=new Zp(this,`textTrack3`),r=new Zp(this,`textTrack4`);this.cea608Parser1=new qp(1,e,t),this.cea608Parser2=new qp(3,n,r)}addCues(e,t,n,r,i){let a=!1;for(let e=i.length;e--;){let r=i[e],o=$p(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{unparsedVttFrags:r}=this;t===z.MAIN&&(this.initPTS=n),r.length&&(this.unparsedVttFrags=[],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]=Ef(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=em(),this.tracks=[],this.captionsTracks={},this.nonNativeCaptionsTracks={},this.unparsedVttFrags=[],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&&!hl(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===df?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,i=this.hls;hf(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,unparsedVttFrags:a}=this,o=i.length-1;if(!i[t.cc]&&o===-1){a.push(e);return}let s=this.hls,c=t.initSegment?.data;uf(c?Cr(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||hf(n,this.initPTS[t.cc],()=>{r.textCodec=df,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=>Of(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++)Of(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=>kf(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&&kf(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 $p(e,t,n,r){return Math.min(t,r)-Math.max(e,n)}function em(){return{ccOffset:0,presentationOffset:0,0:{start:0,prevCC:-1,new:!0}}}var tm=/\s/,nm={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++)tm.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=rf(l.trim()),p=lf(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=>Of(e,t))),i}},rm=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 xt}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(Ht(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=Bt(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 im(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch{}return!1}var am=/(\d+)-(\d+)\/(\d+)/,om=class extends rm{constructor(e){super(),this.fetchSetup=void 0,this.request=null,this.response=null,this.controller=null,this.fetchSetup=e.fetchSetup||um}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=sm(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),(sl(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 dm(t||`fetch, bad network response`,e,r)}n.loading.first=a,n.total=lm(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(Ht(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 fs,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 sm(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 cm(e){let t=am.exec(e);if(t)return parseInt(t[2])-parseInt(t[1])+1}function lm(e){let t=e.get(`Content-Range`);if(t){let e=cm(t);if(P(e))return e}let n=e.get(`Content-Length`);if(n)return parseInt(n)}function um(e,t){return new self.Request(e.url,t)}var dm=class extends Error{constructor(e,t,n){super(e),this.code=void 0,this.details=void 0,this.code=t,this.details=n}},fm=(e,t,n)=>Math.max(t,Math.min(e,n)),pm=/^age:\s*[\d.]+\s*$/im,mm=class extends rm{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(Ht(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&&pm.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}},hm=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:mm,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:lo,requireKeySystemAccessOnStart:!1,testBandwidth:!0,progressive:!1,lowLatencyMode:!0,cmcd:void 0,enableDateRangeMetadataCues:!0,enableEmsgMetadataCues:!0,enableEmsgKLVMetadata:!1,enableID3MetadataCues:!0,emsgKLVSchemaUri:void 0,enableInterstitialPlayback:!0,interstitialAppendInPlace:!0,interstitialLiveLookAhead:10,iframeCacheLimit:2097152,useMediaCapabilities:!0,preserveManualLevelOnError:!1,errorPenaltyExpireMs:0,certLoadPolicy:{default:{maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:null,errorRetry:null}},keyLoadPolicy:{default:{maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:2e4,backoff:`linear`},errorRetry:{maxNumRetry:8,retryDelayMs:1e3,maxRetryDelayMs:2e4,backoff:`linear`}}},manifestLoadPolicy:{default:{maxTimeToFirstByteMs:1/0,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},playlistLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:2,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},fragLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:12e4,timeoutRetry:{maxNumRetry:4,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:6,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},steeringManifestLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},interstitialAssetListLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:3e4,timeoutRetry:{maxNumRetry:0,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:0,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},manifestLoadingTimeOut:1e4,manifestLoadingMaxRetry:1,manifestLoadingRetryDelay:1e3,manifestLoadingMaxRetryTimeout:64e3,levelLoadingTimeOut:1e4,levelLoadingMaxRetry:4,levelLoadingRetryDelay:1e3,levelLoadingMaxRetryTimeout:64e3,fragLoadingTimeOut:2e4,fragLoadingMaxRetry:6,fragLoadingRetryDelay:1e3,fragLoadingMaxRetryTimeout:64e3,streamController:Zf,abrController:Xi,bufferController:wl,capLevelController:Ml,errorController:sa,fpsController:Jd,id3TrackController:Wf,gapController:Ff,latencyController:Ep},gm()),{},{subtitleStreamController:Op,subtitleTrackController:Mf,timelineController:Qp,audioStreamController:pl,audioTrackController:_l,emeController:Hd,cmcdController:Fd,contentSteeringController:Ld,iframeController:ap,interstitialsController:Tp});function gm(){return{cueHandler:nm,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 _m(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=fm(e,2,1/0);r!==e&&n.warn(`hls.js config: "liveMaxUnchangedPlaylistRefresh" clamped from ${e} to ${r}.`),t.liveMaxUnchangedPlaylistRefresh=r}let r=vm(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 vm(e){return e&&typeof e==`object`?Array.isArray(e)?e.map(vm):Object.keys(e).reduce((t,n)=>(t[n]=vm(e[n]),t),{}):e}function ym(e,t){let n=e.loader;n!==om&&n!==mm?(t.log(`[config]: Custom loader detected, cannot enable progressive streaming`),e.progressive=!1):im()&&(e.loader=om,e.progressive=!0,e.enableSoftwareAES=!0,t.log(`[config]: Progressive streaming enabled, using FetchLoader`))}var bm=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=Cm(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 Ai(e),n=e.supplemental;if(n!=null&&n.videoCodec&&!Sm(n.videoCodec,this.hls.config.preferManagedMediaSource)){let e=Error(`SUPPLEMENTAL-CODECS not supported "${n.videoCodec}"`);this.log(e.message),t.supportedResult=mi(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))&&Ei(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||xm(e.audioCodec,u)),wm(o)),t.subtitles&&(s=t.subtitles,wm(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 Ti.indexOf(e.videoRange)-Ti.indexOf(t.videoRange);if(e.videoCodec!==t.videoCodec){let n=Qr(e.videoCodec),r=Qr(t.videoCodec);if(n!==r)return r-n}if(e.uri===t.uri&&e.codecSet!==t.codecSet){let n=$r(e.codecSet),r=$r(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=>Cm(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));Qo(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 xm(e,t){return Yr(e,`audio`,t)}function Sm(e,t){return Yr(e,`video`,t)}function Cm(e,t){let{audioCodec:n,videoCodec:r}=e;n&&(e.audioCodec=n=ri(n,t)||void 0),r&&=e.videoCodec=si(r);let{unknownCodecs:i}=e;return!(i?.length||n&&!xm(n,t)||r&&!Sm(r,t))}function wm(e){let t={};e.forEach(e=>{let n=e.groupId||``;e.id=t[n]=t[n]||0,t[n]++})}var Tm=class extends Jt{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(Em(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(Em(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=pr(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 ${Bn(n)} keyUri: ${r}`),go.setKeyIdForUri(r,n);else{let e=go.addKeyIdForUri(r);this.log(`Patching empty keyId with ${Bn(e)} keyUri: ${r}`),n=e}e.decryptdata.keyId=n}}return this.emeController.loadKey(e).then(()=>({frag:e,keyInfo:{decryptdata:e.decryptdata}}))}return Promise.reject(Em(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(Em(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: `+Bn(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 r(Em(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(Em(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(Em(e,I.KEY_LOAD_TIMEOUT,Error(`key loading timed out`),i))},onAbort:(t,n,i)=>{this.resetLoader(n),r(Em(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 Em(e,t=I.KEY_LOAD_ERROR,n,r,i){return new Aa({type:F.NETWORK_ERROR,details:t,fatal:!1,frag:e,response:i,error:n,networkDetails:r||null})}function Dm(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 Om(e,t){let n=e.url;return(n===void 0||n.indexOf(`data:`)===0)&&(n=t.url),n}var km=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(),To.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=Om(e,n),s=To.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];Yr(o,`audio`,n)?(e.audioCodec=r=r?`${r},${o}`:o,qr.audio[r.substring(0,4)]=2,t.splice(a,1)):Yr(o,`video`,n)&&(e.videoCodec=i=i?`${i},${o}`:o,qr.video[i.substring(0,4)]=2,t.splice(a,1))}}});let{AUDIO:h=[],SUBTITLES:g,"CLOSED-CAPTIONS":_}=To.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 Ha({}),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=Om(e,n),u=P(s)?s:P(o)?o:0,d=Dm(n),f=To.parseLevelPlaylist(e.data,l,u,d,0,this.variableList);if(c===R.MANIFEST){let e={attrs:new Ha({}),bitrate:0,details:f,name:``,url:l};f.requestScheduled=t.loading.start+Jo(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=Om(t,r),m=Dm(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 vs}static isMSESupported(){return Kf()}static isSupported(){return qf()}static getMediaSource(){return nn()}static get Events(){return L}static get MetadataSchema(){return Is}static get ErrorTypes(){return F}static get ErrorDetails(){return I}static get DefaultConfig(){return e.defaultConfig?e.defaultConfig:hm}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 _s,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=tn(t.debug||!1,`Hls instance`,t.loggerId||t.assetPlayerId),r=this.config=_m(e.DefaultConfig,t,n);this.userConfig=t,r.progressive&&ym(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 fa(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 km(this),w=r.contentSteeringController,T=w?new w(this):null,E=this.levelController=new bm(this,T),D=u?new u(this):void 0,O=new Tm(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=bt.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=gn(),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){wi(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 gi(e,Li(t),navigator.mediaCapabilities)}};$.defaultConfig=void 0;var Am={droppedFrames:0};function jm(e){try{return new URL(e).host}catch{return``}}var Mm=/\.(m3u8|ts|m4s|mp4|cmfv|cmfa)(\?|$)/i;function Nm(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`||Mm.test(i.name))&&i.startTime>=n){let e=jm(i.name);e&&(t=e,n=i.startTime)}return t}function Pm(e){let t=e.getVideoPlaybackQuality?.();return{dropped:t?.droppedVideoFrames??0,totalFrames:t?.totalVideoFrames??0}}var Fm=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=Pm(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 Im(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 Lm=2e3,Rm=3,zm=500,Bm=6e3,Vm=.25,Hm=250,Um=.05,Wm=4,Gm=12e3,Km=.25,qm=1e3;function Jm(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 Ym(e){return!!(e??(typeof document<`u`?document.createElement(`video`):void 0))?.canPlayType(`application/vnd.apple.mpegurl`)}function Xm(){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 Zm(){if(typeof navigator>`u`||!Xm())return!1;let e=navigator.userAgent??``;return/iPhone|iPad|iPod/.test(e)?!0:/Macintosh/.test(e)&&typeof navigator.maxTouchPoints==`number`&&navigator.maxTouchPoints>1}var Qm=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 Fm(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=th(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=Jm(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||=Nm(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<=Wm,!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=$m();if(document.visibilityState===`hidden`){this.hiddenSince=e,this.cancelRefocus();return}let t=this.hiddenSince;this.hiddenSince=null,t!=null&&e-t>=Lm&&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=$m,n=t(),r=0,i=()=>{if(this.refocusTimer=null,Number.isFinite(this.deps.video.duration))return;r+=zm;let a=this.liveEnd(),o=a!=null&&(e==null||a>=e+Vm),s=Math.max(r,t()-n)>=Bm;if(o||s&&a!=null){this.snapToLive();return}this.refocusTimer=setTimeout(i,zm)};this.refocusTimer=setTimeout(i,zm)}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=eh(e,e.currentTime);t!=null&&((this.lastBufferedEnd==null||Math.abs(t-this.lastBufferedEnd)>=Um)&&(this.bufferedAdvancedAt=$m()),this.lastBufferedEnd=t)},Hm)}checkEndStale(){if(this.endedEmitted)return;let e=$m(),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)>=Km;this.lastSeekableEnd=n;let i=this.deps.video,a=typeof document<`u`&&document.visibilityState===`hidden`;if(r||t>qm||a||i.paused){this.edgeStampedAt=e;return}e-(this.edgeStampedAt??e)>Gm&&(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=eh(e,e.currentTime)??this.lastBufferedEnd;if(n!=null){let e=this.bufferedAdvancedAt,r=n+(e==null?0:Math.max(0,($m()-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-Rm,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 $m(){return typeof performance<`u`?performance.now():Date.now()}function eh(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 th(e,t){return t?`${e}${e.includes(`?`)?`&`:`?`}CMCD=${encodeURIComponent(`sid="${t}"`)}`:e}function nh(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 rh=4096;function ih(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>rh))try{return new TextDecoder().decode(n)}catch{return}}var ah=15e3,oh=5e3,sh=6;function ch(e){try{let t=new URL(e);return t.searchParams.delete(`CMCD`),t.toString()}catch{return e}}var lh=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=ch(e);if(this.entries.has(r))return;let i=this.perTrack.get(t)??0;if(i>=sh)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)},ah)}take(e){let t=ch(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 uh(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,`stats`,dh())}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||oh,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 dh(){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 fh(e){return e===`audio`?`audio`:`main`}function ph(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 mh(e,t){return e.length===0?0:e[Math.min(e.length,Math.max(1,Math.ceil(t/100*e.length)))-1]??0}function hh(){return $.isSupported()}var gh=1e6,_h=20,vh=1e4,yh=3,bh=5,xh=3,Sh=1e4,Ch=3e4,wh=12e3,Th=3e3,Eh=.02,Dh=6e3,Oh=.5,kh=3,Ah=.5,jh=1.1,Mh=.25,Nh=5e3,Ph=4e3,Fh=2,Ih=5,Lh=2,Rh=2,zh=4,Bh=4,Vh=2e3,Hh=3e4,Uh=1,Wh=2;function Gh(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 Kh=.2,qh=30,Jh=2,Yh=2,Xh=2,Zh=9,Qh=.5,$h=64,eg=1e4,tg=8,ng=.6,rg=.4,ig=.4,ag=2,og=6e4,sg=.5,cg=3.5,lg=300;function ug(){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 dg(e){if(e.liveSyncDurationCount!=null||e.liveMaxLatencyDurationCount!=null){delete e.liveSyncDuration,delete e.liveMaxLatencyDuration;return}e.liveSyncDuration??=Xh;let t=Math.max(12,e.liveSyncDuration+Zh);(e.liveMaxLatencyDuration==null||e.liveMaxLatencyDuration<=e.liveSyncDuration)&&(e.liveMaxLatencyDuration=t),fg(e,e.liveSyncDuration)}function fg(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 pg=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 Fm(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=Ym(n)&&Xm(),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&&(Je(n),tt()),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}},Nh))}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+Qh||(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)<Eh)){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=Ym(this.deps.video)&&Xm(),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:qe.video,audioRobustness:qe.audio,videoEncryptionScheme:qe.scheme,audioEncryptionScheme:qe.scheme},...He()?{requestMediaKeySystemAccessFunc:Ke(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||!nh(this.licenseUrl)){s();return}let l=this.hls,u,d=new Promise(e=>{u=setTimeout(()=>e(void 0),Sh)});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 lh({sessionId:t.analytics?.sid,contentId:t.matchUrn}),n=uh(e);n&&(this.prefetch=e,d.fLoader=n)}dg(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 $(d);if(this.hls=f,this.armHoldBack(f,d),f.on($.Events.FRAG_PARSED,(e,t)=>this.reanchorPartTimeline(f,t)),f.on($.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($.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},Ch)))}),f.on($.Events.FRAG_LOADING,(e,t)=>{t?.frag?.type===`main`&&(this.lastFragLoadingMs=Date.now())}),f.on($.Events.FRAG_LOADED,(e,t)=>{t?.frag?.type===`main`&&(this.mainFragsSinceTick+=1,this.bwFragsLoaded+=1,this.maybeRememberBandwidth(!1));let n=t?.frag?.stats,r=n?.loaded;typeof r==`number`&&(this.bytesLoaded+=r),!this.reportedFirstBytes&&typeof r==`number`&&r>0&&(this.reportedFirstBytes=!0,c({type:`firstBytes`}));let i=n?.loading;i&&i.end>0&&i.start>0&&(this.requestCount+=1,this.requestTimesMs.push(Math.max(0,Math.round(i.end-i.start))),this.requestTimesMs.length>$h&&this.requestTimesMs.shift()),this.sampleHoldBack(t);let a=t?.frag?.url;if(a){let e=jm(a);e&&(this.cdnHost=e)}}),f.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}))}),f.on($.Events.LEVEL_LOADED,(e,t)=>this.trackEnd(t)),this.prefetch){let e=this.prefetch;f.on($.Events.KEY_LOADING,(t,n)=>{let r=n?.frag,i=fh(r?.type);if(r&&e.isActive(i))for(let t of ph(f,r))e.prefetch(t.url,i,t.kind)}),f.on($.Events.KEY_LOADED,(t,n)=>e.keyUsable(fh(n?.frag?.type)))}f.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()},Th),f.on($.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($.Events.AUDIO_TRACK_SWITCHED,(e,t)=>c({type:`audiotrackchange`,id:t.id})),f.on($.Events.SUBTITLE_TRACK_SWITCH,(e,t)=>c({type:`texttrackchange`,id:t.id})),f.on($.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=Ml.getMaxLevelByMediaSize(e.levels,r*s,i*s),l=this.deps.sizeCapHeadroom;if(l==null&&o>=Wh)return c;let u=l??Uh,d=Number.isNaN(u)?Uh:u===1/0?e.levels.length:Math.max(0,Math.floor(u));return Gh(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?Vh:Hh;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=>nt(e)!==!0);let t=new Set(e.levels.map(e=>e.videoCodec).filter(e=>!!e&&Ye(e)!==`avc`&&!!Ye(e)));for(let n of t)et(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&&Ye(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:!Ye(e.videoCodec)||nt(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>Dh&&this.suspendChasing(),e>wh&&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<Dh,i=this.lastFragLoadingMs!==0&&n-this.lastFragLoadingMs>Ph,a=t.readyState<HTMLMediaElement.HAVE_FUTURE_DATA&&!t.paused,{totalFrames:o,dropped:s}=Pm(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>zh&&this.recentMainFrags.shift(),this.clearRecoveryReset(),this.kickPending&&this.kickTicks>=Lh&&(this.clearKick(),this.starvationRebuilds<Rh)){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>=Fh,d=!i&&this.deadTicks>=zh&&this.recentMainFrags.reduce((e,t)=>e+t,0)>=Bh;if((u||d)&&(this.resetStarvationWindow(),!(this.starvationKicks>=Ih))){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>Oh?this.catchUpEngaged=!0:this.catchUpEngaged&&r<=Oh&&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=Yh,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}=Pm(t),i=this.fpsLastFrames<0,a=n-this.fpsLastFrames,o=r-this.fpsLastDropped;if(this.fpsLastFrames=n,this.fpsLastDropped=r,i||a<qh||o<0){this.fpsBadTicks=0;return}if(this.fpsGraceTicks>0){--this.fpsGraceTicks,this.fpsBadTicks=0;return}if(o<=Kh*a){this.fpsBadTicks=0;return}if(this.fpsBadTicks+=1,this.fpsBadTicks<Jh)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(jh,i)&&r<=i&&typeof n==`number`&&Number.isFinite(n))){this.resetChaseWindow();return}if(this.chaseLatency<0||this.chaseLatency-n>=Ah){this.chaseLatency=n,this.chaseTicks=0;return}if(this.chaseTicks+=1,this.chaseTicks<kh)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+Mh||(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=ug();if(!(n>=lg))return;let r=typeof t==`number`&&t>0?t:this.holdBackBase,i=Math.min(this.holdBackCeiling(e),this.holdBackBase+sg);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:cg,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=(e.part??e.frag)?.stats?.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-eg,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<tg){this.holdBackSlowTicks=0;return}let c=r.map(e=>e.ratio).sort((e,t)=>e-t),l=mh(c,95),u=mh(c,50),d=Math.round(l*1e3);if(l>=ng&&u>=rg){if(this.holdBackFastSince=0,this.holdBackSlowTicks+=1,this.holdBackSlowTicks<ag)return;this.holdBackSlowTicks=0;let t=Math.ceil((s-o)/sg),n=Math.ceil((a-o)/sg-1e-9);if(n>this.holdBackStepCount&&(this.holdBackStepCount=n),this.holdBackStepCount>=t)return;this.holdBackStepCount+=1;let r=Math.min(s,o+this.holdBackStepCount*sg);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>=ig){this.holdBackFastSince=0;return}if(this.holdBackFastSince===0){this.holdBackFastSince=t;return}if(t-this.holdBackFastSince<og||(this.holdBackFastSince=t,this.holdBackStepCount===0||a!==this.holdBackApplied))return;--this.holdBackStepCount;let f=Math.max(o,o+this.holdBackStepCount*sg);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?gh:Le()??gh}maybeRememberBandwidth(e){if(this.deps.rememberBandwidth===!1||this.bwFragsLoaded<_h)return;let t=Date.now();if(!e&&t-this.bwSavedAt<vh)return;let n=this.hls?.bandwidthEstimate;typeof n!=`number`||!Number.isFinite(n)||n<=0||(this.bwSavedAt=t,Re(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>=xh)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<bh){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<yh){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(ih(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)}},mg=15e3,hg=6e5,gg=3e5,_g=100,vg=1,yg=1e3,bg=3e4,xg=1e3,Sg={inline:`PRESENTATION_INLINE`,fullscreen:`PRESENTATION_FULLSCREEN`,pip:`PRESENTATION_PIP`},Cg={widevine:`KEY_SYSTEM_WIDEVINE`,fairplay:`KEY_SYSTEM_FAIRPLAY`,none:`KEY_SYSTEM_NONE`},wg=new Set([`INVALID_URN`,`NOT_FOUND`,`GEO_DENIED`,`GONE`,`TOO_EARLY`,`UNAVAILABLE`,`UNAUTHORIZED`,`FORBIDDEN`,`RATE_LIMITED`,`TIMEOUT`]),Tg={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 Eg(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 Dg=(e,t)=>e.replace(/\/$/,``).toLowerCase()===t.replace(/\/$/,``).toLowerCase(),Og=new Set,kg=new Set,Ag=new Set,jg=e=>`this page's Content-Security-Policy blocks QoE beacons. Add ${e} to connect-src; until then none are sent.`;function Mg(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(Og.has(t)&&!kg.has(t)){kg.add(t),b(jg(new URL(t).origin));for(let e of Ag)e.noteCspBlocked()}}function Ng(e,t){return b(t,e),{disabledReason:t}}function Pg(e,t,n){if(n)return t&&!Dg(t,n)&&b(`analytics.endpoint "${t}" ignored; the server named "${n}".`),{endpoint:n};if(t)return{endpoint:t};if(t!==void 0)return Ng(`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=Eg(e);if(r)return{endpoint:r};let i;try{i=new URL(e).hostname||e}catch{i=e}return Ng(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 Fg=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??mg,idleMs:e.idleMs??hg},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(),yg),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&&Og.add(this.cspKey),document.addEventListener(`securitypolicyviolation`,Mg),Ag.add(this),this.noteCspBlocked(),this.onVisibility())}checkSuspension(e){if(this.endedFlag||!this.opts.idleMs)return!1;let t=Math.max(this.opts.idleMs,gg);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(vg,i-this.startupAnchorMs)),this.firstAudioMs===0&&!this.isMuted&&(this.firstAudioMs=Math.max(vg,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(vg,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:Tg[e]??`PLAYER_STATE_UNSPECIFIED`,toState:Tg[t]??`PLAYER_STATE_UNSPECIFIED`,presentation:Sg[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<xg}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(vg,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=vg),this.firstPlaylistMs>0&&(this.firstPlaylistMs=vg),this.firstFragLoadMs>0&&(this.firstFragLoadMs=vg),this.drmSetupMs>0&&(this.drmSetupMs=vg))}noteReady(){this.manifestLoadMs===0&&(this.manifestLoadMs=Math.max(vg,this.now()-this.startupAnchorMs))}noteFirstPlaylist(){this.firstPlaylistMs===0&&(this.firstPlaylistMs=Math.max(vg,this.now()-this.startupAnchorMs))}noteDrmReady(){this.drmSetupMs===0&&(this.drmSetupMs=Math.max(vg,this.now()-this.startupAnchorMs))}noteFirstBytes(){this.sawFirstBytes=!0,this.firstFragLoadMs===0&&(this.firstFragLoadMs=Math.max(vg,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(wg.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=Tg[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=mh(n,50),o.requestTimeP95Ms=mh(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=Cg[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,Ag.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<=bg&&(i.abandonAfterStallMs=Math.max(vg,Math.round(n-this.lastStallMs))),l&&this.lastErrorMs>0&&n-this.lastErrorMs<=bg&&(i.abandonAfterErrorMs=Math.max(vg,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?.(jg(new URL(this.url).origin)))}cspBlocked(){return!!this.cspKey&&kg.has(this.cspKey)}enqueue(e){if(!this.cspBlocked())for(this.pending.push(this.wrap(e));this.pending.length>_g;){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 Ig(){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 Lg(){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 Rg(){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=Ig(),n={deviceClass:Lg(),integration:t.integration,...Rg()};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 Bg(){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 Vg=`2.23.0`,Hg={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`},Ug={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 Wg(e,t){let n={...Hg,...t};for(let t of Object.keys(Ug))e.style.setProperty(Ug[t],n[t]);n.logoUrl&&e.style.setProperty(`--havik-logo`,`url("${n.logoUrl}")`)}var Gg=`havik-player-styles`,Kg=`
|
|
45
45
|
.havik-player{position:relative;display:block;width:100%;background:var(--havik-bg,#0e0f13);
|
|
46
46
|
color:var(--havik-text,#fff);font-family:var(--havik-font,system-ui,sans-serif);
|
|
47
47
|
overflow:hidden;line-height:1.4;-webkit-tap-highlight-color:transparent}
|
|
@@ -169,5 +169,5 @@ Schedule: ${a.map(e=>xp(e))} pos: ${this.timelinePos}`),s.length&&this.log(`Remo
|
|
|
169
169
|
.havik-menu__item:hover{background:var(--havik-surface-muted,#2a2c36)}
|
|
170
170
|
.havik-menu__item[aria-checked="true"]{color:var(--havik-accent,#E1B600);font-weight:600}
|
|
171
171
|
.havik-menu__item[aria-checked="true"]::after{content:'✓'}
|
|
172
|
-
`,Fg=new WeakMap;function Ig(e=document,t){let n=e.querySelector(`style#${Ng}`);if(n&&(!t||Fg.get(n)===t))return;let r=e.createElement(`style`);r.id=Ng,t&&(r.nonce=t,r.setAttribute(`nonce`,t)),r.textContent=Pg,Fg.set(r,t),n?n.replaceWith(r):e.head.appendChild(r)}var Lg={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 Rg(e){return`<svg viewBox="0 0 24 24" aria-hidden="true" focusable="false" fill="currentColor">${Lg[e]}</svg>`}var zg=3e3,Bg=250,Vg=new Set([`GONE`,`NOT_FOUND`,`GEO_DENIED`,`INVALID_URN`,`UNAUTHORIZED`,`DRM_DEVICE_REVOKED`]);function Hg(e){let t=`This match isn't available in your country`;return e?`${t} (${e})`:t}var Ug=`This device can't play protected video`;function Wg(e){return new Gg(e)}var Gg=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??zg,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,Ig(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=Rg(n),i};this.overlay=t(`div`,`havik-overlay`),this.center=t(`button`,`havik-center`,{type:`button`,"aria-label":`Play`}),this.center.innerHTML=Rg(`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=Rg(`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)},Bg)}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`?Hg(this.lastError.country):this.lastError?.code===`DRM_DEVICE_REVOKED`?Ug: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=Rg(`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&&!Vg.has(this.lastError.code)){let e=this.doc.createElement(`button`);e.type=`button`,e.className=`havik-status__btn`,e.innerHTML=`${Rg(`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=`${Kg(this.video.currentTime)} / ${Kg(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(qg(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(Jg(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(Yg(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=Rg(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 Kg(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 qg(e){return e.height?`${e.height}p`:`${Math.round(e.bitrate/1e3)} kbps`}function Jg(e){return e.name||e.lang||`Track ${e.id}`}function Yg(e){return e.name||e.lang||`Track ${e.id}`}var Xg=6e3,Zg=45e3,Qg=2e3,$g=3,e_=5e3,t_=2e3,n_=48e4,r_=`keySystemLicenseRequestFailed`;function i_(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 pt(e.env);if(!e.baseUrl)throw new a(`INTERNAL`,0,`createPlayer: env or baseUrl is required (env: 'integration' | 'production')`);return e.baseUrl}async function a_(e){if(!e.video||typeof e.video.play!=`function`)throw new a(`INTERNAL`,0,`createPlayer: opts.video must be an HTMLVideoElement`);let t=i_(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 o_({...e,baseUrl:t});return await n.start(),n}var o_=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??Se(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:Zg,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)};_(Xg),this.armingSub=xe({eventsBaseUrl:t,matchUrn:this.opts.matchUrn,credential:this.opts.credential,onAlive:()=>_(Zg),onState:e=>{i||p()||(e.state===`live`||e.state===`gone`)&&setTimeout(g,Math.random()*Qg)},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=Im(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}=Sg(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 Cg({endpoint:o,sid:r,player:t.name===`native`?`PLAYER_SAFARI_NATIVE`:`PLAYER_HLSJS`,sdkVersion:kg,environment:Dg(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()??Am,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()),Og().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:Te(),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,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 Qm(i);if(o===`hls`)return new eg(i);if(e.drmEnabled&&e.drm?.fairplay?.licenseUrl&&e.drm.fairplay.certificateUrl&&Ym(this.opts.video)&&Xm()||!e.drmEnabled&&Zm()&&Ym(this.opts.video))return new Qm(i);if(mh())return new eg(i);if(Ym(this.opts.video))return new Qm(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`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??Se(this.opts.baseUrl);if(!t)return;this.closeLiveState();let n=0,r=!1;this.liveStateSub=xe({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:()=>{this.destroyed||e!==this.loadGen||r||this.endedHandled||(n+=1,n>=$g&&(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>=e_&&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()*Qg))}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),Mg(n,this.opts.theme),this.container=n,this.controlBar=Wg({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!==r_||e.error.httpStatus!==403||e.error.code!==`FORBIDDEN`||e.error.serverCode===`license_refused`?!1:nh(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||nh(this._descriptor?.drm?.widevine?.licenseUrl)&&this.refreshLicense()},document.addEventListener(`visibilitychange`,this.onRefocus));let e=this.opts.licenseRefreshMs??n_;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()??Am}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 s_(e){return!!e&&typeof e==`object`&&typeof e.type==`string`&&e.type.startsWith(`oddin:`)}function c_(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||!s_(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 l_=/^[A-Za-z0-9:_.-]{1,128}$/;function u_(e){if(typeof e==`boolean`)return e;if(typeof e==`object`&&e){let t=e.endpoint;return typeof t==`string`?{endpoint:t}:{}}}function d_(){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:u_(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 f_(){let e=d_();m_();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`}),p_(t,e)})},s=async n=>{i?.destroy(),i=null;try{let r=await a_({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`&&l_.test(e.matchUrn)&&s(e.matchUrn);break;case`oddin:destroy`:c()}},u=e=>{n&&e.origin===n&&s_(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 p_(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 m_(){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.ODDIN_THEME=Ag,e.PlaybackError=a,e.applyTheme=Mg,e.baseUrlForEnv=pt,e.bootEmbed=f_,e.clearDeviceId=Ee,e.clearRememberedBandwidth=ze,e.createPlayer=a_,e.deriveEventsBaseUrl=Se,e.detectDrmSupport=lt,e.enterVideoFullscreen=de,e.exitVideoFullscreen=fe,e.fetchCatalog=pe,e.fetchTournament=he,e.flattenMatches=_e,e.fullscreenSupported=ue,e.getDeviceId=Te,e.isLowLatencyManifest=dt,e.isOddinMessage=s_,e.licenseRequestHeaders=Oe,e.mountEmbed=c_,e.pollToLive=N,e.resolveStream=te,e.subscribeLiveState=xe,e.videoFullscreenActive=le,e.watchStatus=ye,e})({});
|
|
172
|
+
`,qg=new WeakMap;function Jg(e=document,t){let n=e.querySelector(`style#${Gg}`);if(n&&(!t||qg.get(n)===t))return;let r=e.createElement(`style`);r.id=Gg,t&&(r.nonce=t,r.setAttribute(`nonce`,t)),r.textContent=Kg,qg.set(r,t),n?n.replaceWith(r):e.head.appendChild(r)}var Yg={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 Xg(e){return`<svg viewBox="0 0 24 24" aria-hidden="true" focusable="false" fill="currentColor">${Yg[e]}</svg>`}var Zg=3e3,Qg=250,$g=new Set([`GONE`,`NOT_FOUND`,`GEO_DENIED`,`INVALID_URN`,`UNAUTHORIZED`,`DRM_DEVICE_REVOKED`]);function e_(e){let t=`This match isn't available in your country`;return e?`${t} (${e})`:t}var t_=`This device can't play protected video`;function n_(e){return new r_(e)}var r_=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??Zg,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,Jg(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=Xg(n),i};this.overlay=t(`div`,`havik-overlay`),this.center=t(`button`,`havik-center`,{type:`button`,"aria-label":`Play`}),this.center.innerHTML=Xg(`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=Xg(`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)},Qg)}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`?e_(this.lastError.country):this.lastError?.code===`DRM_DEVICE_REVOKED`?t_: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=Xg(`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&&!$g.has(this.lastError.code)){let e=this.doc.createElement(`button`);e.type=`button`,e.className=`havik-status__btn`,e.innerHTML=`${Xg(`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=`${i_(this.video.currentTime)} / ${i_(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(a_(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(o_(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(s_(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=Xg(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 i_(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 a_(e){return e.height?`${e.height}p`:`${Math.round(e.bitrate/1e3)} kbps`}function o_(e){return e.name||e.lang||`Track ${e.id}`}function s_(e){return e.name||e.lang||`Track ${e.id}`}var c_=6e3,l_=45e3,u_=2e3,d_=3,f_=5e3,p_=2e3,m_=48e4,h_=`keySystemLicenseRequestFailed`;function g_(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 pt(e.env);if(!e.baseUrl)throw new a(`INTERNAL`,0,`createPlayer: env or baseUrl is required (env: 'integration' | 'production')`);return e.baseUrl}async function __(e){if(!e.video||typeof e.video.play!=`function`)throw new a(`INTERNAL`,0,`createPlayer: opts.video must be an HTMLVideoElement`);let t=g_(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 v_({...e,baseUrl:t});return await n.start(),n}var v_=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??Se(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:l_,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)};_(c_),this.armingSub=xe({eventsBaseUrl:t,matchUrn:this.opts.matchUrn,credential:this.opts.credential,onAlive:()=>_(l_),onState:e=>{i||p()||(e.state===`live`||e.state===`gone`)&&setTimeout(g,Math.random()*u_)},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=Im(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}=Pg(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 Fg({endpoint:o,sid:r,player:t.name===`native`?`PLAYER_SAFARI_NATIVE`:`PLAYER_HLSJS`,sdkVersion:Vg,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()??Am,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()),Bg().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:Te(),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 Qm(i);if(o===`hls`)return new pg(i);if(e.drmEnabled&&e.drm?.fairplay?.licenseUrl&&e.drm.fairplay.certificateUrl&&Ym(this.opts.video)&&Xm()||!e.drmEnabled&&Zm()&&Ym(this.opts.video))return new Qm(i);if(hh())return new pg(i);if(Ym(this.opts.video))return new Qm(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??Se(this.opts.baseUrl);if(!t)return;this.closeLiveState();let n=0,r=!1;this.liveStateSub=xe({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:()=>{this.destroyed||e!==this.loadGen||r||this.endedHandled||(n+=1,n>=d_&&(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>=f_&&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()*u_))}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),Wg(n,this.opts.theme),this.container=n,this.controlBar=n_({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??p_);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!==h_||e.error.httpStatus!==403||e.error.code!==`FORBIDDEN`||e.error.serverCode===`license_refused`?!1:nh(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||nh(this._descriptor?.drm?.widevine?.licenseUrl)&&this.refreshLicense()},document.addEventListener(`visibilitychange`,this.onRefocus));let e=this.opts.licenseRefreshMs??m_;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()??Am}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 y_(e){return!!e&&typeof e==`object`&&typeof e.type==`string`&&e.type.startsWith(`oddin:`)}function b_(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||!y_(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 x_=/^[A-Za-z0-9:_.-]{1,128}$/;function S_(e){if(typeof e==`boolean`)return e;if(typeof e==`object`&&e){let t=e.endpoint;return typeof t==`string`?{endpoint:t}:{}}}function C_(){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:S_(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 w_(){let e=C_();E_();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`}),T_(t,e)})},s=async n=>{i?.destroy(),i=null;try{let r=await __({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`&&x_.test(e.matchUrn)&&s(e.matchUrn);break;case`oddin:destroy`:c()}},u=e=>{n&&e.origin===n&&y_(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 T_(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 E_(){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.ODDIN_THEME=Hg,e.PlaybackError=a,e.applyTheme=Wg,e.baseUrlForEnv=pt,e.bootEmbed=w_,e.clearDeviceId=Ee,e.clearRememberedBandwidth=ze,e.createPlayer=__,e.deriveEventsBaseUrl=Se,e.detectDrmSupport=lt,e.enterVideoFullscreen=de,e.exitVideoFullscreen=fe,e.fetchCatalog=pe,e.fetchTournament=he,e.flattenMatches=_e,e.fullscreenSupported=ue,e.getDeviceId=Te,e.isLowLatencyManifest=dt,e.isOddinMessage=y_,e.licenseRequestHeaders=Oe,e.mountEmbed=b_,e.pollToLive=N,e.resolveStream=te,e.subscribeLiveState=xe,e.videoFullscreenActive=le,e.watchStatus=ye,e})({});
|
|
173
173
|
//# sourceMappingURL=havik-player.global.js.map
|